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.
Answer by yummy81 · Apr 27, 2020 at 06:24 AM
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;
}
thx you. resolved btw i replace GetComponent by AddComponent
There are many ways to achieve this. The other one is to turn On$$anonymous$$ouseDown into IEnumerator. In this case there is only one script, which you attach to the Spawner gameobject. Enjoy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : $$anonymous$$onoBehaviour
{
public GameObject prefab;
public GameObject spawnPosition;
bool canSpawn = true;
IEnumerator On$$anonymous$$ouseDown(){
if (canSpawn){
canSpawn = false;
GameObject newPrefab = Instantiate(prefab, spawnPosition.transform.position, prefab.transform.rotation);
yield return new WaitForSeconds(3f);
Destroy(newPrefab);
canSpawn = true;
}
}
}