uGUIには標準のタブレイアウトがない
面倒くさがり屋の俺はどんなに簡単に自前で用意できるものでも時間短縮のため基本的にアセットストアで買う。でも売ってないものは買えない。
なんか手頃なuGUIでタブレイアウトを扱えるアセットがなかった。止むを得ず嫌々書いた。
スクリプト
適当に保存する。
GUITabLayout.cs
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
[AddComponentMenu("UI/Advanced/Tab Controller")]
public class GUITabController : MonoBehaviour {
[SerializableAttribute]
public struct TabContentsPair {
public Button tab;
public CanvasRenderer contentBody;
public Optionals optionals;
public void SetTabInteractable(bool b) {
tab.interactable = b;
if (optionals.selectedTab != null) {
optionals.selectedTab.gameObject.SetActive(!b);
tab.gameObject.SetActive(b);
}
}
}
[SerializableAttribute]
public struct Optionals {
public CanvasRenderer selectedTab;
}
public List<TabContentsPair> tabContentsPairs;
// Use this for initialization
void Start() {
if (tabContentsPairs != null) {
tabContentsPairs.ForEach(pair => {
// initialize tab state
pair.SetTabInteractable(!pair.contentBody.gameObject.activeSelf);
// add click listener
pair.tab.onClick.AddListener(() => {
// switch active contents
tabContentsPairs.ForEach(p => p.contentBody.gameObject.SetActive(false));
pair.contentBody.gameObject.SetActive(true);
// switch interactable
tabContentsPairs.ForEach(p => p.SetTabInteractable(true));
pair.SetTabInteractable(false);
});
});
}
}
}
使い方
基本的にはこんな感じの構成のとき
Tabsあたりにコンポーネントとしてアタッチして
のように設定して使う。
なおOptionalsは任意。ない(null)ならないで良しなにしておく感じ。
Toggle バージョン
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
[AddComponentMenu("UI/Advanced/Tab Controller")]
public class GUITabController : MonoBehaviour
{
[SerializableAttribute]
public struct TabContentsPair
{
public Toggle tab;
public CanvasRenderer contentBody;
public Optionals optionals;
public void SetTabInteractable(bool b)
{
tab.interactable = b;
if (optionals.selectedTab != null)
{
optionals.selectedTab.gameObject.SetActive(!b);
tab.gameObject.SetActive(b);
}
}
}
[SerializableAttribute]
public struct Optionals
{
public CanvasRenderer selectedTab;
}
public List<TabContentsPair> tabContentsPairs;
// Use this for initialization
void Start()
{
if (tabContentsPairs != null)
{
tabContentsPairs.ForEach(pair => {
// initialize tab state
pair.SetTabInteractable(!pair.contentBody.gameObject.activeSelf);
// add click listener
pair.tab.onValueChanged.AddListener((value) => {
// switch active contents
tabContentsPairs.ForEach(p => p.contentBody.gameObject.SetActive(false));
pair.contentBody.gameObject.SetActive(true);
// switch interactable
tabContentsPairs.ForEach(p => p.SetTabInteractable(true));
pair.SetTabInteractable(false);
});
});
}
}
}