Unity3D C#继承问题

Unity3D C# Inheritance Issue

我有两个 C# 脚本。
一个给大炮:

using UnityEngine;
using System.Collections;

public class CannonScript : MonoBehaviour {

    public GameObject bullet; //bullet object
    public Transform spawnpoint; //spawn point
    float bulletspeed=-3000f; //bullet speed
    public int bullets=10; //number of bullets

    void Update () {
        if ((Input.GetKeyDown ("space") || Input.GetMouseButtonDown(0)) && bullets > 0) {
            GameObject newbullet; //make a new bullet
            newbullet=Instantiate(bullet,spawnpoint.position, spawnpoint.rotation)as GameObject; //instantiate the new bullet
            newbullet.rigidbody.AddForce(spawnpoint.forward * bulletspeed); //add force to the new bullet
            bullets--; //decrease the number of bullets left
        }
    }
}

屏幕上的 UI 文本:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class BulletCountScript : CannonScript { //inherit from the CannonScript

    Text text;

    void Start () {
        text = GetComponent<Text> ();
    }

    void Update () {
        text.text = bullets.ToString(); //display the number of bullets
    }
}

当我 运行 它时,屏幕上的 UI 文本永远不会改变。
我知道 CannonScript 工作正常,因为我只能发射 10 发子弹。
如何让我的 UI 文本显示剩余的项目符号数量?
我在继承方面做错了什么吗?

我认为你误解了继承的概念。我看到的问题是 类 都是 不同的实例 ,这就是原因,因为文本总是相同的。

要实现你想要的,只需这样做:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class BulletCountScript : MonoBehaviour { 

    public CannonScript cannon;
    Text text;

    void Start () {
        text = GetComponent<Text> ();
    }

    void Update () {
        text.text = cannon.bullets.ToString(); //display the number of bullets
    }
}

将拥有CannonScript的对象拖到游戏对象属性即可 在 BulletCountScript 中,现在,它们都引用同一个实例。

希望对您有所帮助!祝你好运!