【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);
    }
}
相关推荐
孙严Pay20 小时前
快捷支付:高效安全的在线支付新选择
笔记·科技·计算机网络·其他·微信
じ☆冷颜〃20 小时前
黎曼几何驱动的算法与系统设计:理论、实践与跨领域应用
笔记·python·深度学习·网络协议·算法·机器学习
想进部的张同学21 小时前
hilinux-3599---设备学习---以及部署yolo
学习·yolo·海思
HyperAI超神经21 小时前
【vLLM 学习】Rlhf
人工智能·深度学习·学习·机器学习·vllm
数据皮皮侠AI1 天前
上市公司股票名称相似度(1990-2025)
大数据·人工智能·笔记·区块链·能源·1024程序员节
yuhaiqun19891 天前
学服务器训练AI模型:5步路径助力高效入门
运维·服务器·人工智能·笔记·机器学习·ai
雍凉明月夜1 天前
深度学习网络笔记Ⅳ(Transformer + VIT)
笔记·深度学习·transformer
一只一只1 天前
Unity之协程
unity·游戏引擎·协程·coroutine·startcoroutine
做cv的小昊1 天前
【TJU】信息检索与分析课程笔记和练习(7)数据库检索—Ei
数据库·笔记·学习·全文检索
AI360labs_atyun1 天前
上海打出“开源”国际牌!2025重磅新政
人工智能·科技·学习·ai·开源