初始化字典问题

时间:2019-05-28 11:49:22

标签: c# unity3d

不仅仅是初始化Screens(Dictionary<GameObject, string> Screens )values ,此代码将使用这些关联的值创建一个新的gameObject屏幕。

问题在这里:Screens[new GameObject(cont.Key)]= cont.Value;这是屏幕的结果:“再次使用相关值创建屏幕 RightOuterPad =,LeftOuterPad =,LeftScreen =,RightOuterPad =,OPENPAD1-video-2,LeftOuterPad = OPENPAD1-video-1,LeftScreen = MAINBOARD1-video-2

词典内容=新的Dictionary();

content = ReadConfigFile(path);

Dictionary<GameObject, string> Screens = config.Screens;

List<string> ScreensNames = new List<string>();

foreach (var screen in Screens)
{
    ScreensNames.Add(screen.Key.name);
}

foreach (KeyValuePair<string, string> cont in content)
{
    if (ScreensNames.Contains(cont.Key))
    {
        Debug.Log(Screens);
        Screens[new GameObject(cont.Key)]= cont.Value;
    }
}

1 个答案:

答案 0 :(得分:2)

听起来你想做的是

using System.Linq;

...

var keyObjectReference = Screens.keys.FirstOrDefault(o => string.Equals(o.name, cont.Key));
config.Screens[keyObjectReference] = cont.Value;

这将检索第一个名称与cont.Key匹配的游戏对象,并使用该引用来访问config.Screens词典中的正确条目。