Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Item Respawn Scripting?

Discussion in 'Scripting' started by xXdragon15Xx, Aug 8, 2014.

  1. xXdragon15Xx

    xXdragon15Xx

    Joined:
    Aug 5, 2014
    Posts:
    28
    Hello, I'm trying to get weapons in my game to respawn after x ammount of seconds. This is the current script that works great other then... if the item is alredy spawned it'll keep spawning the item after each 10 seconds. So If you wait 20 seconds you have two of the same items.. How can I get / change the script so that it detects if the item is still there or if the item was picked up by a player it'll start the timer to respawn then activate the timer when a player picks it back up.

    Here is the current script:
    Code (JavaScript):
    1. var cube : GameObject;
    2. var spawn_position;
    3. var timer = 0.0;
    4.  
    5. function spawn_cube ()
    6. {
    7. spawn_position = Vector3(1,1,1);
    8. var temp_spawn_cube = Instantiate (cube, spawn_position, Quaternion.identity);
    9. }
    10.  
    11. function Start () {
    12.  
    13. }
    14. function Update () {
    15. timer += Time.deltaTime;
    16. if(timer > 20)
    17. {
    18. spawn_cube();
    19. timer = 0.0;
    20. }
    21. }
    IE: Player picks it up, timer starts, item spawns and waits to be picked up before timer and spawner start again.
     
  2. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    Set a bool, isSpawned. When the player picks up the object, set isSpawned to false. When the object is spawned, set isSpawned to true before resetting the timer to 0. Only respawn the object if both isSpawned == false AND timer > spawnTime.
     
  3. xXdragon15Xx

    xXdragon15Xx

    Joined:
    Aug 5, 2014
    Posts:
    28
    Examples..?
     
  4. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    Code (csharp):
    1. var bool: isSpawned;
    2.  
    3. ......
    4. function spawn_cube(){
    5.     isSpawned=true;
    6.     spawn_position = Vector3(1,1,1);
    7.     var temp_spawn_cube = Instantiate (cube, spawn_position, Quaternion.identity);
    8.  
    9. }
    10.  
    11. function ClaimItem(){
    12.     isSpawned=false;
    13.     timer = 0;
    14. }
    15.  
    16. function Update(){
    17.     timer += Time.deltaTime;
    18.     if(!isSpawned && timer >20){
    19.         spawn_cube();
    20.     }
    21. }
    You'll need some system of accessing this script and calling ClaimItem() whenever someone walks over and picks this up. There are a few ways to handle this - it depends on how you've set up the code to pick up the weapon (is the item on the ground destroyed?).