一、观察者模式
1、不断的询问
游戏开发场景:
1、播放一个大招,在0.5秒时播放一个音效
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObserverBase : MonoBehaviour
{
//此部分为伪代码
Animation animation;
float timeCount = 0;
// Start is called before the first frame update
void Start()
{
animation = GetComponent<Animation>();
}
// Update is called once per frame
void Update()
{
if (!animation.isPlaying)
{
//do something
}
timeCount += Time.deltaTime;
//一直询问是否满足条件
if (timeCount > 0.5)
{
timeCount = 0;
PlayBigAttack();
}
}
public void PlayBigAttack()
{
animation.Play("BigAttack");
timeCount = 0;
}
}
二、代理模式
代理:指向方法的指针
基础铺垫
ProxyMode.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class ProxyMode : MonoBehaviour
{
//代理模式 指向方法的指针
public Button button;
// Start is called before the first frame update
void Start()
{
button = transform.GetComponent<Button>();
//factoryBase = new FactoryBase();//指针指向对象
//分配的空间 在 堆上
button.onClick.AddListener(new UnityAction(OnClick));//new出来的UnityAction对象指向OnClick方法
//分配的空间 在 栈上
//button.OnClick.AddListener(OnClick());
}
// Update is called once per frame
void Update()
{
}
public void OnClick()
{
}
}
正式项目
DelegateBase.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Husband
{
Wife myWife;
public void AddMoney()
{
Debug.Log("AddMoney");
myWife.LeadMoney();
}
public void Notice()
{
Debug.Log("Say Words");
}
public void NoticeTwo()
{
Debug.Log("Say Words Two");
}
}
public class Wife
{
//声明一个委托,委托的名字是 WifeSister 委托是一个方法的类型
public delegate void WifeSister();//简单看成一个特殊的变量。会指向方法
public WifeSister wifeSister;
//取钱
public void LeadMoney()
{
Debug.Log("LeadMoney");
}
public void SayBadWord()
{
Debug.Log("SayBadWord");
wifeSister();
}
}
public class DelegateBase : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Husband tmpHuaband = new Husband();
tmpHuaband.AddMoney();
Wife tmpWife = new Wife();
//多播
tmpWife.wifeSister += tmpHuaband.Notice;
tmpWife.wifeSister += tmpHuaband.NoticeTwo;
tmpWife.SayBadWord();
}
// Update is called once per frame
void Update()
{
}
}