salipshitz
salipshitz

Reputation: 67

Unity c# - Error in a script that should change text

I am trying to make a level select menu. Here is a screenshot of my layout: enter image description here To make this work, this is my script for making it happen:

    using UnityEngine;
using UnityEngine.UI;

public class ChooseLevel : MonoBehaviour
{

    string[] levelNames;
    int i = 0;


    public Button addIndex;
    public Button subtractIndex;
    public Text levelChooser;

    string lvlName = "";

    void Start()
    {
        levelNames = PlayMenu.levelNames;

        addIndex.onClick.AddListener(delegate () { i += 1; });
        subtractIndex.onClick.AddListener(delegate () { i -= 1; });

    }

    void Update()
    {
        i = Mathf.Clamp(i, 0, levelNames.Length);
        lvlName = levelNames[i];
        levelChooser.text = lvlName;
    }

}

The code is attached to the canvas and here are screen shots of the scene and a section of the inspector for the canvas:
enter image description here
enter image description here

The error i get is:

NullReferenceException: Object reference not set to an instance of an object
ChooseLevel.Update () (at Assets/ChooseLevel.cs:28)

Upvotes: 0

Views: 134

Answers (2)

salipshitz
salipshitz

Reputation: 67

It was just a small error in another script.

Upvotes: 0

Maximilian Gerhardt
Maximilian Gerhardt

Reputation: 5353

You declare your string right above void Start(), but don't initialize it. (Implicitly null)

string lvlName;

So then when you go in Update() for the first time, the value of lvlName is null.

void Update()
{
    levelChooser.text = lvlName; //null the first time 
    lvlName = levelNames[i]; //THEN it's changed
    Mathf.Clamp(i, 0, levelNames.Length);
}

So depending on your game logic you must either FIRST assign to lvlName or initialize it with an empty string. I guess

void Update()
{
    i = Mathf.Clamp(i, 0, levelNames.Length); //FIRST clamp. Thanks to Joe Blow for pointing out that it never gets reassigned.
    lvlName = levelNames[i]; //then update lvlName
    levelChooser.text = lvlName; //then Change the text. 
}

should work fine. Also make sure that i doesn't hit the exact value levelNames.Length but I think that logic is okay. You'll notice when you get an out-of-bounds exception.

Upvotes: 2

Related Questions