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

1

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!

Hiroko answered 28/4, 2017 at 20:35 Comment(3)
A GameObject could have properies/components, however a GameObject can't contain other GameObjects. Its a different story if you want to assign a parent as a GameObject to another.Conduplicate
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?Hiroko
Correct, but its not a component of the parent.Conduplicate
S
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>();
Saran answered 28/4, 2017 at 20:43 Comment(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.Saran

© 2022 - 2024 — McMap. All rights reserved.