- Home /
Can't position instantiated objects on canvas
I have a canvas set to screen space - camera. All works fine except for instantiated elements ( a 3d model and some rect transforms). When they are created, their position and size are completely different o.O. Any suggestions? It's working perfect with a world space canvas, but I find it more difficult to fit it to the screen..
Answer by MrWy07 · Aug 19, 2021 at 11:40 AM
The idea is to create this objects dynamically based on some data, so I can't have them in the hierarchy before playing. Anyway, using transform.SetParent(transform, false) instead of transform.parent = gameTrans.transform does the trick, but I'll try your code and maybe see why this happens. Thank you!
Ah I see! Can be frustrating sometimes, even the something as simple as changing a line can make the world of difference! Post again if you are still finding trouble, Good luck.
Answer by GameDevMark · Aug 19, 2021 at 10:02 AM
Check what scale size of the objects you are instantiating(prefabs). They instantiate to whatever size they are set to.
Let me know.
Thanks for your answer, but the object I am instantiating is much smaller. It seems to work when I set a UI panel as parent using another method:
chInstance = Instantiate(selectedCh.character, new Vector3(transform.position.x, transform.position.y / 2, transform.position.z), transform.rotation);
chInstance.transform.Rotate(0, 180, 0);
// chInstance.transform.parent = transform;
chInstance.transform.SetParent(transform, false);
chInstance.transform.localPosition = new Vector3(0, -chInstance.transform.parent.position.y / 2 , 0);
chInstance.SetActive(true);
Try changing transform.rotation for Quaternion.identity
when instantiating. Just a maybe..
or maybe simplify it - just have the button or object disabled in hierarchy and then enable it in code? - SetActive(gameobject);
I've been messing around with instantiating buttons, texts, 3d objects onto the UI - Screen space, and it seems to work for me. I'll attach some code see if anything pops out for you, it is only simple code.
void Start()
{
Button newButt = (Instantiate(buttonUI, transform) as GameObject).GetComponent<Button>();
Text newText = (Instantiate(textUI, textTrans) as Text).GetComponent<Text>();
}
// spawn triangle
void SpawnIT(int gridSizeee = 4)
{
for (int y = 0; y < gridSizeee; y++)
{
for (int x = y; x < 2 * gridSizeee - y - 1; x++)
{
Vector3 pos = new Vector3(x, y, 0f);
var ballTri = Instantiate(balls, pos, Quaternion.identity);
ballTri.transform.parent = gameTrans.transform;
Debug.Log(balls);
}
}
}