- Home /
Random spawning of objects
Hi I am am trying to create a mini game in C# where random notes drop from a piano and when the player collides with the notes a note is played.
I am haveing trouble on figuring out how to spawn random prefabs from the piano with a specific note attached, So far I am only able to spawn clones of the same prefab, here is my attached code
using UnityEngine;
using System.Collections;
public class SpawnBoxes : MonoBehaviour
{
public Rigidbody box;
public bool readynow = true;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (readynow)
{
StartCoroutine(makeBox());
}
}
IEnumerator makeBox()
{
readynow = false;
Instantiate(box, transform.position, transform.rotation);
yield return new WaitForSeconds(1);
readynow = true;
}
}
Can anyone offer any advice on how to approach this problem
Thanks
Answer by Kortekk · Jan 28, 2013 at 01:01 AM
Instead of only defining one prefab, "box", you can turn that into an array of different prefabs:
public Rigidbody[] boxes;
Then when you want to instantiate a random box, generate a random array index to determine which prefab in the array will be instantiated:
int i = Random.Range(0, boxes.Length);
Instantiate(boxes[i], transform.position, transform.rotation);
Answer by Gizmoi · Jan 28, 2013 at 01:03 AM
I assume you have a script attached to your box object that describes what note it is? Instantiate returns the instantiated GameObject. You can use GetComponent on that to get your note script and assign it a random note.
Answer by The_Town_drunk · Feb 02, 2013 at 05:52 PM
Hi thanks guys for helping out, I got it working following your advice but i need to brush up on arrays which is my next task! thanks again.
Answer by The_Town_drunk · Feb 02, 2013 at 05:51 PM
@Gizmoi yeah I found a tutorial on YouTube where a guy makes a piano keyboard, and used the script he showed to create the notes.
Your answer
![](https://koobas.hobune.stream/wayback/20220613091714im_/https://answers.unity.com/themes/thub/images/avi.jpg)