N
N
Nikolay2021-04-29 04:14:21
C++ / C#
Nikolay, 2021-04-29 04:14:21

Why is NullReferenceException thrown?

There is a program

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

public class NewBehaviourScript : MonoBehaviour
{
    int i;
    Text ruby;

    void Update()
    {
        i++;
        ruby.text = i.ToString();
    }
}

You get the following error at the line ruby.text = i.ToString();: NullReferenceException: Object reference not set to an instance of an object
NewBehaviourScript.Update() (at Assets/Scripts/NewBehaviourScript.cs:14).
Tried to instantiate a Text() object: Then the error Assets\Scripts\NewBehaviourScript.cs(14,20) is generated: error CS0122: 'Text.Text()' is inaccessible due to its protection level. ruby = new Text();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
none7, 2021-04-29
@unt_test

You can't just take and create Text. It should be created by GameObject. Example .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question