Enums(枚举) allow u to create readable selections that are based of integer values and u can use them in a English format when you’re writing codes.
C# Enums
枚举声明方式如下
public enum LevelSelector{
Easy, //0
Normal, //1
Hard, //2
Expert //3
};
public LevelSelector currentLevel;
private void Start()
{
currentLevel = LevelSelector.Hard;
}
每个枚举元素的值默认按顺序从0到1排下来,也可以自己设定。在inspector的地方我们可以看到currentLevel对应的是一个下拉选择框。
C# Enums: Enemy AI
KEY:
FSM(finite state machine): make ur npc have some sort of intelligence where they have different states such as patrolling, attacking, idling and even a death state.(比如The sims4, 我们的角色会因为某些数值降低啊或者触发某些事件改变心情和行为)我们可以用Enums来设定使用这些状态并用switch来进行状态切换。
举个栗子 比如我们现在有个怪 它的初始状态是巡逻血量1000,在游戏开始后5秒中从巡逻状态改变为追逐状态(其实改变为玩家进入范围内或者受到攻击时开始追逐会更合理(先不管了意思一下 在追逐或者攻击状态(战斗状态)下血量降为0时 怪就领便当了 (可以再加一个当追逐时到一定范围内就开始进攻 反正这边就是一个大概的框架 了解一下
namespace ChapterEnums{
public class EnemyAI : MonoBehaviour
{
public enum EnemyStates{
Patrolling,
Attacking,
Chasing,
Death
}
public EnemyStates currentStates;
public int health;
// Start is called before the first frame update
void Start()
{
currentStates = EnemyStates.Patrolling;
health = 1000;
}
// Update is called once per frame
void Update()
{
switch(currentStates){
case EnemyStates.Patrolling:
Debug.Log("Patrolling");
if(Time.time > 5){
currentStates = EnemyStates.Chasing;
}
break;
case EnemyStates.Attacking:
Debug.Log("Attacking");
if(health <= 0){
currentStates = EnemyStates.Death;
}
break;
case EnemyStates.Chasing:
Debug.Log("Chasing");
if(health <= 0){
currentStates = EnemyStates.Death;
}
break;
case EnemyStates.Death:
health = 0;
Debug.Log("Death");
break;
}
}
}
}
C# Enums: Custom Classes
一个简单的enums的使用
namespace ChapterEnums{
[System.Serializable]
public class Item
{
public string name;
public int id;
public Sprite icon;
public enum ItemTypes{
None,
Weapon,
Consumable
}
public ItemTypes itemType;
public void Action(){
/*
switch(itemType)
{
case ItemTypes.Weapon:
Debug.Log("weapon");
break;
case ItemTypes.Consumable:
Debug.Log("consumable");
break;
default:
Debug.Log("None");
break;
}*/
Debug.Log(itemType);
}
}
}
Casting Enums to Ints
在运行玩家所选择的难度场景时,我们需要用到enums,但是根据enums的值无法来运行场景。这个时候,就要通过索引。
SceneManager.LoadScene()
: 加载场景,可根据场景索引和场景名字进行加载
还是第一节的选择器
using UnityEngine.SceneManagement;
namespace ChapterEnums{
public class SelectDifficulty : MonoBehaviour
{
// Start is called before the first frame update
public enum LevelSelector{
Easy, //0
Normal, //1
Hard, //2
Expert //3
};
public LevelSelector currentLevel;
private void Start()
{
//currentLevel = LevelSelector.Hard;
SceneManager.LoadScene((int)currentLevel);
}
}
}
场景整合:File->Build Settings ->把场景拖入Scenes in Build 可以注意到在Scenes in Build中每个场景后面都有一个索引号 这个是场景的索引(不是枚举那边的索引 如果没有对应上的话就无法跳转或者跳转到其他场景 这一点需要注意一下