Search Unity

Question Clone a button

Discussion in 'Scripting' started by melissa_NL, Sep 4, 2020.

  1. melissa_NL

    melissa_NL

    Joined:
    Feb 5, 2019
    Posts:
    1
    Hi all,

    I have six GameObject that i am spawning. I use the clone method for it.
    Now at a certain point, the GameObject need to display a countdown button. Every cloned GameObject, needs his own button.

    I have a countdown button in the scene.
    I use the following to let the button follow the GameObject, and it works.
    Code (CSharp):
    1. Vector3 btnPos = Camera.main.WorldToScreenPoint(this.transform.position);
    2. btn.transform.position = btnPos;
    The problem is, the one button in the scene, hops over to the clone objects.
    So, i tried to clone the button the same way i clone the other GameObjects and i try to assign them.
    But somehow it doesn't show anything.

    Can somebody help me with this.
     
    Last edited: Sep 4, 2020
  2. gaglabs

    gaglabs

    Joined:
    Oct 17, 2019
    Posts:
    185
    Wen you clone it you must assign it it the parent object.

    Code (CSharp):
    1.  GameObject _btn = Instantiate(_btnPrefab);
    2. _btn.transform.SetParent(_theParent.transform, false);
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Exactly what @gaglabs said but you can also do it in a single step to reduce the chance of it being missed, and also to make sure you don't omit the critical second optional boolean argument to
    .SetParent()
    :

    Code (csharp):
    1. GameObject _btn = Instantiate<GameObject>(_btnPrefab, _theParent.transform);
     
    gaglabs likes this.
  4. piggyfatguy

    piggyfatguy

    Joined:
    Mar 4, 2023
    Posts:
    3
    guys I'm trying to clone a button and then move it and clone it again and so on...
    so i can make a grid that i generate through code but how do i clone the button each time i move it and keep the position of witch the button i cloned it from before.