使用字符串变量来标识类

时间:2016-08-23 21:45:35

标签: c# unity3d

我有一个简单的类来定义房间。最初我设置了我需要的所有房间(可能是长列表中的数百个),尽管在我的示例中我只设置了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; }
}

1 个答案:

答案 0 :(得分: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);这样的东西会更合适。)

希望这有帮助!如果您有任何问题,请告诉我。