- Home /
populate array values automatically in inspector
ill try and make this brief.
I have a project that I am experimenting with, it has a "crafting" and resource collecting system in place. all items in the game are stored in a single class as an enum
and then everything that uses that enum
calls it at runtime to populate itself.
for example
[System.Serializable]
public class testItem
{
public enum itemList {coal,gold,silver}; //you get the idea
}
[System.Serializable]
public class recipeList
{
public string itemName;
public bool craftable;
public testItem.itemList ingredientOne;
public testItem.itemList ingredientTwo;
//and so on for each ingredient for the item(if it's craftable)
}
public class craftItems : MonoBehaviour
{
public recipeList[] allItems = new recipeList[100]; //or whatever value
void start()
{
for(int i = 0; i < allItems.Length; i++)
{
allItems[i].name =Enum.GetName(typeof(testItem.itemList),i);
}
}//start()
}//class craftItems
*****and in another separate script.......
[System.Serializable]
public class inventory
{
public string name;
public int quantity;
public void adjustStock(int amount)
{
quantity += amount;
}
}//class inventory
public class mainBase : MonoBehaviour
{
public inventory[] inStock = new inventory[100];
void Start()
{
for (int i = 0; i < inStock.Length; i++)
{
inStock[i].name = Enum.GetName(typeof(testItem.itemList),i);
}
}//start()
}//class
so, this works fine, its not a bad system and it allows me a great deal of flexibility when it comes to assigning resource points, and workers to collect them, the recipe system works really well also.
after all this code, my question really is,
can i populate the inStock[]
array and the recipeList[]
array before runtime? this would allow me to create recipes easily and also adjust starting stock levels and so on, sorry if this has been a drawn out example, but im scratching my head a bit here as to what to do.
please ignore syntax errors, this is not my original code, i wrote it for the question.
bubzy.
Answer by bubzy · Oct 02, 2014 at 11:01 PM
I actually found out that I can
[ExecuteInEditMode]
before the classes, this way everything is populated prior to running the game,
the caveat is that you cannot affect certain objects properties
Answer by dmg0600 · Sep 29, 2014 at 09:50 AM
If you want it to be length fixed you can always assign new values to the elements of an array almost as you are assigning their names in your script.
inStock[index] = whatever;
If you want it to be more flexible and to be able to add and remove elements, just use lists insted of arrays:
public List<inventory> inStock = new List<inventory>();
To add and remove objects just use the Add and Remove methods from the list. you can take a look to lists use here.