Unity使用可空类型(Nullable Types)
译林军 范春彦|2014-04-09 09:46|0
你怎么确定一个Vector3,int,或float变量是否被分配了一个值?一个方便的方式就是使用可空类型!
有时变量携带重要信息,但只有在特定的游戏事件发生时触发。例如:一个角色在你的游戏可能闲置,直到他被告知去一个指定的目的地。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class Character : MonoBehaviour { Vector3 targetPosition;
void MoveTowardsTargetPosition()
{
if (targetPosition != Vector3.zero)
{
//Move towards the target position!
}
}
public void SetTargetPosition(Vector3 newPosition)
{
targetPosition = newPosition;
}
} |
在这种情况下,我们希望这个角色走向目标位置,仅仅在它被设定的时候。在上面的代码中,我们通过检查targetPosition是否不等于其默认值(0,0,0)来实现.但现在我们有一个问题:如果你想要你的角色move to(0,0,0)呢?你不用怀疑这个值,因为它确实可能会在游戏中出现!
幸运的是,有一个诀窍来:可空类型.它避免了通过比较任意值来确认一个变量是否被初始化。
使用可空类型
创建可空类型,仅需在任何一个值类型(如Vector3,Rect,int,float)的变量声明后,添加一个“?”。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class Character : MonoBehaviour { //Notice the added "?"
Vector3? targetPosition;
void MoveTowardsTargetPosition()
{
if (targetPosition.HasValue)
{
//Move towards the target position!
//use targetPosition.Value for the actual value
}
}
public void SetTargetPosition(Vector3 newPosition)
{
targetPosition = newPosition;
}
} |
看到这里,可空类型有两个属性我们可以使用:HasValue(如果已经指定了变量则为true,否则false),和Value(变量的实际分配值)。
1
2
3
4
5
6
7
8
9
|
//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!
} |
用法注释
- 回复可空类型为“无值”,将其设置为null
- 你不能从类或引用类型(他们已经可以设置为null)创建可空类型
像往常一样,如果你有任何问题或建议,在下面的评论中回复!
原文链接:Nullable Types