Frequent call of audioSource.Stop()?

Every “Update” when Space is not pressed, the function calls audioSoure.Stop().
Isn’t it better to check first if the sound is being played and only stop in this case?

Just inserted if(audioSource.isPlaying) after else

        rb.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime );
    else if(audioSource.isPlaying)

I think it could be faster and safer, or am I wrong?

I would guess you’re right, but unlike the old days when you could count every clock cycle with the assembly, things are complex enough that even the best guesses turn out to be wrong. Only way to be sure is to test.

(E.g. in the old days, they said, “cache every computation to keep from redoing it”. Nowadays, memory access is slower than computation so that doesn’t always work).

It only calls it if the audio is playing hence the:

So all it’s doing is checking if space is being pressed and a boolean.

But you’re right. There’s a more efficient way to do it. There’s a new Input system that eliminates the need to have the Update running every turn.


As I always try to write save code, I would rather first check whether it is necessary and only then call the function.
Therefore, “if(audioSource.isPlaying)” was added to the original code to prevent the running call of Stop().

And sorry, I started at Z80 time and the efficiency of the code is rooted deep into my brain.

That is fine as long as you consider that the audio source may also check this before attempting to stop it, and it may take longer/more cycles to check if it’s running than actually just letting the audio source try to stop it. The audio source’s code is written in C++ and may be magnitudes faster to just let run, rather than do a C# check first. A bit like remembering that it is harder for the computer to divide than multiply, and therefore better to do neither (like using sqrMagnitude over magnitude) when it can be helped, or multiplying - for instance - by 0.5f rather than dividing by 2.

And after all that, I think there is no harm in defensive coding while it doesn’t affect performance. I would say calling stop all the time when it is not playing is certainly not necessary and your code is fine


This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms