【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 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
XiHongShi20165 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
爱吃苹果的日记本5 天前
离散数学第六课
学习·离散数学
SmalBox5 天前
02-07-原理篇-文件系统与跨平台适配
unity3d·游戏开发
只睡四小时5 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
AI职业加油站5 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
深圳老胡5 天前
STM32F407 控制 L6470 步进电机驱动 —— 控制过程简介
笔记·stm32·单片机·嵌入式硬件·代码规范
旖旎夜光5 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
奇思妙想聪明勤奋的小羊5 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型