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

Unity调换方法内代码顺序后Debug日志不输出及不可达代码告警原因咨询

问题原因说明

调整前后代码对比

原正常运行代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyCharater : MonoBehaviour
{
    void Start()
    {
        int charaterLevel = 12;
        int nextSkillLevel = GenerateCharater("Spike", charaterLevel);
        Debug.Log(nextSkillLevel);
        Debug.Log(GenerateCharater("Jet", charaterLevel));
    }

    // 原方法实现
    public int GenerateCharater(string name, int level)
    {
        Debug.LogFormat("Charater: {0} - level: {1}", name, level);
        return level + 5;
    }
}

调整顺序后报错的代码

// 修改后的方法实现
public int GenerateCharater(string name, int level)
{
    return level + 5;
    // 第18行:后续不会执行的Debug代码
    Debug.LogFormat("Charater: {0} - level: {1}", name, level);
}

错误根因

  • C# 语法规定,return 是方法终止语句,执行到return后会立刻将返回值传递给调用方,终止当前方法的运行,return之后的所有代码都不会被执行。
  • 你调换两行代码顺序后,return 语句出现在Debug.LogFormat之前,编译器在编译阶段就能识别到这行Debug代码处于不可达路径,因此抛出*Unreachable code detected(检测到不可达代码)*的告警,控制台自然不会输出对应日志。
  • 原代码中先执行日志打印、再返回结果,所有代码都在可达执行路径上,因此运行无异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:54:03