- Home /
An Instantiated object to array problem
Hello! What is the problem? I get this error: NullReferenceException: Object reference not set to an instance of an object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[System.Serializable]
public class inventorySlot
{
public int slotID;
}
public class inventoryDisplay : MonoBehaviour {
public GameObject slotPrefab;
public int slotsCount = 36;
public inventorySlot[] slots;
GameObject slotsBody;
private void Awake()
{
slots = new inventorySlot[slotsCount];
}
private void Start()
{
slotsBody = GameObject.Find("SlotsBody");
for(int i = 0; i < slotsCount; i++)
{
Instantiate
slots[i].slotID = 1;
}
}
}
Answer by Commoble · Mar 13, 2017 at 01:37 AM
After you instantiate an array of objects (any class type, not just UnityEngine.Objects), you also have to instantiate each object in the array.
The Instantiate() function (which you're not using the correct syntax for) is specifically for copying a GameObject from a prefab or an existing GameObject, and placing the copy into the scene. To instantiate an instance of a normal class (like your inventorySlot), you do this:
private void Awake()
{
slots = new inventorySlot[slotCount];
for (int i=0; i<slotsCount; i++)
{
slots[i] = new inventorySlot();
slots[i].slotID = 1;
}
}
Your answer
Follow this Question
Related Questions
how can i check if there is a blanc spot in my list 3 Answers
Add two radius on the same shader 1 Answer
Can´t instantiate objects in list correctly 1 Answer
Prefabs instantiated from an array are keeping their public int value 1 Answer
Initiate class array at start and assign class values. 0 Answers