My script doesn't work without a try catch block. Need help figuring out why

Hi, the title pretty much says it all.

I have a script running on my GameController which cycles through all the gameobjects of my scene, checks if they have a particular tag and if so calls a method on them.

I’ll leave here a snipper of the code

private void SetUpConsumables()
    {
        object[] objectsInScene = GameObject.FindObjectsOfType(typeof(GameObject));

        foreach (object item in objectsInScene)
        {
            GameObject currentGameObject = (GameObject) item;
            string consumableTag = currentGameObject.tag;

            switch (consumableTag)
            {
                case "Coin":
                case "BiggerCoin":
                    try
                    {
                        coinController coin = currentGameObject.GetComponent<coinController>();
                        coin.SetUp();
                    } catch (Exception e)
                    {
                        Debug.Log(e.Message);
                    }
                    break; 

                case "DoubleJump":
                    try
                    {
                        doubleJumpController doubleJump = currentGameObject.GetComponent<doubleJumpController>();
                        doubleJump.SetUp();
                    }
                    catch (Exception e)
                    {
                        Debug.Log(e.Message);
                    }
                    break;

                case "SpeedUp":
                case "SpeedDown":
                    try
                    {
                        speedModifierController speedModifier = currentGameObject.GetComponent<speedModifierController>();
                        speedModifier.SetUp();
                    }
                    catch (Exception e)
                    {
                        Debug.Log(e.Message);
                    }
                    break;
            }
        }
    }

SetUp() example (it’s very similar in every one of the different cases)

public void SetUp()
    {
        pickedUp = false;
        // dirty way to create a persistent ID
        iD = (transform.position.x.ToString() + transform.position.y.ToString()).Replace(",", "").Substring(0, 6);
    }

The weird thing about this snippet of code is that, if i remove the try catch, i get a nullreferenceexception and the SetUp() method is never called.

However, if I add the try catch like in the example above, the code runs and the SetUp() method is called and works correctly… however i still get a log message in my console telling me about the same nullreferenceexception

Can anyone explain why this happens? I’m fairly new to c# so I might be missing something although after a little bit of research I am kind of at a loss for words.

Thanks for the help!

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

1 Like

Thanks or the tips!

I’ll look at all the links you provided me and will try to find out what’s null and how to fix it

However i’d like to ask you a question that is bugging me… if it is in fact a null item that I’m calling my method on, why does it work inside a try catch block? isn’t it supposed to be null no matter what?

also, it surely does not matter too too much but i’m working on a 2d project rn

The idea of a Try-Catch is that you are expecting your code to die in some cases, and give an alternative control sequence for when it dies :wink:

so even if it has null-ref in one frame, the entire script wont crash for that frame

this is never a solution for errors tho, more of a rough bandadge that doesnt fix anything^^

1 Like

Thanks that’s something I didn’t consider. So the code is failing at some point inside my method but keeps running and executes the stuff that shows me correct results. It does however still crash at some point. This makes sense

Yes absolutely, I’m looking into it right now but god save me ahah

thanks for clarifying anyway!

Yea, your For loop is able to run through everything since its never stopped by an uncatched exception :slight_smile:

most likely one of the objects in your scene has one of your switch-tags but not the associated component for this tag, while other objects do, so most likely the loop has trouble with one of the objects it loops through but not the others

you could just check which object this is by debug logging its name whenever the exception is catched

Just to make this extra clear; there are valid reasons to have try-catches into production ready code. Of course not to turn a blind eye on errors you may prevent by other means. But since there are some situations which may throw exceptions that are out of your hand to take care of otherwise. Imagine networking code connecting to some other party B… and then B goes off-line while you attempt to connect to them. So in that case the networking code may rightfully throw an exception, and you calling that code will have to watch out for these corner cases, as you dont want your program to crash just because an exception occured. That’s what try-catch is intended for.
“Try this, it should work” - “but it it does not, catch this exception and handle it as follows”

1 Like

Yea of course, I wasnt trying to say that there is no point to them btw, if it came across like that^^

was just trying to say that they dont solve errors/ they dont fix them, errors dont go away because of them
i was trying to say that just because code is able to run with Try-Catch doesnt mean the errors are gone

I got why you said what you said, but i still thought it may be easy to misunderstand that they do have their uses based on what was said in the thread haha. I just thought it didnt hurt mentioning it to make sure :slight_smile: