I have a game object and I attached two behaviours to it. How can I make them see each other, if one depends on another and vice versa?
If both components are on the same game object, you can simply grab the component like so:
[RequireComponent (typeof (ComponentB))]
public class ComponentA
{
private ComponentB compB;
public void Awake()
{
compB = GetComponent<ComponentB>();
// Do something with compB
}
}
Notice the RequireComponent attribute at the top of the class. This makes absolutely sure that you cannot add ComponentA to a game object that doesn’t have ComponentB. This way, it will not crash if it’s missing. If ComponentB is optional, then remove that attribute, but make sure you check that the component is indeed there:
compB = GetComponent<ComponentB>();
if (compB != null)
{
// Do something with compB
}
Keep in mind that if both ComponentA needs to access ComponentB and ComponentB needs to access ComponentA, then you might be better off just making a single component. Or not. Just make sure you are not tangling your component relationships too much, as that will make things a lot harder for you when you need to change stuff later on.