首页 > 其他分享 >枚举、Flags和位运算符

枚举、Flags和位运算符

时间:2022-09-24 13:01:02浏览次数:49  
标签:int enum 运算符 枚举 Flags attackType static public

如果你是一个游戏开发者,你可能很熟悉描述一个特性的不同变化的需要。无论它是哪种攻击类型(近战、冰、火、药丸。。。),或是敌人的状态(空闲、警戒、追逐、攻击、休息。。。),你都无法避免。实现这一点最简单的方法就是使用常量:

public static int NONE = 0;
public static int MELEE = 1;
public static int FIRE = 2;
public static int ICE = 3;
public static int POISON = 4;

public int attackType = NONE;

缺点就是你无法实际控制分配给attackType的值。它可能是整型值,你也可以做点危险的事情,比如attackType++。

枚举构造

幸运的是,C#有个构造叫做enum(结构体),它专门为以下情况进行设计的:

 1 // Outside your class
 2 public enum AttackType {
 3     None,
 4     Melee,
 5     Fire,
 6     Ice,
 7     Poison
 8 }
 9 
10 // Inside your class
11 public AttackType attackType = AttackType.None;

enum的定义创建了一种仅支持限定范围或限定值的类型。为清晰起见,这些值被赋予符号标签,并且在需要的时候做为sting进行返回:

1 attackType = AttackType.Poison;
2 Debug.Log("Attack: " + attackType); # Prints "Attack: Poison"

在内部,每个标签都有一个整型值。枚举从0开始,每个标签被分配给下一个整数值。None是0,Melee是1,Fire是2,以此类推。你可以显式地更改标签的值。

1 public enum AttackType {
2     None,     // 0
3     Melee,    // 1
4     Fire,     // 2
5     Ice = 4,  // 4
6     Poison    // 5
7 }

将enum类型转换为int类型会返回它的整型值。公平来说,枚举实际上就是整数。

枚举之所以如此有趣,是因为它们自动集成在Unity检查器中。

标签:int,enum,运算符,枚举,Flags,attackType,static,public
From: https://www.cnblogs.com/chenlight/p/16725412.html

相关文章