Move GameObject in top left of other element

I have an UI Panel and a GameObject (prefab)

This is my code :

//Retrieve the panel
RectTransform panel = this.GetComponent<RectTransform> ();

//Instantiate prefab and 
GameObject currentTile = Instantiate (tile.tilePrefab, Vector3.zero, Quaternion.identity) as GameObject;
currentTile.transform.SetParent(transform);

So with this code, i can instantiate my Prefab and move into the panel.

But how can i move my prefab in top left of my panel (with a margin :slight_smile: )? For now i move my prefab manually with 2 variables X Y.

Thanks !

There’s probably a better way of doing this but drag the parent panel / canvas onto the ParentPanel and I used a panelPrefab rather than your tilePrefab.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class MovePanel : MonoBehaviour {

	public GameObject panelPrefab;
	public RectTransform ParentPanel;
	private float offSet = 10f;
	
	void Start () {
		float parentWidth = ParentPanel.rect.width;
		float parentHeight = ParentPanel.rect.height;


		GameObject currentTile = Instantiate (panelPrefab, Vector3.zero, Quaternion.identity) as GameObject;
		currentTile.transform.SetParent(ParentPanel);
		currentTile.transform.localScale = new Vector3(1,1,1);

		float myHeight = currentTile.GetComponent<RectTransform>().rect.height;
		float myWidth = currentTile.GetComponent<RectTransform>().rect.width;

		float tempX = -(parentWidth / 2) + ((myWidth / 2) + offSet);
		float tempY = (parentHeight / 2) - ((myHeight / 2) + offSet);
		currentTile.transform.localPosition = new Vector3(tempX, tempY, currentTile.transform.localPosition.z);

	}
}

The offSet will be the padding from the left and top, you can set to two different variables if you want to. You’ve got to get the parent width and height and the instantiated objects width and height.

Anyway you can see the code.