Files
netease-bedrock-wiki/mcguide/20-玩法开发/13-模组SDK编程/2-Python脚本开发/9-事件简介.md
2024-12-23 10:57:59 +08:00

61 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
front:
hard: 入门
time: 分钟
---
# <span id="事件简介"></span>事件简介
事件依赖于系统事件需要系统才能监听触发因此在使用事件之前需要先拥有自己的系统system。事件分为 监听事件、反监听、发布事件和响应事件。
* 监听事件
监听事件的含义是将回调函数注册到事件上当事件发生时主动调用该回调函数。监听函数ListenForEvent
* 反监听事件
不再需要监听的事件可以使用UnListenForEvent函数取消监听
* 发布事件
发布事件是指在事件发生时发布这个事件通知所有监听了这个事件的回调函数。引擎定义的事件会在引擎事件发生时自动发布自定义事件的发布需要在需要的地方进行发布需要先CreateEventData创建事件数据发布函数有BroadcastEvent / NotifyToClient / BroadcastToAllClient / NotifyToServer.
* 响应事件
上述的发布事件很多都是广播但是不是每条消息都需要每个system都处理因此响应函数只会响应那些监听了这些事件且消息源有发布这些事件的时候才会响应。
响应函数会响应在监听事件时ListenForEvent的参数中的回调函数。**回调函数必须传入一个参数**类型一般为dict不同事件的参数在下面具体事件中进行了说明其中部分参数是可设置参数可以通过修改值来改变事件的结果。
* 示例
```python
class MyClientSystem(ClientSystem):
def __init__(self, namespace, systemName):
ServerSystem.__init__(self, namespace, systemName)
# 注册监听
self.ListenForEvent(clientApi.GetEngineNamespace(), clientApi.GetEngineSystemName(), 'AddEntityEvent', self, self.OnAddEntity)
self.ListenForEvent(clientApi.GetEngineNamespace(), clientApi.GetEngineSystemName(), 'ClientJumpButtonPressDownEvent', self, self.OnClientJumpButtonPressDown)
# 监听回调函数
def OnAddEntity(self, data):
entityId = data["id"]
logger.info("AddEntityEvent callback... data: %s" % data)
def OnClientJumpButtonPressDown(self, data):
# continueJump是可设置参数可设置是否执行跳跃逻辑
data["continueJump"] = False
```
**请勿对引擎事件的回调参数添加自定义的key**,如有需要利用回调参数的字典做其他逻辑,请进行拷贝,例如:
```python
# 某回调函数
def OnAddEntity(self, data):
myData = {
"id": data["id"],
"myKey": "myValue"
}
do_something(myData)
```