Search Unity

Help with Spawning object

Discussion in 'Scripting' started by shellac85, Apr 30, 2017.

  1. shellac85

    shellac85

    Joined:
    Mar 29, 2016
    Posts:
    23
    Hi I have this script to spawn these money bags throughout the the level that the player will collect. However when I run the game these bags just begin spawning at a rapid rate. How do I slow it down and randomise their spawn location. Thanks
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class MoneySpawn : MonoBehaviour {
    6.  
    7.     public float frequency = 1;
    8.     public float amplitude = 1;
    9.     public GameObject Money;
    10.  
    11.     // Use this for initialization
    12.     void Start () {
    13.  
    14.         Invoke ("Spawn", 1);
    15.        
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Spawn () {
    20.  
    21.         GameObject spawnedObject = Instantiate(Money) as GameObject;
    22.         spawnedObject.transform.position = transform.position; spawnedObject.GetComponent<Rigidbody>().AddForce(new Vector3(1, 0, 0)*amplitude,
    23.             ForceMode.Impulse); Invoke("Spawn", 1/frequency);
    24.        
    25.     }
    26. }
    27.  
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    To go by simply the code you've posted, adjust the 2nd paramter of the Invoke function to slow down the spawn (always/sometimes). :)
    Lookup Unity's Range.Range to get some random numbers. There are 2 overloads. 1 for floats and 1 for integers.
    https://docs.unity3d.com/ScriptReference/Random.Range.html
     
  3. shellac85

    shellac85

    Joined:
    Mar 29, 2016
    Posts:
    23
    the 2nd paramter of the Invoke function slows down the initial spawn, but once its invoked it goes crazy. How do I have a gap between each invoke? Tks
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, just a question, does the game object you're spawning have this script on it? That's the only thing I can think of, based on what I've seen you post, that could be responsible for what you're describing.
     
  5. shellac85

    shellac85

    Joined:
    Mar 29, 2016
    Posts:
    23
    I have actually started using InvokeRepeat now. Also Yes I had the script attached to the money bags.
     
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    That was the problem. InvokeRepeating is good, too, I was thinking of suggesting it, but it was essentially what you had written, anyways.
    You do not want that script on the spawned, though, right, unless you modified it. Because you were growing exponentially :)
    Glad ya got it fixed up. Enjoy your game.