简体   繁体   English

Unity:如何从另一个脚本引用变量?

[英]Unity: How do I reference a variable from another script?

How do I reference a variable from another script?如何从另一个脚本引用变量? I am new and have been working on this for over twenty hours and I am super frustrated.我是新手,已经为此工作了二十多个小时,我非常沮丧。 I have tried many things and could not get it to do what I needed.我尝试了很多事情,但无法让它做我需要的事情。 I would greatly appreciate any kind of help.我将不胜感激任何帮助。 I either need to see how to reference the variable from the first script or how to access the variable from the method in the first script.我要么需要查看如何从第一个脚本中引用变量,要么需要查看如何从第一个脚本中的方法访问变量。

//Heres the first script. //这是第一个脚本。

public class Key : MonoBehaviour {
public bool fireCode;

public void fcodeOff()
{
 fireCode = false;
} 
}

//Heres the second script //这是第二个脚本

public class FireTRAP : MonoBehaviour 
{ 
public Key script;

void Update(){
script.fcodeOff();

}    

This is where I get confused and not sure what to do.这是我感到困惑的地方,不知道该怎么办。 I can use script.fcodeOff();我可以使用 script.fcodeOff(); in update and it is using the method from the other script but I need to reference the fireCode variable or the fireCode variable in that method.在更新中,它正在使用其他脚本中的方法,但我需要在该方法中引用 fireCode 变量或 fireCode 变量。

Any help would be appreciated.任何帮助,将不胜感激。 Thank You,谢谢你,

It's hard to tell what you are doing just by those 2 blocks of code.仅仅通过这两个代码块很难判断你在做什么。

Are you attaching the script or object from the Unity Game Engine into the serialized field in the inspector for your fire trap class?您是否将 Unity 游戏引擎中的脚本或对象附加到检查器中的序列化字段中,用于您的防火陷阱类?

If you aren't you should be instantiating your script class如果你不是,你应该实例化你的脚本类

public class FireTRAP : MonoBehaviour 
{ 
    public Key script;

    void Start(){

        Key = new Script();

    }

    void Update(){
        script.fcodeOff();

    }    

Doing it this way you should be able to reference the fireCode variable just by calling Key.fireCode这样做你应该能够通过调用Key.fireCode来引用 fireCode 变量

    void Update(){
        Debug.Log(Key.fireCode);
    }    

Should print false to the Debug Console.应该将false打印到调试控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM