How do I display maxGuessesAllowed on the Canvas?

Hi all, I wanted to display maxGuessesAllowed in another text box. I am stumped. I cant understand how I get another text box to display anything else from the nextGuess() function. A little help please would be incredibly helpful/

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


public class NumberWizard : MonoBehaviour {
	int max;
	int min;
	int guess;
	public int maxGuessesAllowed = 5;

	public int TriesLeft; //>>?? Use this to display maxGuessesAllowed?
	public Text text;

	// Use this for initialization
	void Start () {
		StartGame ();
}
	void StartGame (){
		max = 1000;
		min = 1;
		guess = 500;
		max = max + 1;
		}
			
	public void GuessHigher(){
		min = guess;
		NextGuess();
	}

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

	void NextGuess (){
		guess = (max + min) / 2;
		text.text = guess.ToString();
		maxGuessesAllowed = maxGuessesAllowed - 1;
		// I am guessing i need to put TriesLeft here somehow
		if (maxGuessesAllowed <= 0) {
			SceneManager.LoadScene ("Win");

		}
	}


}

Hi,

Create your self a second Text UI GameObject in the scene and place it where you want it, make sure its wide enough to fit your number/font size etc.

In your NumberWizard script, add variable, like this;

public Text triesLeft;

Save the script.

Back in Unity, select your NumberWizard GameObject and your script component will now display the triesLeft field, drag your Text UI GameObject from the Hierarchy into this field.

Back in your script you can access this via your triesLeft Text variable via its text property;

triesLeft.text = guessRemaining;

In the above, guessesRemaining would be an int variable holding how many guesses are remaining.

Hope this helps :slight_smile:


See also;

Hi Rob,

Thanks for the help, I was on the right path, but i was failing to either, convert maxGuessesAllowed into a string, or relate the specific text object at any given point. Probably because I hadn’t linked my text object properly! Showing how poor my memory is having done this already once! I think i’ll add some more random ideas to it to make sure its drilled in.

guessesRemaining = maxGuessesAllowed;
triesLeft.text = guessesRemaining.ToString();

1 Like

You’re more than welcome Andy, happy to help, and giving it some more features sounds like a fab idea :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms