首页 > 解决方案 > 初始化字典问题

问题描述

而不仅仅是初始化

Screens (Dictionary<GameObject, string> Screens) values

此代码使用这些关联值创建一个新的游戏对象屏幕。

问题在这里:

Screens[new GameObject(cont.Key)] = cont.Value;

这是屏幕的结果:“屏幕再次使用关联值 RightOuterPad=、LeftOuterPad=、LeftScreen=、RightOuterPad=、OPENPAD1-video-2、LeftOuterPad=OPENPAD1-video-1、LeftScreen=MAINBOARD1-video-2 创建

Dictionary<string, string> content = new Dictionary<string, string>();

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;
    }
}

标签: c#unity3d

解决方案


听起来你想做的是

using System.Linq;

...

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

而是检索第一个具有匹配名称的 GameObject,cont.Key并使用该引用来访问config.Screens字典中的正确条目。


推荐阅读