OnMouseButtonDown

Hi everyone, I am new in Unity
I wrote this code :

public GameObject prefab;

public GameObject spawnPosition;

void Start()
{
}

void Update ()
{
}

void OnMouseButtonDown()

{
GameObject newPrefab = Instantiate (prefab, spawnPosition.transform.position);

Destroy(newPrefab, 3f);
}

if I click few time on the mouse button, it continues to instantiate gameobjects. How can I enable OnMouseButtonDown() function only after Destroy(newPrefab, 3f) been completed ?

Thx for helps.

At first, look carefully at method names. It is not OnMouseButtonDown, but OnMouseDown. Wrong naming is the source of many wasted hours.

I wrote 2 scripts for you. The first one is for the Spawner. Attach it to you gameobject, which you will click, and remember to add any type of collider component (CircleCollider2D, or something else), otherwise it won’t work.

Next, attach the second script (I called it NewPrefabScript) to your prefab.

And of course, don’t forget to drag and drop necessary objects to slots into the inspector. Enjoy:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour
{
	public GameObject prefab;
	public GameObject spawnPosition;
	public bool canSpawn = true;
	
	void OnMouseDown(){
		if (canSpawn){
			
			GameObject newPrefab = Instantiate(prefab, spawnPosition.transform.position, prefab.transform.rotation);
			
			newPrefab.GetComponent<NewPrefabScript>().spawner = this;
			
			Destroy(newPrefab, 3f);
		}
	}
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewPrefabScript : MonoBehaviour
{
	public Spawner spawner;
	
	void Start() => spawner.canSpawn = false;
		
	void OnDestroy() => spawner.canSpawn = true;
}