Homing missile: choosing a new target

Hey guys student here

And for the record my instructor told me: find all the help you can get.

So here I am my issue is this:

I have a working homing missile script however I want them to choose a new target or the nearest target. Honestly I was originally going to randomly choose a gameobject to home in on but I think that moving to the nearest one would be better and less time consuming

(which ever one you guys are willing to show me.)

Here is my script:

public class HomingMissile : MonoBehaviour {

    public GameObject[] targets;
    public float speed;

    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();

    }

    void FixedUpdate()
    {
        GameObject target = targets[Random.Range(0, targets.Length)];

        transform.LookAt(target.transform.position);

        float step = speed * Time.deltaTime;

        transform.position = Vector3.MoveTowards(transform.position, target.transform.position, step);
    }
}

Now my issue is I want to choose a new target every time a object is spawned however as you can see in my code It will choose a new object every frame. However I can’t move the ‘target’ gameobject to the start function cause it loses the reference for looking at and moving towards the target. So I am SUPER stumped on how I can do this.

So any suggestions?

Ok I think I get what you’re saying. Assuming you want to choose the target when the HomingMissile is spawned, move the declaration of target outside of FixedUpdate so that it can be used in any function.

 public class HomingMissile : MonoBehaviour {
 
     public GameObject[] targets;
     public float speed;
 
     private Rigidbody rb;
     private GameObject chosenTarget;
 
     void Start()
     {
         rb = GetComponent<Rigidbody>();   
         ChooseTarget();
     }

     void ChooseTarget() 
     {
          //you can change this as you like if you want something non-random
           chosenTarget = targets[Random.Range(0, targets.Length)];
     }
 
     void FixedUpdate()
     { 
         transform.LookAt(target.transform.position);
 
         float step = speed * Time.deltaTime;
 
         transform.position = Vector3.MoveTowards(transform.position, target.transform.position, step);
     }
 }

As a side note, the code you wrote technically doesn’t choose a new target every frame, since FixedUpdate() is called independently of frame rate. I recommend reading up on the execution order of Monobehaviour events.