我目前處於丟失狀態,因爲我的GameObject返回null。從另一個類中調用時,GameObject數組返回null
關於這個問題,我不確定是否因爲我錯過了一件小事,或者如果我直接編寫完全錯誤的多個類的使用。
我的代碼,我產生了遊戲對象數組:
public class gridInit : MonoBehaviour {
const int mapWidth = 33;
const int mapHeight = -27;
const float tileSizeUnits = 1.0f/3;
public GameObject tile;
// Use this for initialization
void Start() {
GenerateTileMap();
Screen.fullScreen = true;
}
void Awake()
{
}
// Update is called once per frame
void Update() {
}
bool walkable = false;
[HideInInspector]
public GameObject[] goTile = new GameObject[892];
void GenerateTileMap()
{
int tileNumber = 0;
for (float y = 0; y > mapHeight; y--)
{
for (float x = 0; x < mapWidth; x++)
{
float tilePosX = x/3;
float tilePosY = y/3;
int layerPos = -2;
goTile[tileNumber] = Instantiate(tile, new Vector3(tilePosX, tilePosY, layerPos), Quaternion.identity) as GameObject;
goTile[tileNumber].name = "tile" + tileNumber;
goTile[tileNumber].tag = "grid";
RaycastHit2D hit;
Vector3 fwd = goTile[tileNumber].transform.TransformDirection(Vector3.forward);
Debug.DrawRay(goTile[tileNumber].transform.position, fwd * 50, Color.green);
hit = Physics2D.Raycast(goTile[tileNumber].transform.position, fwd, 200);
if (hit)
{
goTile[tileNumber].tag = "walkableGrid";
}
tileNumber++;
}
}
}
而且我的課,我想用一組GameObjects:
public class gameCalibration : MonoBehaviour {
bool calibrationComplete = false;
public gridInit gInit;
public cam Cam;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
{
for (int i = 0; i < gInit.goTile.Length; i++)
{
if (calibrationComplete == false)
{
gInit.goTile[i].GetComponent<Renderer>().enabled = true;
}
else
{
gInit.goTile[i].GetComponent<Renderer>().enabled = false;
}
}
if (calibrationComplete == false)
{
Calibrate();
}
else
{
gInit.GenerateObjects();
calibrationComplete = true;
}
}
}
Vector2[] camTileCenter;
Vector2 tempCenter;
void Calibrate()
{
for (int i = 0; i < gInit.goTile.Length; i++)
{
gInit.goTile[i].GetComponent<SpriteRenderer>().color = Color.red;
if (Cam.redBlobs[i] != null && camTileCenter[i] != tempCenter)
{
camTileCenter[i] = new Vector2(Cam.redBlobs[i].Width/2, Cam.redBlobs[i].Height/2);
tempCenter = camTileCenter[i];
}
}
}
}
我試着用一些值瞎搞,以及如何該課程已初始化,但沒有佔上風。
我的完整的錯誤:在gameCalibration
NullReferenceException: Object reference not set to an instance of an object
gameCalibration.Update() (at Assets/Scripts/gameCalibration.cs:21)
錯誤行:gInit.goTile[i].GetComponent<Renderer>().enabled = true;
您需要實例化類的外觀,因爲你永遠不會這樣做 - 它從來沒有將其稱爲啓動方法 –
您是否在檢查器中爲gInit分配參考?你能指出它拋出異常的那一行嗎? –
您可以添加一些日誌記錄來確定哪個引用爲空?它是'goTile [i]'還是'GetComponent()'?知道這些信息會澄清手頭的問題。 –
Serlite