Ich habe gesucht und ich kann das nicht zur Arbeit bringen. Ich glaube, ich kenne einfach nicht die richtige Syntax oder begreife den Kontext einfach nicht.Wie kann man mit GetComponent auf eine Variable von einem anderen Skript in einem anderen Spielobjekt zugreifen?
Ich habe ein BombDrop-Skript, das eine öffentliche int enthält. Ich habe das mit öffentlichen Static arbeiten lassen, aber jemand hat gesagt, dass das eine wirklich schlechte Programmiergewohnheit ist und dass ich Kapselung lernen sollte. Hier ist, was ich schrieb:
BombDrop Skript:
<!-- 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);
}
}
So möchte ich die Bombe Skript, das auf dem prefabgameobject Bombprefab angebracht ist, die maxBombs integer in BombDrop zuzugreifen, so dass, wenn die Bombe zerstört wird fügt in BombDrop +1 zu maxBombs hinzu.
Und das ist das Bomb Skript, das die Referenz benötigt.
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);
In der Dokumentation heißt es, dass es so etwas wie
BombDropScript = otherGameObject.GetComponent<BombDrop>();
sein sollte, aber das funktioniert nicht. Vielleicht verstehe ich die Syntax hier einfach nicht. Soll es anderenGameObject sagen? Denn das tut nichts. Ich bekomme immer noch den Fehler: "Objektreferenz nicht gesetzt, mache eine Instanz eines Objekts" auf meiner BombDropScript.maxBombs in der explode()
können Sie diese 'verwenden BombDropScript = this.GetComponent();' –
Hmm. Immer noch der gleiche Fehler. :/ – DoubleCode
mögliche Duplikate von [Was ist eine NullReferenceException und wie behebe ich sie?] (Http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix- it) – LearnCocos2D