- Home /
Update the GUI when string changes
I have a class that creates a GUI Box to be filled with information. The information is read from a text file and converted into a string. I know this works because using Debug.Log(string) gives me the contents of the file in the console.
The problem is, the changes to this string are done in Update() and I want to use the string in a GUI.Box Can I update my OnGUI() method from Update()?
Answer by DannyB · Oct 04, 2012 at 10:36 PM
Are you reading a file on each iteration of the Update()? This sounds way too expensive, you should probably avoid that. But nevertheless, something like the below should work for you I hope:
string text;
void Update() {
text = GetTextFromSomewhere();
}
void OnGUI() {
GUI.Label( new Rect(...), text );
}
Is your code structured like the example I provided? Can you provide (add to question) the most relevant snippet of your code? (remove all but the lines that actually matter to the problem at hand).
Well, the problem with this script is that the global variable "contents" is not what you populate in your Update() loop.
Change this:
string contents = ConvertStringArrayToStringJoin(allcontents);
To this:
contents = ConvertStringArrayToStringJoin(allcontents);
BTW I don't see it resetting searchField.Confirm - make sure that is only valid for a single frame or this code will run every Update. You would probably be better of using Send$$anonymous$$essage when that condition is true rather than checking it in an Update loop.
I agree. Checking for such things in the update loop makes me worried. A small misstep and you have a huge performance liability.
I wouldn't necessarily use Send$$anonymous$$essage, but I would use a method that does not require a test in Update().
Buddy.... are you reading the answers? I know your debug.log prints it correctly, because it is in the same scope as your contents variable. The contents variable you are using in your Update loop is in local scope, and the one you are using in the OnGUI is your global field.
Do what I mentioned 4 comments ago, or follow the pattern in the answer and your problem is gone.
I have tested the script you have provided, and made the change I mentioned which solves it.
If you follow the solution and still have a problem, post again.
(and don't confuse yourself with Send$$anonymous$$essage now, it is not going to solve your problem).
Answer by victorafael.com · Oct 05, 2012 at 12:02 AM
The changes on Update() will reflect on OnGUI() Method...
if this doesn't works... try to create a display string variable, displaying it on OnGUI() method and changing it on Update()