Creating an instance of a script withing another script

I have a

public class base_alarm : MonoBehaviour

in one script that I want to use in a player controller script multiple times, without having to drag & drop on my player object. In my player controller, I attempted to do the following

public base_alarm
alarm0,
alarm1,
(etc);

then in

void Start()
{
alarm0 = new base_alarm();
alarm1 = new base_alarm();
(etc…);
}

I get an error message that I cannot use “new” to create the base_alarm and must use AddComponent.
I attempted to change it to
alarm0 = AddComponent<base_alarm>();
and other variations thereof, but it says that AddComponent does not exist in this context. I then looked it up and see that AddComponent was removed from Unity 5.x.

How can I go about correcting this without using AddComponent and without having to make 8 “physical” copies of my script to drag on to the player prefab?

AddComponent belongs to GameObject. So you’ll need to create a GameObject to add this to first.

You may also be interested in intantiating prefabs instead.

You can’t use new to create an instance of any class that inherits from MonoBehaviour.

AddComponent is not removed, it’s just gameobject.AddComponent…however, this adds a component to your gameobject. If that is what you want, whatever gameobject has the script on it will end up with several copies on the gameobject. If you don’t want to do that, you’ll have to change how things are structured.

Would the gameobject be the character object I have the controller script attached to?

The controller script is currently attached to a prefab called obj_base_ship.

Basically I want the functionality of using the base_alarm script up to 8 times in multiple prefabs (almost all characters and enemies in my game) without having to make a million actual copies of the script.

Would I need to do any special GetComponent or similar to get a gameobject reference?
Or can I simply change my line to something like
alarm0 = gameObject.AddComponent<base_alarm()>;

After some trial and error I think it is now working. I’ll have to work out a few issues with some results I’m getting, but I changed the lines to

alarm0 = gameObject.AddComponent<base_alarm>();

and the scripts now show up in the inspector window when I run the game.

Progress! Thanks!