Defining a variable later in script

hello all, I have a kind of annoying problem that’s outside of my knoeldge base.

I simply am declaring a variable(component) for a script; though this variable can be one of many scripts dependent on what level is currently being played though all of these scripts are attached to an object of the same name.

my problem is that it’s declared dynamically; but I can’t think of any way round this…

var B : GameObject;
public var BSC : Component;

function Start(){

//what level are we in?
	if (level == 1){
		Debug.Log("level One");
		levelOne();
	}
}



   function levelOne(){
    		B = GameObject.FindWithTag("enemy1");
    		var BS = B.GetComponent(bossOneScript);
    		BSC = BS;
    }

function levelTwo(){
B = GameObject.FindWithTag("enemy1");
var BS = B.GetComponent(bosstwoScript);
BSC = BS;
}

Any suggestions?

Thanks, Bobble.

This seems like a job for inheritance! After all what is the point of having a ‘BSC’ if you can’t talk to it.

You could create a class called ‘BossScriptBase’ or something like so:

class BossScriptBase extends MonoBehaviour
{
}

Then every ‘boss’ would simply extend that base:

class BossScriptOne extends BossScriptBase
{
}

class BossScriptTwo extends BossScriptBase
{
}

Note that each would have to be in a separate file. Then you could have your level start script work as follows:

var bossObject : GameObject;
public var bossScriptComponent : BossScriptBase;
 
function Start()
{
    // Get the boss and their component
    bossObject = GameObject.FindWithTag("enemy1");
	bossScriptComponent = bossObject.GetComponent(BossScriptBase);
	Debug.Log(bossScriptComponent);
}

Note that I just guessed at what the names of your variables represented - but its best if you spell out what the variable actually is. BS, BSC, etc are horrible variable names.

The magic of inheritance takes care of the rest so if you attach BossScriptOne - then the start script gets BossScriptOne, if you attach BossScriptTwo the start script gets BossScriptTwo.