Strategy for reusing scripts on multiple levels

Hi,

I have many smaller scripts that connect to a main one that builds my level and runs it. The main script accesses the smaller ones and many of the smaller ones access the main script.

I make more levels. Each of them has its own main script because the builds and the gameplay of each level change and there will be many levels. All of the smaller scripts remain the same, but I can’t figure out an efficient way to tell them to access a different main script depending on the level. As far as I know or can find I can only access a script if I identify it specifically by name when assigning it to a variable. Each level has its own main script with its own name. Is there a better way to set up my scripts for this?

Thanks for any help.

This may not be a viable solution based on exactly how your project is set up, but this sounds like it may be a job for Inheritance/Polymorphism, one of the reasons object oriented programming is great. Make a base class (maybe called something like MainLevelScript) and then have each of your main scripts inherit from this script. Then your objects could interact with this script regardless of which type it is.

public abstract class MainLevelScript : Monobehavior{

    public abstract string name;

    public static MainLevelScript currentLevel;
}

public class LevelOneScript : MainLevelScript{
    public override string name = "Level One";

    void Start(){
        MainLevelScript.currentLevel = this;
    }
}

public class LevelTwoScript : MainLevelScript{
    public override string name = "Level Two";

    void Start(){
        MainLevelScript.currentLevel = this;
    }

    public void DoSpecialLevelTwoStuff(){
        Debug.Log("I am in level 2");
    }
}

Now here’s an example script of how you could interact with your main scripts

public class SmallScript : Monobehavior{

    void Start(){
        MainLevelScript mainScript = MainLevelScript.currentLevel;

        //I don't care what type the script is, I just want to know the level name
        Debug.Log(mainScript.name);

        //Do stuff only for some levels
        LevelTwoScript l2script = (LevelTwoScript)mainScript;
        if(l2script!=null){
            l2script.DoSpecialLevelTwoStuff();
        }
    }
}