- Home /
Can't get Transform.LookAt to work
Trying to get an enemy to look at the player. Simple script. Doesn't work. Here's the code. Its attached to the enemy game object.
private var player : Transform;
player = GameObject.FindWithTag("Player").transform;
function Update()
{
transform.LookAt(player.transform);
}
Yet it does nothing. Any ideas? Something I might be missing? All help appreciated, sorry for the noob question.
Answer by lukewilliams · Feb 21, 2014 at 02:19 AM
So it turns out that because the levels are additively loaded, the find with tag function wasn't working as the player hadn't as yet been loaded into the scene. I put the findwithtag function inside onUpdate, and now it works. One small problem.. all my code says is "rotate toward player"... my wolves have started flying. Now I'm really confused.
Answer by CodeElemental · Feb 20, 2014 at 08:32 PM
As far i can see , player object is already a Transform. perhaps you can try
transform.LookAt(player);
Thanks for the response. I tried that but still can't get anything. Have also tried using player.position, but nothing.
I tried parenting the enemy with an empty and running the script on the empty but that doesn't work either. Now I'm trying to run it on a cube. It's like it just doesn't detect my player. Could that be because they're additive scenes (the player is on one, the enemy on another)?
Answer by rutter · Feb 21, 2014 at 02:01 AM
This:
player = GameObject.FindWithTag("Player").transform;
Looks like it should run during Start():
function Start() {
player = GameObject.FindWithTag("Player").transform;
}
It is possible to initialize variables outside of a function, but usually only a good idea when using constant expressions (like 5
, "chicken"
, 3.14
, etc.).
Past that, is the script attached to anything in the scene? You can check to make sure a function is being called with a simple Debug.Log() call:
function Start() {
Debug.Log("Start is called");
//other code
}
You might also check to make sure that the player transform is, indeed, being found:
function Start() {
player = GameObject.FindWithTag("Player").transform;
if (player != null) {
Debug.Log("Found player");
} else {
Debug.Log("No player found");
}
}