mercredi 22 mars 2023

C# (Unity): Automatically generate properties to access a field's fields

I created a small Presettable system: each Presettable object has a Preset field where Preset is simply a ScriptableObject:

public abstract class PresettableMonoBehaviour<TPreset>: MonoBehaviour, IPresettable<TPreset> 
        where TPreset : IPreset
    {
        [SerializeField] 
        private TPreset preset;
        public TPreset Preset => preset;

        ...
    }

Let's assume I defined this simple Presettable/Preset pair:

public class MyPresettable : PresettableMonoBehaviour<MyPreset>
{
        public int RelevantNumberIncremented() { return Preset.RelevantNumber + 1; }
}

public class MyPreset : Preset<MyPresettable>
{
        [field: SerializeField]
        public int RelevantNumber { get; private set; } = 10;
}

Ideally, I'd like to be able to access Preset.RelevantNumber by calling only RelevantNumber because logically it is directly part of MyPresettable. However I don't want to define properties to access each Preset's field one by one, I'd like to automatically generate (explicitly or implicitly) properties that fulfils the same role as private int RelevantNumber => Preset.RelevantNumber;

Is it possible?

I tried to look into custom Attributes, but the problem didn't change: I'd still have to call myAttribute.RelevantField.

Another option is to use strings and reflection, however I don't really like it because it requires you to know the exact name of every field in your Preset





Aucun commentaire:

Enregistrer un commentaire