【发布时间】:2014-12-20 12:10:40
【问题描述】:
我已经四处搜索,但我无法让它工作。我想我只是不知道正确的语法,或者只是不太了解上下文。
我有一个包含公共 int 的 BombDrop 脚本。我让这个与公共静态一起工作,但有人说这是一个非常糟糕的编程习惯,我应该学习封装。这是我写的:
BombDrop 脚本:
<!-- language: c# -->
public class BombDrop : MonoBehaviour {
public GameObject BombPrefab;
//Bombs that the player can drop
public int maxBombs = 1;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space)){
if(maxBombs > 0){
DropBomb();
//telling in console current bombs
Debug.Log("maxBombs = " + maxBombs);
}
}
}
void DropBomb(){
// remove one bomb from the current maxBombs
maxBombs -= 1;
// spawn bomb prefab
Vector2 pos = transform.position;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
Instantiate(BombPrefab, pos, Quaternion.identity);
}
}
所以我希望附加到 prefabgameobject Bombprefab 的 Bomb 脚本访问 BombDrop 中的 maxBombs 整数,这样当炸弹被摧毁时,它会在 BombDrop 中的 maxBombs 上加一。
这是需要引用的 Bomb 脚本。
public class Bomb : MonoBehaviour {
// Time after which the bomb explodes
float time = 3.0f;
// Explosion Prefab
public GameObject explosion;
BoxCollider2D collider;
private BombDrop BombDropScript;
void Awake (){
BombDropScript = GetComponent<BombDrop> ();
}
void Start () {
collider = gameObject.GetComponent<BoxCollider2D> ();
// Call the Explode function after a few seconds
Invoke("Explode", time);
}
void OnTriggerExit2D(Collider2D other){
collider.isTrigger = false;
}
void Explode() {
// Remove Bomb from game
Destroy(gameObject);
// When bomb is destroyed add 1 to the max
// number of bombs you can drop simultaneously .
BombDropScript.maxBombs += 1;
// Spawn Explosion
Instantiate(explosion,
transform.position,
Quaternion.identity);
在文档中它说它应该类似于
BombDropScript = otherGameObject.GetComponent<BombDrop>();
但这不起作用。也许我只是不明白这里的语法。是否应该说 otherGameObject?因为那没有任何作用。我仍然收到错误:“对象引用未设置做对象的实例”在我的 BombDropScript.maxBombs 中的爆炸()
【问题讨论】:
-
你可以用这个
BombDropScript = this.GetComponent<BombDrop>(); -
嗯。还是同样的错误。 : /