Your destroy() method doesn’t actually do anything. It defines a local method called OnCollisionEnter, but doesn’t actually execute any code. In essence, none of your code actually does anything.
OnCollisionEnter is meant to be a top-level method on your class, like your destroy() and Update() methods. Unity will call the method automatically if a collision is detected
If your trees have colliders and no rigidbodies OnCollisionEnter will not be called. At least one object in the collision needs to have a rigidbody.
Both trees in the collision will receive the OnCollisionEnter callback. Meaning both of your trees will be destroyed if you set this up properly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class destroyif1 : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == “Tree”)
{
print(“collision”);
Destroy(gameObject);
}
}
}
so like this?
and I added rigidbody to all of the trees
But beware, it lets you spawn ALL the trees, THEN all the collision messages are processed AFTERWARDS, during the physics update portion of the game loop.
When you post code properly formatted, statements like this:
can more clearly show you are destroying the object that this script is on, not what it is hitting. Is this what you want? Also, in my test, two objects spawned on top of each other (with Rigidbodies and convex colliders) were BOTH told that the other one spawned on them, so without further checking they would blindly Destroy() each other.
I also did NOT test the case of three objects at once. It might not do what you expect.
If you are trying to explicitly deconflict something, just keep a list of what you have spawned and check for distance and explicitly despawn it. You’re likely to have a lot of problems relying on edge case physics behaviors.