Search Unity

UI Image not updating "graphic" after anchoredPosition is changed

Discussion in 'UGUI & TextMesh Pro' started by par-002, Sep 18, 2017.

  1. par-002

    par-002

    Joined:
    Jul 4, 2012
    Posts:
    52
    This is driving me up the <bleeping> wall.

    I have a terrain. I have a canvas set to world space so that I can use UI elements on top of the terrain.

    When I click somewhere on the terrain a UI Canvas button pops up. I am using the mouse's world location and converting it to the canvas location for the button. I use anchoredPosition for setting its location.

    The first time I click the mouse button everything works perfectly. The UI button's anchoredPosition is changed to where I want it, I use setActive(true) on the object and it correctly shows where I want it on the screen (both Scene editor and Game Windows).

    Unfortunately, when I attempt to move the button's anchored position via code (i.e. change it's anchoredPosition), its actual ON-SCREEN GRAPHIC does NOT update it's position on the screen, it stays exactly where it was first placed.

    In the inspector and in Debug.Log(), the button's position is correctly showing the new location, but neither in the Scene window nor the Game window is the actual on-screen graphic position of the button where it needs to be.

    For the life of me I cannot figure this out. I have tried Canvas.ForceUpdateCanvases() and everything.

    The ONLY thing that seems to work is literally grabbing the button in the Scene editor and moving it. Once I do that, it's on-screen position jumps to where it should be. This leads me to believe its some kind of Canvas update issue... but alas, I cannot find a solution.

    Any help would be greatly appreciated!

    Thanks!
     
  2. danp

    danp

    Joined:
    Jun 20, 2013
    Posts:
    21
  3. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,689
    DO you have a sample scene you can share to demonstrate the issue?
     
  4. par-002

    par-002

    Joined:
    Jul 4, 2012
    Posts:
    52
    Bah! From now on when I have a question like this I'll go ahead and create a demo scene in order to replicate. By doing so I found out what I was doing wrong.

    Ok, so I was confused when the canvas was put on "World Space". I had assumed that meant I could use the transform.position to move it around which is legit. But I realized that I wasn't changing the axis. I was using transform.y for the world space z value. And since I tilted it, nothing was happening.

    So, when changing a Vector2 anchored position that is in world space, know what each axis maps to. Mine were:

    Code (CSharp):
    1. currentlyHighlightedCell.GetComponent<RectTransform>().anchoredPosition = new Vector2(desiredLocation.x, desiredLocation.z);

    Thanks Simon!