Scriptname.getcomponent and gameobject.getcomponent

public class Enemy : MonoBehaviour {

	PlayerHealth playerHealth;
	GameObject player;

	void Awake()
		player = GameObject.FindGameObjectWithTag ("Player");
		playerHealth = player.GetComponent<PlayerHealth>();


This code works fine. However i don’t understand what is the difference between:

playerHealth = GetComponent<PlayerHealth>();


playerHealth = player.GetComponent<PlayerHealth>();

And why first one gives me null exception.
And what they return.

This has to do with something in programming called scope. When you call GetComponent the compiler has some rules to find which object to call that function on. It’s going to look in the current object, then it’s parent class, and so on.

In this case it finds the function defined in the Component class and that’s the one that gets called. The Component.GetComponent method simply calls GetComponent on the GameObject that the component is attached to.

When you call player.GetComponent you’re just going right to the player gameobject, so it’s going to search for the component just on the player gameobject.

To answer your specific question…

playerHealth = GetComponent() is searching for the component in the gameobject that your Enemy script is attached to.

playerHealth = player.GetComponent() is searching for the component in the player gameobject.

The first one gives you the component of the Enemy, because the other way is not defined. I bet that you have no PlayerHealth on Enemy, so there is the reason of NULL.

These lines return you the requred component. If you need a float or int in return, write PlayerHealth script an put a public function in it which will return a health variable.