Updating a scene in Unity with a script from Edit Mode

Viewed 1059

I am trying to add same components to different game objects in a scene in Unity. To make it faster I am trying to write a script that will do this for a list of game objects like (enemy1, enemy2, enemy3...).

I know that adding a script named Enemy I will do:

gameObject.AddComponent<Enemy>();

But the problem is once I stop the play mode the component is gone. Is there a way to achieve this?

1 Answers

You can directly select all the game objects (the list of enemies you mentioned) from the Hierarchy by holding ctrl and then add in the inspector the script Enemy to all of them.

However, if you want to use a script to do it, which can be executed outisde of the Play Mode you need to add ExecuteInEditMode before the script, like this:

[ExecuteInEditMode]
public class TriggerEdit : MonoBehaviour
{
    // List of GameObjects
    String[] enemyList = {"enemy1", "enemy2", "enemy3"};
    
    void OnEnable()
    {
        foreach(String enemy in enemyList){
            go = GameObject.Find(enemy);
            go.AddComponent<Enemy>();
        }
    }
}

Then you need to add that script to any game object in your scene. Everytime you want to trigger the script you just need to disable and enable the script TriggerEdit in the editor:

enter image description here

One problem with this approach is that everytime you enable the script, it will add a new component, independently if there is already a compoment of type Enemy in the game object, so you may end up with a lot of Enemy components. Something you can try then is to clean all Enemy components in the scene before adding anything else new. For example:

object[] enemiesToDelete = GameObject.FindObjectsOfType<Enemy>();

foreach(UnityEngine.Object enemyComponent in enemiesToDelete)
{
    DestroyImmediate(enemyComponent);
}
Related