AI doesn't know what my player is

I have made a simple script that spawns an enemy every few seconds, however, when spawned, the enemy doesn’t have any idea what my player is, so it just wanders away. It’s spawning a prefab of “enemy” so is there a way to set my player as its target right when it is spawned? or even better yet, just have my player be the target in the prefab? Thanks in advance.

void Start(){
    player=GameObject.Find("Player);
}

change “Player” to the name of the player object in the scene, and player to whatever your variable is

2 Likes

You can also search for the gameobject by tag which is what I prefer:

private GameObject player;
public string playerTag

private void Start()
{
   player = GameObject.FindGameObjectWithTag(string playerTag);
}

private void Update()
{
    if(player != null)
    {
        dosomething;
    }
}

Or you can pass in a reference when you instantiate it.

Or you can get a static reference to the player.

Or you can use ray casts and line of sight to attempt to find the player.

Plenty of ways to skin this cat.

var Health = 100;
var Player : Transform;
var MoveSpeed : int = 5;
Player = GameObject.Find("Player");


function Update ()
{
    if (Health <= 0)
    {
        Destroy(gameObject);
    }
   
    transform.LookAt(Player);
    transform.position += transform.forward * MoveSpeed * Time.deltaTime;
}

I have my player as a transform. I tried changing it to a game object, but then the transform.LookAt(Player) doesn’t work. is there a way to either make it something like GameObject.LookAt(Player) and so on, or can I do something like Transform.Find(“Player”);

Use the code I posted before, but just add .transform at the end.

(GameObject.Find(“Player”).transform instead of GameObject.Find(“Player”))

Also, I don’t know much about Javascript in unity, but move the “Player=…” line to inside of the Start() function so it works properly. Unless you don’t have to do that and I’m mistaken?

1 Like

You have it right.

Worked like a charm! now the enemies follow my player when spawned! thanks a ton!

No problem.