Create empty GameObject dynamically

Hi, is there anyway to create empty gameobject by using script only? i need to create a path based on xml data in runtime. thanks in advance

2 Likes
var go = new GameObject();

–Eric

14 Likes

excellent! i thought i need an api to do that. thanks

Been learning Unity recently and would like to add something else to this, since I found it searching on google and it was helpful, but:

var go = new GameObject().AddComponent<AudioSource> ();
go.name = "Music Player";

You can add components like that. I’m using something like this for playing music dynamically using only code. You can add any component you’d like, though, like a mesh and then a rigid body to create an object.

I don’t know what others thoughts on this are, but I felt like it’s better practice to have a player start position on the game map, but then maybe have the entirety of the player object created dynamically by just code. It feels like there’s a lot more control that way to me. In fact, I just feel like it’s better practice if you’re going to have tons of scenes as maps to have global objects created through script, like a global SFX Player, Music Player, Player object, etc… That way you don’t have to re-create any objects in mapping, so mapping is just mapping.

3 Likes

I’d have to quibble with that code and suggest that the variable name be “audioSource”, since it’s referring to the AudioSource component and not the GameObject. As far as best practices, I’d say that it depends, but it’s more likely to be a better practice to use a prefab. That way level designers can tweak parameters as necessary for each level, and they won’t have to recreate any objects. Just drop the prefab in.

–Eric

3 Likes

This can (now?) be also achieved using only

new GameObject("Music Player", AudioSource);

which I find more readable

Not quite, it’s new GameObject("Music Player", typeof(AudioSource));

I’ve never found the Type[ ] you’re using there useful. If I’m adding components, I generally need to do something with them, so using it would require me to GetComponent right after, so I might as well use AddComponent. The method is also a params method, so (afaik) it allocates an array for the elements you supply, even if you’re only adding one component.

1 Like