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 /
avatar image
0
Question by Clevereen · Apr 21, 2018 at 01:29 PM · gameobjectscriptingbasicschildrenaddcomponent

How to add component to a child of gameobject

bonjour/hello everyone,

i'm struggling with a basic script : i want to add a collider component to the children of my gameObject. But it's not working; I've been looking for hours and i'm sure it's simple! The purpose of this code is when i enable a toggle script it adds component to the children.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 
 [ExecuteInEditMode] //pour executer les evenements
 
 public class ShowCollider : MonoBehaviour
 {
     public GameObject gOchild;
     
     void OnEnable()
     {
        int numOfChildren = transform.childCount;//compte le nombre d'enfant du GameObject
         int i = 0;
         List<GameObject> goChild = new List<GameObject>();
 
         print("Script is Enable, number of children = " + numOfChildren);
 
         for (i = 0; i < numOfChildren; i++)
         {
            GetComponentInChildren.AddComponent<>(SphereCollider);
             //SphereCollider sc = gameObject.AddComponent<SphereCollider>() as SphereCollider; ;
         }
     }
 
 }

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

3 Replies

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

Answer by Cherno · Apr 21, 2018 at 01:47 PM

goChild is empty, you never fill it with any GameObjects.

Here is how you would need to do it:

 List<GameObject> childrenList = new List<GameObject>();
 //get all transforms in the hierarchy
 Transform[] children = GetComponentsInChildren<Transform>(true);
 //go through the transform array and only add their gameObjects to the list if they are not the parent (this) gameObject.
 for(int i = 0; i < children.Length; i++) {
      Transform child = children[i];
      if(child != transform) {
             childrenList.Add(child.gameObject);
     }
 }
 //go thorugh the list and add the component.
 for(int i = 0; i < childrenList.Count; i++) {
      SphereCollider sc = childrenList[i].AddComponent<SphereCollider>();
 }
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 Clevereen · Apr 21, 2018 at 11:37 PM 0
Share

Hello,

thank you very much for your help. I'm starting to understand more the logic of unity.

I'm still getting an error at

Transform[] children = GetComponentsInChildren(true);

"impossible to convert a UnityEngine.Transform type to a Transform[] "

i assume its because Transform is an array?

avatar image Cherno Clevereen · Apr 21, 2018 at 11:56 PM 0
Share

Are you sure you are using the correct code? It's important to use "GetComponent*s*InChildren as opposed to GetComponentInChildren. The former will yield an array with elements that are of type Transform, the latter a single Transform. See also the Scripting API:

https://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html

avatar image Clevereen Cherno · Apr 22, 2018 at 12:35 AM 0
Share

Ooooh! You were right! I've forgot the S! Sooorry!!

avatar image
0

Answer by Hellium · Apr 21, 2018 at 01:48 PM

 void Awake() // Don't use `OnEnable`, otherwise, each time your gameObject is enabled again, the function will run and you may end with several colliders to each children
  {
      // Compte le nombre d'enfants
      int childCount = transform.childCount;

      // Ajout un Collider à chaque enfant du gameObject
      for (int childIndex = 0; childIndex < childCount ; childIndex++)
         transform.GetChild( childIndex ).AddComponent<SphereCollider>();
  }
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 Clevereen · Apr 22, 2018 at 12:26 AM

I finally found the right syntax of the code! Thank you all!

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 
 [ExecuteInEditMode] //pour executer les evenements
 
 public class ShowCollider : MonoBehaviour
 {
     private Transform[] childrenTransform;//déclaration d'un tableau de transform
 
     
     void OnEnable()
     {
         /*DECLARATION DES TABLEAUX*/
         List<GameObject> childrenList = new List<GameObject>();// création d'une list de type GameObject
         childrenTransform = new Transform[transform.childCount]; //get all transforms in the hierarchy
 
         /*DECLARATION DES VARIABLES DE METHODES*/
         int numOfChildren = transform.childCount;//compte le nombre d'enfant du GameObject
         int i = 0;
        
         print("Script is Enable, number of children = " + numOfChildren);
 
         for (i = 0; i < numOfChildren; i++)
         {
             childrenTransform[i] = transform.GetChild(i); //récupère la position du GO child et le stock dans le tableau
             print("position du child : " + childrenTransform[i]);
             if(childrenTransform[i] != transform)
             {
                 childrenList.Add(childrenTransform[i].gameObject);
             }
             
         }
 
         //go through the list and add the component
         for(i=0;i<childrenList.Count;i++)
         {
             print("on ajoute : ");
             SphereCollider sc = childrenList[i].AddComponent<SphereCollider>() as SphereCollider;
         }
     }
 
 }
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

123 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 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 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 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 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 avatar image avatar image avatar image

Related Questions

how to control spriterRenderer in childrens 1 Answer

What is the order of execution for the instantiated object's GetComponent.Script.DoSomething? 1 Answer

Is it possible to get the width (in unity units) of a GameObject including all of its children? 1 Answer

Can't add component because class doesnt exist 1 Answer

Recursively get all children 1 Answer


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