unity-game-engineaudio-source

AudioSource.Play() not working in Enumerator


I have an Enumerator for the effects played when you shoot a gun. It is:

private IEnumerator ShotEffect()
    {
        gunAudio.Play();

        laserLine.enabled = true;

        yield return shotDuration;

        laserLine.enabled = false;
    }

When I take the gunAudio.Play() out, the code works fine. However, when I add it in, the sound does not play and the line doesn't disable. I assume there is a problem with the shotDuration?

The variable gunAudio is given the audio component in start, and shotDuration is a wait for seconds.

EDIT:

Also, if I set it to play on awake, it plays. Therefore I think there is a problem with the code, not the component.

Here is where I call the Enumerator:

if (Input.GetKey(KeyCode.Mouse0) && Time.time > nextFire) 
        {

            torsoDamage = (int)Random.Range(50f, 70f);
            legDamage = (int)Random.Range(20f, 30f);
            handDamage = (int)Random.Range(5f, 15f);
            nextFire = Time.time + fireRate;
            StartCoroutine (ShotEffect());
            Vector3 rayOrigin = fpsCam.ViewportToWorldPoint (new Vector3(0.5f, 0.5f, 0.0f));
            RaycastHit hit;
            laserLine.SetPosition (0, gunEnd.position);
            if (Physics.Raycast (rayOrigin, fpsCam.transform.forward, out hit, weaponRange))
            {
                laserLine.SetPosition (1, hit.point);
                if (enemyAi.enemy_currentHealth != null)
                {                                       
                        if (hit.collider.gameObject.tag == "head")
                        {                   
                                enemyAi.Damage(100);
                        }
                        if (hit.collider.gameObject.tag == "torso")
                        {
                            enemyAi.Damage(torsoDamage);
                        }
                        if (hit.collider.gameObject.tag == "leg" || hit.collider.gameObject.tag == "arm")
                        {
                            enemyAi.Damage(legDamage);
                        }
                        if (hit.collider.gameObject.tag == "hand" || hit.collider.gameObject.tag == "foot")
                        {
                            enemyAi.Damage(handDamage);
                        }
                }

                if (hit.rigidbody != null)
                {
                    hit.rigidbody.AddForce (-hit.normal * hitForce);
                }
            }
            else
            {
                laserLine.SetPosition (1, gunEnd.position + (fpsCam.transform.forward * weaponRange));
            }
        }

Solution

  • I fixed it - there was some weird problem with another variable that was being called from another script.

    The code works fine now.