Home > Software engineering >  UNITY How do I change image position?
UNITY How do I change image position?

Time:01-27

Below is a snippet of code thats running every update but when I log the local position of the image it still says 0,0,0 when it should be 10,10,10. What am I doing wrong??? Ultimately I am trying to understand how to programmatically move an image around on screen

public partial class MainCanvasSystem : SystemBase
{
    protected override void OnUpdate()
    {
        if (MainGameObjectCanvas.Instance != null && SystemAPI.HasSingleton<MainEntityCanvas>())
        {
            Entity mainEntityCanvasEntity = SystemAPI.GetSingletonEntity<MainEntityCanvas>();
            LocalToWorld targetLocalToWorld = SystemAPI.GetComponent<LocalToWorld>(mainEntityCanvasEntity);
            Canvas canvas = MainGameObjectCanvas.Instance;
            Image image = canvas.GetComponentInChildren<Image>();

            var rect = image.GetComponent<RectTransform>();
            rect.localScale.Set(10,10,10);
            Debug.Log(rect.localPosition.x);
        }
    }
}

CodePudding user response:

I think there is general misunderstanding here.

rect.localScale.Set(10,10,10);

does .. nothing!

Transform.localScale is a property and returns a COPY of a Vector3 struct.

You are calling Vector3.Set on it which replaces the values within that Vector3 copy, yes, but then you never actually apply it anywhere.

=> you need to actually set the property!

You rather would do e.g.

rect.locaScale = Vector3.one * 10;

or

rect.localScale = new Vector3(10,10,10);

However, this said, changing a localScale won't change the position at all. The RectTransform.anchoredPosition is probably rather the one to go with.

  • Related