[SOLVED] Changing int maxguessesallowed to public seems to disable it

Per the tutorial video, I changed the integer maxGuessesAllowed to public, but it seems to disable the integer altogether. It makes my max guesses 10 regardless of the number there. Removing the ‘public’ fixes it and make the max guesses whatever number I have there. Am I missing something?

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

public class NumberWizard : MonoBehaviour {
	// Use this for initialization
	int max;
	int min;
	int guess;

	public int maxGuessesAllowed = 8;
	public Text text;
	
	void Start () {
		StartGame();
	}
	
	void StartGame () {
		max = 1000;
		min = 1;
		guess = 500;
		
		max = max + 1;
	}
	
	public void GuessLower(){
		max = guess;
		NextGuess();		
	}
	
	public void GuessHigher(){
		min = guess;
		NextGuess();	
	}
	
	public void NextGuess () {
		guess = (max + min) / 2;
		text.text = guess.ToString();
		maxGuessesAllowed = maxGuessesAllowed - 1;
		if(maxGuessesAllowed <=0){
			Application.LoadLevel("Win");
		}
	}
}

Have you change the value in editor to 10 ?
The value you put in the editor has a higher priority than the default value in the script.

1 Like

Where in the editor would that value be? Everything is calling back to the script. The only thing I’m changing is:

public int maxGuessesAllowed = 8;

to

int maxGuessesAllowed = 8;

That fixes it.

The difference here is that if you dont specify an access modifier? e.g. public / private then the default will be used, the default is private.

As @Dieedi suggests, you most likely have the value of 10 set in the Inspector, you shpuld be able to see this if you select the game onjbject in the Hierarchy which has this script attached to it, and then look for the Max Guesses Allowed field.

The reason it will be working now is because, setting it to private prevents it from showing up in the Inspector, thus the value of 10 wpuld be ignored and your private variable is veing set to 8 in your code.

Hope this helps a little further. :slight_smile:

This conversation is really helpful, thank you to all!

But honestly I’m curious why it’s working in the course video other way.

Btw you can leave it on public at declaration, and initialize it within Start method.
Like this:

public class NumberWizard : MonoBehaviour {
// Use this for initialization

int max;
int min;
int guess;

public int maxGuessesAllowed;
public Text text;

void Start () {
	StartGame();
}

void StartGame () {	
	guess = 500;
	min = 1;
	max = 1000;	
	max = max +1;
	maxGuessesAllowed = 10;
}

Privacy & Terms