Why won't my GUI.button disappear?

Hi,

I’m a c# novice learning as I go. Currently I’m trying to write a c# script where a gui.button appears and then once clicked it’d make itself disappear. I’m doing this by only making the button appear if bool showMessage us true. What’s supposed to happen is that once the button gets clicked, showMessage will become false, which in turn should the button NOT appear. Am I missing something?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreateMessage : MonoBehaviour {

    string message = "Hellow world";
    bool showMessage = false;

    // Use this for initialization
    void Start () {

    }
   
    // Update is called once per frame 
    void Update () {
    }

    void OnGUI()
    {
        showMessage = true;

        if (showMessage == true)
        {
            if (GUI.Button(new Rect((Screen.width / 2) - 100, (Screen.height / 2) - 100, 200, 200), message))
            {
                showMessage = false;
            }
        }
    }
}

You set it to true before it is evaulated so it will always be true by the time your statement is executed.

bool showMessage = false; //Change this to true

    void OnGUI()
    {
        showMessage = true; //<- This line is causing your problems and needs to go
        if (showMessage == true)
        {
            if (GUI.Button(new Rect((Screen.width / 2) - 100, (Screen.height / 2) - 100, 200, 200), message))
            {
                showMessage = false;
            }
        }
    }

Also consider moving away from OnGUI and use Unity’s new UI system. Then simply turn off the button when it’s clicked on. You can tie the SetActive straight into the button click, super simple. OnGUI is generally considered more for editor scripts now.