0

As much as it makes sense I'm trying to use interfaces when working with scripts, something like this:

public interface IConsumable
{
    Sprite Icon { get; set; }
}

However when using this approach, any classes implementing the interface do not show these properties in the inspector and I end up with something like this:

public class TestConsumable : MonoBehaviour, IConsumable
{
    public Sprite Icon { get { return IconSprite; } set { IconSprite = value; } }

    // Hack just to show up in Editor
    public Sprite IconSprite;
}

This doesn't really make sense to me and I was hoping there was a better solution.

Side-note, I'm not using getters / setters exclusively for Interfaces but also for some validation etc.

Thanks!

0

1 Answer 1

0

By default properties with get/set will not show up in the editor. You need to mark them with the "[SerializeField]" attribute in order to use them in the editor. The reason is that unity will only display types that it can save.

public class TestConsumable : MonoBehaviour, IConsumable
{
[SerializeField]
private Sprite icon;
public Sprite Icon { get { return icon; } set { icon = value; } }    
}
Sign up to request clarification or add additional context in comments.

5 Comments

Just tried it. Still doesn't work. The property still does not show up with getters / setters.
Sorry, forgot that you need to have a private backing variable for the property. Above code confirmed to work.
Awesome! That works. Didn't expect a backing variable to make all the difference :O Thanks mate.
You may not need the getter / setter if you have the SerializedField now of course. Unless you're using the accessor else where in the code, but I'm assuming the getter setter was just for the Serialization.
That code will reveal your private field icon in the inspector, not the property. When you set the field in the inspector, your setter block won't get called. If you want that you need to implement a custom inspector / propertyDrawer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.