null reference error when restarting a scene

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
SekaiXIV
Posts: 4
Joined: Sun Aug 27, 2023 9:02 am

null reference error when restarting a scene

Post by SekaiXIV »

Hi Pixel Crushers,

I have a problem in my game when i add dialogue manager in my hierachy.
Without any function added to it, just plain prefab of dialogue manager will create a null reference error when i restart a scene for a second time in game

Context:

When player die i enable a fade canvas with a restart game button on it

This is the code i use to restart scene:

Code: Select all

public void RestartScene()
    {
        SaveManager.instance.SaveGame();
        Scene scene = SceneManager.GetActiveScene();
        SceneManager.LoadScene(scene.name);
    }
It only happens on the second time the player die. the fade with the restart button won't spawn, instead error log shows this:

Code: Select all

NullReferenceException: Object reference not set to an instance of an object
PlayerDeathState.Enter () (at Assets/Scripts/Player/PlayerDeathState.cs:21)
PlayerStateMachine.ChangeState (PlayerState _newState) (at Assets/Scripts/Player/PlayerStateMachine.cs:20)
Player.Die () (at Assets/Scripts/Player/Player.cs:209)
PlayerStats.Die () (at Assets/Scripts/Stats/PlayerStats.cs:56)
CharacterStats.TakeDamage (System.Int32 damage) (at Assets/Scripts/Stats/CharacterStats.cs:379)
PlayerStats.TakeDamage (System.Int32 damage) (at Assets/Scripts/Stats/PlayerStats.cs:23)
CharacterStats.DoDamage (CharacterStats targetStats) (at Assets/Scripts/Stats/CharacterStats.cs:171)
EnemyAnimationTriggers.AttacTrigger () (at Assets/Scripts/Enemy/EnemyAnimationTriggers.cs:22)
when i disable/remove the dialogue manager prefab everything works fine.
User avatar
Tony Li
Posts: 22112
Joined: Thu Jul 18, 2013 1:27 pm

Re: null reference error when restarting a scene

Post by Tony Li »

Hi,

Check line 21 of your PlayerDeathState.cs script.

This is probably related to: How To: Manage Player Controls and Scene Changes
SekaiXIV
Posts: 4
Joined: Sun Aug 27, 2023 9:02 am

Re: null reference error when restarting a scene

Post by SekaiXIV »

Turns out there were 2 canvas gameobject in my scene. one from dialogue manager prefab and one from my own project.

and i was doing GameObject.Find("Canvas").GetComponent<UI>().SwitchOnEndScreen(); when player enter death state.

so it was confused which canvas to find.

Thanks Tony!
User avatar
Tony Li
Posts: 22112
Joined: Thu Jul 18, 2013 1:27 pm

Re: null reference error when restarting a scene

Post by Tony Li »

Glad you found the issue!
Post Reply