2016-08-23 37 views
0

我有一個簡單的類來定義房間。最初,我設置了所有我需要的房間,(可能是數百個長列表),雖然在我的例子中我只設置了3個。然後我有一個字符串,我將用它來引用Rooms類的正確實例。例如,這可能是「X10Y10」。我想使用該字符串來標識相應的Rooms實例,但不知道如何關聯它們。使用字符串變量來標識類的相應實例

void Start() { 

     Rooms X10Y10 = new Rooms(); 
     X10Y10.Name = "The Great Room"; 
     X10Y10.RoomMonsters = 10; 
     X10Y10.Ref = "001"; 

     Rooms X11Y10 = new Rooms(); 
     X11Y10.Name = "Smoking room"; 
     X11Y10.RoomMonsters = 2; 
     X11Y10.Ref = "002"; 

     Rooms X12Y10 = new Rooms(); 
     X12Y10.Name = "Hunting Room"; 
     X12Y10.RoomMonsters = 7; 
     X12Y10.Ref = "003"; 



     // Don't Know the room Ref until runtime, during game. 
     // Want to get the room instance properties of one of the rooms eg. 

     string RoomAtRuntime = "X11Y10"; // dont know this until game is running 


     // fix following lines 
     print(RoomAtRuntime.RoomMonster); // would return 2 
     print(RoomAtRuntime.Name); //  would return Smoking room 
} 

public class Rooms 
{ 
    public string Ref { get; set; } 
    public string Name { get; set; } 
    public int RoomMonsters { get; set; } 
} 
+0

而不是標記'[[Resolved]]'(這裏不是「一件事物」),如果您可以接受現有的答案,或者如果實際解決方案明顯不同,並將*標記爲接受的答案 –

回答

2

這聽起來像你所需要的就是一個Dictionary - 這與鍵關聯的值的集合。在你的情況下,你可以將每個字符串關鍵字與不同的Rooms實例關聯起來,使其可以輕鬆(高效地)快速訪問任何實例。這裏是你的代碼可能會是什麼樣這種變化:

// Declare and initialize dictionary before using it 
private Dictionary<string, Rooms> roomCollection = new Dictionary<string, Rooms>(); 

void Start() { 
    // After you instantiate each room, add it to the dictionary with the corresponding key 
    Rooms X10Y10 = new Rooms(); 
    X10Y10.Name = "The Great Room"; 
    X10Y10.RoomMonsters = 10; 
    X10Y10.Ref = "001"; 
    roomCollection.Add("X10Y10", X10Y10); 

    Rooms X11Y10 = new Rooms(); 
    X11Y10.Name = "Smoking room"; 
    X11Y10.RoomMonsters = 2; 
    X11Y10.Ref = "002"; 
    roomCollection.Add("X11Y10", X11Y10); 

    Rooms X12Y10 = new Rooms(); 
    X12Y10.Name = "Hunting Room"; 
    X12Y10.RoomMonsters = 7; 
    X12Y10.Ref = "003"; 
    roomCollection.Add("X12Y10", X12Y10); 
    // The rooms should now all be stored in the dictionary as key-value pairs 

    string RoomAtRuntime = "X11Y10"; 

    // Now we can access any room by its given string key 
    print(roomCollection[RoomAtRuntime].RoomMonster); 
    print(roomCollection[RoomAtRuntime].Name); 
} 

請注意,您可能需要將指令using System.Collections.Generic添加到您的腳本文件。

您可以(也可能應該)也使用鍵字以外的字符串。在這裏,我認爲爲這些X/Y座標使用Vector2值會更有意義,而不是字符串。 (所以,像roomCollection.Add(new Vector2(10, 10), X10Y10);這樣的東西會更合適。)

希望這有助於!如果您有任何問題,請告訴我。

+0

魔術!你太棒了!我一直在此花費大量時間。謝謝你,謝謝!我已經測試過它,它工作。 Lee – Ferrari177

+0

@ Ferrari177太棒了!真的很高興我能幫助你。不要忘記,當答案令人滿意地解決了一個問題時,您可以通過點擊旁邊的複選標記來接受它。這標誌着它在系統中被回答 - 所以不需要編輯你的問題標題。 – Serlite

+0

@ Ferrari177以下是如何操作http://meta.stackexchange.com/a/5235 – Programmer

相關問題