-3
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.

Liu_064
  • 33
  • 4
  • 1
    Because the return statement ends execution of the method and returns to the called. All following statements in the method are skipped. – Klaus Gütter Sep 29 '21 at 03:26
  • The 'return' is a command to return the value from the function, anything past it will not get executed. If return is called, the function is considered done by the compiler. –  Sep 29 '21 at 03:26

2 Answers2

0

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.

Higg Higg
  • 79
  • 8
0

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)