
Unity 基础 之 Enum(enum) 枚举 的简单介绍,和枚举变量同时赋值多个值,并且分解枚举变量包含多个值
目录
Unity 基础 之 Enum(enum) 枚举 的简单介绍,和枚举变量同时赋值多个值,并且分解枚举变量包含多个值
一、简单介绍
Unity中的一些基础知识点。
本节简单介绍给枚举值赋值多个值,和分解包含的多个枚举值。
二、什么是枚举 Enum (enum)
枚举是值类型,数据直接存储在栈中,而不是使用引用和真实数据的隔离方式来存储。
(1)默认情况下,枚举中的第一个变量被赋值为0,其他的变量的值按定义的顺序来递增(0,12,3...),因此以下两个代码定义是等价的:
enum TrafficLight
{
Green,
Yellow,
Red
}
enum TrafficLight
{
Green = 0,
Yellow = 1,
Red = 2
}
(2)enum枚举类型的变量的名字不能相同,但是值可以相同
enum TrafficLight
{
Green = 0,
Yellow = 1, // Duplicate value, OK
Red = 1 // Duplicate value, OK
}
(3)如果enum中的部分成员显式定义了值,而部分没有;那么没有定义值的成员还是会按照上一个成员的值来递增赋值,例如:
enum LoopType
{
None, // value is 0
Daily, // value is 1
Weekly = 7,
Monthly, // value is 8
Yeayly, // value is 9
DayGap = 15,
WeekGap, // value is 16
MonthGap, // value is 17
YearGap // value is 18
}
三、枚举变量赋值多个值
enum枚举成员可以用来作为位标志,同时支持位的操作(位与,位或等等),所以使用 位或操作,就可以实现给枚举变量同时赋值多个值
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace TestSpace {
[Flags]
public enum MySelect {
None,
Yes,
No
}
public enum TransformType
{
/// <summary>
/// No transform.
/// </summary>
None = 0,
/// <summary>
/// Translation.
/// </summary>
Translation = 0x1,
/// <summary>
/// Rotation.
/// </summary>
Rotation = 0x2,
/// <summary>
/// Scaling.
/// </summary>
Scaling = 0x4
}
public class TestEnum : MonoBehaviour
{
TransformType mCurTransformType = TransformType.Rotation | TransformType.Scaling;
MySelect mCurMySelect = MySelect.No | MySelect.Yes;
// Start is called before the first frame update
void Start()
{
Debug.Log(GetType()+ "/Start()/ mCurMySelect : " + mCurMySelect);
Debug.Log(GetType()+ "/Start()/ mCurTransformType : " + mCurTransformType);
mCurTransformType |= TransformType.Translation;
Debug.Log(GetType() + "/Start()/ mCurTransformType : " + mCurTransformType.ToString());
}
}
}
结果:刚好是几个值的或运算结果(注意使用 System.Flags 属性标记打印的不同结果)

四、分解出枚举变量包含的多个值
就是把之前位或的多个值解析出来
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace TestSpace {
[Flags]
public enum MySelect {
None,
Yes,
No
}
public enum TransformType
{
/// <summary>
/// No transform.
/// </summary>
None = 0,
/// <summary>
/// Translation.
/// </summary>
Translation = 0x1,
/// <summary>
/// Rotation.
/// </summary>
Rotation = 0x2,
/// <summary>
/// Scaling.
/// </summary>
Scaling = 0x4
}
public class TestEnum : MonoBehaviour
{
TransformType mCurTransformType = TransformType.Rotation | TransformType.Scaling;
MySelect mCurMySelect = MySelect.No | MySelect.Yes;
// Start is called before the first frame update
void Start()
{
//Debug.Log(GetType()+ "/Start()/ mCurMySelect : " + mCurMySelect);
//Debug.Log(GetType()+ "/Start()/ mCurTransformType : " + mCurTransformType);
//mCurTransformType |= TransformTyp

本文详细介绍Unity中枚举的使用,包括枚举的基本概念、如何给枚举变量赋值多个值及如何分解这些值。此外还提供了多种枚举的实用技巧和应用场景。
1375

被折叠的 条评论
为什么被折叠?



