- Home /
Trying to place an UI Canvas Image next to another UI Image
I've been trying to place 2 images on my canvas. Both image (ImageA, ImageB) will be side by side of each other. I get ImageA's width and move ImageB by half of the width. This is the code I currently have.
// Define and assign posX and posY
ImageA.GetComponent<RectTransform>().anchoredPosition= new Vector2(posX, posY);
posX -= ImageA.GetComponent<RectTransform>().rect.width / 2.0f;
ImageB.GetComponent().anchoredPosition= new Vector2(posX, posY);
However, the 2 Images are not exactly side by side to each other. Currently, ImageA and ImageB are a child object of gameobject that I am using to organize stuff on my inspector. Would these 2 images being a child of a parent gameobject interfere with positioning? The parent is placed at 0,0 on the canvas. Any help would be greatly appreciated.
Edit: A little more explanation. ImageA and ImageB do not have the same parent game object. The hierarchy looks like the following:
Both ImageA Container and ImageB Container has their anchors set to top left, and both ImageA and Image B has their anchor set to middle. All gameobjects has their pos X and pos Y are set to 0, 0 on the inspector, and ImageA Container and ImageB Container's width and height value under the Rect Transform component is set to 0,0 (since they are an empty game object without an image).
Answer by allenallenallen · Feb 21, 2016 at 11:28 PM
First, did you use widthOffSet for posX or something? Because it looks like you're setting ImageA and ImageB to be at exactly the same position. Shouldn't you do something like:
ImageB.GetComponent().anchoredPosition= new Vector2(posX + widthOffSet, posY);
So that ImageB will actually have an offset?
Second, the empty GameObject will have an effect. The anchors for the two images will be at the parent position. But the main problem is that it's an empty GameObject not made for Canvas. I think it's best if you use an Image game object as a parent. Just remove the Image component from it so it still has RectTransform and Canvas Renderer components equipped.
Sorry, updated the code snippet. But yes, I was changing the value of the position.
The parent game object had a RectTransform isn$$anonymous$$d of a transform coponent. I've manually added the Canvas Renderer Component to the parent game object. But it doesnt seem to have made a difference.
Your answer
![](https://koobas.hobune.stream/wayback/20220612065113im_/https://answers.unity.com/themes/thub/images/avi.jpg)