NullReferenceException: Object reference not set to an instance of an object..., please help me with the problem

Hello! Can you please help me with a problem?

I’m making a simple board game from a tutorial on youtube. I think i’ve done everything the same as it is shown on the video, but when i start the game, i get a bunch of errors (all the errors are NullRederenceException).

This is a part of my code from KontroleIgre class:

void Start()
{
    igralec1 = GameObject.Find("igralec1_zelen");
    igralec2 = GameObject.Find("igralec2_zelen");

    igralec1.GetComponent<PremikanjeIgralca>().dovoljenoPremikanje = false;
    igralec2.GetComponent<PremikanjeIgralca>().dovoljenoPremikanje = false;
}

// Update is called once per frame
void Update()
{
    if (igralec1.GetComponent<PremikanjeIgralca>().indexPozicije > igralec1Pozicija + stranKockePriMetu)
    {
        igralec1.GetComponent<PremikanjeIgralca>().dovoljenoPremikanje = false;
        igralec1Pozicija = igralec1.GetComponent<PremikanjeIgralca>().indexPozicije - 1;
    }
    if (igralec2.GetComponent<PremikanjeIgralca>().indexPozicije > igralec1Pozicija + stranKockePriMetu)
    {
        igralec2.GetComponent<PremikanjeIgralca>().dovoljenoPremikanje = false;
        igralec1Pozicija = igralec2.GetComponent<PremikanjeIgralca>().indexPozicije - 1;
    }
    if (igralec1.GetComponent<PremikanjeIgralca>().indexPozicije == igralec1.GetComponent<PremikanjeIgralca>().pozicije.Length)
    {
        konecIgre = true;
    }
    if (igralec1.GetComponent<PremikanjeIgralca>().indexPozicije == igralec1.GetComponent<PremikanjeIgralca>().pozicije.Length)
    {
        konecIgre = true;
    } 
}

This is a part of class PremikanjeIgralca:

public class PremikanjeIgralca : MonoBehaviour
{
    public Transform[] pozicije;

    [HideInInspector]
    public int indexPozicije = 0; //trenutni index pozicije()

    [SerializeField]
    private float hitrost = 1f;

    public bool dovoljenoPremikanje = false;

The problem is in the sentences:

  • igralec1.GetComponent<PremikanjeIgralca>().______
  • igralec2.GetComponent<PremikanjeIgralca>().______

I hope someone can find the solution. :confused:

NullReferenceExceptions are caused when you try to access some part of a reference, but that reference has never been set to a value. When you get one of these errors, you need to determine which reference is null and then check which code was supposed to set the reference to non-null.

In your case, it is likely that the GameObject.Find function is not finding any object. You need to check that the expected objects exist and have the name you specify here.

A more reliable solution may be to define igralec1 and igralec2 in a serialized field and then drag the expected game object to that field in the inspector.

[SerializeField] private GameObject igralec1;
[SerializeField] private GameObject igralec2;