Object reference not set to an instance of an object.

Hello guys! I’m very new to C# and I’m currently making my second game using this language. The game is a moba and everything was fine until now, but I’m having problems because it’s giving an error on the console and I can’t solve it. Basically, the error is about the health bar that should appear on the characters that will appear because of the photon

my code health bar

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

public class Health : MonoBehaviour
{

    public Slider playerSlider3D;
    Slider playerSlider2D;

    public int health;

    void Start()
    {
        playerSlider2D = GetComponent<Slider>();

        playerSlider2D.maxValue = health;
        playerSlider3D.maxValue = health;
    }

    void Update()
    {

        playerSlider2D.value = health;
        playerSlider3D.value = playerSlider2D.value;

    }
}

console error:
NullReferenceException: Object reference not set to an instance of an object
Health.Update () (at Assets/Scripts/Health.cs:25)

I apologize if I made a mistake in the post.

8676540--1169463--upload_2022-12-20_18-15-38.png
8676540--1169463--upload_2022-12-20_18-15-38.png

It’s ALWAYS the same three steps… ALWAYS! You never have to post to the forum for this error.

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

Unity should make nullable default when they move to .NET 6. Will kill all these null posts in a heart beat :slight_smile: though hard moving to nullable when constrctor cant be used.