2016-08-23 75 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