NullReferenceException: Object reference not set to an instance of an object

Linus K 21 Reputation points
2022-07-22T06:22:29.42+00:00

Error: NullReferenceException: Object reference not set to an instance of an object
MeteorController.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/MeteorController.cs:23)

Code:

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
using UnityEngine.SceneManagement;  
  
public class MeteorController : MonoBehaviour  
{  
    float speed = 5;  
  
    private void Start()  
    {  
        speed = Random.Range(5, 10);  
    }  
  
    private void OnCollisionEnter2D(Collision2D collision)  
    {  
        if (collision.gameObject.tag == "Player")  
        {  
            SceneManager.LoadScene(0);  
        }  
        else if (collision.gameObject.tag == "Laser")  
        {  
            ScoreManager.instance.AddPoint();  
            Destroy(collision.gameObject);  
            Destroy(gameObject);  
        }  
    }  
  
    // Update is called once per frame  
    void Update()  
    {  
        transform.position -= new Vector3(0, speed, 0) * Time.deltaTime;  
  
        if (transform.position.y < -10)  
        {  
            Destroy(gameObject);  
        }  
    }  
}  
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Reza Aghaei 4,986 Reputation points MVP Volunteer Moderator
    2022-07-28T16:16:54.79+00:00

    You can take a look at my answer here: System.NullReferenceException 'Object reference not set to an instance of an object.'.

    Here is a short summary:

    • When you have a statement like A.B.C = E.F;, and you receive an NullReferenceException 'Object reference not set to an instance of an object.' on that line of code, it basically means either A, or B or E are null.
    • To figure out what's wrong there, you can set a breakpoint on the same line, start debugging and then when the breakpoint hits, just check the value of A, B or E.

    Learn more

    For more information and examples, take a look at the following links:

    0 comments No comments

  2. satya karki 996 Reputation points MVP
    2022-07-29T09:30:39.383+00:00

    Hi, I think, it is better to keep breakpoint, debug and check. Maybe, ScoreManager.instance is null.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.