Ultra useful Unity snippet for developers who use interfaces

Unity can’t serialize interfaces. But sometimes you want to have access to any component, as long as it implements an interface. They are incredibly useful in game development, particularly if you’re coding for reuse. So what can you do? There’s a fairly lengthy workaround. You create a serialized Unity property for a GameObject. Then you create a second property (this time not serialized) for your interface. You use the interface property’s getter to get a component from the GameObject property that implements your desired interface.

I found myself writing this fairly lengthy code so often, I’ve turned it into my own Visual Studio snippet. Since I use it so much, maybe you will too. The code you’ll need is as follows:

Obviously swap privateGameObjectName, PublicGameObjectName, privateInterfaceName and PublicInterfaceName property names with ones suitable to your situation, and swap InterfaceType to the interface you want to use. After that, usage is as simple asĀ  PublicInterfaceName.DoWhateverInterfaceFunctionYouWant()

Leave a Reply

Your email address will not be published. Required fields are marked *