如何在Unity中动态在公共变量和私有变量之间切换

问题描述

我在Unity C#中编写了以下脚本。

Test.cs

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

public class Test : MonoBehavIoUr
{

    public bool showParams = true;
    public int test1 = 100;
    public string test = "";
    
    // Use this for initialization
    void Start()
    {
    }

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

    }
}

我想通过打开/关闭showParams变量来切换是否在检查器中显示其他参数。

如下图所示,当showParams为ON时,所有变量都是公共的。

enter image description here

如下图所示,我想防止在showParams为OFF时显示所有变量。

enter image description here

我想通过打开/关闭showParams变量来切换是否在检查器中显示其他参数。

如下图所示,当showParams设置为ON时,所有变量都是公共的。

如下图所示,我想防止在showParams为OFF时显示所有变量。

Unity C#是否可以?

解决方法

您需要为您的类编写一个自定义编辑器才能执行此操作。在代码编译之后,您不能更改类的成员的访问修饰符(公共和私有),这需要发生,以便它们出现在检查器中。

请参见docs for how to write a custom editor

,

正如其他人指出的那样,该选项不是Unity内置的。您将必须编写自己的自定义检查器或属性抽屉。

幸运的是,在您面前,有很多人都遇到过同样的问题,因此,互联网上有多个Unity编辑器扩展可以做到这一点。您可以在Google或Github中搜索“联合条件隐藏”以找到它们。 我个人认为有用的是https://github.com/krishx007/ConditionalHideAttribute_Unity