我经常需要将无效位置传递给那些可选使用位置的函数(例如 RTS 单位动作)。但这样的代码无法编译:
public abstract void CastSpell(Spell spell, Vector3 targetLocation = null);
那么我该如何创建一个合适的 无效 Vector3 来确定无效或“不关心”的位置?我看到过一些向量使用 -999999 坐标,但这是一种会导致错误的恶劣技巧(例如在大型地图上)。
我经常需要将无效位置传递给那些可选使用位置的函数(例如 RTS 单位动作)。但这样的代码无法编译:
public abstract void CastSpell(Spell spell, Vector3 targetLocation = null);
那么我该如何创建一个合适的 无效 Vector3 来确定无效或“不关心”的位置?我看到过一些向量使用 -999999 坐标,但这是一种会导致错误的恶劣技巧(例如在大型地图上)。
我过去也遇到过类似的问题,我找到了两种解决方案。第一种解决方案是为该类创建一个包装器。
Class Vector3Wrapper
{
Vector3 vector;
}
那么,如果Vector3Wrapper不为null,则我只需将其设置为null,然后访问其向量即可。更好的方法是将其设置为Nullable类型。以下是一个示例。
http://unitypatterns.com/nullable-types/
public class Character : MonoBehaviour
{
//Notice the added "?"
Vector3? targetPosition;
void MoveTowardsTargetPosition()
{
//First, check if the variable has been assigned a value
if (targetPosition.HasValue)
{
//move towards targetPosition.Value
}
else
{
//targetPosition.Value is invalid! Don't use it!
}
}