c# - Unity3D C#继承问题

标签 c# inheritance unity3d

我有两个 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 中,现在,它们都引用同一个实例。

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

关于c# - Unity3D C#继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920309/

相关文章:

c# - User.Identity.Name 在 PasswordSignInAsync MVC .Net Core 3.0 之后始终为 null 并声明计数为 0

c# - foreach 父类(super class)列表中的继承(子类)对象

.net - 从界面或基础继承注释

java - 具有继承性的 Spring @Autowire

iOS 11,Unity3d随机启动崩溃

c# - OnCollisionEnter 未检测到

c# - 在用 C# 编写的 COM+ 组件上处理 dispose

c# - 从 C# 调用 python 脚本不起作用,不会引发错误

c# - 使用 C++ 将 C# 方法编码到 Unity3D

c# - 字符串操作:以-字符分隔此字符串吗?