- Home /
I want to create a for loop to create 10 balls using javascript
Hi Guys, I would like to change my method of creating balls to a for loop function but I searched over the internet and couldn't find suitable code for javascript. Any help please??? Here is my current code:
var ball:Rigidbody;
var balls:int;
var timer:int;
var playtime:int;
static var gameWin : boolean = false;
var gameWinskin : GUISkin;
public var Win: ParticleSystem;
function OnGUI(){
if (gameWin == true){
screenHeight = Camera.main.ScreenToWorldPoint(Vector3(0,Screen.height,0)).y;
screenWidth = Camera.main.ScreenToWorldPoint(Vector3(0,Screen.height,0)).x;
GUI.skin = gameWinskin;
GUI.Label(Rect((screenWidth+100),screenHeight+100,250,100),"YOU WIN");
}
}
function Start () {
Win= GameObject.Find("Win").GetComponent(ParticleSystem);
if(MainCameraScript){
MainCameraScript.BALLS = 10;
timer = Random.Range(1,2);
balls = MainCameraScript.BALLS;
if(balls>=1){
InvokeRepeating("ThrowBallsLevel",timer,timer);
}
}
}
function Update () {
if (StickmanScript.SCORE == 10)
{
audio.Stop();
Win.Emit(1000);
gameWin = true;
}
}
function ThrowBallsLevel () {
if(balls>=1){
Instantiate(ball,Vector3(10,10,0),transform.rotation);
balls--;
}
}
Answer by rutter · Jan 18, 2014 at 01:08 AM
Welcome to Unity Answers!
You might check out this other thread: How do I use 'for' to create loops in my script.
@duck's answer over there has quite a bit of detail.
There are a lot of for-loop tutorials out there; you may not find one which covers your exact scenario, but that's why it's so important that you understand the fundamentals. If you know what's going on, under the hood, you'll be able to adapt examples to fit your needs.
Short answer, something like this could spawn a bunch of balls in a stack:
var i : int;
for (i=0; i<10; i++) {
var spawnPos = Vector3.up * i;
Instantiate(ball, spawnPos, transform.rotation);
}