- Home /
Is there a way to simplify this code?
So I am making a platform fighter game and for each move I have a ton of code that I think can be simplified but I don't know how
//variables
public GameObject jab; //The jabbing hitboxes
private bool isJabbing = false;
private int jabTime;
//Check if button is pressed
if (Input.GetKeyDown(KeyCode.P) && isJabbing == false)
{
isJabbing = true;
jabTime = 0;
}
//Jabs for 10 frames then stops
if (isJabbing && jabTime <= 10)
{
jab.SetActive(true);
jabTime++;
}
else
{
jab.SetActive(false);
isJabbing = false;
}
Answer by tuinal · Jul 14, 2020 at 04:30 AM
void Start(){
StartCoroutine(Jabs());
}
IEnumerator Jabs(){
yield return new WaitUntil(()=>Input.GetKeyDown(Keycode.P));
jab.SetActive(true);
yield return new WaitForSeconds(10f);
jab.SetActive(false);
StartCoroutine(Jabs());
}
Answer by Z_Doctor · Jul 14, 2020 at 05:07 AM
@IrOn_KiT Well when you say shorten, I assume you also mean more readable. I've been experimenting using Pattern Matching with Switch Statements as an alternative to the classic If-Else statements and I went ahead and added some comments to my code and took the liberty of adding a few variables and features. This is probably how I would do it, but feel free to experiment and add your own twist.
public bool IsJabbing { get; protected set; }
public int Jabs { get; protected set; }
[SerializeField]
private GameObject jabHitbox;
[Tooltip("The amount of frames a jab lasts.")]
[SerializeField]
private int maxJabs = 10;
private void Update()
{
// Checks that the jabHitbox has been assigned
if (jabHitbox)
switch (IsJabbing)
{
// The first frame when you are not jabbing and jab button is pressed
case false when Input.GetKeyDown(KeyCode.P):
IsJabbing = true;
Jabs = 0;
jabHitbox.SetActive(true);
break;
// When you are jabbing and hit the maximum amount of frames for jabbing
case true when Jabs > maxJabs:
jabHitbox.SetActive(false);
IsJabbing = false;
break;
// When you are otherwise jabbing
case true:
Jabs++;
break;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613003135im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Simplify Code 3 Answers
Flip over an object (smooth transition) 3 Answers