I’m making a game which lets you spawn units in a game, and to start spawning a unit I need to instantiate the unit prefab first to then get the necessary components from their individual variables. However I can not instantiate the gameObject into the array.
public GameObject[] instantiatedUnits;
float[] unitLastSummonTime = new float[5];
float[] unitCooldowns = new float[5];
float[] unitCosts = new float[5];
public void InstantiateAllUnits()
{
for (int i = 0; i < 5; i++)
{
instantiatedUnits _= (GameObject)Instantiate(Resources.Load("Units/" + UnitManagement.unitsName*.ToString()), new Vector3(0, 3, 0), new Quaternion());*_
Well, i’d do this using List<> instead of array, here’s how i’d do it:
//First, using List is way better for adding the units instantiated:
public List<GameObject> instantiatedUnits = new List<GameObject>(); // Changed from array[] to List<>. !!REMEMBER TO ADD THE NAMESPACE: using System.Collections.Generic!!
float[] unitLastSummonTime = new float[5];
float[] unitCooldowns = new float[5];
float[] unitCosts = new float[5];
public void InstantiateAllUnits()
{
for (int i = 0; i < 5; i++)
{
//now here we create a GameObject named "UNIT" and we instantiate the unit you'd like:
GameObject UNIT = Instantiate(Resources.Load("Units/" + UnitManagement.unitsName*.ToString()), new Vector3(0, 3, 0), new Quaternion());*
//then we add the UNIT GameObject to the instantiatedUnits List: instantiatedUnits.Add(UNIT); //DONE! Now you can access your instantiated Unit and its properties like in arrays: instantiatedUnits[Index] unitCooldowns = instantiatedUnits*.GetComponent().cooldown;* unitCosts = instantiatedUnits*.GetComponent().cost;* Destroy(instantiatedUnits*);* } }