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

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");
    		}
    	}

1 Answer

1

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.

Okay, how do I reference one that's in a different gameobject then? I can see how to do it for the one in enemystats but not playerstats

Check out this page: http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html Basically your options are have public PlayerStats and EnemyStats variables in your scripts, which you assign from the Inspector. Or, use GameObject.Find or GameObject.FindWithTag which are slower but let you do the reference at runtime.

Thanks! With your help I have figured it out, I think...I got one script to work at least, now to try the other. Any tips for combat scalability for when I actually intend to have more than one enemy on the screen/in the fight?