Skip to main content
3 of 6
added 363 characters in body; edited title

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. This used to work, however, now, I'm trying to make these Trash cans work so that they are more independent, and don't require as much specific things as before. This Player Detection System used to work, however, now, it appears as if the booleans I'm using with this Detection Script no longer work, and I have no idea why. Everything works if I change the boolean in the Inspector, but it won't work in the Script.

When I try entering the Trigger, I get this error:

NullReferenceException: Object reference not set to an instance of an object RacoonPlayerDetect.OnTriggerEnter (UnityEngine.Collider col) (at Assets/Scripts/RacoonPlayerDetect.cs:33)

Line 33 is:

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

Here's My Current Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RacoonPlayerDetect : MonoBehaviour
{
    public bool isPlayerDetect = false;
    public bool firstNotice = true;

    public GameObject player;

    public RacoonNAVAI racNav;

void Start()
{
    isPlayerDetect = false;
    firstNotice = true;
}

void OnTriggerEnter(Collider col)
{

    if(col.gameObject.tag == "PlayerBody" && firstNotice == true)
    {
        Debug.Log("RacoonPlayerDetect- " + col.gameObject.name + " detected!");
        Debug.Log("RacoonPlayerDetect- " + col.gameObject.tag + " detected!");
        Debug.Log("RacoonPlayerDetect- " + firstNotice + " bool state!");

        //player = col.gameObject;
        Debug.Log("RacoonPlayerDetect- Parent: " + transform.parent.gameObject.name);
        Debug.Log("RacoonPlayerDetect- Parent of Parent: " + transform.parent.parent.gameObject.name);

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

        Debug.Log("RacoonPlayerDetect- PlayerBody Detected!");

        isPlayerDetect = true;
        firstNotice = false;
    }
}
}

The isPlayerDetect boolean does not seem like it wants to work, it will not change unless I change it in the Inspector. The same goes for the firstNotice boolean.

When I try Entering the Trigger Collider, here's what the Debug.Log's output:

RacoonPlayerDetect- MALE_ANATOMY_LOW_POLY_DELIVERY.001 detected!
RacoonPlayerDetect- PlayerBody detected!
RacoonPlayerDetect- True bool state!
RacoonPlayerDetect- Parent: Racoon
RacoonPlayerDetect- Parent of Parent: Racoon_Parent

If anyone needs any more information, please, let me know! Thanks!