Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Moving and resizing object on Canvas

Discussion in 'Scripting' started by Jaf0, Jan 10, 2016.

  1. Jaf0

    Jaf0

    Joined:
    Jan 4, 2016
    Posts:
    3
    So, I have two questions about using C# script in canvas.

    Lets that I have a Panel, and on that panel I instantiate an Image. Everything is on Canvas, and canvas scale with screen size.
    Now I want to move that image little lower. I check in scene view and I know that this image must be lowered by, lets say 50 pixels, to be in center of the screen.
    Problem is - yeah, that will work but only in resolution I'm testing in. If resolution will change then 50 pixels will mean another distance.

    My question is how do I move that image so it will always end up in same place in all resolutions. Center of the screen was just an example here. Image also change size with screen, so size isn't a problem.

    Second question is similar to first - let's say that I want to instantiate x images, one on top of another on Panel, but I want that panel to "extend" (so I will be able to use scroll rect to view all instantiated images).

    So I have this code:
    Code (CSharp):
    1. GetComponent<RectTransform> ().offsetMin = new Vector2 (this.GetComponent<RectTransform> ().offsetMin.x, this.GetComponent<RectTransform> ().offsetMin.y - (x * 100);
    where x is amount of created images.
    And of course I have same problem as before - image height is 100, and that integer will work in my resolution, but not in other one.

    So I guess my question is - how do I make these integers scale with canvas size?
     
  2. Notter

    Notter

    Joined:
    Mar 8, 2015
    Posts:
    65
    You need to multiply your offset by the screen scale.
    cause as you said, when you move in your native resolution, you wanna move 50 pixels.
    but if it's half that resolution? then you wanna move it by only 25 pixels.

    for that, you've got Canvas.ScaleFactor
    that's a property on your canvas.
    just multiply whatever you do by that factor.
     
  3. zoran404

    zoran404

    Joined:
    Jan 11, 2015
    Posts:
    520
    If you use the CanvasScaler (attached to a Canvas by default) and set it to Scale with screen size, then you will be able to use the Reference resolution no matter what screen size you're on.