C
C#7mo ago
Goblini

Can you store a unique function within a class?

I'm new to working with classes in C# and would like to be able to use them for a game I'm working on - seems very integral to coding efficiently. public class Entity { public string Name { get; set; } public int Health { get; set; } public List<Ability> Abilities { get; set; } } public class Ability { public string Name; public string Description; public void Effect() { } } Ability Fireball = new Ability() { Name = "Fireball", Description = "A ball of fire."}; This is my current code, and I'd like to be able to allocate predefined abilities/actions to the individual entities, but when I try to define 'Fireball' in this example, I can't set what it's effect is? I imagine it's because the way I have it written currently, the effect would be constant within the class of Ability, rather than being a function I can assign to each one. Is there a way I can do this, or an alternative method to achieve this? What I'm currently working towards is being able to write my code as if it were Entity.Abilities[0].Effect(); or something similar.
3 Replies
Jimmacle
Jimmacle7mo ago
if you want to set it to a specific function at runtime, you're looking for a delegate which works similarly to a function pointer in other languages
Thinker
Thinker7mo ago
public class Ability
{
public string Name { get; set; }
public string Description { get; set; }
public Action Effect { get; set; }
}
public class Ability
{
public string Name { get; set; }
public string Description { get; set; }
public Action Effect { get; set; }
}
Ability fireball = new()
{
Name = "Fireball",
Description = "A ball of fire.",
Effect = () => Console.WriteLine("Fire!!!"),
};
Ability fireball = new()
{
Name = "Fireball",
Description = "A ball of fire.",
Effect = () => Console.WriteLine("Fire!!!"),
};
This is one way you could do it using a delegate (Action), as @Jimmacle mentioned. Action (and some related types, like Func) are essentially references to methods which you can store and call later.
Goblini
Goblini7mo ago
I did some extra reading up on actions and this seems prime, thank you very much! As a follow up to this, I have what feels like a niche issue at the moment - is there a way I can reference a parent class's variable within this subclasses action? I haven't been able to figure out how to access one of my Entities variables from the Ability's action (I.e. retrieving entity's health variable and modifying that from the entity's ability's action)