"NullReferenceException: Object reference not set to an instance of an object" only appear in build

Hello,

I am currently working on a platformer for a friend, and since I have the basics of the player movements I wanted to let him test it out. However, when I build the game for Windows I couldn’t move my player!

I’ve been searching for well over 2hours now and I’m not managing to figure out where the issue is…

My player uses the new input system to move, and these are the actions I put. The left/right, as well as the up/down, are 1D Axis, and the MoveLeftRight and MoveUpDown are both Values with Any as the control type. It is my first time really using this new input system so my first thoughts were to look in here to see if I had messed up something. I didn’t see anything wrong, but maybe I missed something…


Then I tried adding a script to get the console logs in build… But it only kept posting this one: “NullReferenceException: Object reference not set to an instance of an object” over and over. While trying this, I realized that even though I can’t jump or move in any direction, the switch action is working fine (switches between two characters’ data from Scriptable objects added on a GameObject in the scene).

Seeing this was the error I added some debug.logs absolutely everywhere to find what was null in my scripts… But nothing came out…
My next idea was to put the debugs in the functions called by the input manager, to see if they were actually getting called or not. Each one of them was called without issue, and I even checked the values that they were getting, and everything is normal.

So… Now I’m back to square one, not really seeing what I messed up… Since I’m not getting any errors in the editor and it’s working perfectly there, I must admit I’m kinda confused.

I’m not sure if my movement code can really help figure this out, but I’m basically using a simple rigidbody2D movement mechanic.
Also, while testing in the editor I realized that the inputs for a gamepad stick weren’t giving me the right values. I don’t know if it’s linked or not, but the gamepad D-Pad was working flawlessly, just like the keyboard, while the Left Stick only worked once in a while and gives like top-movement values instead of right-movements, etc. I tested this gamepad on another project yesterday and everything worked well with the Left Stick, so I assume it’s something from my input actions, but I’m not sure of anything right now…

So yeah, basically, if one of you had any ideas on where I might look to fix this issue, it would be greatly appreciated (and if you had an idea for the gamepad issue, if it’s not related to the first one, it would be great too!)

Thank you!

@TheanaProductions Please share your movement code

Here it is:

    private void FixedUpdate()
    {
        if (isJumping)
        {
            rb2D.AddForce(new Vector2(speed * movX, jumpForce), ForceMode2D.Impulse);
            isJumping = false;
        }
        else if (isWalkingOnStair || isGrounded)
            rb2D.velocity = new Vector2(speed * movX, rb2D.velocity.y);
    } 

private void OnJump()
    {
        if (isGrounded || isOnStair || isWalkingOnStair)
        {
            isJumping = true;

            if (isWalkingOnStair)
                GameEvents.instance.GetOffStairs();
        }
    }

    private void OnMoveLeftRight(InputValue value)
    {
        movX = value.Get<float>();

        if (isGrounded)
            GameEvents.instance.GetOffStairs();
    }

    private void OnMoveUpDown(InputValue value)
    {
        if ((isBottomStairs && isGrounded && value.Get<float>() <= 0) || (!isBottomStairs && isGrounded && value.Get<float>() >= 0))
        {
            movX = 0;
            GameEvents.instance.GetOffStairs();
        }

        if (isOnStair)
        {
            if (!hasPressedUp)
            {
                if ((isBottomStairs && value.Get<float>() > 0) || (!isBottomStairs && value.Get<float>() < 0))
                {
                    GameEvents.instance.GetOnStairs(stairManager);
                    movX = value.Get<float>();
                    isWalkingOnStair = true;
                    hasPressedUp = true;
                }
            }
        }

        if (isWalkingOnStair)
            movX = value.Get<float>();
    }

    private void OnSwitch()
    {
        GameEvents.instance.SwitchCharacter();
    }

I don’t see any Debug.Log statements? What line is the error on?

Such a common simple problem there’s a three step process pinned in the forum. Here you go:

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

  • Identify what is null <---- don’t even THINK about anything else until you do this
  • Identify why it is null
  • Fix that

I don’t know which line the error is on. The logs I’m getting from the build only give me the first line of the error (the one I put in the title). I tried multiple scripts from the forum, hoping that maybe one would allow me to get the line too, but none did
For the debugs, I didn’t know if it was best or not to have them in here when sharing the script so I took them away. With the debugs in this script it is like that (I also did a check for each variable in each of my scripts in the scene to see if one of them was null, but nothing came out of it in my logs):

        private void FixedUpdate()
    {
        if (isJumping)
        {
            rb2D.AddForce(new Vector2(speed * movX, jumpForce), ForceMode2D.Impulse);
            isJumping = false;
        }
        else if (isWalkingOnStair || isGrounded)
            rb2D.velocity = new Vector2(speed * movX, rb2D.velocity.y);
    }

