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

C#中数组访问首尾时如何实现索引循环回绕(Unity FPS武器切换场景)

问题根源

你出现IndexOutOfBounds错误的核心原因是边界检查的执行顺序完全错误,同时向下切换武器的逻辑没有做负数边界校验:

  • SwitchToNextWeapon方法中,你先执行了current_weapon_index++,然后直接用自增后的索引访问武器数组,最后才做越界判断。当你当前已经持有最后一把武器时,自增后的索引已经等于数组长度,此时直接访问数组就会触发越界,后续的重置索引逻辑根本不会生效。
  • SwitchToPreviousWeapon方法完全没有做边界处理,当你持有第一把武器时执行索引减1,会得到-1的索引值,访问数组同样会触发越界。
  • 额外的潜在问题:数字快捷键逻辑硬编码了0-5的索引,如果你的武器数组长度不足6,按对应数字键也会触发越界错误。

修正后的完整代码

public class WeaponManager : MonoBehaviour
{
    [SerializeField]
    private WeaponHandler[] weapons;

    private int current_weapon_index;

    void Start()
    {
        current_weapon_index = 0;
        weapons[current_weapon_index].gameObject.SetActive(true);
    }

    void Update()
    {
        // 优化数字快捷键逻辑,自动适配武器数组长度,避免硬编码越界
        for (int i = 0; i < Mathf.Min(weapons.Length, 6); i++)
        {
            if (Input.GetKeyDown(KeyCode.Alpha1 + i))
            {
                TurnOnSelectedWeapon(i);
            }
        }

        if(Input.mouseScrollDelta.y > 0)
        {
            SwitchToNextWeapon();
        }

        if (Input.mouseScrollDelta.y < 0)
        {
            SwitchToPreviousWeapon();
        }
    }

    void TurnOnSelectedWeapon(int weaponIndex)
    {
        weapons[current_weapon_index].gameObject.SetActive(false);
        weapons[weaponIndex].gameObject.SetActive(true);
        current_weapon_index = weaponIndex;
    }

    void SwitchToNextWeapon()
    {
        weapons[current_weapon_index].gameObject.SetActive(false);
        // 先更新索引并做边界校验,再访问数组
        current_weapon_index++;
        if (current_weapon_index >= weapons.Length)
        {
            current_weapon_index = 0;
        }
        weapons[current_weapon_index].gameObject.SetActive(true);
    }

    void SwitchToPreviousWeapon()
    {
        weapons[current_weapon_index].gameObject.SetActive(false);
        // 先更新索引并做负数边界校验,再访问数组
        current_weapon_index--;
        if (current_weapon_index < 0)
        {
            current_weapon_index = weapons.Length - 1;
        }
        weapons[current_weapon_index].gameObject.SetActive(true);
    }
}

核心改动说明

  • 调整了SwitchToNextWeapon的代码顺序:先做索引自增和越界重置,再用合法的索引访问武器数组启用对应武器
  • 补充了SwitchToPreviousWeapon的负数边界校验:索引小于0时自动重置为武器数组的最后一个索引,实现循环切换
  • 优化了数字快捷键逻辑:改为循环匹配按键,自动适配武器数组长度,避免硬编码索引导致的越界问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:51:00