- Home /
Float won't update when clicking multiple objects
I'm trying to update a float (spheresHit) when I click spheres that appear on the screen. I have a couple UI buttons that make 1 and 2 more spheres active in the scene. The problem being is that when there is more then one sphere on the screen the float doesnt update as many times as I want it to, only updating for one sphere. How can I get it so that when any sphere is clicked sphereHit gets updated? Here's both scripts that are being used:
public class ClickTargets : MonoBehaviour
{
float spheresHit;
float totalHits;
float accuracy;
public Text accuracyText;
public Text sphereHitText;
private void Start()
{
spheresHit = 0;
totalHits = 0;
accuracy = 0;
accuracyText.text = "Accuracy: " + accuracy.ToString("N2") + " %";
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
totalHits += 1;
accuracy = spheresHit / totalHits * 100;
}
accuracyText.text = "Accuracy: " + accuracy.ToString("N2") + " %";
sphereHitText.text = "Targets Hit: " + spheresHit + "/" + totalHits;
//Debug.Log(accuracy);
}
public void Hit()
{
spheresHit += 1;
transform.position = TargetBounds.Instance.GetRandomPosition();
sphereHitText.text = "Targets Hit: " + spheresHit + "/" + totalHits;
//accuracyText.text = "Accuracy: " + accuracy.ToString("N2") + " %";
Debug.Log(spheresHit);
}
}
public class TargetShooter : MonoBehaviour
{
[SerializeField] Camera cam;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
if (Physics.Raycast(ray, out RaycastHit hit))
{
ClickTargets target = hit.collider.gameObject.GetComponent<ClickTargets>();
if (target != null)
{
target.Hit();
}
}
}
}
}
Answer by TheGingerWoods · Jun 22, 2021 at 12:39 PM
Nevermind, all I had to do was make the spheresHit variable static
Your answer
Follow this Question
Related Questions
summing up items price in runtime 1 Answer
Keeping a float variable within a range based on keyboard input 1 Answer
Function not updating 1 Answer
How to make UI Label text loop through colors ? (example attached) 1 Answer
Since I can't add a yield during an update, how would I go around it? 1 Answer