[英]How to make a kills counter in Unity2D with C#?
I want to make a kill counter but for some reason it's not working.我想制作一个杀戮计数器,但由于某种原因它不起作用。 Here is what i did I create a new empty GameObject
Game Manager
And add a new component Score
, Here is the code:这是我所做的,我创建了一个新的空 GameObject
Game Manager
并添加了一个新组件Score
,这是代码:
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public Text kills_UI;
private int Kills_Counts; //How many kills
public void Increase_score() //This will update the UI text to the current kills count
{
Kills_Counts++;
kills_UI.text = Kills_Counts.ToString();
}
}
After that i called this function in the enemy script BulletColision
after he is killed:之后我在他被杀后在敌人脚本
BulletColision
中调用了这个 function:
using UnityEngine;
public class BulletColision : MonoBehaviour
{
Score kills_score;
void Start()
{
kills_score = GetComponent<Score>();
}
public void OnCollisionEnter2D(Collision2D others) //When a bullet collide with en enemy prefab
{
if (others.gameObject.CompareTag("Enemy"))
{
Destroy(gameObject); //Destroy the enemy
kills_score.Increase_score(); //Calling the function from 'GameManager'
Destroy(others.gameObject); //Destroy the bullet
}
}
}
The problem is with your kills_score
reference, if you do:问题出在您的
kills_score
参考上,如果您这样做:
kills_score = GetComponent<Score>();
You are searching for Score
component on your BulletCollision
, which I guess do not have Score
component since it's a bullet.您正在
BulletCollision
上搜索Score
组件,我猜它没有Score
组件,因为它是一颗子弹。
Quick fix:快速解决:
Attach to your GameManager
a new TAG
like "GameManager", then use将新
TAG
附加到您的GameManager
,例如“GameManager”,然后使用
kills_score = GameObject.FindWithTag("GameManager").GetComponent<Score>();
instead of代替
kills_score = GetComponent<Score>();
To quickly validate this make your score variable public
and see in your editor if the reference is correctly set.要快速验证这一点,请
public
您的分数变量,并在您的编辑器中查看参考设置是否正确。
Also and as a side note, try to maintain your variables with lowerCamelCame nomenclature, meaning that starts with lower case.此外,作为旁注,请尝试使用 lowerCamelCam 命名法维护您的变量,这意味着以小写字母开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.