- Home /
My monster only choose one Target
Hi, I have been using as base, script monsters made by Unity, but now I have a problem, I have a couple of characters on the Game, so it have became a problem for my monsters, they don't know how to choose the Target properly, here you have the part of the code that chooses a player (It always choose the second). What I can do to make my monster consider both players?
if (!target)
target = GameObject.FindWithTag("Player").transform;
If you have every player Game Object in your scene tagged as "Player", FindWithTag() will always return the first Game Object with that tag that it finds.
Answer by Ejlersen · May 07, 2011 at 05:48 PM
As equalsequals says, that method will return the first occurence of a game object with the tag "Player".
Besides, you might want to keep an array with all your game objects with the tag "Player", because it can become quite expensive to lookup game objects every time your monsters don't have a target.
Answer by Ejlersen · May 10, 2011 at 06:23 PM
I'm just going to create a new answer for the comment question above :-)
You could create a manager script to keep track of all players. E.g.:
public class Manager { public List<GameObject> players = new List<GameObject>();
public GameObject GetClosestPlayer(GameObject monster)
{
Vector3 monsterPosition = monster.transform.position;
float closestDistance = Mathf.Infinity;
GameObject closestPlayer = null;
for (int i = 0; i < players.Count; i++)
{
GameObject otherPlayer = players[i];
float tempDistance = (otherPlayer.transform.position - monsterPosition).sqrMagnitude;
if (closestDistance < tempDistance)
continue;
closestPlayer = otherPlayer;
closestDistance = tempDistance;
}
return closestPlayer;
}
// Singleton
private static Manager instance;
public static Manager Instance
{
get
{
if (instance == null)
instance = new Manager();
return instance;
}
}
}
There are several ways of doing it. This one is done by using a Singleton. It can be accessed by all scripts by saying Manager.Instance.GetClosestPlayer(obj)
;
You do need to add the players to the list as they spawn, and ofcourse remove them if they are removed.
Your answer
![](https://koobas.hobune.stream/wayback/20220613132414im_/https://answers.unity.com/themes/thub/images/avi.jpg)