// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; namespace Microsoft.MixedReality.Toolkit.UI { /// /// Place an object in space relative to another object's scale /// Good for responsive buttons that can stretch and object realign /// [ExecuteInEditMode] [AddComponentMenu("Scripts/MRTK/SDK/ButtonLayout")] public class ButtonLayout : MonoBehaviour { /// /// Where to set this object's center point in relation to the Anchor's center point. /// [Tooltip("Where to set this object's center point in relation to the Anchor's center point")] public Vector3 Alignment; /// /// A pixel to Unity unit conversion, Default: 2048x2048 pixels covers a 1x1 Unity Unit or default primitive size. /// [Tooltip("A pixel to Unity unit conversion, Default: 2048x2048 pixels covers a 1x1 Unity Unit or default primitive size")] public float BasePixelSize = 2048; /// /// The transform this object should be linked and aligned to. /// [Tooltip("The transform this object should be linked and aligned to")] public Transform Anchor; /// /// Offset this object's position based on the same pixel based size ratio. /// [Tooltip("Offset this object's position based on the same pixel based size ratio")] public Vector3 AnchorOffset; public bool OnlyInEditMode; /// /// A transform is required for alignment /// protected virtual void Awake() { if (Anchor == null) { Anchor = this.transform; } } /// /// Set this object's position /// protected virtual void UpdatePosition() { // set the default directions Vector3 startPosition = Anchor.localPosition; if (Anchor != this.transform) { startPosition = Anchor.localPosition + (Vector3.Scale(Anchor.localScale * 0.5f, Alignment)); } transform.localPosition = startPosition + (AnchorOffset / BasePixelSize); } // Update is called once per frame protected virtual void Update() { if (Anchor != null) { if ((Application.isPlaying && !OnlyInEditMode) || (!Application.isPlaying)) { UpdatePosition(); } } } } }