I'm trying to create an invincibility power up. I have a DestroyByContact script on each of my enemies, the invincibility power up calls a function in the DestroyByContact script which turns the invincible bool to true. Then self explanatory in the OnTriggerEnter part when collider.other tag == "Player". if statement checks if bool is false, if it is proceed as usual, if true then not. Sounds simple enough. invincible turns true, no problem. but it only stays true for 1 collision then it turns itself back to false. This confuses me as there is no other conflicting code otherwise. I don't know if something like this is supposed to work. When I planned it out, this seemed the best and only way to achieve invincibility. I really didn't want to bother anyone with this, I found out what is going wrong but don't know how it is. I would appreciate any help offered. Cheers DestroyByContact Code (CSharp): void OnTriggerEnter (Collider other) { if (other.tag == "Boundary" || other.tag == "Enemy" || other.tag == "Hazard") { return; } if (explosion != null) { Instantiate(explosion, transform.position, transform.rotation); //Destroy (other.gameObject); } if (other.tag == "Player") { Debug.Log(invincible); if(invincible == false) { Instantiate(playerExplosion, other.transform.position, other.transform.rotation); Destroy (other.gameObject); Debug.Log(invincible); gameController.GameOver(); } } gameController.AddScore(scoreValue); //calls public AddScore function Destroy (gameObject); } public void Invincible(float countdown) { invincible = true; Debug.Log(invincible); } } This is how DestroyByContact worked before I messed with it incase that doesn't make sense. Code (CSharp): void OnTriggerEnter (Collider other) { if (other.tag == "Boundary" || other.tag == "Enemy" || other.tag == "Hazard") { return; } if (explosion != null) { Instantiate(explosion, transform.position, transform.rotation); } if (other.tag == "Player") { Instantiate(playerExplosion, other.transform.position, other.transform.rotation); gameController.GameOver(); } Destroy (other.gameObject); Destroy (gameObject); }
You would be better off if you handled all things invincibility within your player's class. I imagine something like this: Code (CSharp): class Player { ... private bool _invincible; public void setInvincible(bool invincible) { this._invincible = invincible; } public bool getInvincible() { return this._invincible; } ... } Then, in the OnTriggerEnter for your powerup, you would do something like this: Code (CSharp): void OnTriggerEnter(Collider other) { if (other.GetComponent<Player>() == null) { return; } var player = other.GetComponent<Player>(); player.setInvincible(true); } Finally, the last thing you'd need to do is in your DestroyByContact script you posted above. Code (CSharp): void OnTriggerEnter(Collider other) { if (other.GetComponent<Player>() != null) { var player = other.GetComponent<Player>(); if (player.getInvincible() == false) { //damage / destroy the player } } }