- Home /
Enabling the particle system with particle.Play(); not working
When trying to re-enable the particle system with particle.Play();
it doesn't work. Basically I am disabling particle system upon game start and then enabling it every time the user presses Input.GetKey(KeyCode.Mouse0)
waiting 0.1f
and then disabling it again. This is for a sword attack. The particle system will disable upon game start but won't re-enable. Why is this happening?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnableParticlse : MonoBehaviour
{
public ParticleSystem particle;
void Start()
{
particle = gameObject.GetComponent<ParticleSystem>();
particle.Stop();
}
void Update()
{
if (Input.GetKey(KeyCode.Mouse0))
{
particle.Play();
StartCoroutine(Wait(0.1f));
particle.Stop();
}
}
IEnumerator Wait(float sec)
{
yield return new WaitForSeconds(sec);
}
}
Answer by joemane22 · Feb 23, 2020 at 07:29 AM
Calling StartCoroutine(Wait(0.1f)) does not block the current method. The whole point of coroutines is to provide non blocking methods.
You need to put the entire thing in a coroutine of your own
IEnumerator SwordAttack(float waitTime)
{
particle.Play();
yield return new WaitForSeconds(waitTime);
particle.Stop();
}
private void Update()
{
if(Input.GetMouseButtonDown(0))
{
StartCoroutine(SwordAttack(0.1f));
}
}
ohhh ok thank you, I though coroutine was like the Sleep(); function from windows.h in c++
Answer by rh_galaxy · Feb 23, 2020 at 07:26 AM
You cannot start a coroutine to just wait... what happens is that you do Play() and Stop() in the same frame. This is code not using coroutines:
bool particleStart = false;
float timer = 0.0f;
void Update()
{
if (Input.GetKey(KeyCode.Mouse0))
{
particle.Play();
particleStart = true;
}
if(particleStart) {
timer += Time.deltaTime;
if(timer >= 0.1f) {
particle.Stop();
particleStart = false;
timer = 0.0f;
}
}
}