這是我第一次在這裏提問,實際上我的腳本存在問題: 我試圖將瓷磚的鄰居添加到列表,但我不斷收到NullReferenceException:在嘗試打印列表中的內容時,未將對象引用設置爲對象的實例。無法將特定瓷磚的「鄰居」加載到列表中
要注意第一個「list.Add」實際上是工作的,其他的不是。 爲了測試它,我總是試圖找到存在的東西,所有Tile_(x)_(y)都存在。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TileStats : MonoBehaviour {
public int x;
public int y;
public List<GameObject> neighbours;
public List<GameObject> populateNeighbours()
{
List<GameObject> list = new List<GameObject>();
//If we're at x, y.
//Left one is at x-1,y
list.Add(GameObject.Find("Tile_" + (x-1) + "_" + y));
//Right one is at x+1,y
list.Add(GameObject.Find("Tile_" + (x+1) + "_" + y));
//Bottom ones are at x,y-1 and x+1,y-1
list.Add(GameObject.Find("Tile_" + x + "_" + (y-1)));
list.Add(GameObject.Find("Tile_" + (x+1) + "_" + (y-1)));
//Top ones are at x,y+1 and x+1,y+1
list.Add(GameObject.Find("Tile_" + x + "_" + (y+1)));
list.Add(GameObject.Find("Tile_" + (x+1) + "_" + (y+1)));
return list;
}
}
...
Tile_GO.GetComponent<TileStats>().x = x;
Tile_GO.GetComponent<TileStats>().y = y;
Tile_GO.GetComponent<TileStats>().neighbours=Tile_GO.GetComponent<TileStats>().populateNeighbours();
...
當我嘗試打印輸入錯誤被拋出: 的foreach(遊戲對象OBJ在ourHitObject.GetComponent()的鄰居。){ 打印( 「名稱:」 + obj.name + 「Atual:」 + i ++); }
解決
@AnthonyLeal我看了看代碼,這就是問題。您正在搜索GameObject,而它們不存在。試想一下:你在for循環中生成一個gameObject,然後在for循環中調用populateNeighbours()函數。 populateNeighbours()函數不會在該循環中生成的GameObject上運行。它會查找尚未生成的其他GameObjects。你做過這麼多次導致超過500個錯誤。 - 程序員
的可能的複製[「對象未設置」錯誤(http://stackoverflow.com/questions/3487637/object-reference-not-set-error) – Henders
你不顯示你所有的代碼,所以沒有人可以幫助你。請注意,很簡單,你不會在任何地方設置「鄰居」。你的意思是把它設置在「人口稠密」嗎? – Fattie
請注意,populateNeighbours **必須**被稱爲PopulateNeighbours,不能填充Neighbours。你需要改變它並編輯代碼來反映它。 – Fattie