[英]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的游戏对象属性,现在,它们都引用同一个实例。
我希望这有帮助! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.