I have two GameObjects and would like both to have a reference to the other. I know this can be done by creating public properties and setting them with Unity's inspector, but my preference is to stay in code whenever possible. Something like this:
public class Object1 : MonoBehavior
{
private Object2 _object2;
public void Start()
{
_object2 = GetComponent<Object2>();
}
}
public class Object2 : MonoBehavior
{
private Object1 _object1;
public void Start()
{
_object1 = GetComponent<Object1>();
}
}
I understand this doesn't work because one Start has to run before the other, but I'm not sure what alternative would be the best from a code quality standpoint.
- I could refactor so Object2 doesn't have a reference to Object1, but then it can't call any functions on Object1. Instead, Object1 would have to constantly query Object2 for whether or not it should do something.
- I could get the other component in Update rather than Start, but that seems like a bad strategy from a performance standpoint - searching for an object every frame even though it's always the same object.
- I could solve it outside of Start / Update. For example, Object2 could have a SetObject1 function that Object1 calls, or an EventManager could be used to communicate between objects. This seems like it might be a tad overkill for something as commonplace as this.
Are any of these a common practice among Unity devs? Is there another option I'm missing?
while (_object1 == null)
before_object1 = GetComponent<Object1>();
\$\endgroup\$object1
is? the name says it's a game object but the code says it's a component \$\endgroup\$