Assign Transform to Variable through Script

Hello Everyone its been a long time since Ive asked a question on these awesome forums but Im having difficulty remembering how to assign a transform to a variable through script (preferably javascript).

This script is on a gameObject that finds the closest enemy near it. How do I add this (closest object (enemy)) to the variable target?

// The target marker.
    var target : Transform;
        
    function FixedUpdate(){
    Debug.Log(FindClosestEnemy().name);
    }
     
    // Find the closest enemy
    function FindClosestEnemy() : GameObject 
    {
        // Find all game objects with tag Enemy
        var gos : GameObject[];
        gos = GameObject.FindGameObjectsWithTag("Enemy");
        var closest : GameObject;
        var distance = Mathf.Infinity;
        var position = transform.position;
    
        // Iterate through them and find the closest one
        for (var go : GameObject in gos) 
        {
            var diff = (go.transform.position - position);
            var curDistance = diff.sqrMagnitude;
            
            if (curDistance < distance) 
            {
                closest = go;
                distance = curDistance;
            }
        }
        return closest;
        //error trying it this way, commented out
        //target = closest.transform;
    }

Id greatly appreciate any help in solving this.

Sincerely,
Michael

You had it right with

target = closest.transform;

However if that is the same position you had it in, there would be a warning as that piece of code would never be run (it’s after the return statement).

Since you already have the code as a function, you can simply call the function and get the Transform of the GameObject that is returned.

target = FindClosestEnemy ().transform;

EDIT: Also, FixedUpdate should only be used for Physics related tasks

Hey DanielQuick,

Thank you very, very much!!! I went the function route outside of FixedUdate and it works perfectly. Again greatly appreciated! Amazingly helpful.

Sincerely,
Michael