- Home /
Resizing button with script, wrong anchor!
So I'm trying to resize a button depending on the screen size and aspect ratio, which isn't really the problem. The problem is that in the editor I set my button's anchor to center but when resized with a script, it folds back unto the bottom left corner, which ultimately makes the button move away from its spot. In this example i'm using localscale but I tried with rectTransform.sizeDelta too and the same thing happened.
My question is, how do I get the button to resize on itself instead of bottom left? Does it have anything to do with the anchor?
Here's what I got right now :
const float ratio = 1.777777777777778f;
float w = Screen.width;
float h = Screen.height;
float dif = w / h;
float CalculatedHeight = w / ratio ;
float CalculatedWidth = h * ratio ;
float CalculatedWidthB=w/1024f;
float CalculatedHeightB=h/768f;
Transform SBt= GameObject.Find ("StartButton").transform;
Image SBi = GameObject.Find ("StartButton").GetComponent<Image> ();
RectTransform t = GameObject.Find ("MainMenuOff").transform as RectTransform;
if (dif<=1.777777777777778f) {
SBi.color=Color.red;
SBt.localScale=new Vector3(t.localScale.x*CalculatedWidthB,t.localScale.y*CalculatedHeightB,t.localScale.z);
GameObject.Find ("StartButton").GetComponent<Image>().rectTransform.position=new Vector2(t.position.x-(SBdim.x/2f),((t.position.y)-(SBdim.y/2f)+(CalculatedHeight/2)*0.66f));
} else {
SBt.localScale=new Vector3(t.localScale.x*CalculatedWidthB,t.localScale.y*CalculatedHeightB,t.localScale.z);
GameObject.Find ("StartButton").GetComponent<Image>().rectTransform.position=new Vector2(t.position.x-(SBdim.x/2f),((t.position.y)-(SBdim.y/2f)+(Screen.height/2)*0.66f));
SBi.color=Color.green;
}
I'm sorry if things don't make too much sense or if the code isn't clean, i've been tinkering with this script for awhile trying to debug problems and I just pasted stuff in there so that snippet would actually be somewhat complete.
Right now if I put that in update and remove the scaling, my button does stay on target no matter the aspect ratio but as soon as I re-enable the resize code, it goes off target pretty easily.
Answer by allenallenallen · Aug 10, 2015 at 12:06 PM
Set your RectTransform to this:
You can copy the values for the Anchors and Pivot but you can also click on the anchor icon and press ALT + SHIFT and click on the center choice to make this happen.
Thank you, I think it's working but my script is a mess, I have to spend some time fixing it then I'll know if it has truly resolved my problem. I accepted this as an answer in the meantime!
It's working flawlessly! Since the pivot point moved, I just had to remove a variable(SBdim.x/2f) from the position's equation and now it's spot on! Thank you so much.