前篇链接:Unity之C#学习笔记(14):委托和事件 Delegates and Events
前一篇中我们已经讲了C#中的委托(不清楚的小伙伴可以点击上面的链接),这节来聊聊两种“特化”的委托:Action和Func。
Action,就是只有参数没有返回值的委托。只有参数意味着函数可以有零个、一个或多个参数,没有返回值,即返回类型为void。Action从字面意义上很好理解,“一个活动”,就是做一件事,做完就行了,不用报告结果。
从一个简单的例子看起:Player脚本当按下空格键时要掉血,同时通知UIManager更新UI,显示当前生命值。使用委托,我们会这样实现:
Player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public delegate void OnDamageReceived(int currentHealth);
public static event OnDamageReceived onDamageReceived;
public int health = 100;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
ReceiveDamage();
}
void ReceiveDamage()
{
health--;
if (onDamageReceived!= null)
onDamageReceived(health);