Sora
Sora

Reputation: 2551

Hiding a UI panel from script in unity

I have a UI Panel containing a Button as a child. The button has a script as a component. The script is as follows:

public GameObject Panel ;
OnMouseDown()
{
  Panel.setActive(false);

  StartCoroutine(takeShot());
}
private IEnumerator takeShot()
{
   Application.CaptureScreenshot("my_img.png");
 }

I am having a problem saying the coroutine can't start because the button is inactive.

How can I fix this problem? Can I hide the panel without using SetActive(false)?

Upvotes: 1

Views: 25974

Answers (3)

Codemaker2015
Codemaker2015

Reputation: 1

For hiding any component in Unity3D without using SetActive() method, you can set the scale of the object as zero.

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

public class HidePanelDemo: MonoBehaviour
{
    public RectTransform panelObject;

    // Start is called before the first frame update
    void Start() {
        panelObject.localScale = new Vector3(0,0,0);
    }
}

Upvotes: 0

Jukes
Jukes

Reputation: 437

I have been battling with the same problem for a while. However, i adopted a different answer that has the same effect. What i did was access the RectTransform component and then hide it by scaling it down.

    public RectTransform Panel;

        void Update ()
        {       
            if(Input.GetButtonUp("Fire1"))
            {            
                Panel.localScale = new Vector3(1, 1);
            }
            if(Input.GetButtonUp("Fire2"))
            {
                Panel.localScale = new Vector3(0, 0);
            }   
}

Upvotes: 2

MattGarnett
MattGarnett

Reputation: 625

Yes I assume you are using the latest version of the unity UI.

You'd want to make use of canvas groups. Attach a canvas group to your parent object, the panel, in your code access the canvas group component and set its alpha to 0 on whatever your trigger may be. This hides the canvas element and all its children but is still active in the scene. Reset it to 1 to make it visible again. Unfortunately you will still be able to interact with it as it is still technically in the scene, so you can solve this by using Renderer.enabled and setting it too false. This updates it but doesn't draw it. SetActive stops it altogether.

Hope this clears things up.

Upvotes: 3

Related Questions