Instantiate working in Awake but on in Update
So I have a list of gameobjects, the list is linked to some UI elements through which I can click to decide which gameobject I want to create. To try out this code I wrote a simple timer in my update to create the object selected in my UI elemet every 3 seconds.
activeBuilding is the var that the list adjusts to decide which building to instantiate
When I call the instantiate line in Awake it works fine (with the list number assigned directly in the code to activeBuilding). However, when I try the same thing in Update it gives me an "Argumentoutofrangeexpection: argument is out of range".
Im not sure what I am doing wrong here, please let me know if you need any more information to help me out! This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Buildings : MonoBehaviour {
private int BuildingType;
private int BuildingGroup;
public List<GameObject> BuildingList;
private int activeBuilding = 3;
private float time = 0;
public void selectBuilding(int index)
{
activeBuilding = index;
}
private void Awake()
{
selectBuilding(0);
}
public void BuildingCreation()
{
}
private void Start () {
BuildingList = new List<GameObject>();
}
public void Update () {
selectBuilding(activeBuilding);
time += Time.deltaTime;
if (time > 3)
{
Debug.Log("active building = " + activeBuilding);
Instantiate(BuildingList[activeBuilding], new Vector3(10, 01, 10), Quaternion.identity);
time = 0;
}
}
}
Answer by Kishotta · Jan 20, 2018 at 04:13 PM
Are you assigning BuildingList in the inspector? If so, when you initialize it in Start(), you are nuking the list and replacing it with a new 0-length list (so any index will be out of range). You can initialize the list on declaration instead:
public List<GameObject> BuildingList = new List<GameObject> ();
Yeah that did the trick, thanks!
I dont fully understand why the Start() would empty my list though?
Start gets called after Awake, but only on the first frame. So in Awake you are setting activeBuilding
to 0, then in Start you are setting BuildingList
to a brand new empty list.
I wish I could tell you the specifics (and someone around here probably can) but the declaration initialization essentially happens when the object is created (before any $$anonymous$$onoBehaviour stuff happens), but is overridden by Inspector values.
This image may help you understand the issue a little better, too.
Thank you for the explanation that clears it up a bit! And thank you for your time :)