How do you remove a script from an object?

I have objects that should be able to add and remove scripts to themselves. I can add the scripts appropriately, but I currently can only disable the wants I want not to work. Is there a way to remove the script entirely?

I worry about this because even if I restart the game, the same scripts keep accumulating, meaning I quickly get 50 disabled scripts attached to one object.

I cannot simply use “destroy()” on the script, as Unity says it is preventing data loss.

Destroy(GetComponent());

Your problem is you are attaching and removing scripts from a prefab, not an instance in the scene. Unity is very reluctant to allow direct editing of prefabs with the Destroy command.

Two options

  1. Create an instance of the prefab in the scene. Disable it. Add and destroy the required components. Then use this instance as a pseudo prefab to instantiate from. Once you exit playmode the pseudo prefab will reset.
  2. Use DestroyImmediate. This will let you touch prefabs. The downside is it will let you touch prefabs. The wrong call can delete prefabs forever. Use with caution. The prefab will never reset itself, and you are stuck with the changes you make.

Why do you want to remove a script during runtime? If you absolutely have to do it, you might want to use this:

go.getComponent("component name").setActive(false);

/TheDDestroyer12

Perhaps you would benefit from the following methods:

public static T AddMissingComponent<T>(this GameObject extends)
    where T : Component
{
    T existing = extends.GetComponent<T>();
    if (existing == null)
        existing = extends.AddComponent<T>();
    return existing;
}

and

public static Object SafeDestroy(Object target)
{
    if (Application.isEditor)
        Object.DestroyImmediate(target);
    else
        Object.Destroy(target);

    return null;
}