如何使用C#在Unity2D中创建一个kills计数器?

问题描述

我想做一个反击计数器,但是由于某种原因它不起作用。 这就是我所做的 我创建一个新的空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();
    }
}

在他被杀死后,我在敌人脚本BulletColision中调用了此函数:

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
            
        }
            
    }
}

解决方法

问题出在您的kills_score = GetComponent<Score>(); 参考上,如果您这样做:

Score

您正在搜索BulletCollision上的Score组件,我猜它没有GameManager组件,因为它是项目符号。

快速修复:

为您的TAG添加一个新的kills_score = GameObject.FindWithTag("GameManager").GetComponent<Score>(); ,例如“ GameManager”,然后使用

kills_score = GetComponent<Score>();

代替

public

要快速验证这一点,请将得分变量const PerformanceComponent = ({style}) => { return <View style={style}>...</View> } export default React.memo(PerformanceComponent) 设为变量,并在编辑器中查看参考设置是否正确。

另外,请注意,尝试使用LowerCamelCame命名法维护变量,这意味着以小写字母开头。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...