Nullable Types
Nullable Types
Posted by David Laskey on January 14th, 2014
Sometimes you have variables that have important information but only after certain game events occur. For example: A character in your game may be idle until they’re told to go to an assigned destination.
public class Character : MonoBehaviour { Vector3 targetPosition; void MoveTowardsTargetPosition() { if (targetPosition != Vector3.zero) { //Move towards the target position! } } public void SetTargetPosition(Vector3 newPosition) { targetPosition = newPosition; } } |
In this case, we want the character to move towards the target position only if it’s been assigned. In the code above, we do this by just checking if targetPosition is not equal to its default value (0, 0, 0). But now we have an issue: what if you want your character to move to (0, 0, 0)? You don’t want to discredit the possibility of that value being used because it might come up sometime during the game!
Luckily, there’s a trick to help avoid comparing arbitrary values for confirming that a variable has been initialized: Nullable Types.
Using Nullable Types
To make a nullable type, just add a “?” after the type declaration of any variable that is a Value Type (eg. Vector3, Rect, int, float).
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; } } |
Seen here, nullable types have two properties we can use: HasValue (true if the variable has been assigned, false otherwise), and Value (the actual assigned value of the variable).
//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! } |
Usage Notes
- To revert a nullable type to having “no value”, set it to null
- You can NOT create nullable types from classes, or reference types (they can already be set to null)
As usual, if you have any questions or tips to add, do so in the comments below!
'Unity3D > Extensions' 카테고리의 다른 글
일괄적으로 Texture Import Setting 변경 (0) | 2015.01.30 |
---|---|
Extension Methods (0) | 2014.08.18 |
ObjectPool (0) | 2014.04.22 |
인스펙터 상의 GUI를 비활성화 시키고 싶을 때.. (0) | 2014.04.02 |
Save Scene while on play mode (0) | 2014.01.12 |