My goal is to make it so when the Wheat gameObject is clicked, it will wait for two seconds before teleporting to a random location. However, when I click on it, it starts teleporting all over the place, and you can see it. How do I fix this?
Start Function
void Start()
{
playerItems = GameObject.Find("Player").GetComponent<PlayerItems>();
enteredGetMouseButtonDown = false;
randomPosition = new Vector2(Random.Range(-8.21f, 17.31f), Random.Range(-4.09f, 15.13f));
randomPosition2 = new Vector2(Random.Range(-8.21f, 17.31f), Random.Range(-4.09f, 15.13f));
randomPosition3 = new Vector2(Random.Range(-8.21f, 17.31f), Random.Range(-4.09f, 15.13f));
randomPosition4 = new Vector2(Random.Range(-8.21f, 17.31f), Random.Range(-4.09f, 15.13f));
randomPosition5 = new Vector2(Random.Range(-8.21f, 17.31f), Random.Range(-4.09f, 15.13f));
randomPosition6 = new Vector2(Random.Range(-8.21f, 17.31f), Random.Range(-4.09f, 15.13f));
Debug.Log("prewheatinstantiated");
InstantiateWheat();
InstantiateWheat2();
InstantiateWheat3();
InstantiateWheat4();
InstantiateWheat5();
InstantiateWheat6();
Debug.Log("postwheatinstantiated");
}
Inside update function
if (Input.GetMouseButtonDown(0))
{
// if (!enteredGetMouseButtonDown){
Debug.Log("stage2");
enteredGetMouseButtonDown = true;
Debug.Log("preraycast");
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hitInfo = Physics2D.GetRayIntersection(ray);
Debug.Log("predef");
if (hitInfo.collider != null)
{
Debug.Log("pretagcheck");
// Debug.Log(Wheat.name);
if (hitInfo.collider.gameObject.tag == "Wheat")
{
Debug.Log("tagged");
WheatClicked = true;
}
}
}
if (WheatClicked){
// coroutineStarted = true;
StartCoroutine(waitCoroutine());
}
waitCorountine
IEnumerator waitCoroutine(){
Debug.Log("CoroutineExample started at " + Time.time.ToString() + "s");
GameObject.Find("Wheat").transform.position = new Vector2(1000, 1000);
yield return new WaitForSeconds(2f);
Debug.Log("CoroutineExample ended at " + Time.time.ToString() + "s");
Debug.Log("prewheatclicked");
GameObject.Find("Wheat").transform.position = new Vector2(Random.Range(-8.21f, 17.31f), Random.Range(-4.09f, 15.13f));
playerItems.wheat += 1;
WheatClicked = false;
enteredGetMouseButtonDown = false;
}
Instantiation
void InstantiateWheat(){
GameObject Wheat = Instantiate(wheatPrefab, randomPosition, Quaternion.identity);
Wheat.name = "Wheat";
Wheat.gameObject.tag = "Wheat";
rn = Random.Range(1f, 3f);
Wheat.transform.localScale = new Vector3(rn, rn, 1);
Wheat.AddComponent<WheatScript>();
Wheat.AddComponent<BoxCollider2D>();
Wheat.GetComponent<SpriteRenderer>().sortingOrder = 1;
}
If you need any other code, let me know! I would really appreciate any help, and thank you!
P.S. I belieeve the object is getting clicked multiple times, but I don’t know how to fix it. I tried GetMouseButtonDown but it still isn’t working.
Notes: 2D game