Skip to content

Instantly share code, notes, and snippets.

@yoiang
Last active September 1, 2021 21:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoiang/e5ff2d0f53208859d63efc78521eba01 to your computer and use it in GitHub Desktop.
Save yoiang/e5ff2d0f53208859d63efc78521eba01 to your computer and use it in GitHub Desktop.
based on Unity Forum user @Adrenesis' lovely hack for Unity GUI Mask Component movement, more error handling and In-Editor support
using System.Collections;
using System.Threading;
using UnityEngine;
[RequireComponent(typeof(RectTransform))]
public class LockUIWorldPosition : MonoBehaviour
{
private RectTransform rectTransform;
private Vector3 originalWorldPosition;
[SerializeField]
private volatile bool lockInEditor = false;
#if UNITY_EDITOR
private Coroutine editorUpdate;
#endif
void Awake()
{
LockPosition();
}
void LockPosition()
{
rectTransform = GetComponent<RectTransform>();
if (rectTransform == null)
{
enabled = false;
Debug.LogError($"{GetType()} expects {typeof(RectTransform)} to operate properly, disabling", this);
return;
}
originalWorldPosition = rectTransform.position;
}
void Update()
{
OptionallyFixPosition();
}
void OptionallyFixPosition()
{
if (rectTransform.position != originalWorldPosition)
{
rectTransform.position = originalWorldPosition;
}
}
#if UNITY_EDITOR
IEnumerator UpdateEditor()
{
while (lockInEditor)
{
OptionallyFixPosition();
yield return null;
Thread.Sleep(1);
}
}
#endif
void OnDestroy()
{
}
void OnValidate()
{
#if UNITY_EDITOR
if (lockInEditor)
{
if (editorUpdate == null)
{
LockPosition();
editorUpdate = StartCoroutine(UpdateEditor());
}
}
else
{
if (editorUpdate != null)
{
StopCoroutine(editorUpdate);
editorUpdate = null;
}
}
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment