Answer the question
In order to leave comments, you need to log in
NullReferenceException: Object reference not set to an instance of an object why?
Why does this error display?
Here is the code:
for(int i = 0; i < inventoryItems.Length;i++)
{
if(inventoryItems[i] != null) continue;
inventoryItems[i] = it;
print("item add - " + inventoryItems[i]);
(new InventoryWindow()).Redraw();
}
public class InventoryWindow : MonoBehaviour
{
[SerializeField] public Inventory targetInventory;
[SerializeField] public Transform itemsPanel;
void Start()
{
Redraw();
}
void Update()
{
if(Input.GetKeyDown(KeyCode.F))
Redraw();
}
public void Redraw()
{
bool ChildNull = true;
bool RemoveSprites = false;
bool finish = false;
while(finish != true)
{
print("z - " + itemsPanel.transform.childCount);
if(itemsPanel.transform.childCount == 0) {ChildNull = true;}
else if(itemsPanel.transform.childCount > 0) {ChildNull = false;}
print("bool - " + ChildNull);
if(ChildNull == true)//если спрайтов нету
{
for(var i = 0; i < targetInventory.inventoryItems.Length; i++)
{
if(targetInventory.inventoryItems[i] != null)
{
var item = targetInventory.inventoryItems[i];
GameObject icon = new GameObject("Icon");
icon.AddComponent<Image>().sprite = item.Icon;
icon.transform.SetParent(itemsPanel);
icon.transform.localScale = Vector3.one;
}
}
}else//если есть
{
if(RemoveSprites == false)
{
for(int i = 0; i < itemsPanel.transform.childCount; i++)
{
Destroy(itemsPanel.transform.GetChild(i).gameObject);
if(i == (itemsPanel.transform.childCount - 1)) RemoveSprites = true;
}
}else if(RemoveSprites == true)
{
for(var i = 0; i < targetInventory.inventoryItems.Length; i++)
{
if(targetInventory.inventoryItems[i] != null)
{
var item = targetInventory.inventoryItems[i];
GameObject icon = new GameObject("Icon");
icon.AddComponent<Image>().sprite = item.Icon;
icon.transform.SetParent(itemsPanel);
icon.transform.localScale = Vector3.one;
}
if(i == (targetInventory.inventoryItems.Length - 1)) finish = true;
}
}
}
}
}
}
print("z - " + itemsPanel.transform.childCount);
if(itemsPanel.transform.childCount == 0) {ChildNull = true;}
Answer the question
In order to leave comments, you need to log in
Firstly, using While is bad.
Secondly, the NullReferenceException error means that you are trying to access an object that is not (null) or empty, you may have deleted it or it has not yet been created. From the described emerges that in itemsPanel.transform. childCount - null(empty). Alternatively, you can write print("z - " + itemsPanel.transform?.childCount);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question