- Home /
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?
Answer by _met44 · Apr 10, 2014 at 05:30 PM
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);
}
You are correct. $$anonymous$$y health script is on my character and my power up script is on my power up.
I have no error this time, but the script is still not disabled.
Are you calling these methods from Update? That might be why it still wont disable.
Your answer
Follow this Question
Related Questions
Increase variable for a few seconds 2 Answers
Different execution rates in IEnumerator 1 Answer
Temporary boost 1 Answer
2D Animation does not start 1 Answer