【问题标题】:How can I return a float from a function with different type arguments?如何从具有不同类型参数的函数返回浮点数?
【发布时间】:2017-10-05 13:48:50
【问题描述】:

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

【问题讨论】:

  • 您可能希望将声明中的object 更改为floatreturn distance;
  • 是的,所有答案和 cmets 都指向答案;)

标签: c# unity3d methods


【解决方案1】:

您的代码有两个问题。

  1. 如果您想返回一个对象类型,那么您需要在使用它之前将结果转换为浮点数。
  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;
}

变化包括:

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

【讨论】:

  • 感谢您的回答,简明扼要,让代码更有效。
【解决方案2】:

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

public object  DistanceToNextPoint(...)

收件人:

public float  DistanceToNextPoint(...)

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

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

【讨论】:

    【解决方案3】:

    您应该将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;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 2019-12-25
      相关资源
      最近更新 更多