- Home /
How do you change UI text in the middle of a method?
When launching the game, I'm loading a lot of data from a database. To lighten the pain I want to show a load bar to show the progress, along with a text informing the user what's being loaded. (in a funny format of course)
For example I have this code:
public void Start()
{
if(LoadingState == LoadingState.StartFromDesktop)
{
SetText("Get Countries", 10);
WorldModel.Countries = DataGameObjects.GetCountries();
SetText("Get Continents", 25);
WorldModel.SubContinents = DataGameObjects.GetSubContinents();
WorldModel.Continents = DataGameObjects.GetContinents();
WorldModel.Areas = DataGameObjects.GetAreas();
WorldModel.States = DataGameObjects.GetStates();
}
}
private void SetText(string text, int progress)
{
_task.text = text;
_percentage.text = progress + " %";
_progressbar.value = (float)progress / 100;
}
Obviously, this doesn't do what I want. It just changes the text to 'Get Continents' at the end of the method, while freezing the loading screen because its busy.
I tried using Coroutines, but that threw an error because it wanted me to return a string of a method. Neither could I work it out using async tasks.
Any suggestions?
Also, what would be the best way to calculate the progress of loading an .sqlite file and .xml files?
Answer by Tjoeker · Jun 24, 2020 at 01:53 PM
I don't think it's the cleanest solution, but I managed it by putting everything I had in the Start() in a coroutine:
public void Start()
{
StartCoroutine(Load());
}
private IEnumerator Load()
{
if (LoadingState == LoadingState.StartFromDesktop)
{
StartCoroutine(SetText("test", 10));
WorldModel.Countries = DataGameObjects.GetCountries();
yield return new WaitForEndOfFrame();
StartCoroutine(SetText("haha", 25));
WorldModel.SubContinents = DataGameObjects.GetSubContinents();
WorldModel.Continents = DataGameObjects.GetContinents();
WorldModel.Areas = DataGameObjects.GetAreas();
WorldModel.States = DataGameObjects.GetStates();
}
}
private IEnumerator SetText(string text, int progress)
{
_task.text = text;
_percentage.text = progress + " %";
_progressbar.value = (float)progress / 100;
yield return null;
}
Obviously it needs some cleaning up and adding features. But this does what I wanted.
Your answer
Follow this Question
Related Questions
Loading screen works perfectly with one scene only and not with others 0 Answers
Loading Screens are confusing 0 Answers
Loading screen bar not loading. 1 Answer
Loading screen with LoadLevelAsync 0 Answers