I’m trying to do something very simple with JavaScript, but cobbling together a script from the samples in the reference documentation isn’t working for me at all.
I have a cylinder prefab, and all I want it to do is duplicate itself in a random position, within a certain radius. That cylinder would then also duplicate itself, etc, into infinity. Idealy, I’d also like to be able to adjust the number of duplicates that are instantiated.
I guess the first thing to do is to make the cylinder duplicate itself at all. This is all I have so far:
var myPrefab : GameObject;
Instantiate(myPrefab, Vector3.zero, Quaternion.identity);
In the script above we instantiate a predefined object which is set to the variable myPrefab in the Inspector. The position is 0 on world-XYZ and the rotation is unchanged.
var myPrefab : GameObject;
var myGameObject = Instantiate(myPrefab, Vector3.zero, Quaternion.identity);
In this script we reference the prefab instantiation to myGameObject. The object will still instantiate as normal but will be able to be easily modified directly and referenced to. For instance:
myGameObject.name = "Instantiated Prefab";
You always define like this: Instantiate(the object to spawn, the position, the rotation);
To instantiate something at a random position try this out:
var rndX : int = Random.Range(-10, 10);
var rndY : int = Random.Range(-10, 10);
var rndZ : int = Random.Range(-10, 10);
Instantiate(myPrefab, transform.position+Vector3(rndX, rndY, rndZ), Quaternion.identity);
Keep in mind that transform.position means the scripts current transform’s position in world-space.
Working version of your code, because explaining it is harder than demonstrating-
var circleRadius : float;
var waitTime : float;
function Start()
{
StartCoroutine(WaitAndDuplicate());
}
function WaitAndDuplicate()
{
while(true)
{
yield WaitForSeconds(waitTime);
var randomOffset : Vector3 = Random.insideUnitCircle * circleRadius;
randomOffset = Vector3(randomOffset.x, randomOffset.z, randomOffset.y);
Instantiate(gameObject, transform.position + randomOffset, transform.rotation);
}
}
Add this script to the gameObject you want turned into a serious grey-goo scenario, and watch your GPU melt!
Instantiate takes 3 things- an original, a location, and a rotation. It copies the original, and puts it where you tell it to with the other two parts! As for the circle thing, Random.insideUnitCircle is a nice way of making random offsets in 2D- I had to rotate it back to the normal plane (in which x and z are the main coordinates and y is height, a decision I may never understand), so that it would spread out instead of up and down.
If you want your object to spawn anywhere in space (not just in a circle), replace
Random.insideUnitCircle
with
Random.insideUnitSphere
still multiplying this with the desired maximum radius (so that it is not just a number between Vector3.zero and one in any direction).