- Home /
Delaying Spawning a Object
I a have script that spawns a object on the mouse click. But since the update function is called every frame the objects are spawned very fast. Is there away to delay the spawning a little bit so the object don't spawn as fast? Here is the script:
using UnityEngine;
using System.Collections;
public class SpawnApple : MonoBehaviour {
private Vector3 SpawnPoint;
public Transform ApplePrefab;
private bool canSpawn;
// Use this for initialization
void Start () {
SpawnPoint = new Vector3(0,0,0);
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButton(0))
{
SpawnPoint = camera.ScreenToWorldPoint(Input.mousePosition);
SpawnPoint.z = 0;
Instantiate(ApplePrefab,SpawnPoint, gameObject.transform.rotation);
}
}
}
Answer by Darwin Mecharov · Apr 08, 2014 at 05:03 AM
Why not try to do GetMouseButtonDown/Up instead so that it only spawns the object once per click. Or, you could try using InvokeRepeating like this InvokeRepeating("SpawnObject", givenSeconds) to spawn an object every given amount of seconds even while mouse is held. Didn't test it yet though.
Thanks, that works great. I don't know why I didn't think of that.
Answer by supernat · Apr 08, 2014 at 05:05 AM
See the answer I just posted here: http://answers.unity3d.com/questions/682547/c-custom-slower-update-function.html
In summary, yes, you can put a timer in to run the code at a periodic interval through a CoRoutine or by creating a timeout that is tested every frame.
If you don't want to spawn except when the mouse first goes down, there's two ways to do that. You can add a bool variable mouseDown to your script and use it for edge detection:
bool mouseDown;
void Update () {
if(Input.GetMouseButton(0) && !mouseDown)
{
SpawnPoint = camera.ScreenToWorldPoint(Input.mousePosition);
SpawnPoint.z = 0;
Instantiate(ApplePrefab,SpawnPoint, gameObject.transform.rotation);
}
mouseDown = Input.GetMouseButton(0);
}
Or, if you only want to do this when the mouse is clicked on a collider attached to this script, you can do this:
void OnMouseDown() {
// Instantiate the object
}
Your answer
Follow this Question
Related Questions
Make delay for spawn 3 Answers
Unity Analytics Bug/Delay 4 Answers
keybind problem 0 Answers