- Home /
Randomly instantiating a list of objects at a random position.
Hi. I recently tried asking this question but I realized it was not a sufficient question. In my game the player is climbing up an infinite wall. I would like objects to fall and try to nock the player off. I have five objects that I want to fall. I want my game to randomly pick one and instantiate it between two points. I would also like the rotation to be random. Here is what I have so far:
using UnityEngine;
using System.Collections;
public class ObjectSpawner : MonoBehaviour
{
public GameObject[] obj = new GameObject[5];
// Use this for initialization
void Start ()
{
SpawnObject ();
}
// Update is called once per frame
void Update ()
{
}
//Spawns objects
void SpawnObject ()
{
Instantiate (obj (Random.Range (0, 4)), transform.position, Random.rotation);
}
}
I got a few errors in this code and I was wondering if someone could point me in the right direction. For example some of these errors are: The member ObjectSpawner.obj' cannot be used as method or delegate. Another is: The best overloaded method match for
UnityEngine.Object.Instantiate(UnityEngine.Object, UnityEngine.Vector3, UnityEngine.Quaternion)' has some invalid arguments. Another is: Argument #1' cannot convert
object' expression to type `UnityEngine.Object'. Please help. Thanks!
$$anonymous$$aybe edit your post and describe what the errors are.
Answer by static_cast · Dec 07, 2014 at 11:33 PM
Use Instantiate(obj[Random.Range (0, 4)], transform.position, Random.rotation);
The problem was the fact that you use [] instead of () to reference the location in an array.
You can also do new Vector3(Random.Range (0, 4),Random.Range (0, 4),Random.Range (0, 4))
instead of transform.position
in the Instantiate call. This will instantiate an object at any position with 0,0,0 and 4,4,4. ;)
Your answer
![](https://koobas.hobune.stream/wayback/20220613173501im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
C# GameObjects Instantiate Into Each Other Issue 1 Answer
GameObject variable change for all of the objects 1 Answer
Three Spots For Three Random Objects 1 Answer
I want gameobjects to move randomly on screen without overlapping.` 2 Answers
How to randomly spawn three non repeating gameobjects from an array? 2 Answers