Im trying to make it so the script will detect the gameobject it’s attached to, then delete it if it goes below the floor. But it just keeps saying the gameobject is null, any help appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destroyer : MonoBehaviour
{
private GameObject Object;
void Update()
{
if (Object == null)
{
Object = transform.parent.gameObject;
}
if (Object.transform.position.y < -30)
{
Destroy(Object);
}
}
}
you’re encountering a NullReferenceException because you’re trying to access the transform.parent.gameObject without ensuring that the object actually has a parent.
As @C_Sharp_Gaming said, you’re trying to access the parent.
A “parent” in unity is the game object that is above in the hierarchie.
For example:
In your case you could have the Destroyer script on your “car” or “bike” GameObjects so when you write this:
if (Object == null)
{
Object = transform.parent.gameObject;
}
Your saying that you will destroy the “Vehicle” GameObject but I guess you don’t have any parent like in the image so you don’t have go with a variable, you can just Destroy(gameObject) since the “gameObject” here represent the one where your script is attached to.