简体   繁体   中英

How to switch display/non-display by right-clicking in C# of Unity

I tried to toggle the visibility of the object with the following code.

However, when I right-clicked the first time, the object was hidden, but when I right-clicked the second time, the object was not displayed.

The object should appear on the second right click.

What's wrong with this code?

using UnityEngine;

public class EnvironmentSettings : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(1))
        {
            Debug.Log(this.gameObject.activeSelf);
            if(this.gameObject.activeSelf)
            {
                this.gameObject.SetActive(false);
            }
            else
            {
                this.gameObject.SetActive(true);
            }
        }
    }
}

If you disable the game object that hold the script, it can't work anymore since it's not active, That's why you can hide the object. but not wake it up.

Use a TargetGameObject field, that you'll enable/disable. Like this:

public class EnvironmentSettings : MonoBehaviour
{
    public GameObject TargetGameObject;

    private void Update()
    {
        if (Input.GetMouseButtonDown(1))
            TargetGameObject.SetActive(!TargetGameObject.activeSelf);
    }
}

Put this script on a GameManger, or at least something that won't be disabled during play time, such as the main camera. Then slide your TargetGameObject to toggle into the field from the scene view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM