# Rewriting a text object [duplicate]

I'm trying to set up a UI system. Say I have a text object 'text' which is visible onscreen. I want to change it with a button press using a script such that the text box's previous string is replaced with a new string held in a string variable 'chat'.

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

public class textchange : MonoBehaviour
{

public Text text; //the text box gameobject is dragged into this

public string chat; //the chat string is filled elsewhere

void Awake()
{

}

void Update()
{
(if button press logic here)
{
text.text = chat;
}
}

}


What I expect is for the text to dynamically change, but what happens is absolutely nothing, the gameobject does not have its text component rewritten. What gives?

• I suspect the "button press logic here" is done wrong. Did you try putting a Debug.Log line inside the function to see if it runs? – TomTsagk Jan 9 '19 at 11:18
• That was the first thing I checked, but I've also got a boolean set up to just light up when the logic is successful (i.e. button is registered and processed correctly) to check against and it's fine. – SPeked Jan 9 '19 at 11:21
• Based on the exchange below, it looks like this was just a null reference exception error. If you get different errors or unexpected behaviour after fixing your exception, please edit your question to include all relevant details and we can re-open it for fresh answers. – DMGregory Jan 9 '19 at 14:46

What you have here looks correct at first glance, but there might be a mistake in the button press logic here part you omitted.
Verify that the line text.text = chat; is actually being executed. You can do that by adding a line like Debug.Log("changing content of " + text.name + " to " + chat) in front of it and looking at the console output or by setting a debugger breakpoint in Visual Studio and running the game in debug mode.
It is also possible that you didn't assign a text field to the public Text text variable. The symptom would be a NullReferenceException error in your Unity console whenever the line text.text = chat is being executed. Open the inspector of the game object with this script and drag the text field you want to control into the "Text" slot of your component.