- Home /
Question by
boxing_rex · Mar 13, 2014 at 06:34 PM ·
c#delay
Delaying a c# funtion
I have been trying for hours to try and add delay between my script sending damage to the player, at the moment it will kill the player almost instantly, whereas I would like it to have delay between taking damage. Is there a simple way of doing this in c# ?
Here's my player damage script:
using UnityEngine;
using System.Collections;
public class PlayerDamage : MonoBehaviour {
public int damage = 10;
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D col){
col.gameObject.BroadcastMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
}
}
Comment
Best Answer
Answer by stevethorne · Mar 13, 2014 at 06:43 PM
Add a cooldown for when you can take damage:
using UnityEngine;
using System.Collections;
public class PlayerDamage : MonoBehaviour {
public float damageCooldown = 5.0f; // cooldown time
private float cooldownTimer = 0.0f;
public int damage = 10;
void Start () {
}
// Update is called once per frame
void Update () {
cooldownTimer -= Time.deltaTime;
}
void OnCollisionEnter2D(Collision2D col){
if ( cooldownTimer <= 0 )
{
col.gameObject.BroadcastMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
cooldownTimer = damageCooldown;
}
}
}
Answer by Jeremy2300 · Mar 13, 2014 at 06:45 PM
Try using coroutines, for example:
void OnCollisionEnter2D(Collision2D col)
{
StartCoroutine( DamageDelay( col ) );
}
IEnumerator DamageDelay( Collision2D col )
{
yield return new WaitForSeconds( 1.0f );
col.gameObject.BroadcastMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
}
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Multiple Cars not working 1 Answer
Saving final score and displaying on main menu 1 Answer
null texture passed to GUI.DrawTexture 0 Answers