7

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!

fritz
  • 25
  • 4
Guntram
  • 414
  • 2
  • 5
  • 18
  • A `GameObject` could have properies/components, however a `GameObject` can't contain other `GameObject`s. Its a different story if you want to assign a `parent` as a `GameObject` to another. – Hristo Apr 28 '17 at 20:39
  • 1
    But let's say I have a plane. I can then add a cube to the plane by dragging it into the plane in the Unity hierarchy. Then the cube (GameObject) is a child of the plane (GameObject). Otherwise I get your point, but how can I assign tmpObject as a child of tmpController? – Guntram Apr 28 '17 at 20:42
  • Correct, but its not a component of the parent. – Hristo Apr 28 '17 at 20:43

1 Answers1

16

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>();
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • 1
    Yes you did. I believe Op wants to create new GameObject and assign it to the `tmpObject` variable but failed when he used `AddComponent` on a GameObject...The new keyword is the solution. – Programmer Apr 28 '17 at 20:53