1

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.

4

2 回答 2

4

你可以像在 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
于 2013-05-27T05:04:50.353 回答
1

虽然看起来已经有一些很好的答案,但值得一提的是 Unity 的 SendMessage 系统。如果您需要做的只是调用另一个对象 SendMessage 上的函数,那么这是一种非常简单的方法。

http://docs.unity3d.com/Documentation/ScriptReference/GameObject.SendMessage.html

简而言之,您可以使用以下语法:

TargetGameObject.SendMessage("targetFunction", argument, SendMessageOptions.DontRequireReceiver);

您还可以使用 SendMessage 从 C# 脚本调用 javascript 函数,反之亦然。

于 2013-05-28T03:37:08.723 回答