简体   繁体   中英

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(); 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.

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?

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

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

Should print false to the Debug Console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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