1

I am following a Unity tutorial and faced this problem

NullReferenceException: Object reference not set to an instance of an object
PieceSpawner.Spawn () (at Assets/Script/PieceSpawner.cs:25)
Segment.Spawn () (at Assets/Script/Segment.cs:30)
LevelManager.SpawnSegment () (at Assets/Script/LevelManager.cs:94)
LevelManager.GenerateSegment () (at Assets/Script/LevelManager.cs:69)
LevelManager.Update () (at Assets/Script/LevelManager.cs:58)

and

NullReferenceException: Object reference not set to an instance of an object
Segment.Awake () (at Assets/Script/Segment.cs:22)
UnityEngine.Object:Instantiate(GameObject)
LevelManager:GetSegment(Int32, Boolean) (at Assets/Script/LevelManager.cs:121)
LevelManager:SpawnSegment() (at Assets/Script/LevelManager.cs:84)
LevelManager:GenerateSegment() (at Assets/Script/LevelManager.cs:69)
LevelManager:Update() (at Assets/Script/LevelManager.cs:58)

. This game is a subway surfers type of game that generates endless objects as you go on. Why is this error happening? Is it related to an unity object or the code? I think happened after updating to 2021.1.26f1. Here is the code, what should I change?

PieceSpawner.cs:

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

public class PieceSpawner : MonoBehaviour {

    public PieceType type;
    private Piece currentPiece;

    public void Spawn()
    {
        int amtObj = 0;
        switch(type)
        {
            case PieceType.jump:
                amtObj = LevelManager.Instance.jumps.Count;
                break;
            case PieceType.slide:
                amtObj = LevelManager.Instance.slides.Count;
                break;
            case PieceType.longblock:
                amtObj = LevelManager.Instance.longblocks.Count;
                break;
            case PieceType.ramp:
                amtObj = LevelManager.Instance.ramps.Count;
                break;
        }

        currentPiece = LevelManager.Instance.GetPiece (type, Random.Range(0, amtObj));
        currentPiece.gameObject.SetActive (true);
        currentPiece.transform.SetParent (transform, false);
    }

    public void Despawn()
    {
        currentPiece.gameObject.SetActive (false);
    }
    }

LevelManager.cs:

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

public class LevelManager : MonoBehaviour {

    public bool SHOW_COLLIDER = true; //$$

    public static LevelManager Instance { set; get;}

    // Level spawning
    private const float DISTANCE_BEFORE_SPWAN = 100f;
    private const int INITIAL_SEGMENT = 10;
    private const int MAX_SEGMENT_ON_SCREEN = 15;
    private Transform cameraContainer;
    private int amountOfActiveSegment;
    private int continiousSegments;
    private int currentSpawnZ;
    private int currentLevel;
    private int y1, y2, y3;

    // List of pieces
    public List<Piece> ramps = new List<Piece>();
    public List<Piece> longblocks = new List<Piece>();
    public List<Piece> jumps = new List<Piece>();
    public List<Piece> slides = new List<Piece>();
    [HideInInspector]
    public List<Piece> pieces = new List<Piece>(); // All pieces on the pool

    // List of segments
    public List<Segment> availableSegments = new List<Segment>();
    public List<Segment> availableTransition = new List<Segment>();
    [HideInInspector]
    public List<Segment> segments = new List<Segment> ();

    // Gameplay
    private bool isMoving;


    private void Awake()
    {
        cameraContainer = Camera.main.transform;
        currentSpawnZ = 0;
        currentLevel = 0;
    }

    private void Start()
    {
        for (int i = 0; i < INITIAL_SEGMENT; i++) {
            GenerateSegment ();
        }
    }

    private void Update()
    {
        if (currentSpawnZ - cameraContainer.position.z < DISTANCE_BEFORE_SPWAN)
        {
            GenerateSegment ();
        }

        if (amountOfActiveSegment >= MAX_SEGMENT_ON_SCREEN) {
            segments [amountOfActiveSegment - 1].DeSpawn();
            amountOfActiveSegment--;
        }
    }

    private void GenerateSegment()
    {
        SpawnSegment ();

        if (Random.Range (0f, 1f) < (continiousSegments * 0.25f)) {
            SpawnTransition ();
            continiousSegments = 0;
        } else {
            continiousSegments++;
        }
    }

    private void SpawnSegment()
    {
        List<Segment> possibleSegments = availableSegments.FindAll (x => x.beginY1 == y1 || x.beginY2 == y2 || x.beginY3 == y3);
        int id = Random.Range (0, possibleSegments.Count);

        Segment s = GetSegment (id, false);
        y1 = s.endY1;
        y2 = s.endY2;
        y3 = s.endY3;

        s.transform.SetParent (transform);
        s.transform.localPosition = Vector3.forward * currentSpawnZ;

        currentSpawnZ += s.lenght;
        amountOfActiveSegment++;
        s.Spawn ();
    }

    private void SpawnTransition()
    {
        List<Segment> possibleTransition = availableTransition.FindAll (x => x.beginY1 == y1 || x.beginY2 == y2 || x.beginY3 == y3);
        int id = Random.Range (0, possibleTransition.Count);

        Segment s = GetSegment (id, true);
        y1 = s.endY1;
        y2 = s.endY2;
        y3 = s.endY3;

        s.transform.SetParent (transform);
        s.transform.localPosition = Vector3.forward * currentSpawnZ;

        currentSpawnZ += s.lenght;
        amountOfActiveSegment++;
        s.Spawn ();
    }

    public Segment GetSegment(int id, bool transition)
    {
        Segment s = null;
        s = segments.Find (x => x.SegID == id && x.transition == transition && !x.gameObject.activeSelf);

        if (s == null) {
            GameObject go = Instantiate (transition ? availableTransition [id].gameObject : availableSegments [id].gameObject) as GameObject;
            s = go.GetComponent<Segment> ();
            s.SegID = id;
            s.transition = transition;

            segments.Insert (0, s);
        } else {
            segments.Remove (s);
            segments.Insert (0, s);
        }

        return s;

    }

    public Piece GetPiece(PieceType pt, int visualIndex)
    {
        Piece p = pieces.Find(x => x.type == pt && x.visualIndex == visualIndex && !x.gameObject.activeSelf);

        if (p == null) {
            GameObject go = null;

            switch (pt) {
            case PieceType.ramp:
                go = ramps [visualIndex].gameObject;
                break;
            case PieceType.longblock:
                go = longblocks [visualIndex].gameObject;
                break;
            case PieceType.jump:
                go = jumps [visualIndex].gameObject;
                break;
            case PieceType.slide:
                go = slides [visualIndex].gameObject;
                break;      
            }
            go = Instantiate (go);
            p = go.GetComponent<Piece> ();
            pieces.Add (p);
        }

        return p;
    }

    }

 
SahilnCode
  • 19
  • 4
  • 2
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) - especially as the code would tell you which line and so what is null which you have not shared – BugFinder Oct 24 '21 at 02:00
  • It doesn't really answer my question. – SahilnCode Oct 24 '21 at 02:08
  • Try looking into your code at line number 25 as per exception details in debug mode. Looks like you are trying to access a method/property on a null object. (at Assets/Script/PieceSpawner.cs:25) – Durga Prasad Oct 24 '21 at 04:48

1 Answers1

0

You are not making reference for your public static LevelManager Instance in LevelManager.cs.

In Awake() make a reference -

private void Awake()
{
    if(Instance == null) 
        Instance = this;
    else 
        Destroy(gameObject);

    cameraContainer = Camera.main.transform;
    currentSpawnZ = 0;
    currentLevel = 0;
}
Srejon Khan
  • 438
  • 2
  • 8