[英]How can I return a float from a function with different type arguments?
I have this function and I want to pass two Vector3 arguments and one int so I can return a float value. 我有此功能,我想传递两个Vector3参数和一个整数,以便返回浮点值。 How can I return a float value even tho I use Vector3 and int as arguments? 即使使用Vector3和int作为参数,如何返回浮点值? This is my code: 这是我的代码:
//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));
}
}
When i replace the "object" keyword with the "return" keyworkd it gives me this error; 当我用“ return”键替换“ object”关键字时,出现此错误; enter image description here 在此处输入图片说明
Two problems with your code. 您的代码有两个问题。
You can try this: 您可以尝试以下方法:
/// <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;
}
The changes include: 更改包括:
just change return type from object
to float
like this: 只需将返回类型从object
更改为float
如下所示:
public object DistanceToNextPoint(...)
To: 至:
public float DistanceToNextPoint(...)
then return your variable distance
in the last line of your method: 然后在方法的最后一行返回您的可变distance
:
public float DistanceToNextPoint(...){
// ...
return distance:
}
You should change the return
type object
to float
. 您应该将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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.