Created
January 23, 2016 07:43
-
-
Save s2kw/a523926337fa9223364e to your computer and use it in GitHub Desktop.
uGUIのLayoutElementの値が、アタッチしたオブジェクトと子オブジェクトの関係性(子のAnchorをBottomにしてたりする)によってレイアウトが安定しない件を解消するスクリプト。
This file contains hidden or 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 UnityEngine; | |
using UnityEngine.UI; | |
# if UNITY_EDITOR | |
using UnityEditor; | |
[CustomEditor( typeof( UISizeFitter ) )] | |
public class UISizeFitterInspector : Editor{ | |
public override void OnInspectorGUI() | |
{ | |
DrawDefaultInspector(); | |
var script = target as UISizeFitter; | |
if( GUILayout.Button("Fit") ){ | |
script.Fit(); | |
} | |
} | |
} | |
# endif | |
// namespace jigaX{ | |
[RequireComponent( typeof( LayoutElement) )] | |
public class UISizeFitter : MonoBehaviour { | |
RectTransform rectTransform; | |
LayoutElement layoutElement; | |
Image image; | |
void Awake(){ | |
this.layoutElement = GetComponent<LayoutElement>(); | |
this.rectTransform = GetComponent<RectTransform>(); | |
this.image = GetComponent<Image>(); | |
} | |
// Use this for initialization | |
void Start () { | |
this.Fit(); | |
} | |
// Update is called once per frame | |
void Update () { | |
} | |
public void Fit(){ | |
var imageRect = this.image.sprite.rect; | |
var ratio = imageRect.height / imageRect.width; | |
var rect = this.rectTransform.rect; | |
Debug.Log(imageRect,this); | |
this.layoutElement.preferredHeight = rect.width * ratio; | |
} | |
} | |
// } // namespace |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment