GameObject creation order issue

1.6k views Asked by At

I'm currently working on an inventory system in Unity3D, and came upon a weird problem. I have created non-MonoBehaviour classes for my inventory system (in case that matters), so that I have an Inventory class which holds a list of Slot objects, which in turn holds a list of Item objects.

Then I added a component script to my "HudInventoryPanel", called "HudInventoryController", which looks like this:

using UnityEngine;
using System.Collections;

public class HudSlotController : MonoBehaviour {

    private InventoryController ic;

    // Use this for initialization
    void Start () {
        ic = GetComponent<InventoryController>();
    }

    // Update is called once per frame
    void Update () {
    }

}

However, inside the Start() method, the InventoryController (part of my Player) hasn't been created yet, and it seems to me like the gameobjects are created in alphabetical order...?

How should I deal with this problem?

3

There are 3 answers

0
Francklin Marroquin On

This was asked a long time ago, but here's a tip if someone comes into this issue as well: You can configure script execution order in Edit>Project Settings>Script Execution Order. Just add any script you require to be executed first before "Default time". Everything before Default time will be executed before it is loaded by Unity, and everything after as you can imagine, will be executed after Unity handles all other scripts.

2
Arttu Peltonen On

You can specify script execution order in the project settings (Edit -> Project settings -> Script execution order), so use that to make sure your scripts are executed in the correct order. In addition to that, you can use the Awake() method as all Awakes are executed before any Start() method. Hope a combination of these helps you!

0
toreau On

I solved this by creating an intermediate variable in my InventoryController script, plus creating a "manual" getter; https://gist.github.com/toreau/f7110f0eb266c3c12f1b

Not sure why I have to do it this way, though.