Sentrygun doesn't asign new target.


I just created a simple Sentrygun-Script. It works, but after the first Target is out of reach, the script doesn’t asign the new target and stays in it’s last position.

Here’s my code:

 #pragma strict
var Warn : AudioSource;
var Target : Transform;
var Me : Transform;
var BulletSpawn : Transform;
var Bullet : Rigidbody;
var DistanceToTarget : float;
var maxDist : float = 5.0f;

function Start(){
  Me = transform;
function Update(){
    Target = GameObject.FindWithTag("AI").transform;
    DistanceToTarget = Vector3.Distance(Me.position,Target.position);
    if(DistanceToTarget < maxDist){
           var Inst : Rigidbody;
           Inst = Instantiate(Bullet,BulletSpawn.position,BulletSpawn.rotation);
    if(DistanceToTarget > maxDist){
      Target = null;


Thanks for every answer,

It’s possible the problem may stem from the line assigning Target in Update.

That line will look through the entire scene hierarchy and return the first object with the tag “AI” that it comes to. So it’s probably returning the same target over and over.

Try GameObject.FindGameObjectsWithTag. That will return an array of all gameobjects that have that tag.

Then use a foreach loop to check the distance of each of those gameobjects. The one that passes the check gets assigned to Target.