![](/img/trans.png)
[英]Unity C# scriptable object with an instance of a serializable scriptable object
[英]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.