Home > Software engineering >  Serializing a property from an Interface in Unity
Serializing a property from an Interface in Unity

Time:04-24

So, I'm currently working on a strategy game that involves 3 types of buildings: "Production", "Storage", and "Refining". Any building can belong to one or more of these types, so a Storage building could also be a Refining building and should then inherit the functionality of both of these types.

Example:

public class Stronghold : Building, IStorage, IRefining, IProduction
{
    public RefiningOption[] RefiningOptions { get; set; }
}

public interface IRefining
{
    public RefiningOption[] RefiningOptions { get; set; }
}

I went about implementing this using interfaces, but I am running into the issue that Unity does not allow you to serialize properties and interfaces can not contain fields.

Is there a way around this that would allow me to inherit from multiple different types in a neat way, or am I approaching this all wrong? I can think of a solution that would involve using separate components for the functionality of each building type, but before I implement that, I wanted to know what the "correct" solution would be.

Thanks in advance. I'm trying to expand my toolset, so any feedback is welcome.

CodePudding user response:

Just like the answer above but in a more "compact" way

[field: SerializeField] public RefiningOption[] RefiningOptions { get; set; }

This is an auto-property that generates a backing field that you can access directly by typing [field: "Your_Attribute_Here"], this is the same as having a [Serialized] private field with a public property exposing it.

CodePudding user response:

just like this ? create a field in private. and this private field can be serialize

private RefiningOption[] _refiningOptions;
public RefiningOption[] RefiningOptions 
{ 
    get { return _refiningOptions; } 
    set { _refiningOptions = value; } 
}
  • Related