Nullreferenceexception after reload Scene (GMTK Tutorial)

Hello I’m new to unity and I started off withe the Gmtk tutorial.
(I used godot before unity, so I’m not a complete beginner)

I get many error after I hit my restart button:

The Error: Nullreferenceexception,object reference not set an instance an object PipeMiddleScript.OnTriggerEnter2D. sc 23)

My code in the Pipemiddlescript

using Unity.VisualScripting;
using UnityEngine;

public class PipeMiddleTriggerScript : MonoBehaviour
{
   public LogicManagerScript logic;

   void Start()
    {
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicManagerScript>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnTriggerEnter2D(Collider2D collision) 
    {
        if (collision.gameObject.layer == 6)
        {
            logic.addScore(1);
            
        }
        
        
    }
}

And here is my code for restart the game:

public class LogicManagerScript : MonoBehaviour
{
    public GameObject gameOverScreen;

    public void gameOver()
    {
        gameOverScreen.SetActive(true);
    }

    public void restartGame()
    {
        
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

The addScrore function didn’t work after i reload the scene, instead I print the error Nullreferenceexception.

And don’t understand why, because should be all objects destroy. Then it’s load the new Scene and every start function runs again ?
I think the problems lays somewhere in the line 10 in my pipemiddlescript, but I’m complete new to C#

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

NullReference is the single most common error while programming. Fixing it is always the same.

Some notes on how to fix a NullReferenceException error in Unity3D:

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

error seems to suggest that “logic” is null,
are you manually destroying objects somewhere or just calling restartGame?

if nothing else comes up,
maybe compare with someone else’s project and see whats the difference:

okay it seems like the logic var is null, I identify this. But why?
Please correct me if I’m wrong.

I restart/reload the scene:

  1. Currently Scene get’s fully destroyed, including the logic script.

2.The scene reloads

  1. The start function on every script runs (ones)

  2. (In my case) the pipe middle script, should find the logic script via Code

And I think there is the problem. But why didn’t it find the logic script? Is I because the game object (logicmanager) isn’t load yet?
Is there a feature that unity runs XY at the very first ?

Yes I destroy pipe after they are outside of the screen (it’s a flappy bird ripoff game)

And other than that, no I don’t destroy thing.

And I’m just restart the game

I looked up the code in the git. Sadly it looks the same, maybe things had change with the new unity version?

That’s a great theory! Now prove it with debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

Here is some timing diagram help:

I also consider this to be crazy ninja coding so i’m never surprised when it fails.

Keep in mind that using GetComponent() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.

Here’s the bare minimum of stuff you absolutely MUST keep track of if you insist on using these crazy Ninja methods:

  • what you’re looking for:
    → one particular thing?
    → many things?
  • where it might be located (what GameObject?)
  • where the Get/Find command will look:
    → on one GameObject? Which one? Do you have a reference to it?
    → on every GameObject?
    → on a subset of GameObjects?
  • what criteria must be met for something to be found (enabled, named, etc.)
  • if your code expects one instance and later you have many (intentional or accidental), does it handle it?

If you are missing knowledge about even ONE of the things above, your call is likely to FAIL.

This sort of coding is to be avoided at all costs unless you know exactly what you are doing.

Botched attempts at using Get- and Find- are responsible for more crashes than useful code, IMNSHO.

If you run into an issue with any of these calls, start with the documentation to understand why.

There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.

In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.

It is ALWAYS better to go The Unity Way™ and make dedicated public fields and drag in the references you want.