我有两个 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/