Categories
Unity

Best way to get variable from another script C# unity

public class Bool_Script_To_Access : MonoBehaviour
{
    public bool Smashed_Ant = false;
}
public class Script_To_Do_Stuff : MonoBehaviour
{
    public GameObject ant;
    private Bool_Script_To_Access bool_script;
    private void Start()
    {
        bool_script = ant.GetComponent<Bool_Script_To_Access>();
    }
    private void Update()
    {
        bool_script.Smashed_Ant = true;
    }
}

This is assuming that the two scripts are attached to two separate game objects. Now, in the inspector, select the game object which is attached to Script_To_Do_Stuff. Then, drag the game object which is attached to Bool_Script_To_Access to where it says “ant.” Done. This will work for most cases you’ll have. If you need more general reference to a game object it gets more difficult, and you might want to look into singleton approach.

You might check out the first 15 minutes or so of https://unity3d.com/learn/tutorials/topics/scripting/persistence-saving-and-loading-data
where he creates a GameControl which stores variables that can be accessed from any script. It is a great video

Ref: https://forum.unity.com/threads/best-way-to-get-variable-from-another-script-c-unity.579322/

Leave a Reply