2015-10-27 105 views
1

在Unity訪問枚舉和變量,我有如何從另一個C#腳本Unity3d

public enum inven {Food,Scissors,Nothing}; 
public inven held; 

我如何可以訪問enum,更重要的是,包含在held變量中的信息,從另一個腳本。 我試過單身方法:

public class Singleton : MonoBehaviour { 

    public static Singleton access; 
    public enum inven {Nothing, Scissors, Food}; 
    public inven held; 

    void Awake() { 
    access = (access==null) ? this : access; 
    } 
} 

,使全局變量,通過

Singleton.inven.food //or 
Singleton.access.held //respectively 

但是訪問,即返回「空引用異常:對象引用不設置到對象的實例。」 我使用此也嘗試:

public class Accessor : MonoBehaviour { 
    void Start() { 
     GameObject HeldItem = GameObject.Find("Story"); //where story is the Gameobject containing the script of the enum and variable 
     TextController textcontroller = Story.GetComponent<Textcontroller>(); //Where TextController is the sript containing the enum and variable 
    } 
} 

通過TextController.held等訪問,返回到它需要的對象引用。這樣做的正確方法是什麼?

+0

我asnwered一個類似的問題在這裏。 http://stackoverflow.com/questions/33113980/how-do-i-use-variables-in-a-separate-script-in-unity3d/33123618#33123618 –

回答

1

這是我如何做我的單身人士。在我的情況下,它叫做SharedData

using UnityEngine; 
using System.Collections; 

public class Booter : MonoBehaviour 
{ 
    void Start() 
    { 
     Application.targetFrameRate = 30; 
     GameObject obj = GameObject.Find("Globals"); 
     if(obj == null) 
     { 
      obj = new GameObject("Globals"); 
      GameObject.DontDestroyOnLoad(obj); 
      SharedData sharedData = obj.AddComponent<SharedData>(); 
      sharedData.Initialize(); 
     } 
    } 
} 

此腳本附加到加載的第一個場景中的對象,並且它以腳本執行順序設置爲先執行。它創建一個GameObject來附加SharedData組件,然後告訴引擎在加載新的級別時不要刪除該GameObject。

然後訪問它,我這樣做:

public class Interface : MonoBehaviour 
{ 
    private SharedData m_sharedData; 

    public void Initialize() 
    { 
     GameObject globalObj = GameObject.Find("Globals"); 
     m_sharedData = globalObj.GetComponent<SharedData>(); 

     m_sharedData.LoadData(); // This is where I use something on the singleton. 
    } 
} 
相關問題