在 Unity C# 中在运行时从另一个脚本访问脚本 [英] Accessing a script from another script at runtime in Unity C#
问题描述
就像在
这是有效的
public Script一个脚本;无效更新(){如果 (script.varX <0) {//...}}
但现在我收到未将对象引用设置为对象的实例"错误,我认为这是由于尝试访问 ScriptA 的脚本附加到实例化预制.
如何在运行时附加脚本和/或游戏对象?
看来你需要先找到你的脚本类型,如果它已经存在于场景中:
public Script一个脚本;无效开始(){script = GameObject.FindObjectOfType();}无效更新(){如果(脚本.变量...)}
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?
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...)
}
这篇关于在 Unity C# 中在运行时从另一个脚本访问脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!