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

How to spawn at random times

Discussion in 'Getting Started' started by kmo86, Jan 19, 2021.

  1. kmo86

    kmo86

    Joined:
    Dec 15, 2020
    Posts:
    104
    on create with code challenge 2 how can I code the 2 bonus bits. Make the spawn interval a random value between 3 seconds and 5 seconds and Only allow the player to spawn a new dog after a certain amount of time has passed

    This is my script.

    public class SpawnManagerX : MonoBehaviour
    {
    public GameObject[] ballPrefabs;

    private float spawnLimitXLeft = -22;
    private float spawnLimitXRight = 7;
    private float spawnPosY = 30;

    private float startDelay = 1.0f;
    private float spawnInterval = 4;
    public float ballIndex;

    // Start is called before the first frame update
    void Start()
    {
    InvokeRepeating("SpawnRandomBall", startDelay, spawnInterval);
    }

    // Spawn random ball at random x position at top of play area
    void SpawnRandomBall ()
    {
    // Generate random ball index and random spawn position
    int ballIndex = Random.Range(0, ballPrefabs.Length);
    Vector3 spawnPos = new Vector3(Random.Range(spawnLimitXLeft, spawnLimitXRight), spawnPosY, 0);

    // instantiate ball at random spawn location
    Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation);
    }

    }

    Thanks for any help. Still learning
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    You generate a random timer with the same Random.Range you're already using.

    https://docs.unity3d.com/ScriptReference/Random.Range.html

    Code (csharp):
    1. float randomTimer = Random.Range(3f, 5f);  //random float between 3 and 5
    Then you can just count it down by subtracting Time.deltaTime from it each update. When it is equal or less than 0f then you act.

    If you need to make sure a certain amount of time has passed, after setting randomTimer to the random value, you can check if it is >= that certain amount of time which needs to have passed. If false, then set randomTimer to whatever that certain amount of time which needs to have passed is.

    Good luck
     
    ilyarusin and xlikesasuke like this.
  3. Kerrigano

    Kerrigano

    Joined:
    Oct 7, 2021
    Posts:
    1
    Hello. While performing this task, I encountered a similar problem. The task hint states -" Hint - Set the spawnInterval value to a new random number between 3 and 5 seconds in the SpawnRandomBall method"
    upload_2021-10-10_10-58-10.png

    But when I start the game in the editor itself, only 1 ball falls.
    I want to understand why this is happening. Thank you in advance for any help.

    After various options, the solution turned out to be on the surface))
     

    Attached Files:

    Last edited: Oct 10, 2021
  4. x2plore

    x2plore

    Joined:
    Mar 10, 2017
    Posts:
    1
    as alternative:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SpawnManagerX : MonoBehaviour
    6. {
    7.     public GameObject[] ballPrefabs;
    8.  
    9.     private float spawnLimitXLeft = -22;
    10.     private float spawnLimitXRight = 7;
    11.     private float spawnPosY = 30;
    12.  
    13.     private float startDelay = 2.0f;
    14.     //private float spawnInterval;
    15.     private float targetTime;
    16.  
    17.     // Start is called before the first frame update
    18.     void Start()
    19.     {
    20.         //InvokeRepeating("SpawnRandomBall", startDelay, spawnInterval);
    21.         targetTime = 2;
    22.     }
    23.     private void Update()
    24.     {
    25.         targetTime -= Time.deltaTime;
    26.         if (targetTime <= 0)
    27.         {
    28.             SpawnRandomBall();
    29.             targetTime = Random.Range(3, 6);
    30.             //Debug.Log(targetTime);
    31.         }
    32.         Debug.Log(targetTime);
    33.  
    34.     }
    35.  
    36.     // Spawn random ball at random x position at top of play area
    37.     void SpawnRandomBall()
    38.     {
    39.  
    40.         int ballIndex = Random.Range(0, ballPrefabs.Length);
    41.  
    42.         // Generate random ball index and random spawn position
    43.         Vector3 spawnPos = new Vector3(Random.Range(spawnLimitXLeft, spawnLimitXRight), spawnPosY, 0);
    44.  
    45.         // instantiate ball at random spawn location
    46.         Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[0].transform.rotation);
    47.  
    48.  
    49.         //Debug.Log(targetTime);
    50.         //targetTime = 0;
    51.  
    52.     }
    53.  
    54. }
    55.  
     
    ViktorMacho and BrBarry like this.
  5. LONGQIUYU

    LONGQIUYU

    Joined:
    Jul 19, 2022
    Posts:
    5
    Hello, can you show me the correct and complete code? thank you very much!!
     
  6. Ale_A

    Ale_A

    Joined:
    Jun 22, 2022
    Posts:
    1
    Please, share the code, I can't solve it by myself :c
     
  7. SpiderFlash95

    SpiderFlash95

    Joined:
    Oct 31, 2022
    Posts:
    2
    Ask yourself following questions:
    1. When do I want a new random number? --> when the SpawnRandomBall function is called.
    2. When do I want to execute the SpawnRandomBall again? --> When I have a new random number generated.
    3. Does my Start function get updated? --> No, it only triggers the start of the game and calls the functions I type in there.

    I fixed it like this:
    Get rid of the repeat invoke in the start function and make it just an invoke to trigger the function to spawn a ball.
    Invoke("SpawnRandomBall", startDelay).​

    Then in the SpawnRandomBall you want to set a random number between 3 and 5 every time this function is called.
    spawnInterval = Random.Range(fastSpawn, lateSpawn);
    Once you know the next interval you just call the same function again, but with the random interval number.
    Invoke("SpawnRandomBall", spawnInterval);

    Every time the SpawnRandomBall is called it will generate a new number and call the function again after that many seconds. Not sure if this is THE solution, but it works very neat.
     
  8. axelchavezj

    axelchavezj

    Joined:
    Sep 12, 2020
    Posts:
    2
    Works Good, I had forgotten the concept of recursion. thanks
     
  9. RichAllen2023

    RichAllen2023

    Joined:
    Jul 19, 2016
    Posts:
    1,026
    With respect mate, you've been around these parts just over 2 years, you should know to use CODE tags.
     
  10. TestRats

    TestRats

    Joined:
    Jan 15, 2023
    Posts:
    1
    Hello everybody! That's how I solved it in my code, maybe it will be useful to someone =)


    public class SpawnManagerX : MonoBehaviour
    {
    public GameObject[] ballPrefabs;

    private float spawnLimitXLeft = -22;
    private float spawnLimitXRight = 7;
    private float spawnPosY = 30;

    private float startDelay = 1;
    private float spawnInterval;

    void Start()
    {
    Invoke("SpawnRandomBall", startDelay);
    }

    void SpawnRandomBall()
    {
    Vector3 spawnPos = new Vector3(Random.Range(spawnLimitXLeft, spawnLimitXRight), spawnPosY, 0);
    int randomBall = Random.Range(0, 3);

    Instantiate(ballPrefabs[randomBall], spawnPos, ballPrefabs[randomBall].transform.rotation);

    spawnInterval = Random.Range(3, 5);
    Invoke("SpawnRandomBall", spawnInterval);
    }

    }
     
  11. cyrcocq

    cyrcocq

    Joined:
    Nov 23, 2022
    Posts:
    1
    Hi all,
    But...
    Isn't i a problem to recurse again and again...
    For a game which dure for long and for witch the time repeating is short...
    Will it not overlaod a recursive heap?
     
  12. Moezinger

    Moezinger

    Joined:
    Dec 3, 2018
    Posts:
    4
    Thank you kindly.
     
  13. Bieeda

    Bieeda

    Joined:
    May 14, 2023
    Posts:
    1
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class SpawnManagerX : MonoBehaviour
    {
    public GameObject[] ballPrefabs;

    private float spawnLimitXLeft = -22;
    private float spawnLimitXRight = 7;
    private float spawnPosY = 30;

    private float startDelay = 1.0f;


    // Start is called before the first frame update
    void Start()
    {
    int spawnInter = Random.Range(1, 25);
    InvokeRepeating("SpawnRandomBall", startDelay, spawnInter);
    }

    // Spawn random ball at random x position at top of play area
    void SpawnRandomBall ()
    {
    // Generate random ball index and random spawn position
    Vector3 spawnPos = new Vector3(Random.Range(spawnLimitXLeft, spawnLimitXRight), spawnPosY, 0);

    // instantiate ball at random spawn location
    int ballIndex = Random.Range(0, ballPrefabs.Length);
    Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation);


    }

    }