Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

unity3d - How to make Unity 3d random range gameobject destroy?

Hi unity random range destroy want make but how make i dont know

instance: random.range (1,3) // 1 with 3 range destroy to make gameobject want

!To explain in more detail, as can be seen in the picture, there are 9 gameobjects, I want them to destroy them randomly when I click on any of them, for example between 1 and 3.

image:enter image description here

question from:https://stackoverflow.com/questions/65859098/how-to-make-unity-3d-random-range-gameobject-destroy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would hae them in a data structure, for example a List so that they can be selected and destroyed randomly.

objPool = new List<GameObject>();  
//fill the list
for (int i = 0; i < 9; i++) 
{
    objPool.Add(yourCubeReference);  
}

Then you can just obtain a random index, and destroy one random item like this

int index = Random.Range(0, 9);//or int index = Random.Range(0, 3); if you wish
GameObject.Destroy(objPool[index];) 
objPool.RemoveAt(index)//keep your list updated

Then if you wish te keep on destroying random objects remember that you have one element less to choose from, so possible max index needs to be -1, so in the next iteration you you need int index = Random.Range(0, 8);. 8 instead of 9.

You can keep this updated taking the elements of the list in the code itslef int index = Random.Range(0, objPool.Count -1); as long as you keep the list updated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...