how to make 2 objects when collide with each other,appear a new one and the old ones dissapear

Hello so I’m trying to make a script that when an object collide with another specific object, they will be destroyed and another one will spawn right in the position where the old 2 collided.
Here is the script how it looks like, for now is not working:

public GameObject object1;
public GameObject object_2;
public float time_to_swap = 3;
void OnCollisionEnter(Collision col) {
        if((col.collider.gameObject.name==object_2.name.Replace("(Clone)","")||col.collider.gameObject.name==object_2.gameObject.name) && Raycast_Forward.carrying==false)
        {
            Invoke ("swap_2_objects", time_to_swap);
            Destroy (col.collider.gameObject);
        }
    }
private void swap_2_objects()
    {
        Instantiate (object1, gameObject.transform.localPosition, gameObject.transform.localRotation);
        Destroy (gameObject);
    }

I will appreciate any help possible :smile:

There are exceptions, but more often than not, if you’re doing any logic based on an object’s name, it’s probably the hard way to go about it, and will generally be unreliable - the slightest change will break your logic. It’s much easier to check for the presence of a particular component, and there’s nothing stopping you from adding an empty MonoBehaviour (empty = delete the Start and Update functions) to your targeted object.

void OnCollisionEnter(Collision col) {
if (col.collider.GetComponent<YourTargetScriptNameHere>() != null) {
//do your logic here
}
}

If that doesn’t fix the issue, you can insert some Debug.Log statements to check whether the code is getting to a particular point. Put one outside and one inside the if statement, for starters - that’ll narrow down whether the collision function is being called, whether the if statement is what’s stopping it, etc. You don’t provide any context as to what Raycast_Forward is or what its value might be, so that could be an issue - may want to check its value with a Debug.Log as well.