Simon Simon - 3 years ago 64
C# Question

Access variables/functions from another script

So im trying to change a variable in another script by touching a cube.
Current setup


  • 1x Player

  • 1x Enemy



Each with their own script
Enemy_Stats
&
Character_Stats


As you can see in this little snippet it's quite a workaround to access the variable from another script.

void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
collision.gameObject.GetComponent<Enemy_Stats>().Health =
collision.gameObject.GetComponent<Enemy_Stats>().Health
- gameObject.GetComponent<Character_Stats>().AttackDamage;

if (collision.gameObject.GetComponent<Enemy_Stats>().Health <= 0)
{
Destroy(collision.gameObject);
}
}
}


Iam new to Unity, but isn't there a way to just refer it with something like:

collision.Health
?

Answer Source

How to access variables/functions from another Class. The variable or function you want to access 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.

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();
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download