Time based score system?

I’m completely new to Unity. I’d like to know how I can click an object and receive 5 points for every 5 seconds after that point. Once the object is clicked again it should no longer render points. Help please?

2 Answers

2

Store a timer, increment it if the object has been clicked, every 5 seconds add 5 points. Here’s a basic example in c#.

bool isCounting = false;
float timer = 0f;
int points = 0;

public void OnObjectClicked()
{
    isCounting = !isCounting;
]

void Update()
{
    if(isCounting)
    {  
        timer += Time.deltaTime;
        if(timer > 5f)
        {
            points += 5;
            timer -= 5f;
        }
    }
}

void OnGUI()
{
    GUI.Label(new Rect(0,0,50,50), points.ToString());
}

You can probably use a self iterating coroutine.

	public void OnMouseOver()
	{
		
		if (Input.GetMouseButtonDown (0) && getPoints == false)
		{
			getPoints = true;
			StartCoroutine ("FivePointsCounter");
		}
		else if (Input.GetMouseButtonDown (0) && getPoints == true)
		{
			getPoints = false;
			StopCoroutine ("FivePointsCounter");

		}

	}


	IEnumerator FivePointsCounter()
	{
		points += 5;

		yield return new WaitForSeconds (5f);
		StartCoroutine ("FivePointsCounter");

	}