I’m making a rpg type game and I need to make a hit function from my stats script that can work with different characters that all have the same public Hit() function. Is this possible?
Ambiguous Stats Script: this script is used on all characters
public float health = 50f;
public Component character;
public void Hit()
health -= amount;
character.Hit();
Character Script, Hit Function the character scripts handle each of the different attacks
public void Hit()
{
animator.SetTrigger("hit");
}
// IHitTarget.cs
public interface IHitTarget
{
void Hit();
}
Then, in each script implementing the Hit method, make them implement the interface :
public class Character : MonoBehaviour, IHitTarget
public class Enemy : MonoBehaviour, IHitTarget
Finally, in your stats script:
public float health = 50f;
public GameObject character;
private IHitTarget characterHitTarget;
private void Start()
{
characterHitTarget = character.GetComponent<IHitTarget>();
}
public void Hit()
{
health -= amount;
characterHitTarget.Hit();
}
so you need to call the function “hit” in all characters right ?
if yes you can use delegates to that.