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

时间:2017-10-05 13:48:50

标签: c# unity3d methods

我有这个函数,我想传递两个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));
    }
}

当我用“return”keyworkd替换“object”关键字时,它会给我这个错误; enter image description here

3 个答案:

答案 0 :(得分:5)

您的代码有两个问题。

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

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

    更改包括:

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

答案 1 :(得分:2)

只需将返回类型从object更改为float,如下所示:

public object  DistanceToNextPoint(...)

要:

public float  DistanceToNextPoint(...)

然后在方法的最后一行返回变量distance

public float DistanceToNextPoint(...){
    // ...
    return distance:
}

答案 2 :(得分:2)

您应该将return类型object更改为float

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