reference variable from another script unity code example
Example 1: unity variable from another script
//Make Health public
public class PlayerScript: MonoBehaviour {
public float Health = 100.0f;
}
//Access it.
public class Accessor : MonoBehaviour {
void Start()
{
GameObject thePlayer = GameObject.Find("ThePlayer");
PlayerScript playerScript = thePlayer.GetComponent<PlayerScript>();
playerScript.Health -= 10.0f;
}
}
Example 2: get variable from other scriptin unity c#
//-------------------------------PUT IN ScriptA-----------
public ScriptB = scriptB;
void Start()
{
scriptB.myFloat = 3.542f;
}
//---------------------------------------------
//---------------------------PUT IN ScriptB---------
//make sure public so it can be accessed from other scripts.
public float myFloat;
//script a will change myFloat to 3.542 from null;
//note this is for Unity and C#
Example 3: how to reference a variable from another script in unity
public class PointScript : MonoBehaviour { public static int playerScore; // Static keyword makes this variable a Member of the class, not of any particular instance. void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player") playerScore++; // The code that any instance can use to cause the score to be incremented, since the playerScore variable is a Static member, all instances of this class will have access to its value regardless of what instance next updates it. } }