Hi everyone. Trying to figure out how do I target next player. Working on multiplayer game, my turret stores all players in GameObjects array:
public Transform turret; // players turret will be set on to the field
private GameObject[ ] players; // storing all the players in this array
private Transform player; // setting nearest player to this Transform
void Update(){
players = GameObject.FindGameObjectsWithTag (“Player”);
var nearestDist = float.MaxValue;
// using foreach in players and setting nearest player to player as Transform
foreach (var ePlayer in players) {
if(Vector3.Distance (turret.transform.position, ePlayer.transform.position ) < nearestDist){
nearestDist = Vector3.Distance(turret.transform.position, ePlayer.transform.position);
player = ePlayer.gameObject.transform; // storing nearest player to Transform player;
// now I’m checking if nearest player is my player and if it is making sure that turret don’t target me or // shoot me
if(player.gameObject.name == playersID){
player = null;
}
}
}
}
Now this code works just fine as long my player is not the nearest player to my turret, as soon my player is the nearest player to my turret then it stops targeting other players.
Would anyone be able to show me the example code on how to set Transform player; to next nearest player if my player is the nearest player to my turret?