im making a police chasing game and have a player that is chased by police i want that when more time the player is alive the more police cars will be in the scene i have set up a navmesh and a police_ai.cs script that makes the cars follow the player correctly and i have set up the the object in the map to static and all works but there is a problem when instantiating more police cars that sometimes they will be instantiated inside other game objects in the map
the script that instantiate the police cars instantiate the cars based on distance that i took the player position and instantiate the enemy 20meter far from the player out of the camera view (transform.position.z-20.0f)
If you store every created car in a list of gameobjects
you can look through the list if one of the gameobject’s position is equal to the position you’re trying to instantiate then you cancel and relook for a new position.
If you also include obstacles and are certain that no new obstacles will be created you can retrieve all gameobjects and cache them and then look through all obstacles position aswel and compare
Here is the good caching version for all gameobjects (including existing police cars)
private GameObject _obstacles;
public GameObject Obstacles
if (_obstacles != null) return _obstacles;
_obstacles = GameObject.FindObjectsOfType<GameObject>();
However know that this will not retrieve new created police cars or obstacles, only the existing ones up to the point you call the obstacles property. So you will need to work with lists for that.