Kill ounter not working

Hello, I have been working on a horde game in which I wanted to add a kill counter. However, when I shoot the enemy, the kill counter increases by one for some time, and returns back to zero. I don’t know how to fix this.
Below is the script inside the ENEMY:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;
public class EnemyAi : MonoBehaviour
{

public int kill;
public Text killText;

// Start is called before the first frame update
private void Start()
{
killText.text = “0”.ToString();
}
}

void OnCollisionEnter(Collision collision)

if (collision.gameObject.tag == “Projectile”)
{
IncreaseKill();
Destroy(gameObject);
Destroy(collision.gameObject);
//killCounterScript.AddKill();
}

void IncreaseKill()
{
kill++;
killText.text = kill.ToString();
}
}

“Destroy(gameObject);”

At this point your script self-destructs. “gameObject” is an object this script is attached to. So you destroy the object and the script. After first hit it will stop working.

2 Likes

Thank you for helping me find the problem. However, could you please share how I could fix this?

Start with any tutorial on scorekeeping or kill counting. This is super-basic simple stuff but there is going to be a LOT more to it than just some code, making this little tiny text box unsuitable for explaining it all, even if you could find someone willing to retype everything here just for you.

The key takeaway is you need a single source of truth for kill count, either in a GameManager or score manager or somewhere central. In your code above you seem to have a kill count in every Enemy AI, which doesn’t make sense.

Imphenzia: How Did I Learn To Make Games:

thank you