Unity 5.6 - C# - Adding a GameObject to another GameObject with AddComponent<T>

Guntram picture Guntram · Apr 28, 2017 · Viewed 7.5k times · Source

The function I'm currently working on instantiates a GameObject (using a prefab). I store this GameObject in a local variable

GameObject tmpObject;

Works flawlessly. Next I try to assign this GameObject to my GameObject representation of my Vive controller, which looks like this:

tmpObject = tmpController.gameObject.AddComponent<GameObject>() as GameObject;

The error that I get is that UnityEngine.GameObject cannot be converted to UnityEngine.Component.

Am I missing a simple / basic there? I tried adding a SphereCollider as per Unity's official guidline and it did work, so why can't I add GameObject? Is there a workaround to adding GameObjects to another GameObject? Any help is greatly appreciated!

Answer

Programmer picture Programmer · Apr 28, 2017

You can't add GameObject to a GameObject. That doesn't even make sense to begin with.You can only attach components. I think that you want to make a GameObject a child of another GameObject... You can use the SetParent function for that. See below for examples how to create a GameObject and of what you can do:

Create a new GameOBject named "BallObject"

GameObject a = new GameObject("BallObject");

Create a new GameOBject named "BrickObject"

GameObject b = new GameObject("BrickObject");

Make "BrickObject" Object parent of "BallObject" Object

a.transform.SetParent(b.transform);

Make the "BallObject" Object to be by itself. "BrickObject" Object is not it's parent anymore

a.transform.parent = null;

Add script/component to your "BrickObject" Object

b.AddComponent<Rigidbody>();