New objects from script

I’ve been scouring the internet and various forums for a few days now with no luck. Hopefully this helps me and helps others who wonder the same thing.

So I was wondering how to create new instances of objects dynamically in a scene. This could be a new player or enemies.

From what I’ve read so far, a script needs to be attached to an object in order to use MonoBehavior, which I think I want. However, it doesn’t make sense to me that if I want to create a new player from scratch that I need to attach it to something. I feel like I should be able to run the game, and the script will run and create a new player during run time.

Let’s say that instead of just creating a game Object, and then attaching a Character Controller and Camera to it from the editor, I want to create a new Game Object in the script, and add a CharacterController and Camera from the script upon starting the game. How would I go about doing this? It doesn’t make much sense to me to have a blank game object just to attach my script to so that I can create a new player from scratch. However, from what I’ve found, this is what many people seem to be saying, but I’m hoping to get some expert advice on how to do this.

I want to learn how to create as many objects from scripts as possible without having to rely on using the unity editor per se. Additionally, it makes me curious as to how one would spawn multiple enemies, for instance, infinitely if an enemy script needs to be attached to an object.

I know I’m confused and I’m sure I’m misunderstanding how this works. Because of this, I’m looking for any links to documentation that might clarify this, expert advice, or just anything in general to clarify how this might work.

Well,

There are many ways but specifically to your question
Unity relies on the prefab concept Unity - Manual: Instantiating Prefabs at run time

which serves this purpose and it allows you a full customization which could be manually from the prefab itself within the editor or through scripts on the fly

Second way of doing thing but it is much more time consuming to script creation of many objects
is this Unity - Scripting API: GameObject.GameObject

Well everything serves its purpose but considering a pre planning for needed GameObjects and time needed you might need to use on over the other.


Regards