Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 darkhog · Oct 17, 2013 at 10:31 PM · c#instantiateitemtoolhand

How to remove all children objects & how to instantiate prefab as child to specific object

I'm making for my 3D first-person adventure game, system so you can see what item do you hold (like e.g. tools/blocks in Minecraft). However to do it, I need to know how to remove all child objects to specific game object ("hand" or rather pivot where items are spawning) without actually removing that object and how to instantiate object as child to said game object (removing/instantiating will occur rarely as game doesn't have any high combat).

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

5 Replies

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

Answer by chillersanim · Oct 17, 2013 at 10:40 PM

The parrent-child concept is made with the transform property of each GameObject.
Instead of removing all childobjects instead of the hand, why don't you make the items be just the child of the hand and delete all of his child without worying what you delete?

Code for adding as child (objectA to objectB):

 objectA.transform.parrent = objectB.transform;

Code for removing all childs from an object:

 for (var i = objectB.transform.childCount - 1; i >= 0; i--)
 {
     // objectA is not the attached GameObject, so you can do all your checks with it.
     var objectA = objectB.transform.getChild(i);
     objectA.transform.parrent = null;
     // Optionally destroy the objectA if not longer needed
 } 

Greetings Chillersanim

Comment
Add comment · Show 5 · 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 darkhog · Oct 17, 2013 at 10:48 PM 0
Share

Well, that's the idea. I have following structure:

 Player
 |--Camera
 |--Hand
 ...|--HandPrefab
 ...|--$$anonymous$$aybe$$anonymous$$oreObjects

I want to remove all children to hand so it'll look like this:

 Player
 |--Camera
 |--Hand

Then I'm getting prefab to instantiate from some global item index (already made) and want to instantiate it as child of "Hand" (name not important). So it'll look like this:

 Player
 |--Camera
 |--Hand
 ...|--HandPrefab

Then again, etc.

Also, JS belongs to browser and only because there isn't anything better until Dart or CoffeeScript will take off and be natively supported by browsers. Please give C# code.

avatar image chillersanim · Oct 18, 2013 at 07:04 PM 0
Share

$$anonymous$$y code is c#
This is not JS, and I think that it looks rather different.
The var keyWord is also used in c#, and is often used.

For what you want, you can just use my code, it should work as is.

Greetings
Chillersanim

avatar image darkhog · Nov 02, 2013 at 06:45 PM 0
Share

I have doubts. Would loop fail? As in either not removing all children or trying to remove non-existent ones and thus causing exception? You know, childCount will be decreasing and causing condition to change...

avatar image chillersanim · Nov 02, 2013 at 07:22 PM 0
Share

You're right, thanks. Updated the code, should work now.

avatar image isteffy · Jul 25, 2016 at 08:41 AM 0
Share

When the child is removed from the parent, the child is given a completely different position. This is not the solution's fault but Unity, i should clarify. Is there any fix for this?

avatar image
3

Answer by rutter · Oct 18, 2013 at 07:57 PM

By "remove" children, do you mean detaching them from the parent, or removing them from the scene?

The GameObject hierarchy is determined by each transform's parent property.

Let's suppose we have two Transform references, child and root:

 Transform child = ...;
 Transform root = ...;

 //attach child to root
 child.parent = root;

 //detach child from root
 child.parent = null;

 //detach all of root's children
 root.DetachChildren();

Or, supposing we want to loop through and Destroy() all of root's children:

 foreach (Transform t in root) {
     Destroy(t.gameObject);
 }

As far as creating a prefab as a child of an object, it's a two-step process:

  • Call Instantiate() to spawn the prefab (this returns a reference to the spawned object)

  • Use that reference to access the instance's transform and set its parent

Something like this:

 GameObject trinketPrefab = ...
 GameObject trinket = (GameObject)Instantiate(trinketPrefab);
 trinket.transform.parent = root;
Comment
Add comment · Show 2 · 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 darkhog · Oct 18, 2013 at 10:59 PM 0
Share

Thanks!!!

avatar image sunwangshu · Jun 23, 2018 at 01:32 AM 0
Share

Thanks!!!!

avatar image
1

Answer by movAX13h · Nov 25, 2014 at 08:02 AM

Destroy all children of a GameObject (container):

 while(container.transform.childCount > 0)
 {
     Destroy(container.transform.GetChild(0).gameObject);
 }
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 rootPL · May 05, 2017 at 05:14 AM 0
Share

Code above create infinite loop.

avatar image movAX13h rootPL · Oct 05, 2017 at 11:17 PM 1
Share

Code works 100%. If it does not for you, you probably forgot the ".gameObject" part.

avatar image TharosTheDragon · Oct 05, 2017 at 10:48 PM 0
Share

Why would it be infinite? Does childCount not decrease when the children are destroyed?

avatar image sunwangshu · Jun 23, 2018 at 01:33 AM 0
Share

I don't understand but this broke my code as well, even after using container.gameobject.transform.childCount for both

avatar image
1

Answer by Develoop · Feb 27, 2020 at 06:27 PM

You can't destroy all childs in one frame for that reason use the follow code [100% working]:

 private IEnumerator IClearItems()
     {
         for (int i = 0; i < content.transform.childCount; i++)
         {
             Destroy(content.transform.GetChild(i).gameObject);
         }
         yield return new WaitUntil(() => content.transform.childCount == 0);
 
         // Code to initialize your new items
     }
Comment
Add comment · 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
0

Answer by pjj_gpu · May 08, 2019 at 01:24 AM

Notes/Warnings....

   Destroy... 
     is **NOT** immediate (as intended by Unity), 
     so if you immediately delete 3 and add 3   
     afterwards you end up with count = 6
     e.g.  null,null,null, newObj, newObj, newObj
 
    DestoryImmediate...
      changes the order in transform array as you delete ( any language thing )
      so can't use foreach( child  or for( i=0....
      as noted in other answer above, must Destroy in reverse order  
     int count = transform.childCount;
     for (int i = count -1; i>=0; i--) {
             GameObject.DestroyImmediate(transform.GetChild(i).gameObject);
     }


   
  


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

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

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Instantiated GameObject Not Rendering 1 Answer

Calculating where to position instantiated clone 1 Answer

Instantiate problem with selected objects 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