你可以像在 C# 中那样做,polymorphism。从单个基本 Controller 类派生所有控制器。然后您的 GameControllervar
可以设置为派生控制器的任何实例化(参见Start()
下面的示例)。
这是一个使用简单控制器的快速示例:
#pragma strict
var controller : MyController;
class MyController {
var data : int;
public function MyController(){
this.data = 42;
}
public function Print(){
Debug.Log("Controller: " + this.data);
}
}
class MyController1 extends MyController {
public function MyController1(){
this.data = 43;
}
public function Print(){
Debug.Log("Controller1: " + this.data);
}
}
class MyController2 extends MyController {
public function MyController2(){
this.data = 44;
}
public function Print(){
Debug.Log("Controller2: " + this.data);
}
}
function Start () {
controller = new MyController();
controller.Print(); // prints Controller: 42
controller = new MyController1();
controller.Print(); // prints Controller1: 43
controller = new MyController2();
controller.Print(); // prints Controller2: 44
}
我假设您的游戏控制器共享函数名称,唯一的区别是每个函数中的代码。
[更新]
关于Heisenbug下面的评论:如果您的控制器是组件,您可以使用GetComponent获取基类控制器。
基类(BaseController.js):
class BaseController extends MonoBehaviour{
public function Print(){
Debug.Log("BaseController");
}
}
扩展类(Controller1.js):
class Controller1 extends BaseController {
public function Print(){
Debug.Log("Controller1: " + this.data);
}
}
测试:
var controller : BaseController;
controller = gameObject.GetComponent("BaseController"); //.GetComponent(BaseController) also works
controller.Print(); // will print "Controller1" if actual attached component is a Controller1 type