My game uses a variety of different game modes, and I'd like to spawn a different GameController script at the beginning of the scene depending on the game mode selected. Then other items (e.g., Enemies), would reference the main GameController, whether that be GameController_Mode1, GameController_Mode2, etc. But how can I have other objects referencing this if I don't know the type?
Unity iOS requires strict unityscript typing, so I can't use duck typing to get around this.
While it looks like there are some good answers already but it is worth mentioning Unity's SendMessage system. It is a really simple approach if all you need to do is call functions on the other object SendMessage.
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.SendMessage.html
In short you can use the following syntax:
You can also use SendMessage to call javascript functions from C# scripts or vice versa.
You can do this the same way you'd do it in C#, polymorphism. Derive all of your controllers from a single base Controller class. Then your GameController
var
can be set to any instantiation of a derived controller (seeStart()
in the example below).Here is a quick example using a simple controller:
I'm making any assumption that your gamecontrollers share function names and that the only difference is the code in each function.
[Update]
Regarding Heisenbug's comment below: You can use GetComponent to get the base class controller if your controller is a component.
Baseclass(BaseController.js):
Extended class(Controller1.js):
Test: