Using return correctly?

Hey there. I’m trying to make a code where the gameObject will look at the closest banana. I have the looking part working, but I’m not sure how to get the gameObject to look at bestTarget. This is my first time using returns, so sorry if this is a simple wrong.

using UnityEngine;
using System.Collections;

public class lookAt : MonoBehaviour {

    private Vector3 v_diff;
    private float atan2;

    Transform GetClosestBanana(Transform[] banana)
        Transform bestTarget = null;
        float closestDistanceSqr = Mathf.Infinity;
        Vector3 currentPosition = transform.position;
        foreach (Transform potentialTarget in banana)
            Vector3 directionToTarget = potentialTarget.position - currentPosition;
            float dSqrToTarget = directionToTarget.sqrMagnitude;
            if (dSqrToTarget < closestDistanceSqr)
                closestDistanceSqr = dSqrToTarget;
                bestTarget = potentialTarget;

        return bestTarget;

    void Update () {
        v_diff = (bestTarget.transform.position - transform.position);
        atan2 = Mathf.Atan2(v_diff.y, v_diff.x);
        transform.rotation = Quaternion.Euler(0f, 0f, atan2 * Mathf.Rad2Deg);

Thanks :slight_smile:

I might be mistaken but it seems like it shouldn’t even compile, because Update()'s bestTarget isn’t defined as nor a local neither a class variable.

Change this line:

v_diff = (bestTarget.transform.position - transform.position)

to this line:

v_diff = (GetClosestBanana(bananas).position - transform.position)

And add this:

public Transform[] bananas;
private Vector3 v_diff;
private float atan2;

Then from the editor, drag-and-drop your items onto “bananas” array.