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

Есть класс WorldGenerator со вложеным циклом. Ошибка возникает на 22 строке

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

Полный текст ошибки:

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);
    }
}

Функция Generate вызывается из класса Game в 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);
    }
}

Ответы (1 шт):

Автор решения: Алексей Бобрович

В ошибке прописано, что DB имеет значение null. Почему у вас AddComponent()? AddComponent добавляет компонент GameObject, используйте GetComponent() чтобы получить компонент. В методе Start вы не присваиваете какое либо значение переменной, DB а наоборот. Поэтому DB это null и соответственно появляется ошибка. Поэтому заменитель AddComponent на GetComponent.

→ Ссылка