- Home /
Simple Program counts OnGUI() If(Button)else(Anywhere but button) Score twice
Hey guys,
I'm really confused about how this code is working in my Unity project. It's a program that's generating randomly placed buttons, and the idea is that your score improves by 1 if you click them before they disappear, and decreases by 1 if you click anywhere else. However, this code is making clicks on the buttons decrease score by 1 and clicks outside the buttons decrease score by 2.
I'd also prefer the score to be calculated on Input.GetMouseButtonDown(0), but I have to use Input.GetMouseButtonUp(0) in order to get the score to synchronize correctly. The scene is extremely simple, with just a main camera, and empty game object with this code attached:
using UnityEngine;
using System.Collections;
public class Button : MonoBehaviour
{
public GameObject button;
public float score;
public float a, b, c, d;
public bool pressed;
public float delay = .5f;
private int width = Screen.width;
private int height = Screen.height;
// Use this for initialization
void Start()
{
}
void OnGUI()
{
if (GUI.Button(new Rect(0, 0, 250, 250), "" + score as string))
{
score += 1;
}
else if (pressed)
{
score -= 1;
}
if (GUI.Button(new Rect(a, b, c, d), "Click me!"))
{
score += 1;
}
}
// Update is called once per frame
void Update()
{
pressed = Input.GetMouseButton(0);
delay -= Time.deltaTime;
if (delay < 0)
{
a = Random.Range(0, width);
b = Random.Range(0, height);
c = Random.Range(0, width);
d = Random.Range(0, height);
delay = 0.5f;
}
}
}
Answer by tanoshimi · Sep 28, 2015 at 09:10 PM
You should never do game logic inside OnGUI () - it's called several times per frame, which probably explains your odd behaviour.
In fact, there's no reason to use OnGUI at all anymore - it's been obsolete since Unity 4.6 when UnityEngine.UI was introduced - I recommend you spend some time to learn that instead.
Your answer
![](https://koobas.hobune.stream/wayback/20220612035346im_/https://answers.unity.com/themes/thub/images/avi.jpg)