How to write type-safe loosely coupled components
How does one go in Unity with enforcing type safety while not heavily relying on inheritance, embracing Unity's component-based architecture?
As a concrete example of what I'm trying to achieve, I have a Unit<T>
component which represents units on a strategy game grid where the cells have type T
. I also have the Selectable<T>
and Movable<T>
components. In some specific point of the code, in another component, I have a method which takes a Unit<T>
as parameter. I wanted to constrain this parameter to accept only Units which are Movable and Selectable. Is it doable somehow without having to refactor Selectable<T>
and Movable<T>
into interfaces and creating another component which inherits from Unit<T>
and implements the new ISelectable
and IMovable
, while maintaining the type safety?
"Embracing" the component based architecture isn't always the best approach. You can always use the RequireComponent attribute, to make sure a gameObject always has another component with it, but it's not really "type safe" at runtime.
Answer by Socapex · Dec 28, 2016 at 09:25 PM
Interfaces are great.
You can also use generic type constraints for more control on what you accept as T. This seems like what you want. public class MyGenericClass<T> where T:IComparable { }
from https://msdn.microsoft.com/en-us/library/bb384067.aspx
You can also do some nifty tricks with GetComponent and generic types. And of course, since you can figure out the type of T, you can perform different things accordingly.
Finally, you can use Duck Typing in C# through reflection. This is excruciatingly slow.
An opinion comment: These types of patterns are nice but have real impact on your software (duck typing for example). They work best in applications that do not need performance. In a video game, I recommend you take performance into consideration and steer away from runtime reflection if at all possible. Coupling your data and classes to improve performance is a valid option that presents itself to you. And with intelligent field/property/method/class renaming, many gripes of tightly coupled patterns are not an issue anymore.
Cheers :)
Your answer
Follow this Question
Related Questions
How to make Surface Effector change direction from script? 0 Answers
How to add a editing option to variables in a script in Inspector? 0 Answers
Physics.Linecast does not return collider between start and end. 1 Answer
Auto Set vs Manual Decrease (How to do both?) 1 Answer
Script help player controller 0 Answers