Search code examples
c#unity-game-enginegameobject

Accessing a script from another script at runtime in Unity C#


Like in here, but the difference is that it's supposed to be done from an instantiated prefab, so I can not drag the GameObject, that has the script with the variable I want to access, into this script.

enter image description here

This was working

public ScriptA script;

void Update() {
   if (script.varX < 0) {
      // . . .
   }
}

But now I'm getting "Object reference not set to an instance of an object" error, which I think comes from the fact that the script trying to access ScriptA, is attached to an instantiated prefab.

How do I attach scripts and/or GameObjects at runtime?


Solution

  • Looks like you need to find your script type first, if it already exists in the scene:

    public ScriptA script;
    
    void Start()
    {
        script = GameObject.FindObjectOfType<ScriptA>();
    }
    
    void Update()
    {
        if(script.variable...)
    }