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

走远了吗. 提交于 2021-02-11 14:02:31

问题


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.

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?


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/49237442/accessing-a-script-from-another-script-at-runtime-in-unity-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!