0
votes

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?

3
It's not a duplicate. I linked that same question in my post, the difference is that I need to access the other script from a prefab GameObject, it can't be done in the same way.RealAnyOne
You instantiate a prefab and then with a reference to that clone, given to you by the instantiate method, you....do the thing listed in the dupe target...Draco18s no longer trusts SE

3 Answers

1
votes

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...)
}
1
votes

You want to use AddComponent, like:

ScriptA script = gameObject.AddComponent<ScriptA>() as ScriptA;

See the docs here: https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html

0
votes

Best way to satify the links is fill the fields in the very next lines after you instantiate, that way you can avoid ugly and expenstive Find* calls (I am assuming the script that does the instancing can be made aware of what the target objects are, after all it knows what and where to instantiate)

Its worth noting that newly instantiated scripts' Awake() method will be called before Instantiate() returns, while its Start() will be called at the start of following frame, this is a major difference between the two calls, so if your instantiated script needs the refectences in Awake() you should either refactor (move stuff to Start()) or use Find* as suggested earlier.