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!

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

Share via Social Media

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

11 Comments