委托事件
定义委托:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//定义委托
public delegate void HPDelegate(int value);
public delegate void MPDelegate(float value);
声明事件
public class PlayController : MonoBehaviour
{
private int hp=100;
private float mp=100;
public static PlayController instance;
private void Awake()
{
instance = this;
}
//事件声明
public event HPDelegate hpDel;
public event MPDelegate mpDel;
注册事件
public class HPLable : MonoBehaviour
{
private Transform m_transform;
private Text hpLabel;
void Start()
{
m_transform = gameObject.GetComponent<Transform>();
hpLabel= m_transform.Find("Label").GetComponent<Text>();
PlayController.instance.hpDel += UpdateHP;//注册事件
}
private void UpdateHP(int vlaue)
{
hpLabel.text = vlaue.ToString();
}
}
使用事件
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
HP--;
Debug.Log("HP:" + HP);
hpDel(HP);//使用事件
}
if (Input.GetKeyDown(KeyCode.B))
{
MP--;
Debug.Log("MP:" + MP);
mpDel(MP);
}
}