简体   繁体   English

Unity的C#如何右键切换显示/不显示

[英]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.我尝试使用以下代码切换 object 的可见性。

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.但是,第一次右击时,object被隐藏了,但我第二次右击时,却没有显示object。

The object should appear on the second right click. object 应出现在第二次右键单击中。

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.如果你禁用了保存脚本的游戏 object,它就不能再工作了,因为它没有激活,这就是你可以隐藏 object 的原因。 but not wake it up.但不要唤醒它。

Use a TargetGameObject field, that you'll enable/disable.使用您将启用/禁用的 TargetGameObject 字段。 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.将此脚本放在 GameManger 上,或者至少放在游戏期间不会被禁用的东西上,例如主摄像头。 Then slide your TargetGameObject to toggle into the field from the scene view.然后滑动您的 TargetGameObject 以从场景视图切换到该字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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