You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将第二个脚本的Int值传入第一个脚本的Bool数组实现武器类型识别?

解决方案

1. 修正类名冲突

第二个脚本的类名与第一个重复,必须改为WeaponSwitching以避免编译错误,同时优化武器状态更新逻辑:

public class WeaponSwitching : MonoBehaviour
{
    public int selectedWeapon = 0;
    // 直接在Inspector面板拖拽Player对象赋值,提升性能
    public GameObject Player;

    void Update()
    {
        UpdateWeaponStatus();
    }

    void UpdateWeaponStatus()
    {
        WeaponController weaponController = Player.GetComponent<WeaponController>();
        if (weaponController == null) return;

        // 先重置所有武器状态为未选中
        for (int i = 0; i < weaponController.CurrentWeapon.Length; i++)
        {
            weaponController.CurrentWeapon[i] = false;
        }

        // 确保选中索引在数组有效范围内,避免越界
        if (selectedWeapon >= 0 && selectedWeapon < weaponController.CurrentWeapon.Length)
        {
            // 将选中武器对应的数组位置设为true
            weaponController.CurrentWeapon[selectedWeapon] = true;
        }
    }
}

2. 优化WeaponController脚本同步逻辑

原脚本仅在初始化时同步数组与单个武器变量,后续数组变化时变量不会更新,改为实时同步:

public class WeaponController : MonoBehaviour
{
    public bool[] CurrentWeapon = new bool[2];

    public bool Wrench;
    public bool Pistol;

    void Update()
    {
        // 实时同步数组状态到单个武器变量
        Wrench = CurrentWeapon[0];
        Pistol = CurrentWeapon[1];
    }
}

核心逻辑说明

  • 每次更新时先重置所有武器状态,确保同一时间只有当前选中的武器处于激活状态
  • 增加索引范围检查,避免数组越界报错
  • 采用拖拽赋值Player对象的方式,替代Update中频繁调用GetComponent,提升运行效率

内容的提问来源于stack exchange,提问作者Alexey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 16:36:11