簡體   English   中英

似乎無法從另一個腳本中獲得正確的值?

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

在 ScriptA 中,我在 Awake() 中調用了一個隨機值(稱為 rndmInt)。 在 ScriptB 中,我試圖在 ScriptB 的 Start() 中正確獲取 rndmInt 的值。

我(認為)它設置正確,因為當我使用 Debug.Log() 時,它不會彈出類似“無法訪問 ScriptA.rndmInt”之類的錯誤。

在 ScriptB 中,我有一個 Debug.Log(),基本上是說 Debug.Log(ScriptA.rndmInt)。 我當然已經在 ScriptA 中公開了 rndmInt,但是當我嘗試將 ScriptA 鏈接到 ScriptB 時,它不會讓我直接這樣做。 相反,我必須將 ScriptA 放到一個 GameObject 上,然后將該 GameObject 拖放到檢查器中的 ScriptB 上,並引用該 GameObject。 我認為這與它有關,但我真的不知道。

在 ScriptA 的 rndmInt 中,它會正確且真實地記錄隨機 integer。當我嘗試記錄 ScriptB 從 ScriptA 獲取 rndmInt 的嘗試時,它總是記錄“0”,而不是正確的值。 ScriptA 並不總是 0。

您應該能夠通過引用其他腳本來訪問它們。

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

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

    ...
}

根據您的問題,我只能假設您目前正在 Debug.Log 中使用 ScriptA 的新實例,它會返回整數類型的默認值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM