Add scripts by script in editor

hello,

I am importing a .fbx file with lots of objects like doors torches and more of that stuff but every door needs a script called “DoorScript” there are like 30 doors en 1000 torches (not 1 scene) I don’t want to add every object’s script manually so is it possible to add a "DoorScript"to every object that is called “Door”.

It must stay on the object for ever and not only when i start the game. so is that possible add lots a scripts automatic and that they will stay on it forever unitl i remove them myself.

Hope this is possible because i change the mesh often and have to replace it in my scene and replace all the scripts again then…

thanks in advance,

mvg. Lemon,

You can use editor script that looks for all such objects. Something like this:

using UnityEngine;
using UnityEditor;

public class Level_Add_Scripts : ScriptableObject {

    [MenuItem ("Custom/Level add scripts")]
    static void LevelAddScripts() {

		GameObject[] allObjects = (GameObject[])Editor.FindObjectsOfType( typeof(GameObject) );
		foreach ( GameObject obj in allObjects )
			if ( obj.name == "Door" ) 
			{
				DoorScript ds = obj.GetComponent(typeof(DoorScript)) as DoorScript;
			    if ( !ds )
			        obj.AddComponent(typeof(DoorScript));
			}

	}

}

And run it when you need.

Just create an AssetPostProcessor and use AssetPostprocessor.OnPostprocessModel to do what ever you want. The example in the scripting reference does something like that. It iterates through all containing objects andlook for objects with “collider” in the name and adds a MeshCollider.

Keep in mind that:

  • the postprocessor does that everytime you reimport the model.
  • the postprocessor is called for every model you import, so make sure you identify the right one.
  • since a new script is added to the model it might loose values you set to public variables of that script.