- Home /
How do I get my enemy to retarget within Random.Range?
I'm building a clone of missile command, and I'm stumped with one aspect. I have a gameobject called GameControl which fires rockets at 1 of 5 cities, so something like this:
int selector;
void FireOne(){
selector = Random.Range(0,5);
}
And then I have an array of gameobjects called cities, and I have the rocket target cities[selector]. My question is once a city is destroyed, how do I get the GameControl to ignore the destroyed city without removing the object from the array?
Thanks for all the feedback, i ended up using the solution very similar to the one suggested by felixpk, but thank you all for helping me out! :D you rock Unity Answers!!
Answer by felixpk · Jul 12, 2015 at 09:21 PM
I think something like this would work:
Add a temp List
Add a parameter to the Cityobject to detect wether this city is destroyed or not:
bool isDestroyed;
Fill your temp List with just the active Cities:
for(int i = 0; i < cities.length; i++) { if(!cities[i].GetComponent<CityScript>().isDestroyed) { tempCityList.Add(cities[i]); } }
Now you have a List with only active Cities and you can select them like this:
selector = Random.Range(0,tempCityList.Count);
tempCityList[selector];
Answer by Cambesa · Jul 12, 2015 at 09:37 PM
Hey,
I would create a separate array to manage the active cities. When the game/scene starts use:
GameObject[] activeCities;
activeCities = GameObject.FindGameObjectsWithTag("city");
Which creates an array featuring all objects which has a tag "city".
Then when you want to fire a missile try:
selector = Random.Range(0,activeCities.Length);
GameObject CityToShootAt=activeCities[selector];
Finally, when a city is destroyed run:
activeCities = GameObject.FindGameObjectsWithTag("city");
again to update the array with only the existing cities.
Hope this helps you out!