# How do I get a reference to a component on a sibling object in C# Script?

I'm working on a game, where the player dumps trash from Trash cans into a Trash Truck. These Trash cans have a random chance of having a Racoon on top of them.

I have a script set up to detect when the player enters a Collider Trigger attached to the Racoon, which will cause it to play an animation and start attacking the player.

To do that, it needs to work with a racoon navigation component on a neighbouring object:

I'm trying to access the RacoonNAVAI component on the Racoon_Mover game object with this line:

racNav = transform.parent.parent.Find("Racoon Mover").gameObject.GetComponent<RacoonNAVAI>();


But it's throwing a null reference exception. How can I correctly get a reference to this component?

In the line below you are looking for Racoon Mover instead of Racoon_Mover, note the _ (underscore symbol).
racNav = transform.parent.parent.Find("Racoon Mover").gameObject.GetComponent<RacoonNAVAI>();

• Wow, that fixed it, thanks. And, so, I have more than one of these Trash cans, and they can be parented to the Trash Truck. And I want these Trash cans to be independent of one another, I want all the related scripts to be self-contained within each Trash can. So Setting it to [SerializeField] would do that? And how would I cache the reference? Thanks. – Fox GAMING_NTF Dec 20 '20 at 23:38
• You may also want to consider transform.parent.parent.GetComponentInChildren<RacoonNAVAI>() - shorter, no string comparisons or corresponding breakages if you misspell/change a name, and it gets you the component directly without a second search. – DMGregory Dec 21 '20 at 4:14