Skip to content

Instantly share code, notes, and snippets.

@sonnguyen9800
Last active September 2, 2025 03:18
Show Gist options
  • Select an option

  • Save sonnguyen9800/22bc52ca8b7d041f64e4dc0fe2b231a5 to your computer and use it in GitHub Desktop.

Select an option

Save sonnguyen9800/22bc52ca8b7d041f64e4dc0fe2b231a5 to your computer and use it in GitHub Desktop.
[Unity] Quickly snap rect to any target RectTransform
// The idea is super simple:
// 1. Set rect transform to be moved to be children of target Rect.
// 2. As a children -> Set local position to 0,0,0
// 3. Set parent of our transform to the old parent (again)
//
// This script is originally used for a HandTutorialObject, so that it points to correct UI Object. This is done because setting
// rectTransform.position proved to be incorrect when target Rect inside a LayoutGroup, ... etc.
using System.Collections;
using UnityEngine;
public static class RectTransformExtensions
{
/// <summary>
/// Snap this RectTransform to target’s pivot position visually,
/// even if anchors/pivots don’t match.
/// </summary>
public static void SnapTo(this RectTransform self, RectTransform target, MonoBehaviour runner)
{
if (!self || !target || !runner) return;
runner.StartCoroutine(SnapCoroutine(self, target));
}
private static IEnumerator SnapCoroutine(RectTransform self, RectTransform target)
{
// Save original parent and sibling index
Transform originalParent = self.parent;
int originalSibling = self.GetSiblingIndex();
// Step 1: temporarily reparent to target
self.SetParent(target, false);
yield return null; // wait one frame
// Step 2: set local position = (0,0,0)
self.localPosition = Vector3.zero;
yield return null;
// Step 3: restore parent while keeping new world pos
self.SetParent(originalParent, true);
self.SetSiblingIndex(originalSibling);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment