The infamous: Object Reference not set to an instance of an object

Been looking everywhere on how to fix this error in my script. It errors on hp = hp - playerShot.damage; Mono autofills it in so I know it at least sees it. I get no console warnings until I shoot the enemy and get “NullReferenceException: Object reference not set to an instance of an object Enemy.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/Enemy/Enemy.cs:47)”

Enemy.cs

public class Enemy : MonoBehaviour {


	public int hp = 10;


	void OnTriggerEnter2D(Collider2D other) {

		if (other.tag == "Boundary") {
			return;
		}

		PlayerShot playerShot = GetComponent<PlayerShot>();

		hp = hp - playerShot.damage;

		if (hp <= 0){
			Destroy (gameObject);
			Destroy (other.gameObject);
			Instantiate (explosion, transform.position, transform.rotation);
		}
	}
}

PlayerShot.cs

public class PlayerShot : MonoBehaviour {

	public int speed = 0;
	public float lifetime;
	public int damage = 1;

	void Start () {

		rigidbody2D.velocity = transform.up.normalized * speed;
		Destroy (gameObject, lifetime);
	}
}

You use GetComponent inside your Enemy script however i guess your PlayerShot script is not attached to your Enemy or is it?

You probably want this instead:

PlayerShot playerShot = other.GetComponent<PlayerShot>();

In addition you should check if the object that collides with the Enemy actually has a PlayerShot script attached by doing a null check before using your playerShot variable:

if (playerShot != null)
{
    hp = hp - playerShot.damage;
    // ...
}