- Home /
Score with Text going up by random increments
Hello all,
I am currently trying to update my SCHMUP so that the player's score goes up by 100 when an enemy is destroyed. I have a Text in the Canvas which has a script managing the score that looks like this:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreScript : MonoBehaviour {
Text scoreWords;
int playerScore;
public int PlayerScore
{
get
{
return this.playerScore;
}
set
{
this.playerScore = value;
UpdateScore();
}
}
// Use this for initialization
void Start () {
scoreWords = GetComponent<Text>();
}
// Update is called once per frame
void UpdateScore () {
string scoreString = string.Format("{0:00000000}", playerScore);
scoreWords.text = scoreString;
}
I also have a script attached to each enemy that controls when they are destroyed that looks like this:
using UnityEngine;
using System.Collections;
public class Damage : MonoBehaviour {
GameObject ScoreText;
public int health = 1;
bool isColliding;
void Start(){
ScoreText = GameObject.FindGameObjectWithTag("Score");
}
void OnTriggerEnter2D(){
if(isColliding) return;
isColliding = true;
health--;
}
void Update(){
isColliding = false;
if(health <= 0){
Die();
}
}
void Die(){
ScoreText.GetComponent<ScoreScript>().PlayerScore += 100;
Destroy(gameObject);
}
}
The problem is, when an enemy is destroyed it randomly adds either 200, 300, or 400 points. Never 100. Also, enemies with health greater than 1 give points from all hits and not just from their destruction. If anyone could help me figure out why this is happening, I would be very grateful.
Answer by $$anonymous$$ · May 10, 2016 at 06:49 AM
Try to use the Update function as little as possible. All your actions are event driven so only activate them on that event. Check your health<=0 in the OnTriggerEnter2D function and call the Die function there.
Thank you @$$anonymous$$. This helped for the inconsistency on the single hit players. One hit and it give 300 points every time. Why it is not 100, I don't know, but the number is arbitrary.. For enemies with more than one hit, however, they still give points on hits that aren't the final blow and those points are inconsistent, even though they use the same Damage script as the single hit enemies.
I have solved this issue now. In case anyone was wondering, the reason for the random increments and the fact that points went up without destroying an enemy, was because I used the same Damage script on each of the bulletPrefabs I was using to destroy them on impact. So each hit brought up the score and when it destroyed an enemy it brought it up even more.
Your answer
Follow this Question
Related Questions
Get Text from an Input Field on one scene and use it as a text on another scene Unity c# 0 Answers
How do I insert a variable into a URL? Please Help! 1 Answer
Display the same string in multiple text boxes 1 Answer
I have a problem with Unity UI Text 0 Answers
Help with GUIStyle showing up 0 Answers