Calling the same function in two different scripts from one script.

So, I have my player with a player script that handles moving, attacking, etc
It has an attack function that goes like this:

public void AttackTrigger()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(attackCheckCollider.position, attackCheckRadius, attackLayer);
        if(colliders.Length != 0 && attackTimer < attackTime * 0.6 && attackTimer > attackTime * 0.4){
            attacked = true;
            RaycastHit2D targetHit;
            if(playerRB.transform.localScale.x == 1){targetHit = Physics2D.Raycast(playerRB.transform.position, Vector2.right, 1000, attackLayer);}
            else{targetHit = Physics2D.Raycast(playerRB.transform.position, Vector2.left, 1000, attackLayer);}

            targetHit.rigidbody.GetComponent<EnemyScript>().Hit(damage);
        }
        else if (attackTimer > attackTime * 0.6){
            attacked = true;
        }
    }

Ignoring how this is kinda messy and outdated, I want where it says “targetHit.rigidbody.GetComponent().Hit(damage);” to be able to reference and activate the function of multiple different scripts (such as enemyScript, bossScript, rangedEnemyScript), and im unsure on what the best way to do this is. Does anyone have any ideas on how this could be implemented?
Thanks in advance

I would suggest all your scripts such as EnemyScript, BossScript, rangedEnemyScript use interfaces. Then you can use GetComponent on that interface instead. You can also look into inheritance.

1 Like

I might approach something like this with events.

For example, the Player attack class could raise an event in the AttackTrigger method and the enemy, Boss and rangedEnemy classes could have listeners for that event.

1 Like

Don’t test floating point values for equality, ESPECIALLY floating point values coming out of an internal property getter such as .localScale, where you have no insight into how that number truly comes out or its likelihood to be precisely 1, as opposed to say 1.00001 or 0.9999, both of which would fail the above test.

You should use single-precision constants 0.6f and 0.4f here because by using 0.6 and 0.4 the entire expression is now going to use double precision math, which is nowhere near as performant as single-precision.

Also, those are magic numbers. They probably should be extracted into semantically-meaningful constants, such as:

const float MinAttackTime = 0.4f;
const float MaxAttackTime = 0.6f;

I’m just guessing the meaning here. You might have an even better way to declare / identify the values so your code becomes self-documenting.

1 Like

thank you! this is the solution i was looking for, i had seen it once but couldnt quite figure out how it worked or what it was called

1 Like

also thanks for these tips :slight_smile: