- Home /
The question is answered, right answer was accepted
Need Help with Dual Scoring System C# (score over time and kill score)
Hi, relatively new here and also with C# / Unity.
I'm building a game where the scoring is based on how long the player survives (score increases over time) but the player can also kill enemies to add on to the score (bonus score for each kill).
I use 2 scripts, one on my camera which updates the score over time and the other on my enemy which is supposed to update the bonus score. I can't seem to get the bonus score to update even though everything else is working fine.
Here's the first script on my Camera.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreBehaviour : MonoBehaviour
{
public static float score;
public Text scoreText;
void Start()
{
score = 0;
}
void Update()
{
score = Time.timeSinceLevelLoad * 27;
int showscore = (int)score;
scoreText.text = "Score: " + showscore.ToString ();
}
public void KillScore()
{
score = (Time.timeSinceLevelLoad * 27) + 500;
int showscore = (int)score;
scoreText.text = "Score: " + showscore.ToString ();
}
}
And the second script on my Enemy.
using UnityEngine;
using System.Collections;
public class EnemyBehaviour : MonoBehaviour
{
private ScoreBehaviour scrScript;
float speed = 5f;
void Start()
{
scrScript = GameObject.Find ("MainCamera").GetComponent<ScoreBehaviour> ();
}
void Awake()
{
Destroy(gameObject, 15f);
}
void Update ()
{
transform.Translate(0, 0, speed * Time.deltaTime);
}
void OnTriggerEnter(Collider laser)
{
if (laser.gameObject.tag == "Laser")
{
scrScript.KillScore();
laser.gameObject.GetComponent<MeshRenderer>().enabled = false;
Destroy (laser.gameObject, 0.7f);
Destroy(this.gameObject);
}
}
}
Answer by OncaLupe · Oct 29, 2015 at 04:09 AM
The problem is you're directly setting the variable score in the Update method, so no matter what change is made to it, the next frame it gets set back. Instead you'll want to increment it with something like this:
score = score + (Time.deltaTime * 27);
or a slightly shorter but equivalent style:
score += Time.deltaTime * 27;
Time.deltaTime is how long the frame took to perform, so adding that every frame will basically do the same thing as your code, but allow it to be changed in other sections of code. Then in the KillScore method:
score += 500;
This will just add 500 to whatever is currently in the score variable, regardless of how long the level has been running.
Follow this Question
Related Questions
How to check if variable is equal to range of integers 2 Answers
Scoring Points. 1 Answer
How to add score after destroying object in unity 2D? 1 Answer
Add bonus to score 1 Answer