我有这个函数,我想传递两个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
答案 0 :(得分:5)
您的代码有两个问题。
你可以试试这个:
/// <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;
}
更改包括:
答案 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;
}
}