1
votes

I'm making some sort of a Evolution simualtor game. I have a script that is supposed to destroy the GameObject it's attached to when a creature's CapsuleCollider Triggers the OnTriggerEnter().

I have a problem that even tho the Creature's collider isn't even close to the Food, it still destroys the GameObject.

My script:

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

public class FoodEat : MonoBehaviour
{
    public GameObject FoodGO;
    public Rigidbody FoodRB;

    private void OnTriggerEnter(Collider Creature)
    {
        Destroy(FoodGO);
    }

    void Start()
    {
        FoodRB = GetComponent<Rigidbody>();
        FoodGO = FoodRB.gameObject;
    }

    void Update()
    {
        Rigidbody[] allRigidBodies = (Rigidbody[])FindObjectsOfType(typeof(Rigidbody));

        foreach (Rigidbody body in allRigidBodies)
        {
            if (body.gameObject.layer == 10)
            {
                 OnTriggerEnter(body.gameObject.GetComponent<CapsuleCollider>());
            }

        }

    }
}
1

1 Answers

3
votes

OnTriggerEnter is a monobehaviour lifecycle method. You should not call it from your own code; it will automatically be called when it detects collisions.

Furthermore, the logic in your code right now seems to be incorrect, it is...

"Every frame, loop through all rigidbodies in the scene and if 1 is found on layer 10, destroy the FoodGO"

Simply remove your entire Update method and put an if in your Collision method, and it should work:

[RequireComponent(typeof(Rigidbody), typeof(Collider))]
public class FoodEat : MonoBehaviour
{
    private void OnTriggerEnter(collider other)
    {
        Debug.Log(other.gameObject.name + " on layer " + other.gameObject.layer);

        if (other.gameObject.layer == 10)
            Destroy(this.gameObject);
    }

}

A few noteworthy edits of your code:

  1. I removed FoodGO, since it's the GameObject this script is attached to, you can access it by just writing gameObject or this.gameObject.
  2. I remove the Rigidbody reference since it is not used anymore, and thus the entire Start() method.
  3. Since this code requires a Rigidbody and a Collider to work, I added a [RequireComponent] attribute in the top, which will make Unity tell you if you forgot to add those components on the object you attach this script to.
  4. I added a Debug.Log that prints the name & the layer on the creature that collides with the food, so you can debug and make sure it is working as expected