- Home /
I am trying to give my player points when an enemy dies
I am trying to give 5 points for every kill and whenever I kill an enemy the text flickers from 5 back down to 0 again. Here is the code I'm using:
using UnityEngine; using UnityEngine.AI; using UnityEngine.UI;
public class Enemy : MonoBehaviour {
public float health = 20f;
public float KillReward = 5f;
public float Score;
public Text scoreText;
void Update ()
{
scoreText.text = "Points: " + Score.ToString();
}
public void TakeDamage (float amount)
{
health -= amount;
if(health <= 0f)
{
Score += KillReward;
Die();
}
}
void Die ()
{
Destroy(gameObject);
}
}
Answer by Cornelis-de-Jager · Nov 19, 2019 at 01:17 AM
You are keeping Score in the Enemy class. But when you kill the enemy you are destroying the game object. This means that previously Score is not found anymore. If it is not found Unity will just use the default value for a float - which is 0.
You Need to keep the score at a different location. I'll post a solution here soon.
So when looking at Enemy-Player interaction, an easy way is to have a class that is available everywhere.
This is usually the Game Manager script. This is accessable everywhere and doesn't get destroyed on scene change.
// GameManager.cs
public class GameManager : MonoBehaviour {
public static GameManager Instance { get; private set; }
void Awake() {
if (Instance == null) {Instance = this; } else if (Instance != this) {Destroy(this); }
DontDestroyOnLoad(gameObject);
}
/* <Future Code Goes Here> */
}
Now lets add some more logic to this Game Manager that will help use keep score.
public Score = 0;
So now we have a score varaible. If you want to increase the score variable then do it like this.
public void TakeDamage (float amount)
{
health -= amount;
if(health <= 0f)
{
// It might be GameManager.Instance.Score += KillReward
GameManager.Score += KillReward;
Die();
}
}
Also I would highly recommend that your Text
object is created in your GameManager isntead of Enemy class. That way you can do this:
GameManager.Score += KillReward;
GameManager.scoreText = GameManager.Score;
Die();
...
Hope this helps!
Thank you, It's my first time using this website and its very useful. Your explanation was very thorough and I will try this later on my game.
After a little bit of tweaking with the code, It worked! Game$$anonymous$$anager.Instance.Score worked for me, thank you for including that! Thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220612215002im_/https://answers.unity.com/themes/thub/images/avi.jpg)