Giovanni Di Toro
Giovanni Di Toro

Reputation: 809

change text based on button-click

I am using Unity3d

I've tried to track where the problem comes from and had no success. The text update in "Guess" occurs properly when done by key press, but no by clicking the button (both log in an exception).

The code:

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

public class NumberWizard : MonoBehaviour
{
    public Text guessText;
    int min;
    int max;
    int guess;

    public void Higher ()
    {
        min = guess;
        NextGuess ();
    }

    public void Lower ()
    {
        max = guess;
        NextGuess ();
    }

    public void Correct ()
    {
        print ("I won!");
        StartGame ();
    }

    private void StartGame ()
    {
        min = 1;
        max = 1000;
        guess = 500;
        guessText.text = guess.ToString();
        print (guess);
    }

    private void NextGuess ()
    {
        guess = (max + min) / 2;
        guessText.text = guess.ToString();
        print (guess);
    }


    // Use this for initialization
    void Start ()
    {
        StartGame ();
    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.UpArrow)) {
            Higher ();
        } else if (Input.GetKeyDown (KeyCode.DownArrow)) {
            Lower ();
        } else if (Input.GetKeyDown (KeyCode.Return)) {
            Correct ();
        }

    }
}

By the way, I've put the buttons on another controller called "LevelManager". I've added [RequireComponent(typeof(LevelManager))] above class declaration, but it didn't work.

Basically, it says that in guessText.text = guess.ToString(); object is not set to an instance, but I've set in Unity3d that the particular text is referenced and that it should use NumberWizard.cs

Upvotes: 0

Views: 148

Answers (2)

Diego Alares
Diego Alares

Reputation: 95

The error says that you have to initialize the variable, whether by doing a "new" or asingning it to a ingame drag'n'drop object as Dinal says.

Upvotes: 0

Dinal24
Dinal24

Reputation: 3192

When you create this script it need to be attached to a GameObject. As you have done the coding it should be attached to an Empty gameObject. Then when you select the script from editor your public variable Text guessText will be available on the edior, Now you have to drag and drop the GUIText you have created on to the guessText property.

Upvotes: 1

Related Questions