4

I want to create dynamically ui button,

I have one prefab,

here is code:

  public class SFSConnect : MonoBehaviour {
        SmartFox sfs;

        public GameObject cnv1;
        public GameObject potchPrf;
        public Canvas fCanvas;
    void Start () {
    fCanvas = cnv1.GetComponent<Canvas> ();

            Button ptf1 = potchPrf.GetComponent<Button> ();

            Instantiate(ptf1,new Vector3 (0, 0, 10), Quaternion.identity);


            potchPrf.transform.SetParent (fCanvas.transform);
    }

}

I tried thousands of posts, but nothing happened

Muhammet Demir
  • 1,995
  • 5
  • 21
  • 42

1 Answers1

7

The problem is likely from potchPrf.transform.SetParent (fCanvas.transform); and this means that you are trying to modify a prefab. You can't change the parent of a prefab from code.

Maybe you wanted to set the parent of the instantied object?

If that's the case then store it in a variable

GameObject uiObj = Instantiate<GameObject>(ptf1,new Vector3 (0, 0, 10), Quaternion.identity);
uiObj.transform.SetParent (fCanvas.transform);

Also, don't attempt to make a prefab a parent of a GameObject. You run into this problem. Both the GameObject you want to set as a parent and the target(child) GameObject should never be a prefab.


If your UI is not complicated, I would totally avoid doing this and just use the DefaultControls to create UI dynamically. See this post with so many examples on how to use DefaultControls to create UI controls.

Programmer
  • 121,791
  • 22
  • 236
  • 328