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): using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoneySpawn : MonoBehaviour { public float frequency = 1; public float amplitude = 1; public GameObject Money; // Use this for initialization void Start () { Invoke ("Spawn", 1); } // Update is called once per frame void Spawn () { GameObject spawnedObject = Instantiate(Money) as GameObject; spawnedObject.transform.position = transform.position; spawnedObject.GetComponent<Rigidbody>().AddForce(new Vector3(1, 0, 0)*amplitude, ForceMode.Impulse); Invoke("Spawn", 1/frequency); } }
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
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
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.
I have actually started using InvokeRepeat now. Also Yes I had the script attached to the money bags.
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.