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

Unity开发遇CS1525错误:Unexpected symbol `else' 求排查修复

解决CS1525: Unexpected symbol else错误

我一眼就发现问题所在了——你在IsLevelUnlocked方法里的if语句块中多写了一个多余的大括号,导致编译器无法正确识别else对应的if结构,这就是报错的核心原因。

错误根源

来看你代码里的这段问题代码:

if (level <= Application.levelCount - 1) {
    {  // 这里是多余的大括号!完全不需要它
        return isLevelUnlocked;
    } else {
        Debug.LogError("Trying to unlock level that isn't in build settings");
        return false;
    }
}

当你在if的第一个大括号后额外加了一个{,编译器会认为这个if语句块已经被提前闭合(包裹return isLevelUnlocked;的那个}就是闭合标记),后面的else就找不到它对应的if了,所以直接抛出了Unexpected symbol 'else'的错误。

修正后的完整代码

只需要删掉那个多余的大括号即可,下面是修复好的完整代码:

using UnityEngine; 
using System.Collections; 

public class PlayerPrefsManager : MonoBehaviour { 
    const string MASTER_VOLUME_KEY = "master_volume"; 
    const string DIFFICULTY_KEY = "difficulty"; 
    const string LEVEL_KEY = "level_unlocked_"; 

    public static void SetMasterVolume(float volume) { 
        if (volume > 0f && volume < 1f) { 
            PlayerPrefs.SetFloat(MASTER_VOLUME_KEY, volume); 
        } else { 
            Debug.LogError("Master volume out of range"); 
        } 
    } 

    public static float GetMasterVolume() { 
        return PlayerPrefs.GetFloat(MASTER_VOLUME_KEY); 
    } 

    public static void UnlockLevel (int level) { 
        if (level <= Application.levelCount - 1) { 
            PlayerPrefs.SetInt(LEVEL_KEY + level.ToString(), 1); //Use 1 for true 
        } else { 
            Debug.LogError("Trying to unlock level that isn't in build settings"); 
        } 
    } 

    public static bool IsLevelUnlocked(int level) { 
        int levelValue = PlayerPrefs.GetInt(LEVEL_KEY + level.ToString()); 
        bool isLevelUnlocked = (levelValue == 1); 
        if (level <= Application.levelCount - 1) { 
            return isLevelUnlocked; 
        } else { 
            Debug.LogError("Trying to unlock level that isn't in build settings"); 
            return false; 
        } 
    } 
}

替换后编译器就能正确解析你的if-else逻辑,这个错误也就消失了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:10:39