Call for damage only once

Hey everyone, sorry if this is a re-post.

I need to know how to keep something in an OnControllerColliderHit script to only call once, or any Update function for that matter. See I have a Baddy shooting a bullet at the player, and it’s dealing 30-50 damage, even though the script only says to take away 1 health at a time, and I’m asuming the problem is that it’s being called every frame, taking away 1 health every frame that the bullet is hitting the player, So how do I fix this?

function OnControllerColliderHit(hit:ControllerColliderHit) {
if(hit.gameObject.tag == ("BaddyBullet")){
TakeDamage();
}
}

function TakeDamage () {
Health -=1;
}

Thanks in advance, looking forward to a reply :slight_smile:

I think that you have the problem right.

You could make sure that OnControllerColliderHit is only called once per bullet (using OnCollisionEnter where-ever you call this function).

You could also make sure that each bullet can only do damage once, like so:

int lastBulletToHit;

function OnControllerColliderHit(hit:ControllerColliderHit) {
    if(hit.gameObject.tag == ("BaddyBullet")){
        if (lastBulletToHit != hit.gameObject.GetInstanceID())
            TakeDamage();
        lastBulletToHit = hit.gameObject.GetInstanceID();
    }
}

function TakeDamage () {
    Health -=1;
}

Guess I mixed C# into it there. I trust you’ll sort that out.

Good luck!

That worked perfectly! Would you care to elaborate on what that script does? I’ve never used GetInstanceID before in my life, what does it mean exactly?

Each time you make use of the function ‘Instantiate’ (like you do with each bullet), you are creating a copy of a given prefab. This is called an instance of the prefab (or class).

Consider a cookie cutter. By itself it doesn’t amount to much, it’s just an oddly shaped circle of metal or plastic. This is your class (or prefab bullet).

When you call instantiate, it’s the same as pressing the cookie cutter against a slab of dough. The resulting cookie is an instance of the class.

Each of these cookies, or GameObjects, are then assigned a unique ID so the computer can keep track of them.

Hope that made you go ‘Aha!’ somewhere :slight_smile:

Otherwise, look here.

Okay, so basically you’re telling it to recognize the InstanceID of each gameObject it hit’s with the BaddyBullet tag correct? And thanks for the help, it is GREATLY appreciated.

Yes, spot on. :slight_smile: