- Home /
WaitForSeconds is not waiting for seconds, at all. Its like it doesnt exist.
using UnityEngine; using UnityEngine.UI; using System.Collections;
namespace Complete { public class ShootingScript : MonoBehaviour {
public Rigidbody m_Shell;
public Transform m_FireTransform;
public Slider m_AimSlider;
public AudioSource m_ShootingAudio;
public AudioClip m_FireClip;
public float m_MinLaunchForce = 2000f;
public Text bulletsLeftText;
public int LeftBullets = 30;
public int TotalBullets = 120;
private float m_CurrentLaunchForce;
private bool m_Fired;
private void OnEnable()
{
m_CurrentLaunchForce = m_MinLaunchForce;
m_AimSlider.value = m_MinLaunchForce;
}
private void Start ()
{
}
private void Update ()
{ bulletsLeftText.text = " ";
bulletsLeftText.text += LeftBullets;
bulletsLeftText.text += "/";
bulletsLeftText.text += TotalBullets;
m_AimSlider.value = m_MinLaunchForce;
}
public void Reload()
{
StartCoroutine (reloading ());
LeftBullets = 30;
TotalBullets = TotalBullets - 30;
}
public void ShootToKill()
{
while (0 < LeftBullets)
{
Fire ();
StartCoroutine (waitbetweenshots());
}
Reload ();
}
public void Fire ()
{
Rigidbody shellInstance =
Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) as Rigidbody;
shellInstance.velocity = m_CurrentLaunchForce * m_FireTransform.forward;
m_ShootingAudio.clip = m_FireClip;
m_ShootingAudio.Play ();
m_CurrentLaunchForce = m_MinLaunchForce;
LeftBullets= LeftBullets-1;
}
IEnumerator waitbetweenshots()
{
yield return new WaitForSeconds (0.25f);
}
IEnumerator reloading()
{
yield return new WaitForSeconds (2);
}
}}
It doesnt wait any time at all I want it to wait 0.25 secs between shots and 2 secs while reloading . and this doesnt work can you help me repair it or give me another idea on how to do this please ?
Answer by Landern · Aug 01, 2016 at 03:38 PM
Go and take a peek at the Coroutine examples, in particular look at the second example. When yielding internally to the method and not yielding outside when Starting the Coroutine will allow the continuation to happen within say your "waitbetweenshots" method but continue to the next line after the StartCoroutine. You will need to yield and set the calling method to IEnumerable, that will cause the continuation after X seconds to continue at that location instead of continuing as it does now. Again look at the second example and a simple refactor is all you need.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# | How to delay a method with parameters 2 Answers
How to pause a Coroutine? 5 Answers
how do i Disable and Enable buttons? 2 Answers