Question by
toroberg · Jul 23, 2019 at 05:40 PM ·
if-statementsif-else
Any way to slim down if/else statements?
Hi!
Anyone know a way to slim this code down a bit?
Code example below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationManagement : MonoBehaviour
{
Animator _animator;
bool _runForward;
bool _runBackward;
bool _jump;
bool _turnRight;
bool _strafeRight;
bool _turnLeft;
bool _strafeLeft;
void Update()
{
_animator = gameObject.GetComponent<Animator>();
_runForward = false;
_runBackward = false;
_jump = false;
_turnRight = false;
_strafeRight = false;
_turnLeft = false;
_strafeLeft = false;
}
void Update()
{
// Run Forward
if (Input.GetKey(KeyCode.W))
{
_runForward = true;
_animator.SetBool("RunForward", true);
}
else
{
_runForward = false;
_animator.SetBool("RunForward", false);
}
// Run Backward
if (Input.GetKey(KeyCode.S))
{
_runBackward = true;
_animator.SetBool("RunBackward", true);
}
else
{
_runBackward = false;
_animator.SetBool("RunBackward", false);
}
// Turn Right
if (Input.GetKey(KeyCode.D))
{
_turnRight = true;
_animator.SetBool("TurnRight", true);
}
else
{
_turnRight = false;
_animator.SetBool("TurnRight", false);
}
// Turn Left
if (Input.GetKey(KeyCode.A))
{
_turnLeft = true;
_animator.SetBool("TurnLeft", true);
}
else
{
_turnLeft = false;
_animator.SetBool("TurnLeft", false);
}
// Starfe Right
if (Input.GetMouseButton(1) && Input.GetKey(KeyCode.D))
{
_strafeRight = true;
_animator.SetBool("StrafeRight", true);
}
else
{
_strafeRight = false;
_animator.SetBool("StrafeRight", false);
}
// Starfe Left
if (Input.GetMouseButton(1) && Input.GetKey(KeyCode.A))
{
_strafeLeft = true;
_animator.SetBool("StrafeLeft", true);
}
else
{
_strafeLeft = false;
_animator.SetBool("StrafeLeft", false);
}
// Jump
if (Input.GetKey(KeyCode.Space))
{
_jump = true;
_animator.SetBool("Jump", true);
}
else
{
_jump = false;
_animator.SetBool("Jump", false);
}
}
}
Comment
Answer by gjf · Jul 23, 2019 at 05:39 PM
You should be more concerned with the fact that your code doesn't compile. You cannot have two Update() functions!
That said, you could change each of your key checks and subsequent animator triggers to something like:
_runForward = Input.GetKey(KeyCode.W);
_animator.SetBool("RunForward", _runForward);
...but that makes it harder to change functionality. You reduce the code but it may be a waste of time until you have everything working correctly. It's known as "premature optimization". As you gain experience, you'll hopefully resist the temptation...