【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);
    }
}
相关推荐
SmalBox16 小时前
【节点】[FresnelEquation节点]原理解析与实际应用
unity3d·游戏开发·图形学
xiezhr17 小时前
米哈游36岁程序员被曝复工当晚猝死出租屋内
游戏·程序员·游戏开发
SmalBox1 天前
【节点】[DielectricSpecular节点]原理解析与实际应用
unity3d·游戏开发·图形学
开维游戏引擎2 天前
开维游戏引擎实例:飞机大战
游戏开发
SmalBox3 天前
【节点】[LinearBlendSkinning节点]原理解析与实际应用
unity3d·游戏开发·图形学
SmalBox3 天前
【节点】[ComputeDeformation节点]原理解析与实际应用
unity3d·游戏开发·图形学
西岸行者4 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky4 天前
Django入门笔记
笔记·django
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意4 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习