FindClosestEnemy gives Error CS0165: Use of unassigned local variable 'closest'

Hello dear community,

First, sorry for any language mistakes, I originally speak French.
Note that I code using C#.

I am working on a game much in the vein of Plants VS Zombies. Everything is going VERY nice so far, but I have a problem making the canonball projectiles (catapult-like motion) to always aim at the closest enemy on the same row (I coded snap-to-grid for drag-and-drop of characters/items). I can easily make everything working, but with an overuse of IF statements, which is definetely bad because I will have to write tons of conditional code for every stage and every enemies wave.

So the problem comes when I try to get rid of overusing all those IF statements; I borrowed a function directly explained in the Unity documentation (ref: here) that checks for the closest enemy. I need to know the closest enemy because my bezier/catapult code needs Start, Mid and End (target) points to create the arc motion for the GameObject, and because I always want the target point of the arc to be the closest enemy on the same row.

However, I get an error “Error CS0165: Use of unassigned local variable ‘closest’”.
I think this can have something to do with the fact that the variable can be null, however I can’t figure out what, how and where to define it…

I tried to paste my code with the code button, but seems like I cannot get it to work properly so please check it on pastebin over here.

edit(copied, reformated and extracted relevant parts of the script)

    private GameObject checkNearestItem;
    
    void Update ()
    {
        // [...]
        checkNearestItem = GameObject.Find(FindClosestEnemy().name);
        //Attack the nearest ENEMY     
        if (checkNearestItem != null)
        {
            // [...]
        }
    }

    GameObject FindClosestEnemy ()
    {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Croc");
        GameObject closest;
        float distance = Mathf.Infinity;
        Vector3 position = transform.position;
        foreach (GameObject go in gos)
        {
            //List only enemies whose Y position is equal to 90.
            if (go.transform.position.y == 90)
            {
                Vector3 diff = go.transform.position - position;
                float curDistance = diff.sqrMagnitude;
                if (curDistance < distance)
                { 
                    closest = go;
                    distance = curDistance;
                }
            }
        }
        return closest;
    }

What am I mistaking or doing wrong??

Of course, any help or hint will be highly appreciated… :wink:

You can also Skype me: nuganx

Or MSN me: nuganx AT hotmail DOT com

Or E-Mail me: exotyktechnologies AT gmail DOT com

Thanks!

This is an easy one. GameObject closest; is not assigned at all times. Only in your if-statements it is possible to find a correct gameobject. But what if all your if-statements fail? There will be no closest. What do you want the value to be? Probably null

Change your GameObject closest; to GameObject closest = null; and you’re good to go.

Bunny83 → Sorry for posting contact infos, my intention was not to “bypass” any rule; I won’t ever do it again. As a way to show the community my good intention, I will share an alternate way to achieve the same result, for making a canonball/catapult projectile move smoothly along a bezier arc, starting from the canon/catapult, and targetting the closest enemy on the same X row, with a middle control point being half the distance between the start point and the end point for x-axis, plus some fixed value for the y-axis (this gives the same visual result and behavior as catapults in Plants VS Zombies). I thought any personal info would have been retrieved by the revision staff if that was not compliant with this forum rules (didn’t had time to read the rules, and not used to use forums for asking help). I also admit that you were absolutely right about the horrible logic I had. I learned Unity and C# only 3 weeks ago. But I found my way out :slight_smile:

Marnix → You are right, I understand. However, I opted for another approach I developped on my own. Maybe it is not as optimized as my new solution, but it works like a charm and there is no apparent impact on the framerate, even when I get many canonballs being fired at the same time on various enemies.

There it is:

http://pastebin.com/0REk3dPB