Assigning a gameObject in the script

I’m sorry but I found it hard to get a good title for what I’m looking for. So, basically I want to assign a gameObject in the script. This is my current script:

	public TestHealth playerScript;
	private GameObject Player;
	
	void Start() {
		playerScript = Player.GetComponent<TestHealth>();
	}

	public void OnCollisionEnter2D (Collision2D other) {
		if(other.gameObject.name == "Player") {
			Debug.Log ("BONK");
			playerScript.curhp -= 10;
		}
	}

How can I assign “Player” to playerScript? When I do this by hand in the Unity interface, the game and function works, but I get an error message with a null reference to a gameObject, like the Player object was not assigned. But I believe this is only for the first frame or something. It is really annoying. I would love some insight on this!

Sorry for my lack of experience and depth, I am working hard to improve :slight_smile:

use

 public GameObject Player; 

or

[SerializeField]
private GameObject Player;

You simply don’t need your “Player” variable at all.

public TestHealth playerScript;
 
public void OnCollisionEnter2D (Collision2D other)
{
    if(other.gameObject.name == "Player")
    {
        Debug.Log ("BONK");
        playerScript.curhp -= 10;
    }
}

If you drag your player object onto the “playerScript” variable, Unity automatically assigns the TestHealth component to that variable. If the object you drag doesn’t have that component, you can’t assign it to that variable. using a GameObject reference and GetComponent in Start is just more complicated and not necessary at all.

In your Start() function you need to assign the Player variable. For example:

Player = GameObject.Find("NameOfThePlayerObjectInYourScene");