Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 /
avatar image
0
Question by pcote · Jul 11, 2011 at 03:31 AM · javascriptgameobjectprefabschildinstance

How to instantiate multiple Prefabs to multiple Childs randomly ?

Hello!

I'm a newbie at JavaScript and would like to know how to write a script to a GameObject which contain multiple childs, to then Instantiate to those childs from an Array of 3 Prefabs.

I successfully could instantiate randomly while applying a script to each of the childs but I want to be able to target multiple childs.

Here is the script I attached to individual childs at first:

 var pArray : GameObject[];
 
 function Start () {
     Invoke("Spawn", 0);
 }
 
 function Spawn(){
     var instance : GameObject = Instantiate(pArray[Random.Range(0, pArray.Length)], transform.position, transform.rotation);
 }


Now, when I apply this script to the parent, it only works on the parent. I don't have a clue of how to target each childs. Everything I tried lead me to errors. It's been hours now, I'm exhausted... T_T

Thanks.

Comment
Add comment
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

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Joshua · Jul 11, 2011 at 03:50 AM

Use GetComponentsInChildren, then iterate through them with a for loop.

This example will find all the children + the parent himself and then child a random prefab to them. Note that GetComponentsInChildren also returns the parent, if you don't want this you need to exclude him.

 var pArray : GameObject[];
 var children : Transform[] = gameObject.GetComponentsInChildren.< Transform>();
 for( var child : Transform in children )
 {
    var instance : GameObject = Instantiate(pArray[Random.Range(0, pArray.Length)], child.position, child.rotation);
    instance.transform.parent = child;
 }
Comment
Add comment · Show 4 · 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 pcote · Jul 13, 2011 at 04:16 PM 0
Share

Well, thanks for helping but that still doesn't work. There seems to be a problem with a portion of the code you provided. Something seems to be missing. I tried to fix it myself but got fed up over 10 $$anonymous$$utes. I tried to remove the parenthesis after "child.rotation" or add one before it. No results. Tried to put as comment to try to isolate the problem. No results.

It always gets me this kind of error:

Test.js(7,1): BCE0043: Unexpected token: .

Sorry about that. (-_-)

avatar image Joshua · Jul 13, 2011 at 04:26 PM 0
Share

Well it seems that this buggy site was not displaying my code properly :s half of it was simply not displayed.. so it's not your nor my fault. Should work now.. =\

avatar image pcote · Jul 13, 2011 at 04:44 PM 0
Share

Hmm... I don't know what's happening but a clean copy / paste gives me this error when I save:

Test.js(6,16): BCE0043: Unexpected token: ..

Phew... (>_<)

  • Update **

I even retyped the whole thing from scratch and it gave me a similar error:

Test.js(6,21): BCE0043: Unexpected token: ..

It doesn't like something on the last line I think...

avatar image pcote · Jul 14, 2011 at 05:21 PM 0
Share

Ok, I finally managed to make it work but there is an error on this line:

var instance.transform.parent = child;

I removed "var" and now it works. It's not exactly what I had in $$anonymous$$d though, as I have to manually define the children. But I'll work with it until I discover how to do it. Thanks Joshua!

avatar image
0

Answer by pcote · Jul 11, 2011 at 06:49 PM

Hello!

Thanks for your answer. Unfortunately, I cannot get it to work.

I get error for the second line of code:

 var children : GameObject[] = gameObject.GetComponentsInChildren.< Respawns >();
   

Child.js(2,68): BCE0018: The name 'Respawns' does not denote a valid type ('not found').

And then I get this error for the last line of code:

 var instance.transform.parent = child.transform;
 

Child.js(20,21): BCE0043: Unexpected token: ..

For the second line, I entered "Respawns" which is the name of the parent than contains those Instances: "Spawner_C1", "Spawner_C2", and so on.

I really suck at coding so syntax is my worse enemy... sorry about that. I'm always wondering why we cannot simply write we want in plain English. Like: Move THIS object THERE WHEN this object reaches THERE. LOOP that for each of THOSE objects, TWICE.

Haha... anyway. I suck... but thanks for helping me out. ^_^

UPDATE

Ok, I've tried to understand the GetComponentInChildren.`` but I cannot find any information anywhere about what <T> does and how it is used. Maybe that's one problem. No documentation about <T> in Unity, could not find anything in those forums and nothing on Google either. I don't understand where to get info on something that looks pretty basic... or maybe those brackets are recognized as commands... I noticed those disappeared when I was about to post this update...

UPDATE AGAIN

Alright, I seem to understand that <T> means "Type" so I reverted to your original syntax but there was something wrong with it at first, which is why tried something else. Here is what it said to me at first:

 var children : GameObject[] = gameObject.GetComponentsInChildren.< GameObject >();

Child.js(2,66): BCE0149: The type 'UnityEngine.GameObject' must derive from 'UnityEngine.Component' in order to substitute the generic parameter 'T' in 'UnityEngine.GameObject.GetComponentsInChildren(boolean)'.

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 Joshua · Jul 11, 2011 at 08:07 PM 0
Share

Hey there, in the future, please do not post comments as answers.

It could be that I was wrong about using GameObject as type, try transform. Other then that it all looks fine. I'll edit my original answer to show you how it should look. You need not change anything, except fill in the first array.

avatar image pcote · Jul 12, 2011 at 02:45 PM 0
Share

Oops, I didn't know how the system worked. Thanks for telling me about it!

Ok, I'll try with your update to see is the result. Thanks!

avatar image speedyzolt · Apr 11, 2014 at 11:06 PM 0
Share

I got the code to work, but wanted to know how to make sure no duplicates are instantiated. Please help thanx.

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Making cube a child of an object. 1 Answer

Calling a function via button from instance of prefab 1 Answer

How to copy a Script as a child of another object 1 Answer

How can I get a parent GameObject of gameObject using Javascript? 6 Answers

How do you Place/Spawn a GameObject or Prefab in front of Player 2 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