-1

I am very new to unity, and this is probably going to seem like a dumb question to all the people who are good at C#, but I don't know why OnTriggerEnter is not working in this program. I have typed it as it said in the tutorial I'm following but it has no effect in the game. Help?

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

public class DetectCollisions : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        void OnTriggerEnter(Collider other)
        {
            Destroy(gameObject);
            Destroy(other.gameObject);
        }
    }
}

I haven't tried anything yet, I don't know what to try.

Zote Bote
  • 18
  • 5
  • The Rigidbody must be in at least one of the two colliding objects. Check if you have a rigid body. – RedStone Nov 02 '22 at 06:35
  • I claim this is a **TYPO**: Your `OnTriggerEnter` is **nested** as a local method within the `Update` method ... This way Unity will not find it when invoking it via its messaging system. I vote to close this question as typo based as it will not really be helpful for others – derHugo Nov 02 '22 at 07:07
  • Honestly the ability to created nested methods in .NET was a dark day indeed. –  Nov 02 '22 at 07:16
  • @derHugo I don't understand what that means. – Zote Bote Nov 02 '22 at 08:28
  • @RedStone I do have a Rigidbody in one of the objects – Zote Bote Nov 02 '22 at 08:28

1 Answers1

2

Ok as you seem to have difficulty to understand what is happening here again.

In

void Update()
{
    // I am a local function within the Update method!
    void OnTriggerEnter(Collider other)
    {
        Destroy(gameObject);
        Destroy(other.gameObject);
    }
}

you have the OnTriggerEnter nested undert the Update method as a local function. This way Unity doesn't "know"/find it when trying to invoke it via its messaging system.

You rather want to have it as a normal method on class level

void Update()
{

}

void OnTriggerEnter(Collider other)
{
    Destroy(gameObject);
    Destroy(other.gameObject);
}

and now since Update and Start are empty it is actually best to remove them all along ;)

derHugo
  • 83,094
  • 9
  • 75
  • 115