繁体   English   中英

C#/Unity - 如何使用枚举在 Scriptable Object 中制作混合/多个 select 菜单

[英]C#/Unity - How to make mixed/multiple select menu in Scriptable Object with enum

这是我的可编写脚本的 object:

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

[CreateAssetMenu(fileName = "New Armory Item", menuName = "Model Manager/New Armory Item")]
[Serializable]
public class ArmoryItemSO : ScriptableObject
{
    public int id;
    public GameObject mesh;
    public RaceBodySlot hidesBodySlot;
    public Textures textures;
}

public enum RaceBodySlot
{
    None,
    Head,
    Torso,
    Arms,
    Hands,
    Thighs,
    Legs,
    Feet,
    Tail,
    MainHand,
    OffHand
}

在编辑器中,我有 hidesBodySlot 的hidesBodySlot菜单。 但是在那个 select 菜单中我只能选择一个选项。 我怎样才能做到这一点,以便我可以选择多个?

之后如何获得hidesBodySlot的所有选定选项?

在枚举上使用flags属性

[Flags]
public enum RaceBodySlot
{
    None = 0,   // or define values via bit shifts:
    Head = 1,   // 1 << 0
    Torso = 2,  // 1 << 1
    Arms = 4,   // 1 << 2
    Hands = 8,  // 1 << 3

    ....

使用[Flags] Unity 也会自动添加“Everything”选项

使用[Flags] Unity 还会为其添加一个“Nothing”选项(为 0),如果您的枚举中没有选项为0

该解决方案使用单个位的逐位比较。 所以0总是意味着“无”(因为没有设置任何位)。

  • 在此示例中, Head的二进制表示为: 0001
  • 在此示例中, Torso将具有以下二进制表示: 0010
  • 在此示例中, Arms的二进制表示为: 0100
  • ...

这就是使用二的倍数很重要的原因。

要检查是否设置了这样的单个位或通过代码创建一些组合,请参见下文:

public static class RaceBodySlotExtensions
{
    RaceBodySlot AddSlot(this RaceBodySlot self, RaceBodySlot other)
    {
        return self | other;
    }

    RaceBodySlot RemoveSlot(this RaceBodySlot self, RaceBodySlot other) 
    {
        return self & ~flag;
    }
        
    public static bool HasFlag(this RaceBodySlot self, RaceBodySlot flag){
        return (self & flag) == flag;
    }

}

使用此扩展方法(另请参阅扩展 class ),您可以在代码中使用它们

myItem.hidesBodySlot.HasFlag(RaceBodySlot.Head)

或者

myItem.hidesBodySlot = (RaceBodySlot.Head).AddSlot(RaceBodySlot.Torso)

暂无
暂无

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

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