rchau
rchau

Reputation: 535

Show and hide gameobject when condition achieved in Unity?

I have a login scene in unity where I am taking user's details then processing it and based on condition I want to show and hide the gameobject.

I have a Loading gameobject which is nothing but the loading animation.

This is what I am doing(& tried):

void Start()  //Start Of Scene
{
Loading = GameObject.Find("CircleGlass");
Loading.SetActive(false);
}

When button clicked:

public void Clicked()
{
Loading.SetActive(true);
//Rest of code fetching data from api using UnityEngine.Networking
if(condition)
 {
 Loading.SetActive(false);
 //Redirect to another page
 }
}

The problem is Loading gameobject just do not show when I click the button. It is taking the processing time but do not show the loader. Here is the attached screenshot: enter image description here

Any help would be much appreciated. Thanks!!

Upvotes: 1

Views: 1338

Answers (1)

Anton Mihaylov
Anton Mihaylov

Reputation: 1348

From what you posted as code, i assume that the code executes synchronously. Meaning that after you execute SetActive(true) there are no update frames before executing SetActive(false), so there is no time to update the actual object's state.

You can change that by using a coroutine:

public void Clicked()
{
    Loading.SetActive(true);
    StartCoroutine(FetchAndDisableLoading());
}

IEnumerator FetchAndDisableLoading(){
    //Rest of code fetching data from api using UnityEngine.Networking
    //If you make a UnityWebRequest here you should do:
    //yield return webRequest.SendWebRequest();
    //This will wait for the web request to finish before proceeding

    //Finally, when all code is executed you should disable the object:
    if(condition)
    {
        Loading.SetActive(false);
       //Redirect to another page
    }
}

Upvotes: 3

Related Questions