Unity ExecuteEvents 消息系统
更多说明: https://docs.unity.cn/cn/current/Manual/MessagingSystem.html
例:假设现在有一辆车(Car)进入停车位(ParkingSpace),在停车位这个类里已经写好车是否进入的逻辑,然后想把车已进入这个消息告诉车,为了实现松散耦合,可以用以下方法:
IOnTriggerParkingSpaceHandler.cs
using UnityEngine.EventSystems;
public interface IOnTriggerParkingSpaceHandler : IEventSystemHandler {
void OnTriggerParkingSpaceHandler (ParkingSpace parkingSpace);
}
Car.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Car : MonoBehaviour, IOnTriggerParkingSpaceHandler {
void IOnTriggerParkingSpaceHandler.OnTriggerParkingSpaceHandler (ParkingSpace parkingSpace) {
Debug.Log("OnTriggerParkingSpace");
}
}
ParkingSpace.cs
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
public class ParkingSpace : MonoBehaviour {
private void OnTriggerEnter (Collider other) {
Car car = other.GetComponent<Car>();
if (car) {
ExecuteEvents.Execute<IOnTriggerParkingSpaceHandler>(car.gameObject, null, (x, y) => x.OnTriggerParkingSpaceHandler(this));
}
}
}