简体   繁体   中英

Can't seem to get correct value from another script?

In ScriptA, I have a random value (call it rndmInt) being called in Awake(). In ScriptB, I'm trying to correctly get the value of rndmInt in ScriptB's Start().

I (think) it's set up correctly, as when I use Debug.Log(), it doesn't pop up with errors saying something like "Can't access ScriptA.rndmInt" or anything.

In ScriptB, I have a Debug.Log() basically saying Debug.Log(ScriptA.rndmInt). I of course have made rndmInt public in ScriptA, but when I try to link ScriptA onto ScriptB, it won't let me do so directly. I instead have to put ScriptA onto a GameObject, and then drag and drog that GameObject onto ScriptB in the inspecter, and reference the GameObject. I'm thinking that has something to do with it but I really don't know.

In ScriptA's rndmInt, it would correctly and truly log a random integer. When I try to log ScriptB's attempt of getting rndmInt from ScriptA, it always logs "0", instead of the correct value. ScriptA isn't always 0.

You should be able to access other scripts by referencing them.

public class ScriptA : MonoBehaviour
{
    public int rndmInt;
    ...
}

public class ScriptB : MonoBehaviour
{
    public ScriptA scriptA;
    void Start()
    {
         Debug.Log(scriptA.rndmInt);
    }

    ...
}

Based on your question I can only assume that you're currently using a new instance of ScriptA in your Debug.Log that returns you the default value of an integral type.

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