Unity C# 基础 Events(事件)

事件 Events

事件(Events) 包含 发布者(Publishers) 和 订阅者(Subscribers)

多个订阅者可以订阅同一事件,当发生事件时,发布者 会触发该事件,所有订阅者都会收到事件被触发的通知

特性

发布者不知道有几个订阅者,发布者只管发送,而接收者只管接收

基础示例

/*发布者*/
public class TEvents : MonoBehaviour
{
	//事件处理程序
	public event EventHandler OnSpacePressed;

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //if(OnSpacePressed != null)
            //{
            //    OnSpacePressed(this, EventArgs.Empty);
            //}

        	//?.Invoke [空值传播运算符] 若event不为null则Invoke
            OnSpacePressed?.Invoke(this, EventArgs.Empty); 

        }
    }
}
/*订阅者*/
public class TEventSubscriber : MonoBehaviour
{

    public TEvents tEvents;

    private void Start()
    {
        //注册方法
        tEvents.OnSpacePressed += Test_OnSpacePressed;
        //注销方法
        //tEvents.OnSpacePressed -= Test_OnSpacePressed;
    }

    /// <summary>
    /// 订阅者收到事件触发通知时调用的方法
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Test_OnSpacePressed(object sender, EventArgs e)
    {
        Debug.Log("订阅者 空格!");
    }


}

进阶示例

自定义事件的类(标准流程)

/*发布者*/
public class TEvents : MonoBehaviour
{
	//事件处理程序
	public event EventHandler<OnSpacePressedEventArgs> OnSpacePressed;

    /// <summary>
    /// 自定义事件类
    /// </summary>
    public class OnSpacePressedEventArgs : EventArgs
    {
        public int SpaceCount;
    }

    private int spaceCount = 0;

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
        	spaceCount++;
            OnSpacePressed?.Invoke(this, new OnSpacePressedEventArgs { SpaceCount = spaceCount});
        }
    }
}
/*订阅者*/
public class TEventSubscriber : MonoBehaviour
{

    public TEvents tEvents;

    private void Start()
    {
        tEvents.OnSpacePressed += Test_OnSpacePressed;
    }

    private void Test_OnSpacePressed(object sender, TEvents.OnSpacePressedEventArgs e)
    {
        Debug.Log($"订阅者 空格! {e.SpaceCount}");
    }

}

事件本质是一种委托,自定义委托

/*发布者*/
public class TEvents : MonoBehaviour
{
	//事件处理程序
	public event TestEventDelegate OnFloatEvent;

    //定义个自定义委托
    public delegate void TestEventDelegate(float f);

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            OnFloatEvent?.Invoke(12.3f);
        }
    }
}
/*订阅者*/
public class TEventSubscriber : MonoBehaviour
{

    public TEvents tEvents;

    private void Start()
    {
        tEvents.OnFloatEvent += Test_OnFloatEvent;
    }

    private void Test_OnFloatEvent(float f)
    {
        Debug.Log($"Float Event: {f}");
    }

}

使用Action (Action 是Unity封装的委托类型,没有返回值,可以带参数)

/*发布者*/
public class TEvents : MonoBehaviour
{
	//事件处理程序
	public event Action<bool, int> OnActionEvent;

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            OnActionEvent?.Invoke(true, 12);
        }
    }
}
/*订阅者*/
public class TEventSubscriber : MonoBehaviour
{

    public TEvents tEvents;

    private void Start()
    {
        tEvents.OnActionEvent += Test_OnActionEvent;
    }

    private void Test_OnActionEvent(bool arg1,int arg2)
    {
        Debug.Log($"{arg1} {arg2}");
    }

}

UnityEvent

方便在编辑器操作

/*发布者*/
public class TEvents : MonoBehaviour
{
	//事件处理程序
	public UnityEvent OnUnityEvent;

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            OnUnityEvent?.Invoke();
        }
    }
}
/*订阅者*/
public class TEventSubscriber : MonoBehaviour
{

    public void Test_UnityEvent()
    {
        Debug.Log("UnityEvent!");
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
The powerful, top-rated dialogue system used in Disco Elysium, Crossing Souls, Jenny LeClue, Last Epoch, The Last Door, and many many more, the Dialogue System for Unity makes it easy to add interactive dialogue and quests to your game. It’s a complete, robust solution including a visual node-based editor, dialogue UIs, cutscenes, quest logs, save/load, and more. The core is a lean, efficient conversation system. A large collection of included, optional add-ons make it quick and easy to drop conversations into your project and integrate them with other assets. No scripting required. Complete C# source included. Demo | Docs | Tutorials | Forum Free Extras | Free Trial Cinemachine & Timeline Integration! Editor: Visual, node-based dialogue editor Importers for Chat Mapper, articy:draft 1/2/3, Twine, Ink, Neverwinter Nights, Talkit, and CSV Export screenplay format, voiceover asset list, CSV, Chat Mapper, and more I2 Localization support Engine: Dynamic, branching conversation trees Barks and alerts Cutscenes (audio, animation, etc.) Quick Time Events (QTEs) Quest system NPC status & relationship system Easy language localization Save/load without scripting Optional Lua scripting and variable system Comprehensive documentation and tutorials Runtime UIs: GUI-independent; works with all GUI systems, including Unity UI & NGUI Built-in support for Unity UI, NGUI, TextMesh Pro, legacy Unity GUI, & more Input system-independent; works with Unity Input, Rewired, New Input System, etc Modular interfaces: swap in your own UI or cutscene system Several beautiful, fully-customizable UI skins Detailed sci-fi environment & animated model Works in 2D and 3D Works in VR (Oculus Rift, Vive, GVR, etc.) Integration: Components for drop-in integration into existing frameworks Cinemachine & Timeline Action-RPG Starter Kit Adventure Creator Animator Timeline Editor articy:draft Behavior Designer Bolt Visual Scripting
Unity框架的事件系统是一个重要的功能,可以让不同的对象之间进行通信和协作。这个系统基于发布订阅模式,其中有两种主要类型的事件Unity事件C#事件Unity事件是一种内置的事件类型,可以在Unity编辑器中创建和配置。例如,当游戏对象被点击或启用时,可以触发Unity事件C#事件是一种自定义事件类型,可以在代码中定义和使用。例如,当游戏对象的状态发生变化时,可以触发C#事件Unity事件C#事件之间的关系是:Unity事件可以触发C#事件,而C#事件可以调用Unity事件。这种交互可以帮助开发者更好地管理游戏对象之间的通信和协作。 Unity事件的实现方式是通过UnityEvent类,它可以在代码中声明和使用。例如,以下是一个简单的示例: ``` using UnityEngine; using UnityEngine.Events; public class MyEvent : MonoBehaviour { public UnityEvent myEvent; void Start() { myEvent.AddListener(MyEventHandler); } void MyEventHandler() { Debug.Log("My event was triggered!"); } } ``` 在这个示例中,我们创建了一个名为“myEvent”的Unity事件,并将其添加到了“MyEventHandler”方法中。当事件被触发时,我们会在控制台中输出一条消息。 C#事件的实现方式是通过EventHandler委托和event关键字。例如,以下是一个简单的示例: ``` using UnityEngine; using System; public class MyEvent : MonoBehaviour { public event EventHandler myEvent; void Start() { myEvent += MyEventHandler; } void MyEventHandler(object sender, EventArgs e) { Debug.Log("My event was triggered!"); } } ``` 在这个示例中,我们创建了一个名为“myEvent”的C#事件,并将其添加到了“MyEventHandler”方法中。当事件被触发时,我们会在控制台中输出一条消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值