2D script that allow to grab an object and destroy or disappear another objects but the same type.

  • Someone can help me out with a 2D script that grab an object that allow to destroy or disappear another objects.
  • For Example i got a red cube when this cube touch this red object allow me to get thought or destroy another red objects.

You can drag an object simply by updating the Object’s transform to the transform of the Vector2 of the Input.mousePosition. This red cube can have a collider and rigidbody2D marked kinematic and is a trigger that calls OnTriggerEnter2D.

void OnTriggerEnter2D(Collider col) {
    if (col.gameObject.tag == "Destroyable") {
        Destroy(col.gameObject);
    }
}

When the red cube (which follows your mouse position) touches another object with the tag “Destroyable” it will call Destroy() on that object.