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);
		}
	
	}
}

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.

See the answer I just posted here:

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
}