[SOLVED] How to set template to top-left of screen?

I want create a template by code, and set it position to the top-left of ui screen.
But always get wrong position.
this is my code.

 var instance = templateAsset!.resource.instantiate()as pc.Entity;
ui.addChild(instance);
let _x = -ui.screen.referenceResolution.x / 2 + instance.element.width/2;
let _y = ui.screen.referenceResolution.y / 2 - instance.element.height/2;
instance.setLocalPosition(_x,_y,0);

btw. i try to use “this.app.graphicsDevice.width” instead but it still not right.

I think it also depends on the settings of your element.

yes in the editor, i can set it to the top-left.
editor

but i can’t do it on script. the child text seems on right position, but the button’s image is not.

instance.element!.anchor.x = 0;
instance.element!.anchor.y = 1;
instance.element!.anchor.z = 0;
instance.element!.anchor.w = 1;
instance.element!.pivot.x = 0;
 instance.element!.pivot.y = 1;
 instance.setLocalPosition(0,0,0);

bug

You don’t have to do that again with code if you’ve already did this on template in the editor. If the child entity is working, I would create the background as child entity too. I think then you get the right result.

Apart from that, I don’t quite understand the exclamation marks in your code.

project/1036563

i write code in typescript , so please don’t mind the exclamation marks.

in the editor , the scene for ui is empty , because i want add button in my script.
i change the anchor and pivot as the same value as in the editor…

Alright, how or when do you instantiate the button? I only see a black screen.

open the “Index” scene and run

Maybe you can try the button setup from my fork of your project.

https://playcanvas.com/editor/scene/1662788

I instantiate the button template with the instantiate script.

wow~~thanks, give it a group parent and it works!

and there is another question, why in your project the HIERARCHI’s tree list show well, but in my project it’s not ?
treebug

Does your current setup works correct? The button background element has different settings as my example.

Do you mean the plus icons? Looks like a bug, because on my side it works correct in your project.

image

yes i know, now i can change the btnBule to left-top or right-top by code~

and maybe the plus icon is a bug ,i switch to chrome it works so don’t mind~

1 Like