- Home /
I want to have my player change respawn points based on their distance to them
I want to have my player change their respawn point based on their location, similar to a checkpoint system but will change if I run through a previous one. I'm using an array to store all of the spawn points and using an incremented counter to cycle through them. void Update() { for (int i = 0; i < spawnPoints.Length; i++) { if (Vector3.Distance(spawnPoints(i).position, player.position) < distance) { playerCloseEnough = true; } else { playerCloseEnough = false; } } This isn't working though and was wondering if anyone has a better way of accomplishing this.
Answer by Happy-Zomby · Apr 21, 2016 at 09:41 PM
Hi, I think you could use the code on this page http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
This one more specfically:
// Find the name of the closest enemy
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Enemy");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
}
You may need to change it somewhat but I guess it should work hope that helps,