🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Trying to loop through enums, stuck on a for loop that's not incrementing correctly

Started by
1 comment, last by SassyPantsy 3 years, 4 months ago

I'm trying to loop through attack patterns, I've got a method that calls an attack based on a direction enum, for instance Directions.Left. I want to create an attack pattern, so I'm trying to loop through the entire values in the instances. I get that I need to use the GetValue() method, so I did, and I cast the value back as an enum. It works, but something in the execution isn't right. Either it goes through all of the elements, and basically executes the actual attack with the last elements, or it's stuck on 0, never incrementing it.

This attack pattern method is being called basically every update (proximity based), and I understand that everytime it gets called the for loop get reset, but when I call it once (like with an Input.GetKeyDown), again it doesn't loop through all of the elements. Anyway, how do I make the incrementation to occur only after the code gets executed (which is a weird question to ask on a for loop)?

This is the code:

		private void AttackPattern()
		{
			if(curentAttackTimer <= 0)
			{
				for (int i= 0; i< Enum.GetValues(typeof(Direction)).Length; i++)
				{
					print(i);
					GetComponent<EnemyFighterWrapper>().Attack((Direction)i);
					curentAttackTimer = attackCooldown;
				}
			}
		}

Again, this gets called every update. What I'm trying to do is get the GetComponent line to execute before incrementing i.

As it stands right now (with this code), all of the values get printed out once every attack pattern - i.e when the attackCooldown has finished, and the attack that's played is the one that's connected to the last element. This gets called every update.

Hope I was clear! Thanks…

None

Advertisement

Ok this is stupid and I can't seem to remove the post because I've actually managed to fix it literally two seconds after posting it (and an hour after starting to work on it)

I turned the code as it was into a Coroutine. This is how it looks right now:

		private IEnumerator AttackPattern()
		{
			if(curentAttackTimer <= 0)
			{
				for (int i = 0; i < Enum.GetValues(typeof(Direction)).Length; i++)
				{
					print(i);
					GetComponent<EnemyFighterWrapper>().Attack((Direction)i);
					curentAttackTimer = attackCooldown;
					yield return new WaitForSeconds(attackCooldown);
				}
			}
		}

I guess that the mods will just remove this, but for anybody having a hard time looping enums this might help ?

None

This topic is closed to new replies.

Advertisement