Object reference not set to an instance of an object (C#)

Hi, I just started scripting in unity unguided (I did a GREAT book tutorial, and I learned alot.) My first attempts all went without a single error, so I decided I should try to code in some temporary placeholder combat code (since I would have no idea how to make permanent combat code at this point) [note this combat code is HORRIBLE and assume there is only one enemy, it’s just a placeholder to test the rest of the things as I make them] The problem is that I get that error on both sides of the combat, and then an error: "!CompareApproximately(det 1.0f, .005f) UnityEditor.DockArea:OnGUI()

I would love some help so that I can know what to avoid in the future. Like I said, I’ve been learning just fine, and the rest of the project has gone fine, but I’m not sure how to do this one…

Here are the combat excerpts in question:

EnemyStats.cs:

	void calcDmg()
	{
		{
			targetHp = GetComponent<PlayerStats>().hp;
			if(targetHp - atk > 0)
			{
				GetComponent<PlayerStats>().hp = targetHp - atk;
				Debug.Log ("You took " + atk + " damage!");
			}
			else
			{
				GetComponent<PlayerStats>().hp = 0;
				Debug.Log ("You have been killed.");
			}
		}
	}


PlayerStats.cs:

    	void calcDmg(float attack, float defense)
    	{
    		float damageDealt;
    		damageDealt = attack - defense;
    		if(GetComponent<EnemyStats>().hp - damageDealt > 0)
    		{
    		GetComponent <EnemyStats>().hp -= damageDealt;
    		}
    		else
    		{
    			Debug.Log ("You have killed the enemy");
    		}
    	}

It looks like GetComponent() and GetComponent() are probably returning null.

As written, your scripts assume the PlayerStats script and EnemyStats script are attached to the same GameObject. If you don’t have both scripts on the same GameObject, then GetComponent will not find anything in these code snippets.

As an aside, GetComponent is slow and generally should be cached in a variable, e.g. during the Awake() function, rather than calling it several times per calculation.