Hey, I’m new to unity, having just jumped on with the 2D update. Also, my commercial programming experience is admittedly much more Java oriented than C#. That said, I’m coming up against a bit of a design question right off the bat.
Using MonoBehaviour’s “GetComponent” to access another MonoBehaviour Component on the current/child gameObject seems like a useful design approach. It’s allowed me to offload a lot of factory / configuration work onto the inspector. However, given that Component is a class (vs an interface) and GetComponent requires referencing the component child class through its generic, this approach quickly introduces a lot of tight coupling between those classes.
public interface PlayerCharacter {
void DoPlayerStuff();
}
public interface RobotCharacter {
}
public class PlayerCharacterImpl : MonoBehaviour, PlayerCharacter
{
public void DoStuff() { }
}
public class RobotCharacterImpl: MonoBehaviour, RobotCharacter
{
void Start()
{
PlayerCharacter player = GetComponent<PlayerCharacterImpl>(); //this class now tightly bound to PlayerCharacterImpl
//PlayerCharacter player = GetComponent<PlayerCharacter>(); //Impossible, PlayerCharacter not of type Component
player.DoPlayerStuff();
}
}
I’d love an API similar to GetComponent, but which allowed an unbounded generic that was assignable from an interface and not only assignable from component. Looser coupling would be allowed and given that Component exposes the world, interfaces would introduce some encapsulation between the two scripts.
I’m cooking up my own quick solution but I figured someone must have come up against this before and has a design solution out there. Alternatively, am I just way over-engineering this or using the functionality inappropriately?