0
\$\begingroup\$
IEnumerator Shooting()
    {
        //Random Delay
        rand2 = random.Next(1, 4);

        if (!audioSource.isPlaying)
        {
            enemyParticles.SetActive(true);
            particle.Play();
            audioSource.Play();

            rand = random.Next(0, 5);
            Vector3 vel = rb.velocity;

            if (rand == 2)
            {
                if (vel.x < 6f || vel.y < 6f || vel.z < 6f)
                {
                    health.numOfHearts -= 1;
                }
            }
        }
        yield return new WaitForSeconds(rand2);
    }

This script is tied to several enemy objects.

random is initialized in the Start method with a different seed for every object. For some reason that I can't figure out, the delay is not randomized here.

The AudioSource for instance is played for all the enemies at the same time with the same delay every time. I'm not too familiar with coroutines and how they are executed, but I always put the WaitForSeconds() statement at the beginning or end which usually works for me.

Here is the Start method:

//Random Seed
    public int RandomSeed;
    private System.Random random;
    private int rand;

    //Random Delay
    private int rand2;


    void Start()
    {
        //Random
        random = new System.Random(RandomSeed);
    }

Could someone explain why the AudioSources of all the enemy objects are played at the same time when I encounter them? Thanks in advance. :)

\$\endgroup\$
0
\$\begingroup\$

I fixed it, figured out that since the StartCoroutine() is in the Update method, the AudioSource plays constantly every time it stops playing as the StartCoroutine() is called every frame. To fix this, I did this:

if (entered == false)
            {
                StartCoroutine(Shooting());
                entered = true;
            }

in the Update method, and this in the Coroutine:

IEnumerator Shooting()
    {
        while (true)
        {
            //Random Delay
            rand2 = random.Next(1, 4);

            if (!audioSource.isPlaying)
            {
                enemyParticles.SetActive(true);
                particle.Play();
                audioSource.Play();

                rand = random.Next(0, 5);
                Vector3 vel = rb.velocity;

                if (rand == 2)
                {
                    if (vel.x < 6f || vel.y < 6f || vel.z < 6f)
                    {
                        health.numOfHearts -= 1;
                    }
                }
            }
            yield return new WaitForSeconds(rand2);
        }

        
    }

That fixes the issue and now I get randomized shooting delays!

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.