- Home /
[solved] Problem getting data from array
I am trying to make an inventory system for my game, but I have a problem, I have an array of Item classes, which hold the data for the inventory, but for some reason when I try to read it to get the icon of the object for use in the GUI, the function ignores everything and treats it as null, I know that the array isn't null, because when an object is picked up, Debug.Log can display the name variable stored in the Item class.
This is the function that reads the array and creates a set of GUILayout.boxes for the items:
GUILayout.BeginVertical(GUI.skin.box, GUILayout.Width(38));
for(int i=0; i<10; i++)
{
Item itm = getItemFromSlot(i);
if(itm != null)
{
GUILayout.Box(itm.icon, GUILayout.Width(32), GUILayout.Height(32));
}
else
{
GUILayout.Box("", GUILayout.Width(32), GUILayout.Height(32));
}
}
GUILayout.EndVertical();
And the getItemFromSlot function:
static Item getItemFromSlot(int slot)
{
return items[slot];
}
And lastly the Item class:
using UnityEngine;
using System.Collections;
public class Item : MonoBehaviour
{
public string type;
public string objName;
public Texture2D icon;
public GameObject obj;
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
if(MainGUIHandler.addItem (this))
Destroy (gameObject);
else
Debug.Log("Failed to add");
}
}
}
I have no idea why the function would return nothing and leave blank boxes every time, the array has objects in it.
Your loop runs 10 times do you have at least 10 slots in the array? When you say you have an array of "item classes", does the class correspond to an item?
You might be better with a List since they are more flexible. Also running loops in OnGUI can cause issues, try to keep as much logic as possible out of OnGUI or avoid OnGUI if possible.
The whole GUI thing is the OnGUI right? T27$$anonymous$$, why is a loop causing issues in OnGUI?
Are you getting any errors? If so you should post them in the question
well you need to start using debug.logs and making arrays public so you can see the values in the editor.
For example i'm not sure if an "empty" array thing is actually null, it might be filled with a default object or just junk.
do this
Item itm = getItemFromSlot(i);
debug.log (itm);
you should probably just use a list ins$$anonymous$$d.
Sorry, I wasn't clear enough. It was my understanding that running loops in OnGUI can result in performance issues. Yes,No?
Your answer
![](https://koobas.hobune.stream/wayback/20220613124923im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
can i find Joystick Position based on screen size? 0 Answers
Reading NFC Tags on Android 0 Answers