为什么我一直得到NullReferenceException?

时间:2018-04-03 03:48:11

标签: c# unity3d

我试图从元素列表中获取变量,但我不断收到此错误:

NullReferenceException:对象引用未设置为对象的实例 tiledebug.Start()(在Assets / Scripts / tiledebug.cs:16)

瓷砖类:

[System.Serializable]
public class Tile {

//Core Tile Variables
public string tileName;
public int tileID;
public GameObject tilePrefab;

//Breaking System Variables
public bool IsBreakable;
public float breakSpeed;


public Tile(int newTileID, string newTileName, GameObject newTilePrefab, float newBreakSpeed) 
{
    tileID = newTileID;
    tileName = newTileName;
    tilePrefab = newTilePrefab;
    breakSpeed = newBreakSpeed;
}
}

tiledebug类:

public class tiledebug : MonoBehaviour {

float breakTime;
TileManager tileManager;


void Start()
{
    breakTime = 0;

    foreach (Tile tile in tileManager.Tiles)
    {
        breakTime = tile.breakSpeed;
    }
}

void Update()
{
    GameObject.Destroy(gameObject, breakTime);
}
}

3 个答案:

答案 0 :(得分:3)

这是因为tileManager类中的tileDebug未设置为对象的实例。

你应该试试!!

TileManager tileManager = new TileManager();

希望这会有所帮助!!

答案 1 :(得分:2)

TileManager内的tiledebug为空,要解决此问题,您需要将以下代码添加到类tiledebug

public tiledebug()
{
     tileManager=new TileManager();
}

答案 2 :(得分:1)

你必须在void Start中初始化tileManager对象,如下所示。试试这个。

tileManager = new TileManager();