Get method in script with Generic list

Hi guys! Right now I’m developing a game with the ability to instantiate objects on the terrain. Now I’m closing up on 20 different buildings, which right now are all instantiated from one script with a variable for every object which is the one to instantiate, rotate and so on. Now, I would like to clean this up a bit, and my idea was to have every script and the associated building (object) in an empty GameObject, and then have a Generic list containing all scripts and then if I choose for example object 5 it should use the script object-5.cs and and then instantiate the object associated with the object 5 script. How would I do this, or is it another way?

Thanks!

You can use either inheritance or delegates.

Inheritance:

Create a c# file with this contents:

public interface IObjectSpawner
{
    void DoWork();
}

Then go to all your scripts that generate stuff and add that interface to their inheritance list. For example, if you have a script called TreeGenerator, edit the declaration so that it looks like:

public class TreeGenerator: MonoBehaviour, IObjectSpawner
{

    [...] // your script contents

    public void DoWork()
    {
        //Call here to the method in this script that does the spawning.
    }

}

And finally, on the centralized place where you want to have a generic list with all the scripts that spawn objects, you can declare it like this:

public List<IObjectSpawner> spawnerList;

And you can iterate over it and call the DoWork() method to spawn their object, for example:

foreach(var spawner in spawnerList)
{
    spawner.DoWork();
}

Delegates:

Declare your list as

public List<Action> spawnerMethods;

Add calls to the spawning methods into that list like:

spawnerMethods.Add(myScript1Object.DoSomeWork);
spawnerMethods.Add(myScript2Thingie.Spawn);
spawnerMethods.Add(myScript3Stuff.MakeClone);

Where the methods DoSomeWork, Spawn and MakeClone belonging to those three scripts all have in common that are called like

public void MethodName ()

that is, with no parameters and no return value.