Destroy Gameobject according to distance value

897 views Asked by At

I have a script that generates objects in the scene from a prefab, and I have a moveable cube. I want a script that gets the name of the object if the distance between the cube and the cloned object is < 0.3f.

I have this UnityScript:

var distance1 = Vector3.Distance(Food.transform.position, cube1.transform.position);
Debug.Log(distance1);

if(distance1 < 0.3f)
{
   //Destroy nearest object

}
2

There are 2 answers

0
Roberto Guajardo On BEST ANSWER

In this case I think is better to use Collision Detection as recommended by Barış Çırıka... but if you want to get it by distance I think you can do something like

var MyCube =  GameObject.FindGameObjectsWithTag("MyCube");
LateUpdate(){
var distance = Vector3.Distance(this.gameObject.transform.position, MyCube.transform.position);
if(distance < 0.3f)
{
Destroy(this.gameObject);
}
}

this script should be attached to every object you instantiate.

0
Barış Çırıka On

If you know which object is near. You can use Destroy.

Destroy(cloneObject);

If you don't know which objects are near, you can use List to add clone objects and check it is near.(When you create clone you need to add clone to the list.)

You need to add using System.Collections.Generic; for using List.

Example code: (It's C# code but you can understand logic)

....
using System.Collections.Generic;
public List<GameObject>cloneObjectList;

private void cloneObject(){
  GameObject cloneObject = Instantiate(originalPrefab,position,rotation);
  cloneObjectList.add(cloneObject);
}

private void checkDistance(){
   foreach(GameObject cloneObject in cloneObjectList){
      float distance = Vector3.Distance(Food.transform.position, cloneObject.transform.position);
      if(distance <0.3f){
         cloneObjectList.Remove(cloneObject);
         Destroy(cloneObject);
      }
   }
}

Moreover you can use Collision detection system.