About 'Play Random Sound From Array'!

In this video (objectives)…

1. Use PlayOneShot instead of Play.

2. Create an array and then use that array to randomly select one of many audio clips.

3. Cache our component reference.

After watching (learning outcomes)…

Randomly play one of many sound effects when an event takes place.

(UVR 19_BR_CUD)

We would love to know…

  • What you found good about this lecture?
  • What we could do better?

Remember that you can reply to this topic, or create a new topic. The easiest way to create a new topic is to follow the link in Resources. That way the topic will…

  • Be in the correct forum (for the course).
  • Be in the right sub-forum (for the section)
  • Have the correct lecture tag.

Enjoy your stay in our thriving community!

I was wondering if it is more or less performant to initialize the AudioSource on Start() or Awake() as opposed to calling directly when using it? For example

[SerializeField] AudioSource audioSource;

void Start()
{
    audioSource = GetComponent<AudioSource>();
}

void OnCollisionEnter2D(Collision2D collision)
{
    audioSource.PlayOneShot(whateverClip);
}

vs

void OnCollisionEnter2D(Collision2D collision)
{
    GetComponent<AudioSource>().PlayOneShot(whateverClip);
}

I know in the context of this lesson it doesn’t matter, but I was wondering which I should be using in more complex projects.

It looks like watching the video all the way to the end answered the question for me. Sorry about that, bad habit of asking questions in the middle of videos.

This will depend on its usage in your class. If you are only calling it in once place, once, then using GetComponent directly is going to be more performant. Of course, this assumes that the required component is available. If its not you’ll just throw an exception as there is no validation in either the course exa. Ple, or yours, to protect against that, nor is the [RequireComponent] attribute being used.

If you were making multiple calls to the component then it would make more sense to cache its reference.

Hope this helps :slight_smile:

1 Like

Privacy & Terms