Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

EveryTime I Run My Game Unity Crashes

So, I'm trying to make a clicker game, I want if the Player doesn't click it on time (five seconds) the button would get destroyed but every time I run this code Unity Crashes!

using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class Clicker : MonoBehaviour

{

  public RectTransform Button;

  public float health = 5;

  bool clicked = false;

  public void Update()

  {

    if (health <= 0)

    {

      Destroy(this.gameObject);

    }

  }

  public void Start()

  {

    onclick();

    StartCoroutine(deathtime());

  }

  public void onclick()

  {

    health = 5;

    clicked = true;

    int RandomX = Random.Range(124, 599);

    int RandomY = Random.Range(138, 1148);

    Button.position = new Vector3(RandomX, RandomY);

  }

  public IEnumerator deathtime()

  {

    while (true) 

    {

      if (clicked == false)

      {

        yield return new WaitForSeconds(1);

        health = -1;

      }

    }

  }

}

I guess it is the while loops that makes it crash but i dont know another way of doing it the way I want as I just explained so can you please help

Comments

  • Instead of calling a function to enumerator make a boolean called deathTime and set that to true


    And then Instead put the stuff in death time in void Update(), instead of a while loop do an if statement like if(deathtime).


    You probably should also have something to make deathTime = false if you need that. Maybe you would do it right after you decrease hp.

  • MintiMinti Member

    It isn’t necessarily crashing, you have it stuck in an infinite loop. Your code only “yields” if click is false. so when click isn’t false, it checks again, and again, and again, and will refuse to move. The next frame wont advance, so it wont register any clicks or inputs. If you stick a “yield return null” outside of that if statement you should be good.

Sign In or Register to comment.