Day 20 — Getting familiar with switch statements in Unity

private float _playerSpeed = 8.0f;
private int _doubleSpeed = 2;
private bool _collectedSpeed = false;
private void Movement()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontalInput, verticalInput, 0); if (_collectedSpeed == false)
{
transform.Translate(direction * _playerSpeed * Time.deltaTime);
}
else if (_collectedSpeed == true)
{
transform.Translate(direction * (_playerSpeed * _doubleSpeed) * Time.deltaTime);
}
}
public void EngageSpeedPowerup()
{
_collectedSpeed = true;
StartCoroutine(SpeedPowerupTimer());
}
IEnumerator SpeedPowerupTimer()
{
yield return new WaitForSeconds(5.0f);
_collectedSpeed = false;
}

The switch statement

With that code in place now we get into the fun of switch statements. First though we need a way to identify our powerups by id, if you’ve attempted to add a reference to the EngageSpeedPowerup() method to the Powerups script you may have noticed that we’ve got no way to distinguish between the powerups when our player collides with one.

[SerializeField]
private int _powerupID;
if (_powerupID == 0)
{
//Engage the triple shot
}
else if (_powerupID == 1)
{
//Engage the speeeed
}
switch(_powerupID)
{
case 0:
_player.EngageTripleShot();
break;
case 1:
_player.EngageSpeedPowerup();
break;
case 2:
Debug.Log("Shields");
break;
default:
Debug.Log("Something has gone horribly wrong");
break;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Connor Fullarton

Connor Fullarton

59 Followers

Hey and welcome! My name is Connor and my goal here is to put out a daily post for a full year about my game development journey.