E
E
Espleth2015-04-06 11:16:25
Programming
Espleth, 2015-04-06 11:16:25

Changing the creation order of objects in Unity?

The problem is this: let's say we have 2 objects, one of them has such a script attached to it

public class GameController : MonoBehaviour
{
    public static GameController Instance;

    public Transform SomeTrasform; // Задается в Editor'e

    private void Start()
    {
        Instance = this;
    }
}

To the second such
public class SomeClass : MonoBehaviour
{
    private void Start()
    {
        Transform someTransform = GameController.Instance.SomeTransform;
    }
}

The problem is that the second object may be created before the first one, and I get a NullReferenceException when trying to call GameController.Instance. How can this be bypassed? I have 2 options so far:
With the help of a coroutine, postpone the creation of the second object for half a second, for example. I think it's an option.
Abandon static GameController.Instance, and use FindGameObjectWithTag("GameController").GetComponent().SomeTransform; Here, too, there are drawbacks, for example, changes in the code are required when transferring the GameController script to another object, and it simply does not turn out so beautifully.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniil Basmanov, 2015-04-06
@Espleth

If you need to manage the sequence of starts, then it's time to change the architecture. Your GameController must either instantiate objects with SomeClass, or initialize them, or whatever. Read about singletons at the link below.
www.gameprogrammingpatterns.com/singleton.html

G
Guriyar, 2015-04-06
@guriyar

1. You can use Awake() instead of Start() for the first object

private void Awake()
 {
        Instance = this;
}

2. Transfer all necessary calculations in the second object from Start() to Update() like this:
public class SomeClass : MonoBehaviour
{
    private bool _inited = false;
    private void MyStart()
    {
        Transform someTransform = GameController.Instance.SomeTransform;
    }

    private void Update()
    {
        if (!_inited)
        {
            MyStart();
            _inited = true;
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question