提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
unity开发者模式__状态模式
state目录下的脚本就是我们在不改变整体项目结构的情况下可以添加自己想要的状态
** 接下来看看这几个脚本分别代表什么,其中是如何去构建的**
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//管理接口的脚本
public interface Istate
{
void Way();
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//可以理解为当前最新状态的管理控制类
public class Context : MonoBehaviour
{
private Istate curState;
//刷新主控制类中的当前状态
public void SetState(Istate state)
{
curState = state;
// Show();
}
//当前状态的切换方法,当然也可以在刷新当前状态的 SetState方法中就选择调用 看个人需求
public void Show()
{
curState.Way();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Run : Istate
{
private Context _context;
public Run(Context c)
{
_context = c;
}
public void Way()
{
_context.SetState(new Walk(_context));
Debug.Log("当前状态切换到------>走");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walk : Istate
{
private Context _context;
public Walk(Context c)
{
_context = c;
}
public void Way()
{
_context.SetState(new Run(_context));
Debug.Log("切换状态到----->跑");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//多个状态来回切换
//1.需要一储存当前状态和行为的控制类 2.每个状态要去实现的方法继承接口 3.多个状态的脚本去实现同一个接口方法
public class Main: MonoBehaviour
{
void Start()
{
Context context = new Context();
context.SetState(new Walk(context));
context.Show();
context.SetState(new Run(context));
context.Show();
}
}
输出后的结果: