Last active
September 1, 2021 21:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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