Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
1
Question by ledisnomad · Mar 23, 2016 at 05:02 PM · scripting probleminstantiate prefabparenting

script add prefab instances to empty gameobject

I want to add multiple instances of a prefab to my scene on start and make them all children of an empty GameObject. This is what I have:

 public class LightWave01 : MonoBehaviour {
 
     public Transform light_fixture;
     public int num_x;
     public int num_z;
     public float space_x;
     public float space_z;
     public float freq1;
     public float freq2;
     public float amp;
     public float start_pt_x;
     public float start_pt_y;
     public float start_pt_z;
 
     private GameObject light_group;
 
     // Use this for initialization
     void Start()
     {
         light_group = new GameObject("LightGroup");
 
         for (int j = 0; j < num_z; j++)
         {
             for (int i = 0; i < num_x; i++)
             {
                 float x = -1.0f * (i * space_x - start_pt_x);
                 float z = -1.0f * (j * space_z - start_pt_y);
 
                 double f1 = Math.Sin(freq1 * x * Math.PI / num_x);
                 double f2 = Math.Sin(freq2 * z * Math.PI / num_z);
                 double y = amp * (f1 * f2) + 0.02 * j + start_pt_z;
 
                 float floatY = (float)y;
 
                 GameObject l = (GameObject) Instantiate(light_fixture, new Vector3(x, floatY, z), Quaternion.identity);
                 l.transform.parent = light_group.transform;
             }
         }
     }
 }

It creates a GameObject called "LightGroup," but only adds one instance of the "light_fixture" prefab, which is added to the bottom of the Hierarchy, not to the LightGroup GameObject. What am I missing?

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image landon912 · Mar 23, 2016 at 05:02 PM 0
Share

$$anonymous$$oved to Help Room.

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Bunny83 · Mar 23, 2016 at 05:22 PM

I don't see any specific error as long as "light_fixture" is of type "GameObject". Are you sure you don't get any error in the console? Tried adding a Debug.Log() into the inner for loop and print the values for "j" and "i"?

If the parenting doesn't work but the instantiate does work it's most likely because the cast to GameObject (in line 21) has failed because your prefab variable "light_fixture" doesn't reference a GameObject. Since the declaration of the variable is missing we can't tell for sure. In any case you should get an Exception about that.

Another thing which i could imagine is that there's an error in a script which is attached to the prefab you're instantiating. If Awake or OnEnable throw an exception that might fall through to your Instantiate line. However in that case you also should get an Exception in the console ^^.

edit
Well, as i though the type of your prefab and the type you're trying to cast to doesn't match. Your "light_fixture" variable is of type "Transform". When you drag a gameobject to that variable you don't store a reference to the gameobject of the prefab, but to it's Transform component.

Instantiate will return the same type that you pass to it. If you pass a component (like Transform but any Component is possible as well) to Instantiate it will clone the whole gameobject that contains that component. However the returned object will be the component you passed in.

So in your case Instantiate will return the Transform component of the cloned prefab. Of course you can't cast a reference to a Transform into a reference to a GameObject.

Change your code to:

 Transform l = (Transform) Instantiate(light_fixture, new Vector3(x, floatY, z), Quaternion.identity);
 l.parent = light_group.transform;
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ledisnomad · Mar 23, 2016 at 05:52 PM 0
Share

Thank you Bunny83. I updated my post to include the variable declarations. There is indeed an error that I didn't see because my console was closed:

"InvalidCastException: Cannot cast from source type to destination type. LightWave01.Start () (at Assets/Scripts/LightWave01.cs:39)" (which is actually line 35 in the posted script).

Instantiate() returns an Object, so how do I reference this new object (which is a clone of a prefab) and add it to the light_group GameObject?

avatar image Bunny83 ledisnomad · Mar 23, 2016 at 08:38 PM 0
Share

I've updated my answer.

Instantiate returns the type Object because thats the most common type of all types that could be returned. Instantiate can basically clone any object that is derived from UnityEngine.Object, not just prefabs. You can also clone materials, meshes, scriptableobjects audioclips, ... Instantiate will always return the actual type that you have passed in as original, just casted to "Object".

Components are just a special case. They can't live on their own. They always need a GameObject. So when you clone a Component it also clones the gameobject it's attached to (including all children and their components). You can also clone objects in the scene. You're not limited to prefabs.

avatar image ledisnomad Bunny83 · Mar 24, 2016 at 01:32 PM 0
Share

Thank you, Bunny83. That did it!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Trying to set the parent of an instantiated object to another instantiated object 1 Answer

Generating random points and instantiating prefabs with a set distance 0 Answers

Instantiate And move the GameObject to the click position from another position. 1 Answer

turret shoot in direction and hit my health (scripts attached,i need to know how to put it together) 0 Answers

Instantiating prefab in a grid help 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges