How can I get this to look at close objects?

I have game Object with constant forward velocty, I want it to look at enemies when it is near them.
Here’s my script:

function AutoAim() : GameObject {
var All : GameObject[];
all = GameObject.FindGameObjectsWithTag("enemy");

for (var go : GameObject in all) {
if(Vector3.Distance(go.transform.position,transform.position) < 80);
transform.LookAt(go.transform.position);
}
}

This is my first time using an array (I do believe I’m using an array :P) I’m getting no error message and as far as I can tell it seams like it should work, it doesn’t so I’m obviously doing something wrong, Please enlighten me :smile:

It is probably the semi-colon at the end of the If statement

if(Vector3.Distance(go.transform.position,transform.position) < 80);

nothing wrong with having more brackets :stuck_out_tongue:

if(Vector3.Distance(go.transform.position,transform.position) < 80)
{
  transform.LookAt(go.transform.position);
}

Btw, there is a slight flaw in the logic - it’ll look at the last enemy that’s < 80, not the closest.

Aha the semi colon, should have noticed that.
So what would you suggest to fix that logic error? since I do in fact need it to look at ANY enemy within 80 units, not just the last one.

Bump. Still trying to figure this out.

If you want to look at the closest enemy then you will have to do something like have a variable named “closest” as a reference to the enemy and “dist” as it’s distance.

In each loop, compare the current enemies distance to dist, if the current distance is < dist then set closest to the currect enemy dist to the curect distance.

At the end of the loop “closest” should be the closest enemy.

Sorry, I’m not quite familiar enough with unity scripting to just give the code off the top of my head(and have it work for you the first time) but it’s should only be 2 or 3 extra lines of code.

Thanks, that’s certain to be helpful! If I can just find the proper syntax now XD