1

so I'am to trying to practice in making a catch an object game in 2D c#, where I want to catch falling objects with my player object. So what I did is created an Empty GameObject and add a script to it that can spawn a falling object, problem is I don't know how to spawn it in a random place in every 2 - 3 seconds or so.

so here is my code and game view.

public class spawnball : MonoBehaviour {

public GameObject ballprefab;
GameObject ballclone;




// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0)) {

        spawn ();
        Destroy (ballclone,3);

    }
}

void spawn()
{
    ballclone = Instantiate (ballprefab,transform.position,Quaternion.identity)as GameObject;
}


}

above the line where I want it to randomly spawn

above the line where I want it to randomly spawn

1 Answer 1

2

You've got the basic idea so far.

The first step is to start using Time.deltaTime so you can work out how long has it been since last time we spawned a ball.

An example would be:

private timeSinceLastDrop: float;
private dropInterval: float = 3f;

void Update(){
    // have we surpassed our interval?
    if(timeSinceLastDrop >= dropInterval){
       this.spawn();
       timeSinceLastDrop = 0;
    }
    else
       timeSinceLastDrop += Time.deltaTime;
}

To meet the second issue of where to drop, you can use Random.Range(min, max) and then use min and max as the outermost parameters you can drop.

For example:

void spawn(){
    ballclone = Instantiate(ballprefab,transform.position,Quaternion.identity)as GameObject;
    ballclone.transform.position.x +=  Random.Range(-10f, 10f);
}



I wrote this without an IDE so there may be a syntax error in there somewhere.

Sign up to request clarification or add additional context in comments.

3 Comments

Only thing to note is that the code here uses UnityScript not C#, some minor conversion is required (variable declarations). Otherwise it looks like it'll compile.
@Draco18s I 100% agree with you, I honestly just assume that when people tag C# for unity they mean unityscript.
Unity compiles for both (and Boo, but lets be honest, no one uses Boo) so that assumption might not be true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.