简体   繁体   English

似乎无法从另一个脚本中获得正确的值?

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

In ScriptA, I have a random value (call it rndmInt) being called in Awake().在 ScriptA 中,我在 Awake() 中调用了一个随机值(称为 rndmInt)。 In ScriptB, I'm trying to correctly get the value of rndmInt in ScriptB's Start().在 ScriptB 中,我试图在 ScriptB 的 Start() 中正确获取 rndmInt 的值。

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.我(认为)它设置正确,因为当我使用 Debug.Log() 时,它不会弹出类似“无法访问 ScriptA.rndmInt”之类的错误。

In ScriptB, I have a Debug.Log() basically saying Debug.Log(ScriptA.rndmInt).在 ScriptB 中,我有一个 Debug.Log(),基本上是说 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.我当然已经在 ScriptA 中公开了 rndmInt,但是当我尝试将 ScriptA 链接到 ScriptB 时,它不会让我直接这样做。 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.相反,我必须将 ScriptA 放到一个 GameObject 上,然后将该 GameObject 拖放到检查器中的 ScriptB 上,并引用该 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 的 rndmInt 中,它会正确且真实地记录随机 integer。当我尝试记录 ScriptB 从 ScriptA 获取 rndmInt 的尝试时,它总是记录“0”,而不是正确的值。 ScriptA isn't always 0. ScriptA 并不总是 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.根据您的问题,我只能假设您目前正在 Debug.Log 中使用 ScriptA 的新实例,它会返回整数类型的默认值。

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

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