I am creating a simple vertical-scrolling listbox. For test purposes I wrote a for-loop to instantiate 20 copies of the list-item prefab (a Button) and parent it on the ScrollRect’s Content child. If I call this loop from Start() the listbox works as expected. If I call this loop from OnEnable() the listbox “knows” the items are there (the scrollbar thumb resizes appropriately) but they are not visible.
Is this known/documented somewhere? Is there a better solution than to just add some cheesy timer to OnEnable?
Using Start:
Using OnEnable:
Hierarchy is exactly the same:
And of course, the code is dead simple:
using UnityEngine;
using UnityEngine.UI;
public class PopulateListbox : MonoBehaviour {
public GameObject ListParent;
public Button ListItemPrefab;
void OnEnable()
//void Start()
{
for(int i = 0; i < 20; i++)
{
Button b = (Button)Object.Instantiate(ListItemPrefab);
b.transform.parent = ListParent.transform;
Text t = b.transform.GetChild(0).GetComponent<Text>();
t.text = "copy " + i.ToString();
}
}
}
Does OnEnable() get called even though the rest of the scene is still busy calling Awake() or was it Start()?
It must mean Start() waits to get called for all the scenes objects after Awake() is done being called for All the scene objects? … and OnEnable() doesn’t? Just gets called immediately after an Awake().
This says Awake then OnEnable is guaranteed to be called on everything in the scene before any Start is called. I suppose I should also have mentioned it is the Canvas which is being enabled/disabled and which has the OnEnable script.
Docs are not right on that one. Have been bugged by this one before. The order changes. If you have OnEnable and Awake, OnEnable is called first. Not sure but if you only have OnEnable, other behaviors that have only Awake() might be called first.
Thanks, good to know. I went ahead and reported it as a bug and Unity responded that it has been fixed in 5.4.
I don’t have the beta installed right now but this was just test code. In the real code I’m writing today, it’ll pull the listbox contents down from a server anyway and that delay will be more than long enough for Unity to get sorted. And it won’t be OnEnable either, it’ll be the callback for the data response. But – looked like a bug so figured it was worth checking.