I’ve completed the Space Shooter tutorial and have been trying to add something I thought would be simple. I’m trying to make it so that when the player hits a button, they will initiate a “dash” where the player’s speed increases and they become invulnerable for about a quarter second. My problem is that for some reason I’m making it so that neither the asteroids nor the player’s ship is ever destroyed, regardless of whether they’re dashing or not. I’m getting NullReferenceException: Object Reference not set to an instance of an object and I’m not sure why.
The idea was to create a variable to hold an instance of the playerController script that is attached to the player’s ship so that I would be able to access its variables, just like the tutorial did with the GameController object. Unfortunately PlayerController is a script attached to the Player object, it isn’t an object itself that I can just drag and drop in the Hierarchy.
Here’s the code in the DestroyByContact script.
public class DestroyByContact : MonoBehaviour {
public GameObject explosion;
public GameObject playerExplosion;
public int scoreValue;
private GameController gameController;
private PlayerController playerController;
void Start()
{
GameObject gameControllerObject = GameObject.FindGameObjectWithTag("GameController");
//Adding the following two lines causes the errors.
GameObject playerControllerObject = GameObject.Find("PlayerController");
playerController = playerControllerObject.GetComponent<PlayerController>();
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameController == null)
{
Debug.Log("Cannot find 'GameController' script");
}
}
void OnTriggerEnter (Collider other)
{
if (other.tag == "Boundary")
{
return;
}
Instantiate(explosion, transform.position, transform.rotation);
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
gameController.GameOver();
//Lines 42-46 are commented out to test my code. It changes nothing when commented out, so it's not the problem.
/* if (playerController.invincible == false)
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
gameController.GameOver();
}*/
}
//The next 3 lines no longer work after adding in lines 12 and 13.
gameController.AddScore(scoreValue);
Destroy(other.gameObject);
Destroy(gameObject);
}
}