Deleting objects one by one

So i have a row of cubes. I want to collide into them and when i do they get destroyed.

void OnTriggerEnter(Collider coll)
{

  if(coll.gameObject.tag == "Buns")
 {
     incube = true;
 }

}

void Update()
{

if (Input.GetKeyDown(Keycode.lol)&& incube == true)

{
//but how to distroy object? Destroy(gameObject); yea i know but how to tell what im colliding with at the moment. I dont wanna break every cube at once. Also they randomly spawn so dont say “Give each a number” or something lol
}

}

How to delete the object im colliding with when i push buttons

And whoever downvoted my question is a real sack of sweaty eyeballs

–

i have a sprite with which i have attached your script and another a prefab assigned to "Object to spawn" variable which i want to spawn and the sprite is at layer "SpawnedObject" but still the error is coming on mouse up (doesnt matter wherever my mouse up is on the scene) ![alt text][1] [1]: /storage/temp/106572-capture.png

–

1 Answer

1

Use OnCollisionEnter(), in a way such as:

void OnCollisionEnter(Collider other){
          if(other.tag == "buns"){
              Destroy(other.gameObject);
       }
}

When you are within the OnCollision loop, you can access both the gameobject whose script this is by using the keyword this or the other gameobject using the name that you give to its collider. In this case other.

Hope it helps!

How to i destroy other.gameObject from inside Update() tho. I already tried the above.

–

Nvm found the solution. Im stupid ;-; public bool incube; public GameObject windowobj; void OnTriggerEnter (Collider coll) { if (coll.gameObject.tag == "Win") { incube = true; windowobj = coll.gameObject; } } void OnTriggerExit (Collider coll) { if (coll.gameObject.tag == "Windows") { incube = false; windowobj = coll.gameObject; } } void Update() { if (Input.GetButtonDown("Fire1") && incube == true) { windowobj.gameObject.SetActive(false); } }

–

I made a video so that I can show you how the script works... because it DOES work, it just needs to be set up properly. However I didn't put the script on a sprite, I put it on an empty game object. I hope the video will help, if it doesn't then I apologize for confusing you. https://www.youtube.com/watch?v=H2PHw0KPPPU&feature=youtu.be

–