如何处理我不知道类型的脚本? [英] How can I address a script I don't know the type of?
问题描述
我的游戏使用各种不同的游戏模式,并且我想根据所选的游戏模式在场景的开头生成一个不同的GameController脚本.然后其他项目(例如,敌人)将引用主要的GameController,无论是GameController_Mode1,GameController_Mode2等.但是,如果我不知道类型,我该如何让其他对象引用此对象?
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要求严格的unityscript类型,因此我不能使用鸭子类型来解决此问题.
Unity iOS requires strict unityscript typing, so I can't use duck typing to get around this.
推荐答案
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 (see Start()
in the example below).
这是一个使用简单控制器的简单示例:
Here is a quick example using a simple controller:
#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
}
我假设您的游戏控制器共享功能名称,唯一的区别是每个功能中的代码.
I'm making any assumption that your gamecontrollers share function names and that the only difference is the code in each function.
[更新]
关于下面的Heisenbug注释:如果您的控制器是组件,则可以使用GetComponent获取基类控制器.
Regarding Heisenbug's comment below: You can use GetComponent to get the base class controller if your controller is a component.
Baseclass(BaseController.js):
Baseclass(BaseController.js):
class BaseController extends MonoBehaviour{
public function Print(){
Debug.Log("BaseController");
}
}
扩展类(Controller1.js):
Extended class(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
这篇关于如何处理我不知道类型的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!