Как лучше сделать автоматическую настройку компонентов?
В обычных GUI обычно используются панели, которые сами настраивают свое положение/разрешение и настраивают дочерние объекты. Кто-нибудь такое делал?
Я вот пока написал такой класс кнопки
Синтаксис:
Используется csharp
[ExecuteInEditMode]
public class GUIButton : MonoBehaviour {
[SerializeField] private Texture texture;
[SerializeField] private string text;
private bool pressedDown = false;
// Update is called once per frame
void Update () {
Vector2 mouse = Input.mousePosition;
mouse.y = Screen.height - mouse.y;
pressedDown = Input.GetMouseButtonDown(0) && GetRect().Contains(mouse);
}
void OnGUI() {
if(Event.current.type != EventType.Repaint) return;
GUI.DrawTexture( GetRect(), texture );
GUI.Label( GetTextRect(), text );
}
private Rect GetRect() {
float aspect = (float) texture.width / texture.height;
float scale = Screen.height;
float w = scale * transform.lossyScale.x / 4 * aspect;
float h = scale * transform.lossyScale.y / 4;
float x = Screen.width * transform.position.x - w/2;
float y = Screen.height * transform.position.y - h/2;
return new Rect(x, y, w, h);
}
private Rect GetTextRect() {
Vector2 textSize = GUI.skin.label.CalcSize( new GUIContent(text) );
Rect textRect = new Rect(0, 0, textSize.x, textSize.y);
textRect.center = new Vector2(transform.position.x*Screen.width, transform.position.y*Screen.height);
return textRect;
}
public bool IsPressedDown() {
return pressedDown;
}
}
public class GUIButton : MonoBehaviour {
[SerializeField] private Texture texture;
[SerializeField] private string text;
private bool pressedDown = false;
// Update is called once per frame
void Update () {
Vector2 mouse = Input.mousePosition;
mouse.y = Screen.height - mouse.y;
pressedDown = Input.GetMouseButtonDown(0) && GetRect().Contains(mouse);
}
void OnGUI() {
if(Event.current.type != EventType.Repaint) return;
GUI.DrawTexture( GetRect(), texture );
GUI.Label( GetTextRect(), text );
}
private Rect GetRect() {
float aspect = (float) texture.width / texture.height;
float scale = Screen.height;
float w = scale * transform.lossyScale.x / 4 * aspect;
float h = scale * transform.lossyScale.y / 4;
float x = Screen.width * transform.position.x - w/2;
float y = Screen.height * transform.position.y - h/2;
return new Rect(x, y, w, h);
}
private Rect GetTextRect() {
Vector2 textSize = GUI.skin.label.CalcSize( new GUIContent(text) );
Rect textRect = new Rect(0, 0, textSize.x, textSize.y);
textRect.center = new Vector2(transform.position.x*Screen.width, transform.position.y*Screen.height);
return textRect;
}
public bool IsPressedDown() {
return pressedDown;
}
}
Масштаб кнопки зависит только от Screen.height, поэтому в меню, в котором все кнопки по вертикали выглядит хорошо. Но не везде будет так просто т.к. от ширины экрана размер кнопки не зависит.
Кто-как делал такое?