I need help for a reference error

Hello,

I need help to find where is the problem with my script. Unity says

“NullReferenceException: Object reference not set to an instance of an object
GameManager.InstanciatePlayer () (at Assets/Scripts/GameManager.cs:48)
GameManager.Start () (at Assets/Scripts/GameManager.cs:37)”

But i don’t get why it can’t find the object… Can someone help me please ?

Here is my script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour {

    private static GameManager instance;

    public static GameManager Instance { get { return instance ;}}

    [SerializeField]
    private Transform playerPrefab;

    private Transform playerInstanciate;

    private Player playerScript;

    [SerializeField]
    private Transform SpawnPoint;

    private Camera2DFollow cam;

    private void awake()
    {
        if(instance != null)
        {
            Destroy(gameObject);
        }

        instance = this;

        cam = Camera.main.GetComponent<Camera2DFollow>();
    }

    void Start ()
    {
        InstanciatePlayer();
    }
   
    private void InstanciatePlayer()
    {
        playerInstanciate = Instantiate(playerPrefab, SpawnPoint.position, Quaternion.identity);

        playerScript = playerInstanciate.GetComponent<Player>();
       
        playerScript.MonEvent += PlayerScript_MonEvent;

        cam.target = playerInstanciate.gameObject;
    }
   
    private void PlayerScript_MonEvent()
    {
        Destroy (playerInstanciate.gameObject);
        StartCoroutine(RespawnPlayer());
        Debug.Log("La coroutine se met en marche");
    }
   
    private IEnumerator RespawnPlayer()
    {
        Debug.Log("3");

        yield return new WaitForSeconds(1);
       
        Debug.Log("2");

        yield return new WaitForSeconds(1);
       
        Debug.Log("1");

        yield return new WaitForSeconds(1);

        InstanciatePlayer();
    }
}

And why am I moderated ? What’s wrong with my post ?

is it possible that you forgot to set the cam object,
You can add a if statement to check

private void InstanciatePlayer()
{
    playerInstanciate = Instantiate(playerPrefab, SpawnPoint.position, Quaternion.identity);

    playerScript = playerInstanciate.GetComponent<Player>();
  
    playerScript.MonEvent += PlayerScript_MonEvent;

    if(!cam)
    {
        Debug.Log("cam was not set, please fix");
    }else
    {
        cam.target = playerInstanciate.gameObject;
    }
}

You’ve got ‘awake’ there, but you need ‘Awake’, otherwise the engine will not invoke it.

1 Like

Good catch, I didn’t see the awake() missed the cap A