private void OnJump()
    {
        Debug.Log("JUMPING Action");

        if (isGrounded || isOnStair || isWalkingOnStair)
        {
            Debug.Log("JUMPING True");

            isJumping = true;

            if (isWalkingOnStair)
                GameEvents.instance.GetOffStairs();
        }
    }

    private void OnMoveLeftRight(InputValue value)
    {
        movX = value.Get<float>();

        Debug.Log("LEFT RIGHT Action " + movX);

        if (isGrounded)
            GameEvents.instance.GetOffStairs();
    }

    private void OnMoveUpDown(InputValue value)
    {
        Debug.Log("UP DOWN Action start");

        if ((isBottomStairs && isGrounded && value.Get<float>() <= 0) || (!isBottomStairs && isGrounded && value.Get<float>() >= 0))
        {
            movX = 0;
            GameEvents.instance.GetOffStairs();
        }

        if (isOnStair)
        {
            if (!hasPressedUp)
            {
                if ((isBottomStairs && value.Get<float>() > 0) || (!isBottomStairs && value.Get<float>() < 0))
                {
                    GameEvents.instance.GetOnStairs(stairManager);
                    movX = value.Get<float>();
                    isWalkingOnStair = true;
                    hasPressedUp = true;
                }
            }
        }

        if (isWalkingOnStair)
            movX = value.Get<float>();

        Debug.Log("UP DOWN Action end " + movX);
    }

    private void OnSwitch()
    {
       Debug.Log("SWITCHING");
        GameEvents.instance.SwitchCharacter();
    }

All of the debugs are seen in the logs I get in the build, but the player still doesn’t move an inch…

That’s kinda my issue… I’m not managing to identify what is null… It might probably be something very simple that I missed, but I don’t know where to look anymore in my script if I’m being honest…

It is in the error message itself. Select it, then go to the lower part of the console and study the stack trace, which tells you what sequence of calls got you to the problem.

If you stop reading at the first line of the message you’ve ignored all the important stuff.

You will need to also follow your Debug.Log output (which you didn’t share). You’ll see them all, until they stop showing, which means your null reference is probably on the very next line. What is the exact error? It should show the line number.

The issue is that I don’t know how to get the full message. Like I said, the error message isn’t showing in my editor console, and everything works well there. To get the error message in the build I tried using 3 different scripts that I found on the forum, and the last one that I’m using right now is this one:

using UnityEngine;
public class ConsoleToGUI : MonoBehaviour
{
     string myLog = "*begin log";
     string filename = "";
     int kChars = 1500;
     void OnEnable() { Application.logMessageReceived += Log; }
     void OnDisable() { Application.logMessageReceived -= Log; }
     public void Log(string logString, string stackTrace, LogType type)
     {
         // for the file ...
         if (filename == "")
         {
             string d = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Desktop) + "/YOUR_LOGS";
             System.IO.Directory.CreateDirectory(d);
             string r = Random.Range(1000, 9999).ToString();
             filename = d + "/log-" + r + ".txt";
         }
         try { System.IO.File.AppendAllText(filename, logString + "\n"); }
         catch { }

        // for onscreen...
        myLog = myLog + "\n" + logString;
        if (myLog.Length > kChars) { return; }
    }
     void OnGUI()
     {
         GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
            new Vector3(Screen.width / 1200.0f, Screen.height / 800.0f, 1.0f));
         GUI.TextArea(new Rect(10, 10, 540, 370), myLog);
     }
}

From there I only get the first line of the error, and no way of getting the rest. If there’s a way to get the full message in build I would be happy to learn about it though, as from there I’m pretty sure I could find and fix the issue by myself

This is what I get when I try the build

And this is what I have in the editor console:

Click the message. What do you see in the lower part of the console window?

7941886--1015972--crash.png

If that log can’t tell you more (some can, some can’t), start looking for things that CAN be null and start putting in code:

if (rb2D == null)
{
  Debug.Log( "rb2d was null?!!!");
}

You MUST do step #1, otherwise how can you reason about what to even fix??

I already did that, on each one of my scripts, for each one of my variables. Nothing came out of it. Also, side note but wouldn’t the editor tell me when I try in play mode already?

Not if it’s a platform-specific crash, or if it’s a crash related (for instance) to script execution order, which can vary from build to build and from the editor.

Either way, bisect it until you at least know the script that is throwing it (eg, delete blocks of code or even entire scripts). You have to make headway and at least isolate which file it is in.

(This presumes you’re using source control properly so you can instantly revert!)

I see. I’ll try deleting some blocks of code to see what I can find. Thank you

EDIT: It seems to be a script execution order issue, I managed to find the line causing the issue, which is in my switching script, when I get the player data. Apparently, it is not managing to get the data in time before the functions needing it are called. I should be able to fix it now, thank you for your help!

1 Like