Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 693
Guntram Avatar asked Apr 28 '17 20:04

Guntram


People also ask

What is the current stable version of Unity?

Download Unity 2022.1 Get Unity 2022.1 from the Unity Hub – our tool to help you manage Unity Editor installations, create new projects, and access your work, all in one place. If you're a new professional user, start by getting a Unity Pro license from your team or the Unity Store.

When did Unity 5.6 release?

Unity Technologies Special Keynote, GDC 2017, San Francisco -- February 28, 2017 -- Today at GDC Unity Technologies announced that Unity 5.6 will release on March 31, 2017, marking the final installment of Unity 5.

Is Unity compatible with 32 bit?

System requirements OS: Windows 7 SP1+, 8, 10, 64-bit versions only; Mac OS X 10.12+; Ubuntu 16.04, 18.04, and CentOS 7.

When did Unity 5 release?

SAN FRANCISCO, CA - March 3, 2015 - Unity Technologies today announced the immediate availability of Unity 5, the next generation of the award-winning Unity multiplatform engine and development tools.


1 Answers

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>();
like image 88
Programmer Avatar answered Sep 30 '22 06:09

Programmer