Search code examples
c#unity-game-enginevuforia

How to hide a image on app start in Unity?


i am having a image which has to be enabled only when a button is clicked! I know the code to enable and disable UI components.

component.enabled=false, component.enabled=true;

But the image is viewable on start of the app!

So how to hide the sprite on start of the app and show only when button is clicked?


Solution

  • Having your code would be usefull...

    Disable the component or set inactive the whole gameobject inside an Awake function (avoid the Start function, unless the script responsible for the disabling of your image is on other gameobject

    // C#
    private UnityEngine.UI.Image image ;
    
    private void Awake()
    {
         image = GetComponent<UnityEngine.UI.Image>();
    
         HideImage();
    }
    
    public void HideImage()
    {
         image.enabled = false ;
    
         // ===== OR =====
    
         gameObject.SetActive(false);
    }
    
    public void ShowImage()
    {
         image.enabled = true;
    
         // ===== OR =====
    
         gameObject.SetActive(true);
    
    }
    

    To detect when a button is clicked, you can add a listener at runtime :

    https://docs.unity3d.com/ScriptReference/UI.Button-onClick.html

        UnityEngine.UI.Button btn = otherGameObject.GetComponent<UnityEngine.UI.Button>();
        btn.onClick.AddListener(ShowImage);