How to add Custom Component to a new child game object.

HI !
I try to add custom component to a new child gameobject. Here’s my code :

private void Initialize(MvtCube Parent)
{
    duplicate = Parent.duplicate;
    TimeSpeed = Parent.TimeSpeed;
    f = Parent.f;
    A = Parent.A;
    nbHarmonique = Parent.nbHarmonique;
    trail = Parent.trail;
    mesh = Parent.mesh;
    filter = Parent.filter;
    duplicate += 2;
}

private void Start()
{
    if (duplicate <= nbHarmonique)
    {
        new GameObject("Cube" + duplicate).AddComponent<MvtCube>().Initialize(this);
        
    }

}
I Just would like to add the component trailRenderer(for exemple) from the parent to the created child.
I’m still new to unity and to this community. I hope i asked my question correctly.
Thanks A lot !!

ah, ok, you need to store a reference to the new game object so you can add more components. So, better to do this first:

  GameObject aCube = new GameObejct("Cube + duplicate);
  // now you can add as many components as you wish using 
  //  aCube variable to reference the new object:
  
  aCube.AddComponent<MvtCube>().Initialize(this);
  aCube.AddComponent<Any component you need>();

it is usually a good idea to store references to objects you create so that you can access them later. If you create multiple objects, store the references in an array or list.

Thanks a lot for your answer. I wasn’t aware about this way of creating, but it seems obvious now :slight_smile:
Thanks