观察者模式例子
当主人公的血量为零时,触发多个系统的反应,包括播放死亡动画、播放死亡音效、重置世界数据和更新存档。
1. 定义事件和委托
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public delegate void Pointer(object obj,EventArgs args);
public class Player : MonoBehaviour
{
public event EventHandler PlayerDied;
// Start is called before the first frame update
public int health;
public int Health
{
get { return health; }
set
{
health = value;
if (health <=0 )
{
OnPlayerDied();
}
}
}
public Player()
{
health = 100;
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
protected virtual void OnPlayerDied()
{
PlayerDied?.Invoke(this, EventArgs.Empty);
}
}
2、 定义观察者 音效、世界、动画、缓存系统
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationSystem : MonoBehaviour
{
public void OnPlayerDied(object sender, EventArgs e)
{
Debug.Log("Playing death animation.");
// 实际播放动画的代码
}
}
using UnityEngine;
using System;
public class SoundSystem : MonoBehaviour
{
public void OnPlayerDied(object sender, EventArgs e)
{
Debug.Log("Playing death sound effect.");
// 实际播放音效的代码
}
}
using UnityEngine;
using System;
public class WorldSystem : MonoBehaviour
{
public void OnPlayerDied(object sender, EventArgs e)
{
Debug.Log("Resetting world data.");
// 实际重置世界数据的代码
}
}
using UnityEngine;
using System;
public class SaveSystem : MonoBehaviour
{
public void OnPlayerDied(object sender, EventArgs e)
{
Debug.Log("Updating save data.");
// 实际更新存档的代码
}
}
3. 订阅事件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
AnimationSystem animationSystem = gameObject.AddComponent<AnimationSystem>();
SoundSystem soundSystem = gameObject.AddComponent<SoundSystem>();
WorldSystem worldSystem = gameObject.AddComponent<WorldSystem>();
SaveSystem saveSystem = gameObject.AddComponent<SaveSystem>();
Player player = gameObject.AddComponent<Player>();
player.PlayerDied += animationSystem.OnPlayerDied;
player.PlayerDied += soundSystem.OnPlayerDied;
player.PlayerDied += worldSystem.OnPlayerDied;
player.PlayerDied += saveSystem.OnPlayerDied;
}
}