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

Unity 2D:重复相似If语句优化需求求助

优化关卡赋值的几种实用方案

方案1:使用数组(最适配你的场景)

把分散的level1~level8变量替换成数组,直接通过索引取值,彻底消除重复判断逻辑,代码简洁还易维护。

修改后的代码:

[SerializeField] private int level;
private GameObject currentLevel;

[Header("Levels")]
// 用数组替代单个变量,在Inspector里按顺序拖入关卡1到关卡8
[SerializeField] private GameObject[] levels;

private void SetCurrentLevel()
{
    // 先做范围检查,避免索引越界导致崩溃(Game Jam里也尽量加上)
    if (level < 1 || level > levels.Length)
    {
        Debug.LogError($"无效关卡编号:{level}");
        return;
    }
    // 数组索引从0开始,所以关卡编号减1对应数组位置
    currentLevel = levels[level - 1];
    // 注意:你原代码里用了`==`(比较运算符),赋值应该用`=`,已经帮你修正
}

操作步骤:在Unity Inspector面板中,把原来的level1到level8按顺序拖进levels数组的元素槽即可。

方案2:使用List(更灵活的扩展方案)

如果后期可能需要动态添加/移除关卡,用List比数组更方便,用法和数组基本一致:

using System.Collections.Generic;
using UnityEngine;

[SerializeField] private int level;
private GameObject currentLevel;

[Header("Levels")]
[SerializeField] private List<GameObject> levels = new List<GameObject>();

private void SetCurrentLevel()
{
    if (level < 1 || level > levels.Count)
    {
        Debug.LogError($"无效关卡编号:{level}");
        return;
    }
    currentLevel = levels[level - 1];
}

方案3:使用字典(适合非连续关卡编号)

如果你的关卡编号不是连续的(比如存在隐藏关卡10、20这类),可以用字典建立编号与关卡对象的映射:

using System.Collections.Generic;
using UnityEngine;

[SerializeField] private int level;
private GameObject currentLevel;

// 可在Awake中初始化映射,或使用第三方可序列化字典插件在Inspector配置
private Dictionary<int, GameObject> levelMap = new Dictionary<int, GameObject>();

private void Awake()
{
    // 手动添加编号与关卡的对应关系
    levelMap.Add(1, level1);
    levelMap.Add(2, level2);
    // ... 其他关卡依次添加
}

private void SetCurrentLevel()
{
    if (levelMap.TryGetValue(level, out var targetLevel))
    {
        currentLevel = targetLevel;
    }
    else
    {
        Debug.LogError($"找不到对应关卡:{level}");
    }
}

Game Jam时间紧张的话,前两种方案足够高效,尤其是数组方案最快捷省心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 14:37:08