我复制了以下代码:https://forum.unity3d.com/threads/clean-est-way-to-find-nearest-object-of-many-c.44315/
但是这段代码:
Transform GetClosestCube (Transform[] cubes);
void GetClosestCube()
{
{
Transform bestTarget = null;
float closestDistanceSqr = Mathf.Infinity;
Vector3 currentPosition = transform.position;
foreach(Transform potentialTarget in cubes)
{
Vector3 directionToTarget = potentialTarget.position - currentPosition;
float dSqrToTarget = directionToTarget.sqrMagnitude;
if(dSqrToTarget < closestDistanceSqr)
{
closestDistanceSqr = dSqrToTarget;
bestTarget = potentialTarget;
}
}
return bestTarget;
}
}
它给出错误:
Assets / Player.cs(29,12):错误CS0501: `Player.GetClosestCube(变换[])&#39;必须有一个身体因为它 没有标记为抽象,外部或部分
如果我使用代码的确如何在线程中:
void GetClosestCube()
{
{
Transform GetClosestCube (Transform[] cubes)
{
Transform bestTarget = null;
float closestDistanceSqr = Mathf.Infinity;
Vector3 currentPosition = transform.position;
foreach(Transform potentialTarget in cubes)
{
Vector3 directionToTarget = potentialTarget.position - currentPosition;
float dSqrToTarget = directionToTarget.sqrMagnitude;
if(dSqrToTarget < closestDistanceSqr)
{
closestDistanceSqr = dSqrToTarget;
bestTarget = potentialTarget;
}
}
return bestTarget;
}
}
}
错误:Assets / Player.cs(34,28):错误CS1525:意外符号
(', expecting
,&#39;,;', or
=&#39;
答案 0 :(得分:0)
从不使用Unity Framework编程,所以我可能不应该在这里发帖但是哦。我同意Rene这看起来不像有效的C#代码。
Transform GetClosestCube (Transform[] cubes)
{
Transform bestTarget = null;
float closestDistanceSqr = Mathf.Infinity;
Vector3 currentPosition = transform.position;
foreach (Transform potentialTarget in cubes)
{
Vector3 directionToTarget = potentialTarget.position - currentPosition;
float dSqrToTarget = directionToTarget.sqrMagnitude;
if (dSqrToTarget < closestDistanceSqr)
{
closestDistanceSqr = dSqrToTarget;
bestTarget = potentialTarget;
}
}
return bestTarget;
}
对我来说更正确。这种方法试图获得最接近的Cube。这意味着你不希望它返回void(或没有)。您希望您的方法返回您在数组中发送的一个多维数据集,最好是最接近的。这就是为什么它有一个返回类型的Transform(因为那是一个立方体)。
我认为你会希望这个方法包含在与Cubes有关的类中。
假设这是在一个名为ReadyPlayerOne的类中(错误的类名,好书),方法的工作是告诉你最接近ReadyPlayerOne实例的多维数据集,你的代码可能看起来像这样。
public class ReadyPlayerOne {
Transform GetClosestCube (Transform[] cubes)
{
Transform bestTarget = null;
float closestDistanceSqr = Mathf.Infinity;
Vector3 currentPosition = transform.position;
foreach (Transform potentialTarget in cubes)
{
Vector3 directionToTarget = potentialTarget.position - currentPosition;
float dSqrToTarget = directionToTarget.sqrMagnitude;
if (dSqrToTarget < closestDistanceSqr)
{
closestDistanceSqr = dSqrToTarget;
bestTarget = potentialTarget;
}
}
return bestTarget;
}
}
然后你可以新建一个实例并像这样调用它。
var playerone = new ReadyPlayerOne();
var closestCube = playerone.GetClosestCube(cubes);
我希望这会有所帮助:)