HelpTextToggle C# Script

 


I asked ChatGPT: "To create a Unity script that toggles the visibility of a HelpText GameObject attached to the Main Camera, you can follow these steps: I also asked it to add an auto-hide timer.

Create a new C# script in your Unity project and name it "HelpTextToggle".
Open the script in your preferred code editor.
Replace the default script content with the following code:

using System.Collections;
using UnityEngine;

public class HelpTextToggle : MonoBehaviour
{
    public GameObject helpTextObject; // Reference to the HelpText GameObject
    private bool isHelpTextVisible; // Keep track of the HelpText visibility state
    private float hideTimer = 7.0f; // Duration to wait before auto-hiding the HelpText

    private void Start()
    {
        isHelpTextVisible = helpTextObject.activeSelf; // Get the initial state of HelpText GameObject
    }

    private void Update()
    {
        ToggleHelpText();
    }

    private void ToggleHelpText()
    {
        // Check if the user pressed the "H" key
        if (Input.GetKeyDown(KeyCode.H))
        {
            // Toggle the visibility of the HelpText GameObject
            isHelpTextVisible = !isHelpTextVisible;
            helpTextObject.SetActive(isHelpTextVisible);

            // If the HelpText is visible, start the auto-hide timer
            if (isHelpTextVisible)
            {
                StartCoroutine(AutoHideHelpText());
            }
            else
            {
                // If the HelpText is manually hidden, stop the auto-hide timer
                StopCoroutine(AutoHideHelpText());
            }
        }
    }

    private IEnumerator AutoHideHelpText()
    {
        // Wait for the specified duration
        yield return new WaitForSeconds(hideTimer);

        // Hide the HelpText GameObject and update the visibility state
        helpTextObject.SetActive(false);
        isHelpTextVisible = false;
    }
}


Comments

Popular posts from this blog

Clone Command Bar Button in Model Driven App: Order & OrderDetails

Model-Driven Apps: Modern Command Bar Customization

Knowledge shared is power squared!