【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);
    }
}
相关推荐
HugoStudio_SWAN33 分钟前
洛谷 B4450 / B3867 / B3923 智慧购物、储蓄与做题——从程序到生活
c++·学习·程序人生·算法·生活
猎头南楼2 小时前
VLA 模型落地端侧:从架构选型到量化部署的工程实践笔记
笔记·架构·大模型
Capricorn19883 小时前
日志级幻觉排障:GPT-6 Astra 迈入 AGI 时代,知芽 Notebook Skill 如何以引用校验与零命中诚实弃权解决长文失忆
论文阅读·人工智能·笔记·gpt·agi
UIU1143 小时前
scanf与cout的误区:探究其内部的机制
c++·学习·c#·scanf
wgslucky3 小时前
Godot GDScript初学者遇到的问题记录
游戏引擎·godot
疯狂打码的少年3 小时前
【数据库技术】多值依赖与第四范式(4NF)
数据库·笔记·算法
tq10863 小时前
算法的另一面
笔记
点心的游戏开发世界5 小时前
GDScript 入门笔记(五):函数
笔记·游戏引擎·godot
SmalBox6 小时前
01-01-认知篇-概念-YooAsset是什么
unity3d·游戏开发
wp123_17 小时前
硬件设计笔记:1μH功率电感选型实战——线艺 XFL4020-102MEC 与 国产 pin to pin MVLH4020-1R0M 详细参数测评
笔记·科技·硬件架构·硬件工程