- Home /
how to instantiate prefabs around the player but when there is an object in that position it dont instantiate
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)
The Physics class has a lot of overlap functions. If you know the size of your cars, you can just do a cast at where you want the car to be spawned and see if it hits something. If not, the space is given.
Answer by ShadyProductions · Jul 02, 2017 at 07:52 PM
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
{
get
{
if (_obstacles != null) return _obstacles;
_obstacles = GameObject.FindObjectsOfType<GameObject>();
return _obstacles;
}
}
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.
the system that working on is like the smashy road game if you know it but designed for pc with better graaphics that i have prepared in maya
if you can explain me more the code and how to cancel the instantiate when there is something
I've given you what you need.
if (!Obstacles.Any(f => f.transform.position == PositionYouWantToInstantiateOn))
{
//instantiate
}