我试着在游戏开发中问这个问题,但是我在这里问它。我试图从另一个脚本更新一个脚本中的浮点变量的值,但我不断收到以下错误
NullReferenceException: Object reference not set to an instance of an object GameController+<asteroidWaves>c__Iterator2.MoveNext () (at Assets/Scripts/GameController.cs:51)
为什么我收到此错误,我需要做些什么才能修复它?
public class GameController:MonoBehaviour{
public GameObject hazard;
public Vector3 hazard_values;
public int min_asteroids;
public int max_asteroids;
private int hazard_count;
public float spawn_wait;
public float start_wait;
public float wave_wait;
private int wave_count = 0;
public Text score_text;
private int score;
public Text restart;
public Text game_over_text;
private bool game_over;
private bool new_game;
private float new_speed = 1f;
void Start(){
game_over = false;
new_game = false;
restart.text = "";
game_over_text.text = "";
score = 0;
updateScore();
StartCoroutine(asteroidWaves());
}
void Update(){
if(new_game){
if(Input.GetKeyDown(KeyCode.Return)){
Application.LoadLevel(Application.loadedLevel);
}
}
}
IEnumerator asteroidWaves(){
yield return new WaitForSeconds(start_wait);
while(true){
wave_count += 1;
AsteroidMover asteroid = GetComponent<AsteroidMover>();
if(asteroid != null){
if(wave_count > 1){
min_asteroids *= wave_count;
max_asteroids += min_asteroids;
asteroid.increaseSpeed(new_speed);
}
}
if(asteroid == null){
Debug.Log ("Meh");
}
hazard_count = Random.Range(min_asteroids, max_asteroids);
for(int i = 0; i < hazard_count; i++){
Vector3 hazard_position = new Vector3(Random.Range(-hazard_values.x, hazard_values.x), hazard_values.y, hazard_values.z);
Quaternion hazard_rotation = Quaternion.identity;
Instantiate(hazard, hazard_position, hazard_rotation);
yield return new WaitForSeconds(spawn_wait);
}
yield return new WaitForSeconds(wave_wait);
if(game_over){
restart.text = "Press 'Enter' to start a new game.";
new_game = true;
break;
}
}
}
public void addScore(int new_score){
score += new_score;
updateScore();
}
void updateScore(){
score_text.text = "SCORE: " +score;
}
public void gameOver(){
game_over_text.text = "Game Over";
game_over = true;
}
}
public class AsteroidMover:MonoBehaviour{
private Rigidbody asteroid;
public float speed;
void Start(){
asteroid = GetComponent<Rigidbody>();
asteroid.velocity = transform.forward * speed;
}
public void increaseSpeed(float new_speed){
speed += (new_speed + 0.5f);
Debug.Log (speed);
}
}
答案 0 :(得分:1)
更改这两行代码:
StartCoroutine(asteroidWaves());
asteroid = GetComponent<AsteroidMover> ();
到
asteroid = GetComponent<AsteroidMover> ();
StartCoroutine(asteroidWaves());