Access variables/functions from another Component
Solution 1:
How to access variables/functions from another Class. The variable or function you want to access or called must be public
not private
.
public class ScriptA : MonoBehaviour{
public int playerScore = 0;
void Start()
{
}
public void doSomething()
{
}
}
Access variable playerScore
in ScriptA
from ScriptB
. First, find the GameObject that the script or component is attached to with the GameObject.Find
function then use the GetComponent
function to retrieve that script or component that is attached to it.
public class ScriptB : MonoBehaviour{
ScriptA scriptInstance = null;
void Start()
{
GameObject tempObj = GameObject.Find("NameOfGameObjectScriptAIsAttachedTo");
scriptInstance = tempObj.GetComponent<ScriptA>();
//Access playerScore variable from ScriptA
scriptInstance.playerScore = 5;
//Call doSomething() function from ScriptA
scriptInstance.doSomething();
}
}
Solution 2:
No since Health
is not part of the collision object, but Enemy_Stats
. You can cache a Component
(that's what Enemy_Stats is) if you use it multiple times to save you some typing (and some performance, but that is rather marginal for this example). Also you can cache "known" components like in this case Player_Stats
. You can do this e.g. in Start
or with a public variable and the inspector.
What you should probably do though is to make the enemy be responsible for his life and not the player, so move the Destroy
-part to Enemy_Stats
(into the Health property to be exact).