Using LookAt() with tags?

Hey, I’m trying to make an NPC face the player using the LookAt() function, but I want to do it using tags so that I don’t have to manually drag the player onto the Transform variable in the Unity Inspector.

Currently, the working code I have is this:

var targetPlayer : Transform;
transform.LookAt(targetPlayer);

But I want to do something like this:

private var targetPlayer : Component.gameObject.tag = "Player";
transform.LookAt(targetPlayer);

However, the above code returns the following error:
Assets/Scripts and Code/NPC interaction/NPCdialogue_simple.js(17,20): BCE0018: The name ‘Component.gameObject.tag’ does not denote a valid type (‘not found’). Did you mean ‘UnityEngine.Touch’?

LookAt() takes type transform, you want to use GameObject.FindWithTag to find the GameObject tagged Player, and then pass that GameObject’s transform component to LookAt(), eg:

var player = GameObject.FindWithTag("Player");
transform.LookAt(player.transform);

Thanks, but that code gives me the following error:

UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.

Ah, sorry:

var player : GameObject;
player = GameObject.FindWithTag("Player");
transform.LookAt(player.transform);

I said the same thing, but it took me longer.

Ah, that worked. Thanks! :slight_smile: