如何从具有不同类型参数的函数返回浮点数?

Noo*_*bie 1 c# methods unity-game-engine

我有这个函数,我想传递两个Vector3参数和一个int,所以我可以返回一个浮点值.即使我使用Vector3和int作为参数,我怎么能返回一个浮点值?这是我的代码:

//find other types of distances along with the basic one
public object  DistanceToNextPoint (Vector3 from, Vector3 to, int typeOfDistance)
{
    float distance;
    //this is used to find a normal distance
    if(typeOfDistance == 0)
    {
        distance = Vector3.Distance(from, to);
        return distance;
    }
    //This is mostly used when the cat is climbing the fence
    if(typeOfDistance == 1)
    {
       distance = Vector3.Distance(from, new Vector3(from.x, to.y, to.z));
    }
}
Run Code Online (Sandbox Code Playgroud)

当我用"return"keyworkd替换"object"关键字时,它给了我这个错误; 在此输入图像描述

Soe*_*hay 5

你的代码有两个问题.

  1. 如果要返回对象类型,则需要在使用之前将结果转换为float.
  2. 并非所有代码路径都返回值.

你可以试试这个:

/// <summary>
/// find other types of distances along with the basic one
/// </summary>
public float DistanceToNextPoint (Vector3 from, Vector3 to, int typeOfDistance)
{
    float distance;

    switch(typeOfDistance)
    {
        case 0:
             //this is used to find a normal distance
             distance = Vector3.Distance(from, to);
        break;
        case 1:
             //This is mostly used when the cat is climbing the fence
             distance = Vector3.Distance(from, new Vector3(from.x, to.y, to.z));
        break;
    }

   return distance;
}
Run Code Online (Sandbox Code Playgroud)

变化包括:

  • 返回浮点类型而不是对象
  • 确保所有代码路径都返回浮点类型
  • 重新组织以使用开关