Is it possible to find the position of an item in an array? For example, I have an array of strings in the format of [15, 2]. I want to find out the value of [1, 0] as an integer. So I want to return ‘1’. Is this possible?
code
private string[,] InvItems = new string[15, 2]
It is used to store 15 items in an inventory with the following properties…
InvItems[0, 0] = "ItemType_JumpPad"
// Type of object to spawn
InvItems[0, 1] = "1"
// Whether this object is enabled or not
InvItems[1, 0] = "ItemType_Platform" InvItems[1, 1] = "1"
InvItems[2, 0] = "ItemType_Platform" InvItems[2, 1] = "1"
It doesn’t seem that this data structure is exactly what you need. The problem with this is that you cannot assess it in proper ways. You should take a look at object oriented programming for this instead. Create a class/enum for your types of objects and save a boolean along. It is probably even better to just create a class per type.
// a simple class that holds information about the type and if it is enabled
// this class is NOT a monobehaviour
public class InventoryType
{
public string Name
{
get;
set;
}
public bool Enabled
{
get;
set;
}
// constructor of the type
public InventoryType(string name, bool enabled)
{
this.Name = name;
this.Enabled = enabled;
}
}
You can now easily save these objects in an array or better, a List
:
public class Foo : MonoBehaviour
{
// create a list at a capacity of 15
private List<InventoryType> inventory = new List<InventoryType>();
public Awake()
{
inventory.Add(new InventoryType("Platform",true));
}
}
Of course there are other ways to do this, but this makes sure that it is flexible. You can always add extra information to your type class. To search for a certain type, you can use functions like Find
, which can make you find objects with a certain criterium (like the name of the type).