Home > front end >  The Debug.Log cannot be detected after changing the order of code [closed]
The Debug.Log cannot be detected after changing the order of code [closed]

Time:09-29

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;
    }
}

The above code runs normally.

But when I changed the order of the two lines of code in the GenerateCharater method, unity reported an alert and displayed "Unreachable code detected" in line 18, and the Debug.Log in line 18 could not be displayed normally in unity.

Please tell me why.

CodePudding user response:

Here's the document:

The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted.

The problem is when you changed the order, the code

Debug.LogFormat("Charater: {0} - level: {1}", name, level);

will be after the return keyword so this code will unreachable

or you can visit this, it already has answer there.

CodePudding user response:

Inside a method, when the return statement is reached, the control goes back to the caller of the method and the codes in the subsequent lines inside the method body are not executed as control never reaches to that line. So any thing after the return statement will not be executed ( different situation occurs for yield return statement)

  • Related