根据浮生梦老师前端课程内容,获取选中目标名称可以通过以下步骤实现:
首先需要注册目标改变事件,然后在事件回调中获取目标数据:
```lua
-- 注册目标改变事件
SL:RegisterLUAEvent(LUA_EVENT_TARGET_CAHNGE, "YourModuleName", OnTargetChange)
-- 目标改变事件回调函数
function OnTargetChange()
-- 获取当前选中的目标ID
local targetID = MainTarget._targetID -- 或者使用其他方式获取目标ID
if targetID and targetID > 0 then
-- 通过目标ID获取角色数据
local actor = SL:GetMetaValue("ACTOR_DATA", targetID)
if actor then
-- 获取目标名称
local targetName = SL:GetMetaValue("ACTOR_NAME", actor)
if targetName then
SL:Print("选中的目标名称是:" .. targetName)
return targetName
end
end
end
SL:Print("没有选中目标或目标不存在")
return ""
end
```
或者如果你已经有一个目标ID,可以直接这样获取:
```lua
local targetID = 12345 -- 假设的目标ID
local actor = SL:GetMetaValue("ACTOR_DATA", targetID)
if actor then
local targetName = SL:GetMetaValue("ACTOR_NAME", actor)
SL:Print("目标名称:" .. targetName)
end
```
**关键点说明:**
1. `LUA_EVENT_TARGET_CAHNGE` 是目标改变事件(注意拼写是"CAHNGE")
2. `SL:GetMetaValue("ACTOR_DATA", targetID)` 通过ID获取角色数据对象
3. `SL:GetMetaValue("ACTOR_NAME", actor)` 从角色数据中获取名称
在实际使用中,你需要确保目标ID是有效的,并且角色数据存在才能成功获取名称。