在使用dictionary中,用struct作为Tkey 出现KeyNotFoundException: The given key was not present in the dictionary.问题。
问题代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class levelManger : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField]
private GameObject[] titlePrefabs;
[SerializeField]
private cameraMovement cameraMovement;
public Dictionary<Point,TitleScript> Tiles {get; set;}
public float TitleSize
{
get{return titlePrefabs[0].GetComponent<SpriteRenderer>().sprite.bounds.size.x;}
}
void Start()
{
Createlevel();
}
// Update is called once per frame
void Update()
{
}
private void Createlevel()
{
Tiles = new Dictionary<Point, TitleScript>();
string[] mapData = ReadLevelText();
int mapX = mapData[0].ToCharArray().Length;
int mapY = mapData.Length;
Vector3 maxTile =Vector3.zero;
Vector3 worldStart=Camera.main.ScreenToWorldPoint(new Vector3(0,Screen.height));
for(int y =0;y<mapY;y++)
{
char[] newTitles=mapData[y].ToCharArray();
for (int x = 0; x < mapX; x++)
{
placeTitle(newTitles[x].ToString(),5*x,5*y,worldStart);
}
}
//问题行 _ **maxTile = Tiles[new Point(mapX-1,mapY-1)].transform.position;**_
cameraMovement.SetLimits(new Vector3(maxTile.x+TitleSize*5,maxTile.y - TitleSize*5));
}
private void placeTitle(string titleType,int x,int y,Vector3 worldStart)
{
int titleIndex=int.Parse(titleType);
TitleScript newTitle= Instantiate(titlePrefabs[titleIndex]).GetComponent<TitleScript>();
newTitle.Setup(new Point(x,y),new Vector3(worldStart.x+(TitleSize * x),worldStart.y-(TitleSize * y),0));
Tiles.Add(new Point(x,y),newTitle);
}
private string[] ReadLevelText()
{
TextAsset bindData = Resources.Load("Level") as TextAsset;
string data = bindData.text.Replace(Environment.NewLine,string.Empty);
return data.Split('-');
}
}
public struct Point {
public int x;
public int y;
}
public class NewBehaviourScript : MonoBehaviour
{
public Dictionary<Point, int> dict = new Dictionary<Point, int>();
void Start()
{
dict.Add(new Point { x=1,y=1},1);
print($"字典结果: {dict[new Point { x = 1, y = 1 }]}");
}
}
经测试毫无问题,你应检查你输入的Key是否在字典内
看起来应该是你的key真的不存在,建议检查逻辑,或者使用前判断是否存在此key
另外不建议使用复杂类型当做字典的key,建议在Point
中重写一下ToString
方法,使用其返回值的字符串当做Key,这样基本可以满足需求,