Toggle UI Text With UI Toggle Button

I have a UI Text object on a canvas that I’m calling with this method but I’m having a difficult time trying to figure out how to get my UI toggle button to switch between the two text messages in Button State 0 & 1

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

public class MessageCentreManager3 : MonoBehaviour {

	int sysHour = System.DateTime.Now.Hour; //gives you the current hour as an integer.

	//UI Text Reference
	public Text MessageCentre3Text;
	public Toggle someToggle;

	//Button States
	public int buttonState = 0;



	void Update ()
	{	 
		if (buttonState == 0) MessageCentre3Text.text = "VOICE PROJECTION SCREEN";
		else if (buttonState == 1) MessageCentre3Text.text = "VOICE PROJECTION";
		else if (buttonState == 2) MessageCentre3Text.text = "ANHARMONIC SYTHESIZER";
	}



	//Default Message
	public void GoDefaultMessage()
	{
		buttonState = 0;
	}

	//Voice Projection Activated
	public void GoVoiceProjectionMessage()
	{
		//buttonState = 0; Toggle ButtonState 0 Message

		//Toggle

		//buttonState = 1; Toggle ButtonState 1 Message

	}

	//Anharmonic Synthesizer Activated
	public void GoAnharmonicMessage()
	{
		buttonState = 2;
	}


}

I believe a rethink of what you want to do would simplify everything a lot. First off, there is no need to check anything in update for this type of behaviour :slight_smile: I would propose something much simpler.

Use the UnityEvent of your button to call a simple method.

Make a script that you attach on the UI Text, it has 1 bool, and 1 method. Something like this:

bool secondSentence;

public void ChangeText()
{
	if (secondSentence) {
		GetComponent<Text>().text = "My second sentence.";
		secondSentence = false;
	} else {
		GetComponent<Text>().text = "My first sentence.";
		secondSentence = true;
	}
}

Then on the button, drag the script onto the Click event and select that method. Done :slight_smile:

You can also use ternary operators to clean it up:

bool secondSentence;

public void ChangeText()
{
	GetComponent<Text>().text = secondSentence ? "Second text" : "First text";
	secondSentence = !secondSentence;
}

PS. Untested but should work.

Edit
It seems you have more states. For that you can store your strings in an array or list, then use an int to assign the string to your text. Every time you call the method, increment the int like so:

sentenceNum = ++sentenceNum % myArray.Length