unity3d 以Vector3为键,GameObject为值的字典

sshcrbum  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(273)

我得到“对象示例未设置为示例对象”

private Dictionary<Vector3, GameObject> wallPositions;

    void Start()
    {
        size = 6;
        HalfMaze = new GameObject("Half Maze");
        traversed = new bool[size, size, size];
        Dictionary<Vector3, GameObject> wallPositions = new Dictionary<Vector3, GameObject>();
        GenerateGrid();
    }
//in some function
        foreach (Transform child in HalfMaze.transform) {
            //Debug.Log("hi2");
            foreach (Transform grandchild in child) {
                //Debug.Log(grandchild.gameObject.name);
                if (!(grandchild.position.x == -0.5f || grandchild.position.x == -0.5f + size || grandchild.position.y == -0.5f || grandchild.position.y == -0.5f + size || grandchild.position.z == 0 || grandchild.position.z == -0.5f + size)) {
                    wallPositions[grandchild.position] = grandchild.gameObject; //issue is here
                    //Debug.Log("hi");
                }
            }
        }

第二个代码块中的if语句内部导致运行时出现问题。我不知道为什么我得到的问题,因为孙子。gameObject不为null。

ia2d9nvy

ia2d9nvy1#

在Start方法中重新声明wallPositions变量。在Start方法中初始化wallPositions变量时,删除类型声明Dictionary〈Vector3,GameObject〉。
替换此行:

Dictionary<Vector3, GameObject> wallPositions = new Dictionary<Vector3, GameObject>();

用这个:

wallPositions = new Dictionary<Vector3, GameObject>();

看看能不能用

5f0d552i

5f0d552i2#

在使用变量之前,你需要初始化变量,包括字典。

private Dictionary<Vector3, GameObject> wallPositions = new();

相关问题