Invincibility Power Up

Hi guys,

I am trying to create a invincibility powerup that lasts a few seconds

I have the following code:

private PlayerHealth healthScript;

	void Awake () 
	{
		healthScript = transform.root.GetComponent<PlayerHealth>();
		
	}

	// Use this for initialization
	void OnCollisionEnter2D (Collision2D other) 
	{
		if (other.gameObject.tag == "Player")
		{	
			StartCoroutine(NoDamage());
			GetComponent<SpriteRenderer>().enabled = false;
			GetComponent<BoxCollider2D>().enabled = false;
		}
	}

	IEnumerator NoDamage () 
	{
		Debug.Log ("Health Disabled " + PlayerHealth.health);
		healthScript.enabled = false;
		yield return new WaitForSeconds(5);
		Debug.Log ("Health Enabled " + PlayerHealth.health);

		healthScript.enabled = true;
		//Destroy(gameObject);
	
	}

and I receive an error saying “object reference not set to an instance of an object” on the line “healthScript.enabled = false;”

This script is on the character.

Why does it tell me the script doesn’t exist? Am I doing it wrong? What other way can I go about it?

It seems that your healthScript variable isn’t set properly. Also, if I understand it right you place this script on the power up and not on the player, so the healthScript = transform.root.GetComponent(); will return null because the script isn’t on the same object you are calling it from.

Try this:

void OnCollisionEnter2D (Collision2D other) 
    {
       if (other.gameObject.tag == "Player")
       { 
         healthScript = other.gameObject.GetComponent<PlayerHealth>();
         StartCoroutine(NoDamage());
         GetComponent<SpriteRenderer>().enabled = false;
         GetComponent<BoxCollider2D>().enabled = false;
       }
    }
 
    IEnumerator NoDamage () 
    {
       healthScript.enabled = false;
       Debug.Log ("Health Disabled " + healthScript.health);
       yield return new WaitForSeconds(5);
       Debug.Log ("Health Enabled " + healthScript.health);
 
       healthScript.enabled = true;
       //Destroy(gameObject);
 
    }