So when you get a kill in my game a number on the screen goes up, and i would like for the final amount of kills to be displayed on the game over screen. How can i do this? My kill counter script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class KillCounter : MonoBehaviour
{
public Text counterText;
public int kills;
// Update is called once per frame
void Update()
{
ShowKills();
}
private void ShowKills()
{
counterText.text = kills.ToString();
}
public void AddKill()
{
kills++;
}
}
If there’s only one KillCounter in your scene then you could simply make it available by making the kills int static
// public int kills;
public static int kills;
then you could access it in another script simply by using
KillCounter.kills
If there are more KillCounters this won’t work though. You’d need to get a reference to the instance (. ie. through GetComponent()
PS. looks like you’re updating the counterText every frame on Update(). It probably makes more sense to put ShowKills() in the AddKill() method. That way it only runs when it needs to run. You might need to add a Start() method and run ShowKills() there as well.
It’s not a heavy operation in this case, but it’s good practice to think about ‘how can I structure my code to make as few calls as possible’, even if that means adding some lines of code. Especially anything you put in Update should be scrutinized of course since it will run literally every frame.