#paste code

1 messages · Page 1 of 1 (latest)

noble trail
finite radish
#
  void Update()
    {
        targetlistgenerate();
        /*I'm putting this code here instead of a separate void because the player will have to be able to switch targets on a button press in the future,
         * and I plan on doing that by just having each button press cycle through the second, third, fourth, etc closest on the targetlist*/
        float distancetoClosestTarget = Mathf.Infinity; 
        GameObject closestTarget;
        
        foreach (GameObject finaltarget in finaltargets)
        {
            float distancetoTarget = (finaltarget.transform.position - this.transform.position).sqrMagnitude;
            if (distancetoTarget < distancetoClosestTarget)
            {
                closestTarget = finaltarget;
                selectedtarget = distancetoTarget;
                Debug.Log(selectedtarget + " selected");
            }

            else
            {
                continue;
            }
        }

        selectedtarget = closestTarget;
    }

noble trail
#

selectedtarget = distancetoTarget; is wrong

#

distancetoclosesttarget = distancetotarget

finite radish
#

Fixed, now have "unassigned local variable 'ClosestTarget'"

noble trail
#

change

#

GameObject closestTarget;

#

to

#

GameObject closestTarget = null;

finite radish
#

That fixed it

wide forge
#

yay

finite radish
#

Thanks! Now going to the older messages about preventing the nullreference exception

noble trail
#

but

#

you need to protect select target at bottom from being null

#

if the foreach loop doesn't select anything you're setting select target to null

#

keep that in mind

finite radish
#

Got you

#

I'm going to attempt to bang my head on the API a bit more for that one before asking for more help here

finite radish
#

Yeah, tried a couple different null reference exception fixes but none of them worked, and it's 10 AM

#

Can null reference exceptions crash a game?

#

Or can I successfully slap a patch on somewhere to just clear the error cache every once in a while?

#

NVM, fixed

#

Thank you guys for all your help! This is easily some of the more confusing programming Ive had to do

#

Oh boy, new problem