- Home /
How do I destroy a specific clone of a GameObject?
I am trying to instantiate prefabs and then be able to walk around with a first person controller and destroy the ones I deem unworthy.
public GameObject RabbitObj;
void Start()
for (int i=0;i<=RabbitInit;i++)
{
Position.x=(float)(UnityEngine.Random.value-0.5)*90f+50f;
Position.y=100.5f;
Position.z=(float)(UnityEngine.Random.value-0.5)*90f+50f;
var qq=GameObject.Instantiate(RabbitObj,Position,Quaternion.identity);
qq.name=("Rabbit"+i.ToString());
RabbitObject.Add(qq);
}
I have been using the Destroy function but it does not have the desired outcome. It deletes one object but when I try delete another object it returns the following error:
"MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it."
I think I understand why it is saying that (as it has deleted the "RabbitObj" GameObject); I just dont know how to delete just one of the cloned game objects I have instantiated.
I would really appreciate any help :)
Are you destroying(RobbitObj) and then later at some point deleting everything in the list/collection in RabbitObject?
I dont really want to destroy RabbitObj. I want to firstly remove a specific clone of RabbitObj (which was created in line 9). For example I would like to destroy the 13th instantiated clone. Along with destroying clone number 13 I would like to remove it from the ArrayList "RabbitObject".
If you could show your destroy code, that could help us help you :)
Something like:
var qq : GameObject = GameObject.Find("Rabit13");
if (qq != null) {
RoabitObject.Remove(qq);
Destroy(qq);
}
If you are going to be doing this a lot, you might consider a dictionary rather than a list and storing string/obj pairs.
Acutally now that you've shared the code, you should be able to do something like:
RabitObject.Remove(CloestObject);
Destory(CloestObject);
Answer by selzero · Mar 04, 2013 at 05:21 PM
Firstly I suggest you make RabbitObject an array list, even better, a list using generics.
public List<GameObject> RabbitObj;
You will need to add:
Using System.Collections.Generics;
to the top of your script.
When you want to destroy item X from the list you can call Destroy(RabbitObj[X]); and then remove the item from the list.