Choosing destinations – finding the nearest spawn point
Rather than just choosing a random spawn point or waypoint, sometimes, we want to select the one closest to some object (such as the player's GameObject). In this recipe, we will modify the previous one to find the nearest spawn point to the player's cube, and use that location to spawn a new red ball prefab.
Getting ready
This recipe builds upon the previous recipe. So, make a copy of this project, open it, and then follow the steps in the next section.
How to do it...
To find the nearest spawn point, follow these steps:
- Add the following method to the C# Script class called
SpawnPointManager
:
public GameObject NearestSpawnpoint (Vector3 source){ GameObject nearestSpawnPoint = spawnPoints[0]; Vector3 spawnPointPos = spawnPoints[0].transform.position; float shortestDistance = Vector3.Distance(source, spawnPointPos); for (int i = 1; i < spawnPoints.Length; i++){ spawnPointPos = spawnPoints[i].transform...