When I LoadNewScene is error

NullReferenceException: Object reference not set to an instance of an object
PlayerController.OnDisable () (at Assets/Scripts/Player/PlayerController.cs:40)
UnityEngine.Object:Destroy(Object)
Singleton`1:Awake() (at Assets/Scripts/SceneManager/Singleton.cs:14)
PlayerController:Awake() (at Assets/Scripts/Player/PlayerController.cs:25)

 protected override void Awake()
    {
        base.Awake();

        playerControls = new PlayerControls();
        rb = GetComponent<Rigidbody2D>();
        myAnimator = GetComponent<Animator>();
        mySpriteRenderer = GetComponent<SpriteRenderer>();
        knockBack = GetComponent<KnockBack>();
    }

    private void OnEnable()
    {
        playerControls.Enable();
    }
    private void OnDisable()
    {
        playerControls.Disable();
    }
protected virtual void Awake()
    {
        if (instance != null && this.gameObject != null)
        {
            Destroy(this.gameObject);
        }
        else
        {
            instance = (T)this;
        }
        if (!gameObject.transform.parent)
        {
            DontDestroyOnLoad(gameObject);
        }
    }

I think I see the issue here…
When you switch scenes, the Player is a Singleton, so the Player in the next scene gets destroyed, but this is happening before the PlayerControls for that Player have been created.

A simple solution is to null check the PlayerControls. Since the PlayerControls are not inherited from MonoBehaviour, we can actually use a shorthand for this.

private void OnDisable()
{
     playerControls?.Disable();
}

This is equivalent to

if(playerControls!=null) 
{
     playerControls.Disable();
}

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms