2013-01-13 201 views
2

我來自Java並且正在採用C#腳本,現在我已經遇到了這個問題,現在正在尋找解決方案,我嘗試將該類設置爲一個實例和一切。這是一個我正在和一些朋友合作的微型遊戲項目。如何從C#中的另一個類調用一個變量

無論哪種方式,我有StatHandler.cs處理所有我們的statpoints ...然後我有HealthManager.cs應該處理所有健康相關的東西。

的問題是,我不能爲我的生活弄清楚如何調用變量,如

public int stamina, strength, agility, dexterity, wisdom; 

從StatHandler.cs

我知道,在Java中這將是爲容易,因爲

maxHealth = StatHandler.stamina * 10; 

雖然,你不能做到這一點與C#,創建實例時的代碼看起來像這樣

maxHealth = StatHandler.instance.stamina * 10; 

它爲我提供了錯誤

NullReferenceException: Object reference not set to an instance of an object 

我也試過inherriting,這樣做

public class HealthHandler : StatHandler { 

但它設置的所有值設爲0的HealthHandler類,它不讀任何東西。


我真的只需要弄清楚如何拉從其他C#文件的變量,因爲這是我的放緩一路下跌。

+0

[這是如何做一個漫長的旅程](http://books.google.com.sg/books/about/Head_First_C.html?id=Rnea7qV_qQAC&redir_esc=y),這裏是你如何[做它現在](http://stackoverflow.com/questions/1392017/calling-a-variable-from-another-class-c);) – bonCodigo

+0

好像你正試圖獲得耐力,就像它是一個靜態的領域。 。或者在StatHandler中將其設爲靜態,或者創建一個StatHandler的新實例並從中獲得耐力。 – Oren

+1

...「拾取C#腳本」...「調用變量」...「從C#文件中提取變量」......這個術語非常奇特。除此之外,它與Java中的相同:您需要一個對象實例來訪問類的非靜態字段。 –

回答

2

它實際上與Java相同。對於非靜態變量,你需要一個類的實例:

StatHandler sh = new StatHandler(); 
maxHealth = sh.stamina * 10; 

,或者您可以在類像

public static string stamina = 10; 

變量聲明爲靜態,然後訪問它

maxHealth = StatHandler.stamina * 10; 
0

在C#中,如果不初始化它,則不能使用值類型變量。

看起來像StatHandler.instancestatic方法。你不能使用你的int變量沒有任何分配。爲它們分配一些值。

例如

public int stamina = 1, strength = 2, agility = 3, dexterity = 4, wisdom = 5; 
+0

他們在我的代碼中稍後分配,使用庫我啓動腳本Start()函數的所有變量,我將這個值應用到所有變量中。 –

0

的NullReferenceException:未將對象引用設置到對象

您需要正確初始化的實例。看起來像StatHandler.instance是靜態的,沒有初始化。

可以在static構造

class StatHandler 
{ 

    static StatHandler() 
    { 
     instance = new Instance(); // Replace Instance with type of instance 
    } 
} 
+0

但是,考慮到這將是多人遊戲時,我們完成它,不會使用靜態變量腳本attatched玩家逆火,並導致每個玩家有相同的統計數據? –

+0

它會,它應該是實例成員。但那是設計問題,你會遇到很多這樣的問題。你可以寫下所有的需求,創建對象模型,然後如果你有進一步的問題,你應該問程序員.stackexchange.com – Tilak

0

有兩種方式去這裏初始化。

全靜態類

public static class StatHandler 
{ 
    public static Int32 Stamina = 10; 
    public static Int32 Strength = 5; 
} 

然後:

maxHealth = StatHandler.Stamina * 10; // get the value and use it 
StatHandler.Stamina = 19; // change the value 

Singleton實例

public class StatHandler 
{ 
    public static StatHandler Instance; 

    public Int32 Stamina = 10; 
    public Int32 Strength = 5; 

    // this is called only the first time you invoke the class 
    static StatHandler() 
    { 
     m_Instance = new Instance(); // Replace Instance with type of instance 
    } 
} 

然後:

maxHealth = StatHandler.Instance.Stamina * 10; // get the value and use it 
StatHandler.Instance.Stamina = 19; // change the value 

// replace the current instance: 
StatHandler.Instance = new StatHandler(); 
StatHandler.Instance.Stamina = 19; // change the value 

我認爲第一個總是最好的選擇,結果相同,複雜性更低。

相關問題