I have class ‘action’ that has parameter of ‘delegate void Perfomance’ - ‘perfomance’ that is initialized in constructor. I want to declare and initialize a variable of ‘action’ class in Character’s(script class) field and give a Character’s method as constructor argument, but i can’t do that because Run is non-static method.
public abstract partial class Character : CharacterBody2D
{
protected class action
{
public delegate void Perfomance();
private readonly Perfomance perfomance;
public action(Perfomance perfomance)
{
actions.Add(this);
this.perfomance = perfomance;
}
}
protected static List<action> actions = new List<action>();
protected action run = new action(Run);
protected void Run()
{
}
public Character()
{
}
}
I need to have a variable of class ‘action’ that can be declared and initialized in Character’s field and have ‘perfomance’ setted as ‘Run’ method.
This error happens because you can’t reference an instance method (Run()) in a field initializer.
using Godot;
using System.Collections.Generic;
namespace Test20241021
{
public abstract partial class Character : CharacterBody2D
{
protected class Action
{
public delegate void Perfomance();
private readonly Perfomance perfomance;
public Action(Perfomance perfomance)
{
actions.Add(this);
this.perfomance = perfomance;
}
}
protected static List<Action> actions = [];
protected Action run;
public Character()
{
run = new Action(Run);
}
protected virtual void Run()
{
}
}
}
Action can be outside Character as internal class that will be not visible outside namespace. With that change code will be more readable in my opinion.
using Godot;
using System.Collections.Generic;
namespace Test20241021
{
public abstract partial class Character : CharacterBody2D
{
internal static List<Action> actions = [];
internal Action run;
public Character()
{
run = new Action(Run);
}
protected virtual void Run()
{
}
}
/// <summary>
/// This is internal class for Character
/// </summary>
internal class Action
{
public delegate void Perfomance();
private readonly Perfomance perfomance;
public Action(Perfomance perfomance)
{
Character.actions.Add(this);
this.perfomance = perfomance;
}
}
}