unity 3d student

Creating Random Spawning

Here is an example of how to create a spawn of an object in 3 potential positions. In my scene I have set up 3 differing locations using empty objects which I then apply to the transform variables in the script. The only other thing you’ll need is a prefab!

var timer : float = 0.0;
  1. var spawning : boolean = false;
  2. var prefab : Rigidbody;
  3. var spawn1 : Transform;
  4. var spawn2 : Transform;
  5. var spawn3 : Transform;
  6.  
  7. function Update () {
  8.  //check if spawning at the moment, if not add to timer
  9.  if(!spawning){
  10.   timer += Time.deltaTime;
  11.  }
  12.  //when timer reaches 2 seconds, call Spawn function
  13.  if(timer >= 2){
  14.   Spawn();
  15.  }
  16. }
  17.  
  18. function Spawn(){
  19.  //set spawning to true, to stop timer counting in the Update function
  20.  spawning = true;
  21.  //reset the timer to 0 so process can start over
  22.  timer = 0;
  23.  
  24.  //select a random number, inside a maths function absolute command to ensure it is a whole number
  25.  var randomPick : int = Mathf.Abs(Random.Range(1,4));
  26.  
  27.  //create a location 'Transform' type variable to store one of 3 possible locations declared at top of script
  28.  var location : Transform;
  29.  
  30.  //check what randomPick is, and select one of the 3 locations, based on that number
  31.  if(randomPick == 1){
  32.   location = spawn1;
  33.   Debug.Log("Chose pos 1");
  34.  }
  35.  else if(randomPick == 2){
  36.   location = spawn2;
  37.   Debug.Log("Chose pos 2");
  38.  }
  39.  else if(randomPick == 3){
  40.   location = spawn3;
  41.   Debug.Log("Chose pos 3");
  42.  }
  43.  
  44.  //create the object at point of the location variable
  45.  var thingToMake : Rigidbody = Instantiate(prefab, location.position, location.rotation);
  46.   thingToMake.AddForce(Vector3(0,0,100));
  47.  
  48.  //halt script for 1 second before returning to the start of the process
  49.  yield WaitForSeconds(1);
  50.  //set spawning back to false so timer may start again
  51.  spawning = false;
  52. }

Share via Social Media

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites

11 Comments