Instantiating a new GameObject in C#

Hi all,
This should be a simple problem, but I haven’t been able to solve it yet!
I am trying to instantiate a bunch of ‘null’ gameobjects (ie with position 0,0,0 and rotation = identity) as helpers in my scene, without the need to drag in a prefab first. (Yes, I know I can just drag in a prefab… but let’s just assume this is for argument’s sake! :slight_smile: )

Is there a way to do this:
GameObject thing = new GameObject(“Thingy”, GameObject.transform.position(0,0,0), GameObject.transform.rotation(Quaternion.identity));

?

I’m using this definition from the scripting reference:
static function GameObject (name : string, params components : Type[ ]) : GameObject
Description
Creates a game object and attaches the specified components.

But maybe I don’t know how to pass in the parameters properly?

GameObject thing = new GameObject("Thingy");

It has a position of Vector3.zero and a rotation of Quaternion.identity by default. Position and rotation aren’t components anyway; they’re just elements of the Transform component.

–Eric

Ah yeah that’s true.

I also notice you can’t instantiate a transform directly, so you can’t just say:

Transform blah = new Transform();

Cos what I really want is a bunch of helper TRANSFORMS, but I’m having to instantiate gameobjects and then use their transforms. Is that correct?

Yeah, you can’t have loose components without a GameObject to hang them on. Also you can’t have a GameObject with zero components, so making an empty GameObject like that automatically adds a Transform component.

Hey, as long as you’ve brought this up, not that it really applies after all, but anyway:

As far as the “GameObject (name : string, params components : Type[ ])” method goes, to use that you’d apparently supply an array of System.Type[ ]. Something like (Javascript):

var someComponents = new System.Type[2];
// Define someComponents[0] and someComponents[1] here
var thing = new GameObject("Thingy", someComponents)

Only thing is, I tried using that once and couldn’t figure out how you get UnityEngine.x (where x = Rigidbody, etc.) to System.Type. So if anyone knows, tell me please. :slight_smile:

–Eric

The function signature has the ‘params’ keyword for the array of types, which means you can add the remaining parameters to the end of the function call instead of putting them in an array:

var yourGameObject = new GameObject("Name", Rigidbody, SphereCollider, YourScript);
1 Like

Aha…actually I tried that first and for some reason it didn’t work; obviously I did something stupid and then made a wrong assumption. Thanks!

–Eric

This does not work for me. The compiler says it´s a type “type” but used as a variable. What am I doing wrong?

new GameObject("Name", typeof(Rigidbody));
3 Likes

Thank you for this answer KelsoMRK.
typeof is needed!