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;
}
}
}