Use a class like a function
I currently have a very simple code that simply deactivates all canvas in the scene, and then activates the ones that I want to keep active (anyways, feel free to suggest any method to optimize this). It is working exactly as I want, but I don't fell its right needing to attach it to a GameObject for this to work. So I thought on doing something like calling DisableCanvas(somethingToKeepActive) but I don't know how to do this in a nice way.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisableCanvas : MonoBehaviour
{
public List<GameObject> canvasToKeepActive = new List<GameObject> ();
private GameObject [] allCanvas;
private void Awake ()
{
allCanvas = GameObject.FindGameObjectsWithTag ( "Canvas" );
// Disables all canvas in scene
for ( int i = 0 ; i < allCanvas.Length ; i++ )
{
allCanvas [ i ].gameObject.SetActive ( false );
}
// Activates the selected canvas
for ( int i = 0 ; i < canvasToKeepActive.Count ; i++ )
{
canvasToKeepActive [ i ].SetActive ( true );
}
}
}
Comment
Answer by ntl92bk · Aug 18, 2017 at 09:55 AM
Try implement state pattern . Code exam ( coded on notepad and not test it work :D ): public class CanvasState { STATE_0, STATE_1, .... STATE_N }
public class CanvasControl : MonoBehavior{
public GameObject canvas1;
public GameObject canvas2;
public GameObject canvasn;
public CanvasState state {get;protected set;}
private CanvasControlState _canvasControlState;
public void SetState(CanvasState nState)
{
if(state==nState)
return;
state = nState;
switch(state)
{
case CanvasState.STATE_0:
SetCanvasControlState(new CanvasControlState1(this));
break;
...
default:
break;
}
}
protected void SetCanvasControlState(CanvasControlState nState)
{
if(_canvasControlState!=null)
_canvasControlState.OnExit();
_canvasControlState = nState;
if(_canvasControlState!=null)
_canvasControlState.OnEnter();
}
}
public interface State{
void OnEnter();
void OnExit();
}
public class CanvasControlState : State{
protected CanvasControl canvasControl;
public CanvasControlState(CanvasControl canvasControl)
{
this.canvasControl = canvasControl;
}
public virtual void OnEnter(){}
public virtual void OnExit(){}
}
public class CanvasControlState1 : CanvasControlState {
public CanvasControlState1(CanvasControl canvasControl):base(canvasControl){}
public override void OnEnter(){
base.OnEnter();
canvas1.SetActive(false);
....
canvasn.SetActive(true);
}
public override void OnExit(){
base.OnExit();
canvas1.SetActive(false);
....
canvasn.SetActive(false);
}
}
public class CanvasControlState2 : CanvasControlState {
public CanvasControlState1(CanvasControl canvasControl):base(canvasControl){}
public override void OnEnter(){
base.OnEnter();
canvas1.SetActive(true);
....
canvasn.SetActive(true);
}
public override void OnExit(){
base.OnExit();
canvas1.SetActive(false);
....
canvasn.SetActive(false);
}
}