【Unity笔记02】订阅事件-自动开门

流程

当玩家移动到触发区域的时候,门自动打开

事件系统

cs 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EventSystem : MonoBehaviour
{
    public static EventSystem Instance { get; private set; }
    public event Action<int> onDoorEnter;
    public event Action<int> onDoorExit;
    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            
        }
        else
        {
            Destroy(gameObject);
        }
        Debug.Log("EventSystem initialized.");
    }


    public void OpenDoor(int id)
    {
        if (onDoorEnter != null)
        {
            onDoorEnter(id);
        }
    }
    public void CloseDoor(int id)
    {
        if(onDoorExit != null)
        {
            onDoorExit(id);
        }
    }
}

门-订阅事件,取消订阅

当物体销毁的时候要取消订阅

订阅事件的时候,接受参数的方法要一样

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class Door : MonoBehaviour
{
    [SerializeField] private int ID;
    private Vector3 originPos;
    public void Start()
    {
        EventSystem.Instance.onDoorEnter += DoorOpen;
        EventSystem.Instance.onDoorExit += DoorClose;
        originPos=gameObject.transform.position;
    }
    private void OnDisable()
    {
        EventSystem.Instance.onDoorEnter -= DoorOpen;
        EventSystem.Instance.onDoorExit -= DoorClose;
    }
    public void DoorOpen(int id)
    {
        if(ID==id)
        {
            Debug.Log("向上移动");
            // 从当前位置向上移动3个单位
            gameObject.transform.DOMove(new Vector3(originPos.x, originPos.y+3f, originPos.z), 1f);
        }
       
    }
    public void DoorClose(int id)
    {
        if (ID==id)
        {
            gameObject.transform.DOMove(originPos, 1f);
        }
        
    }
}

触发区域

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriggerArea : MonoBehaviour
{
    [SerializeField] private int ID;
    private void OnTriggerEnter(Collider other)
    {

        Debug.Log("进入触发区域");
        EventSystem.Instance.OpenDoor(ID);
    }
    private void OnTriggerExit(Collider other)
    {
        EventSystem.Instance.CloseDoor(ID);
    }
}
相关推荐
一只小菜鸡..5 小时前
南京大学 操作系统 (JYY) 学习笔记:进程、系统调用与状态机管理
笔记·学习
DeviceHub5 小时前
硬件工程师选型笔记:ALPS RK12L1230C0K 与 Tonevee RK12L1230C0K 电位器 PIN TO PIN 评估指南
笔记
whyTeaFo6 小时前
GAMES101: Lecture 13: Ray Tracing 1 (Whitted-Style Ray Tracing) ppt笔记
笔记
天国梦8 小时前
2026英语教学系统选型实战:AI如何让备课效率提升42%?天学网技术落地全解析
人工智能·学习
维克兜率天8 小时前
【维克】大数定律与中心极限定理:为什么长期均值终将回归?
经验分享·学习·金融·概率论
中微极客9 小时前
降维算法75倍加速:从PCA到稀疏字典学习的工程实践
人工智能·学习·算法
吃好睡好便好10 小时前
MATLAB中图像的读取、写入和显示
开发语言·图像处理·学习·计算机视觉·matlab
~kiss~10 小时前
大模型中的强化学习算法和对齐算法的区别
学习
MartinYeung511 小时前
[论文学习]InjecAgent:工具集成大语言模型智能体的间接提示注入基准测试
网络·学习·语言模型
XS03010611 小时前
SpringMVC核心知识点实操笔记
笔记