- Home /
Temporary invulnerability in a platformer
Hello,
I am working on a 2.5D platformer and we are in the finishing stages.
However, there is a feature I never understood how to implement (it's the first time I tried coding and I have zero programming formation).
We want to have a temporary invulnerability after the character takes a hit (like in the Mario games) so that life can't be drained in a second by continuous hits.
We are using "damage" trigger zones. How could I add a condition so that the trigger is only effective if there hasn't been damage in the last X seconds?
Here is the damage script:
var sound : AudioClip;
function OnTriggerEnter (other : Collider) { if(other.gameObject.tag == "Player"){ audio.PlayOneShot (sound); LifeGUI.charge--; } }
Many thanks in advance. Please remmember that I am not a programmer, so that what seems obvious to you isn't to me! ;)
When posting code, please format it using the code button (icon with 0s and 1s). $$anonymous$$akes it easier to copy/paste/alter!
Answer by · Sep 16, 2010 at 12:01 AM
You could use WaitForSeconds in conjunction with a boolean to create a timeout delay where damage cannot be applied. For example:
var sound : AudioClip; var damageTimeout : float = 1.0; private var canDamage : boolean = true;
function OnTriggerEnter (other : Collider) { if(other.gameObject.tag == "Player") { if ( canDamage ) // if damage can be applied ApplyDamage(); // apply the damage } }
function ApplyDamage () { audio.PlayOneShot (sound); // play the sound LifeGUI.charge--; // subtract the life charge canDamage = false; // disallow further damage yield WaitForSeconds(damageTimeout); // wait for the specified damage timeout canDamage = true; // allow damage again }
Any questions, please ask.
Wow, this look excellent. However, Unity is giving me errors I don't understand with your script:
It's asking for a ";" after the ApplyDamage function
It's giving me the following error on line 18 (LifeGUI.charge--;):
DamageDelay.js(16,29): BCE0044: expecting :, found ';'.
I really don't understand these errors, this seems against all I've learned in the last days about scripting.
Sorry if the answer is obvious, I feel dumb now...
Oops, I forgot to declare the function - can't test from where I am, sorry! Updated the answer, should be fine now.
Thanks! This seems obvious now, but I was totally clueless yesterday. Well, I should get more confortable with Javascript someday...!
Your answer
![](https://koobas.hobune.stream/wayback/20220613073258im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Collision, tags, and triggers 1 Answer
Delay audio collisions 1 Answer
Changing State of Character Model on Trigger 0 Answers
How can I make an enemy hurt the player? 3 Answers