How can you store a reference to something that you don't know the type of yet?

I have 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 mini-managers (e.g., SpawnController), 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?

Interfaces, abstract classes, or a base class with an override. Take a look at the answer by @asafsitner in this question:

http://answers.unity3d.com/questions/381529/how-to-address-scripts-without-knowing-their-names.html

So after a little searching and thanks to a great answer from Jerdak on Stackoverflow, I’ve found the Javascript / Unityscript answer is in Polymorphism, or basically the use of script inheritance. Here’s a basic example for anyone who might find it useful. We create these three following scripts and create an empty GameController gameObject then add the ‘GameController’ script to it, as well as the ‘Controller_SurvivalMode’ script.

BaseController:

var c : String;

function WhatControllerIsThis()
{
	c = "I am the Base Class";
	Print( c );
}

function Print( d : String )
{
	Debug.Log("This controller is: " + this);
	Debug.Log(d);
}

Controller_SurvivalMode:

class Controller_SurvivalMode extends BaseController
{
	function WhatControllerIsThis()
	{
		c = "Today I will be a survival controller";
		Print( c );
	}
}

GameController:

var controller : BaseController;

function Awake()
{
	controller = GetComponent(BaseController);
	controller.WhatControllerIsThis();
}

Running this results in printing:

"This controller is: Controller_SurvivalMode"
"Today I will be a survival controller"

Usually you couldn’t store a reference to one script of under another type of script, but because of the extends keyword, the ‘Controller_SurvivalMode’ script is treated as a BaseController script through inheritance. Whatever different game mode you want, attach that ‘Controller_[Mode]’ script to the GameController GameObject, and so long as it extends the BaseClass, you’ll only ever need to typecast it as the BaseClass! :slight_smile: