A
A
aqkrie2020-05-06 21:15:31
C++ / C#
aqkrie, 2020-05-06 21:15:31

NullReferenceException Object reference not set to an instance of an object Unity?

There is a class WorldGenerator with a nested loop. The error occurs on the line

GameObject block = Instantiate(DB.blocks[0].gObj, new Vector3(x, y, 1), Quaternion.identity);


Full error text: NullReferenceException: Object reference not set to an instance of an object WorldGanerator.Generate (System.Int32 size) (at Assets/Scripts/WorldGanerator.cs:22)"

public class WorldGanerator : MonoBehaviour
{
    public GameObject PlayerInventoryPanel;
    public GameObject Player;
    DataBase DB;

    private void Start()
    {
        DB = gameObject.AddComponent<DataBase>();
    }

    public void Generate(int size)
    {
        for(int y = -size/2; y < size; y++)
        {
            for (int x = -size/2; x < size; x++)
            {
                GameObject block = Instantiate(DB.blocks[0].gObj, new Vector3(x, y, 1), Quaternion.identity);
                block.GetComponent<SpriteRenderer>().sprite = DB.blocks[0].Img;
            }
        }

        Instantiate(Player, Vector3.zero, Quaternion.identity);
    }
}


The Generate function is called from the Game class in Start

public class Game : MonoBehaviour
{
    DataBase DB;
    WorldGanerator WG;

    public GameObject PlayerInventoryPanel;

    private void Start()
    {
        DB = gameObject.AddComponent<DataBase>();
        WG = gameObject.AddComponent<WorldGanerator>();

        DB.Setup();
        WG.Generate(10);

        PlayerInventoryPanel.SetActive(false);
    }
}


The error seems to say that the problem is in the size variable, but I can’t understand what exactly

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question