Skip to content

Instantly share code, notes, and snippets.

@sfszh
Last active December 19, 2015 06:08
Show Gist options
  • Save sfszh/5908899 to your computer and use it in GitHub Desktop.
Save sfszh/5908899 to your computer and use it in GitHub Desktop.
a simple TabView controller in unity3D, require NGUI
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TabController : IgnoreTimeScale {
public List<UICheckbox> tabs;
public bool canStartUncalled = true;
public int StartedTabNumber = 0; // there should be one tab started as checked
public delegate void OnTabSelected(int tabNumber);
public OnTabSelected onTabSelected;
public bool canDisabled = true; // whether tabs can be disabled
private bool _inited = false;
bool isFirstTime;
private List<BoxCollider> _tabColliders = new List<BoxCollider>();
// Use this for initialization
void Start () {
InitTabs();
}
void OnEnable() {
TabsSetActive(true);
isFirstTime = true;
}
private void InitTabs(){
if (_inited) {
return;
}
for(int i = 0; i < tabs.Count; i++){
TabChecker tabChecker = new TabChecker(i, this);
tabs[i].onStateChange = tabChecker.eventHandler;
}
if(!canStartUncalled){
tabs[StartedTabNumber].isChecked = true;
}
TabsSetActive(true);
//onTabSelected += DisableTabs;
_inited = true;
}
public void CheckTab(int num){
if (num >= tabs.Count) {
Debug.LogError("Tab intended to check does not exit");
return;
}
if (!_inited) {
InitTabs();
}
tabs[num].isChecked = true;
}
// after initTabs you can append tab;
public void AppendTab(UICheckbox tab,bool startedChecked){
if(!tabs.Contains(tab)){
tabs.Add(tab);
TabChecker tabChecker = new TabChecker(tabs.Count-1,this);
tabs[tabs.Count-1].onStateChange = tabChecker.eventHandler;
tab.isChecked = false;
tab.radioButtonRoot = transform;
if(startedChecked){
tab.isChecked = true;
}
}
}
// Update is called once per frame
void Update () {
if (isFirstTime && !canStartUncalled) {
tabs[StartedTabNumber].isChecked = true;
isFirstTime = false;
}
}
// paramets are only for matching the delegate needs
void DisableTabs(int num) {
TabsSetActive(false);
}
void TabsSetActive(bool state) {
if (!canDisabled) {
return;
}
if (_tabColliders.Count < tabs.Count) {
_tabColliders.Clear();
foreach (UICheckbox tab in tabs) {
_tabColliders.Add(tab.GetComponent<BoxCollider>());
}
}
foreach(BoxCollider collider in _tabColliders){
collider.enabled = state;
}
}
}
// check whether that tab was selected and call a delegate with _tabNumber
public class TabChecker {
int _tabNumber;
public TabController _tabController;
public TabChecker(int tabNumber, TabController tabController) {
_tabNumber = tabNumber;
_tabController = tabController;
}
public void eventHandler(bool state){
if (state == true && _tabController.onTabSelected != null) {
_tabController.onTabSelected(_tabNumber);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment