- Home /
Instantiating objects randomly based on the length of an object
Searched everywhere and tried various ways but I don't believe I am able to do this. I want to make a group of 3 asteroids (that are randomly selected) spawn based on the length of an empty gameobject (I am using box collider to determine length). I currently have it based on random z or x axis but those are creating some wonky things and making it so its based on the length of a particular axis of a collider sounds much easier and more automated.
The setup I have now is an empty gameobject called "Asteroid Generator" and a child (that has this script and does the spawning) called "Asteroid Spawner"
I also plan to have another child within generator that will be the same box size that will end up deleting all asteroids that pass as well as a timer that will randomly spawn the asteroids rather than spawn infinite asteroids at once.
Here's what I have:
#pragma strict
var asteroids = new GameObject[3];
var pos1: float;
var pos2: float;
function Start () {
}
function Update () {
// for (var child : Transform in transform) {
for(var i : int = 0; i < asteroids.length; i++)
{
var randomPosition = Vector3(transform.position.x, 0, Random.Range(pos1, pos2)); //randomly spawns asteroids across z axis (done here as forloops update here)
var thingToSpawn : int = Random.Range( 0, asteroids.length ); //chooses randomly diferrent asteroids
var setAsteroid = Instantiate( asteroids[thingToSpawn], randomPosition, transform.rotation ); //instantiates selected asteroid
setAsteroid.transform.parent = transform;
Debug.Log("instatiating");
}
// }
}
What do you mean by the length of the object? The X, Y or Z axis?
are you just trying to get the length of a collider or?
collider.bounds.x / y/ z will get you that.
Im trying to get the z-Axis of an object. So if an object has a very long z-axis then the asteroids should spawn all across that z-axis. If it has a short z-axis then it only spawns within that.
So would collider.bounds.xyz work in a vector3 or instantiate line? I'll experiment with that and post results.
GetComponent.<Collider>().bounds.size.z
API here: http://docs.unity3d.com/ScriptReference/Bounds-size.html
Well yeah, we guessed that you have one end of the collider at zero so that our code would work.
Obviously if one end of your collider isn't at zero, there will be offsets.
Random.Range(zOffset, zOffset + GetComponent<Collider>().bounds.size.z)
zOffset will deter$$anonymous$$e the starting point. You can find this value by looking at the Z axis, scale and maybe doing some math.
Your answer
Follow this Question
Related Questions
prevent object from falling to the left side when instantiated (spawned) ? 1 Answer
Instantiate objects at random positions on axis 2 Answers
Checking if object intersects? 1 Answer
Instantiate a rotated object 4 Answers
Help needed on getting distance value of chain of links after instantiation 0 Answers