0
\$\begingroup\$

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:

Unity Script Hierarchy

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?

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

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>();

Also, it is not a good idea to use find in runtime code like this. Instead, you can assign it as a serialized component if they are part of the same prefab or at least cache the reference so that you won't need to look it up each time. Good luck!

\$\endgroup\$
5
  • \$\begingroup\$ 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. \$\endgroup\$ Dec 20, 2020 at 23:38
  • \$\begingroup\$ 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. \$\endgroup\$
    – DMGregory
    Dec 21, 2020 at 4:14
  • \$\begingroup\$ @DMGregory Ok, thanks. It's funny, I thought there was a better way of doing this than having to put in .parent a billion / multiple times. I guess not, interesting. Thanks. \$\endgroup\$ Dec 22, 2020 at 17:58
  • \$\begingroup\$ The better way is the serialized variable. \$\endgroup\$
    – DMGregory
    Dec 22, 2020 at 17:59
  • \$\begingroup\$ Oh, ok, thanks. \$\endgroup\$ Dec 22, 2020 at 19:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .