Question by
syarizal24 · Jan 19 at 12:14 AM ·
scorescore systemdestroygameobject
Score does not increment correctly
I just created a very simple game, where there are about 27 spheres, and the spheres are destroyed when the user clicks it with the mouse. I tried to add a score function, the score will add by 1 each time the sphere is destroyed. But, the problem is the score increment by 26, and then 25 (after 1 got destroyed) and then 24, and so on. How do I fix this? Maybe because I assigned the same ClickAndDestroy script to all 27 spheres?
ClickAndDestroy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickAndDestroy : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
SphereCollider sc = hit.collider as SphereCollider;
if (sc != null)
{
Destroy(sc.gameObject);
ScoreScript.scoreValue += 1;
}
}
}
}
}
ScoreScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreScript : MonoBehaviour
{
public static int scoreValue = 0;
Text score;
// Start is called before the first frame update
void Start()
{
score = GetComponent<Text> ();
}
// Update is called once per frame
void Update()
{
score.text = "Score: " + scoreValue;
}
}
Comment
Q: Maybe because I assigned the same ClickAndDestroy script to all 27 spheres?
A: No. Because your Update code will execute on every instance with the same results.
public class ClickAndDestroy : MonoBehaviour
{
void OnMouseDown ()
{
Destroy( gameObject );
ScoreScript.scoreValue += 1;
}
}
is all you need.