Search Unity

[FIXED]Adding prefab with script to Canvas

Discussion in 'Scripting' started by HVutov, Apr 24, 2015.

  1. HVutov

    HVutov

    Joined:
    Mar 16, 2015
    Posts:
    18
    Im trying to add prefab to canvas and it look like this in scene view i have to change LEFT,TOP,RIGHT,BOTTOM to 0 to show the gameObject properly but i dont know how


    Code (CSharp):
    1.   GameObject talkBox = (GameObject)Instantiate(box);
    2.             RectTransform boxRect = talkBox.GetComponent<RectTransform>();
    3.             talkBox.transform.parent = canvas.transform;
    4.             boxRect.transform.localScale = new Vector3(1, 1, 1);
    5.             talkBox.GetComponent<RectTransform>().localPosition = new Vector3(0,0,0);
     
  2. martin-protostar

    martin-protostar

    Joined:
    Dec 14, 2014
    Posts:
    13
    You should use
    Code (CSharp):
    1. talkBox.GetComponent<RectTransform>().rect = new Rect(LEFT, TOP, RIGHT, BOTTOM);
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    What are left, right, top and bottom set to on your prefab? They shouldn't change.

    You may need to use SetParent to get this to work. One of the bool settings prevents the RectTransfom from automatically updating.
     
  4. HVutov

    HVutov

    Joined:
    Mar 16, 2015
    Posts:
    18
    left, right, top and bottom are 0 on the prefab but they get changed runTime and i dont know how
    I set parent here talkBox.transform.parent = canvas.transform;
     
  5. HVutov

    HVutov

    Joined:
    Mar 16, 2015
    Posts:
    18
    I fix it the problem was anchors i set the in the middle and its ok now