- Home /
random show objects
I creat the 30 empty gameobject in different places.
I have cube and sphere.
Start game, I want to randomly the 10 of empty gameobject were in place show cube or sphere.
(Cube and Sphere location are empty gameobject)
I know "random.range" this script.
But this can only set a range, and can't specify the location of objects.
What can i write the code? thanks!
Answer by DaveA · Apr 03, 2011 at 06:47 PM
You could do
pos :Vector3 = new Vector3 (Random.Range(-10.0, 10.0), Random.Range(-10.0, 10.0), Random.Range(-10.0, 10.0));
to make them show in random spots within the cubic volume -10,10 or look at 'insideUnitSphere' for example.
If you want to randomly choose one of your empty game objects:
var spots : Transform[]; // drag the objects from Hierarchy to Inspector to set these elements, something like this:
function Start()
{
for (var i=0; i < 10; i++)
{
var spot = Random.Range(0,spots.Length);
Instantiate (thing, spots[spot].position);
}
}
You'll have to fix the syntax but it's close. Note that this lets you put as many or few empty objects into the array. Also it might result in more than one object appearing at the same spot. To avoid that, you could make an array of booleans like 'usedSpot' and set that when a spot is chosen, and check for it not being set before choosing another. Keep chosing random numbers until an unused one is found. Or you could look into a 'shuffle' algorithm, but this is getting beyond what I can get into right now.
Answer by starta · Apr 05, 2011 at 02:09 PM
Thank you
I use other guy's suggestion and his method is easy understand for me
I'm a beginner
As below:
I create cube and sphere into prefabs.
and create a script is called generateObjects.js:
static var objectCount:int=0;
and create another script is called generateObjects.js:
var cubePrefab:gameObject;//set these in the inspector var spherePrefab:gameObject;//set these in the inspector var haveAnObject:boolean=false; function Update() { if(globalCount.objectCount<10 && !haveAnObject) { var rand=Random.Range(0,100);//to see if we should create an object if(rand>50) { haveAnObject=true; globalCount.objectCount +=1; rand=Random.Range(0,100);//to see if we should make a cube or sphere if(rand>50) Instantiate (cubePrefab, transofrm.position, transform.rotation); else Instantiate (spherePrefab, transofrm.position, transform.rotation); } } }
put generateObjects.js to all my empty objects.
Your answer

Follow this Question
Related Questions
Generating a Displacement Map in Unity3d? 1 Answer
Teleport to a random height 1 Answer
Need help with Flashlight Script 1 Answer
keep an if statement updating per frame in function Update 1 Answer
Transform to a random height 0 Answers