There are lots of ways to skin this cat.
You could decide your axis first, then decide the direction along that axis:
public static Vector2 GetRandomCardinalDirection() {
Vector2 direction = Vector2.zero;
int componentIndex = Random.Range(0, 2);
direction[componentIndex] = Mathf.Sign(Random.value);
}
You could use a switch statement to pick one of your four possible values:
public static Vector2 GetRandomCardinalDirection() {
int direction = Random.Range(0, 4);
switch(direction) {
case 0: return Vector2.up;
case 1: return Vector2.right;
case 2: return Vector2.down;
default: return Vector2.left;
}
}
You could store the 4 values in an array, and use your random value as an index:
static readonly Vector2[] _cardinalDirections = new Vector2[] {
Vector2.up, Vector2.right, Vector2.down, Vector2.left
};
public static Vector2 GetRandomCardinalDirection() {
return _cardinalDirections[Random.Range(0, 4)];
}
You could do some bit tricks to decode a direction from an integer 0-3:
public static Vector2 GetRandomCardinalDirection() {
// Make a random number 0-3 (that's 00, 01, 10, or 11 in binary)
int dieRoll = Random.Range(0, 4);
// Take just "the ones bit" and use it as our axis (0 = x, 1 = y)
int axis = dieRoll & 1;
// Take "the twos bit" (value 0 or 2) and subtract 1 to get -1 or +1
int sign = (dieRoll & 2) - 1;
// Initialize a vector2 with zeroes (0, 0)
Vector2 direction = Vector2.zero;
// Set our chosen axis, x or y, to have our desired -1/+1 value
direction[axis] = sign;
// Send that vector back to our caller.
return direction;
}
...etc.