Random spawn and random sounds, Unity 3D

by on under Code snippets
1 minute read

This two things are easy to do but many people don’t know how, so I will explain.
Random spawn :

public GameObject[] prefab;
void RandomSpawn(){
	Instantiate(prefab[Random.Range(0, prefab.Length)], position, rotation);

Play random sounds:

public AudioClip[] sound;
void RandomSounds(){
	AudioSource.PlayClipAtPoint(sound[Random.Range (0, sound.Length)], Camera.main.transform.position);

I’ve used playClipAtPosition to play the song even if the gameObject gets destroyed.
The idea is: we get a random number between 0 and the lenght of the array and play the sound with that index.

Unity 3D, code snippets, random
comments powered by Disqus