- Home /
Spawn object in cube
Hello,
I Was wondering if anyone could help me with this; So i have 8 cubes, which would possibly use a trigger, anyway. I Have an object, and i want to spawn the object inside ONE OF THE CUBES, so it's different every time, it could be cube 1, or 2 or 3 or 4 or 5, and so on. So it chooses one cube and spawns the object there.
Could anyone possibly help me out with how i would do this?
Thanks
Store your 8 cubes in a list/array. When it comes to spawn time, choode a random number, find that number cube in the list, spawn object at chosen cube.
Search 'unity spawn points' , this is an example of what I am describing : http://answers.unity3d.com/questions/13657/mulitple-spawn-points-with-random-seed.html
Answer by mwinteringham · Sep 18, 2012 at 12:45 PM
I am not going to write the code but I see the logic as this:
Randomly generate a number between 1 and 8. This can be done by using the Random class: http://docs.unity3d.com/Documentation/ScriptReference/Random.html
Once you have your number, you will need to find your objects. I would set all the objects with same tag and use GameObject.FindGameObjectsWithTag to return an array of all the Cubes you want to spawn into: http://docs.unity3d.com/Documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html
Once you have your array of GameObjects, use the randomised number from step 1 to select a specific GameObject and use that GameObject's position as a the location for your initial object Object to spawn
Answer by inco · Sep 18, 2012 at 12:45 PM
YourCubeObjectType[] cubes = FindObjectsOfType(typeof(YourCubeObjectType)) as YourCubeObjectType[];
Instantiate(YourSpawnObjectType, cubes[Random.Range(0, cubes.Length)].transform.position, Quaternion.identity)
Should do it (it's almost the same in JS if that's your preference). Of course, you can use Vector3.zero position for instantiation, and then you can add your spawned object as a child of one of the cubes if you wish for it to move with the parent cube like:
YourCubeObjectType[] cubes = FindObjectsOfType(typeof(YourCubeObjectType)) as YourCubeObjectType[];
YourSpawnObjectType spawned = Instantiate(YourSpawnObjectType, Vector3.zero, Quaternion.identity)
spawned.transform.parent = cubes[Random.Range(0, cubes.Length)].transform;