Arma 3中AddAction无法识别外部作用域变量的解决求助
问题分析与解决方案
核心问题
Arma 中 addAction 的匿名代码块是在全局作用域触发执行的,无法直接访问 initBillboard.sqf 局部作用域内定义的 _billboard、_images、_updateImage 变量,这就是你遇到「未定义变量」错误的根本原因。
解决思路
将需要跨作用域访问的数据(图片数组、更新函数)存储到广告牌的对象变量中,在 addAction 的代码块里通过触发对象(_this select 0)读取这些变量,即可实现数据共享。
修改后的完整代码
scripts\initBillboard.sqf
params [ ["_billboard", objNull, [objNull]], ["_images", [], [[]]] ]; // 将图片数组、当前索引存储到广告牌的对象变量中 _billboard setVariable ["_images", _images, true]; _billboard setVariable ["_currentIndex", 0, true]; // 重定义更新函数:从对象变量读取依赖数据 private _updateImage = { private _targetBillboard = _this select 0; private _currentIdx = _targetBillboard getVariable "_currentIndex"; private _imageList = _targetBillboard getVariable "_images"; _targetBillboard setObjectTexture [0, _imageList select _currentIdx]; }; // 初始渲染图片 [_billboard] call _updateImage; // 将更新函数也存入对象变量 _billboard setVariable ["_updateImage", _updateImage, true]; // 添加「Next」动作 _billboard addAction ["Next", { private _target = _this select 0; private _currentIdx = _target getVariable "_currentIndex"; private _imageList = _target getVariable "_images"; _currentIdx = _currentIdx + 1; if (_currentIdx >= count _imageList) then { _currentIdx = 0; }; _target setVariable ["_currentIndex", _currentIdx, true]; // 调用更新函数 private _updateFunc = _target getVariable "_updateImage"; [_target] call _updateFunc; }]; // 添加「Previous」动作 _billboard addAction ["Previous", { private _target = _this select 0; private _currentIdx = _target getVariable "_currentIndex"; private _imageList = _target getVariable "_images"; _currentIdx = _currentIdx - 1; if (_currentIdx < 0) then { _currentIdx = (count _imageList) - 1; }; _target setVariable ["_currentIndex", _currentIdx, true]; // 调用更新函数 private _updateFunc = _target getVariable "_updateImage"; [_target] call _updateFunc; }];
关键细节说明
- 对象变量传递数据:使用
setVariable将需要共享的数据绑定到广告牌对象上,getVariable读取,确保跨作用域能访问到数据。 addAction代码块的_this:触发动作时,_this的第一个元素就是当前广告牌对象(_this select 0),以此为入口读取所有绑定的变量。- 更新函数的参数适配:修改
_updateImage函数,通过传入的广告牌对象读取内部变量,避免依赖外部局部作用域。
内容的提问来源于stack exchange,提问作者Assad Rajab
相关产品推荐
相关产品推荐

