- Home /
Help on kill counter script!
I put a kill counter script inside my enemy health script, so (theoretically) every time the object (enemy) gets destroyed, the counter goes up by one. using UnityEngine; using System.Collections;
public class Health : MonoBehaviour {
public static int kills;
public int hp = 3;
public bool isEnemy = true;
// Use this for initialization
void Awake()
{
kills = 0;
}
void OnGUI()
{
GUI.Label(new Rect(0, 0, 100, 25), "Kill Count: " + kills);
}
void OnTriggerEnter2D (Collider2D collider) {
ShotScript shot = collider.gameObject.GetComponent<ShotScript>();
if (shot != null) {
if (shot.isEnemyShot != isEnemy) {
hp -= shot.damage;
Destroy (shot.gameObject);
if (hp <= 0) {
Destroy (gameObject);
Health.kills++;
}
}
}
}
}
Here is what happens currently: Every time the health script executes (its a wave game, so it executes every second or so) *The Gui pops up *The enemy count goes back down to zero
I need it to where the GUI stays on the moment the game starts instead of It popping up when I execute the health script and the kill count does not reset. I know the code is tied into the health script so it's no surprise that this happens, but any help would be great.
Why not put the killcount and other shared data on a separate script/gameobject such as the player or a data gameobject. This way you can manage things much more easily, and if needed you can serialize this class too.
Just reference this script/object in the enemy and add a kill every time just before you destroy it.
@yashpal, you are totally wrong. Try this:
using UnityEngine;
using System.Collections;
public class TestScript : $$anonymous$$onoBehaviour {
// Use this for initialization
void Start () {
Destroy(gameObject);
Debug.Log ("It works!");
}
}
Btw, you don't know what static variables are, so you think they are destroyed too when an instance of a class is destroyed. Try reading more about them.
It works perfectly now! Thank you!
I just wondered but how would I be able to add, lets say, If you kill this enemy, you get 2 points, if you kill THIS one you get 1 etc? I would assume you would use the FindGameObjectsWithTag function, but I do not know to word it to where it would "work"
@incorrect, Thank you. I just deleted my comment. you are correct.
Your answer
Follow this Question
Related Questions
Killer + assistance id for shooter game 1 Answer
Keeping Score from Kills 0 Answers
Multiplayer Kill Counter? 2 Answers