| Parameter | Description |
|---|---|
| target | The RectTransform to fit this RectTransform inside. |
| allowShrink | Whether to scale this RectTransform down uniformly when it is larger than target. If false and the RectTransform doesn't fit, this method returns RectTransform.FitResult.FailLargerThanTarget. |
FitResult The result of fitting. Refer to FitResult enumeration for possible values.
Moves and optionally shrinks this RectTransform so that it fits inside the given coplanar RectTransform.
When allowShrink is true and this RectTransform is too large to fit, this method uniformly reduces both axes of RectTransform.sizeDelta to preserve the aspect ratio before translating.
This method does not verify the target size, nor does it check whether the two RectTransforms are coplanar or share the same Z rotation. Use RectTransform.TryFitInsideCoplanarRectTransform to perform both checks.
Additional resources: TryFitInsideCoplanarRectTransform, FitResult.
//Attach this script to a tooltip panel that is a child of a screen-space canvas. //When the button is clicked, the tooltip will attempt to fit inside the canvas at the button's position. using UnityEngine; using UnityEngine.UI;
public class TooltipController : MonoBehaviour { [SerializeField] RectTransform m_ScreenRectTransform;
[SerializeField] Button m_Button;
RectTransform m_TooltipRectTransform;
void Awake() { m_TooltipRectTransform = GetComponent<RectTransform>(); gameObject.SetActive(false); m_Button.onClick.AddListener(() => { ShowAt(m_Button.GetComponent<RectTransform>()); }); }
public void ShowAt(RectTransform anchor) { gameObject.SetActive(true); m_TooltipRectTransform.position = anchor.position;
// Constrain the tooltip to the container. RectTransform.FitResult fitResult = m_TooltipRectTransform.FitInsideCoplanarRectTransform(m_ScreenRectTransform, true); } }