我无法理解如何解耦控制器的业务逻辑和Unity3D GUI控件的视图。
例如,如果我有一个GUI.Box
,我如何实现一个控制器淡入或淡出视图的OnGUI
生命周期阶段?
查看
using UnityEngine;
public class ExampleView : MonoBehaviour {
protected void OnGUI () {
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
}
如果我实例化控制器以更改alpha
的{{1}},则需要从主视图线程中通知GUI.color
。
要大致封装功能,如果这是一个单独的脚本,它可以实现为:
Update()
类似于iTween如何使用using UnityEngine;
public class ExampleView : MonoBehaviour {
private Color color;
protected void Start () {
color = Color.white;
}
protected void OnGUI () {
GUI.color = color;
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
protected void Update () {
if(color.a > 0)
color.a -= Time.deltaTime / 3;
}
}
动画更改属性如何使用iTween.fadeTo(gameObject, ...
等语句为Unity3d GUI控件实现这些?
除非指定了多个控制器实例FadeOut()
,否则可能无法定位单个GUI控件。但是,控制隔离的GUI实例(例如OnGUI()
后跟GUI.Box
的淡入淡出会很酷。
答案 0 :(得分:1)
你在寻找这样的东西吗?:
using UnityEngine;
public class ExampleView : MonoBehaviour {
private Color color;
private bool bFadeIn = false;
private bool bFadeOut = false;
protected void Start () {
color = Color.white;
}
public void FadeOut(){
bFadeOut = true;
bFadeIn = false;
}
public void FadeIn(){
bFadeIn = true;
bFadeOut = false;
}
protected void OnGUI () {
GUI.color = color;
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
protected void Update () {
if(bFadeOut && color.a > 0.0)color.a -= Time.deltaTime / 3;
if(bFadeIn && color.a < 1.0)color.a += Time.deltaTime / 3;
}
}
您可能还想要包含一个标志来确定控件何时不可见,如果不可见,则跳过完整的GuiRender函数。
答案 1 :(得分:0)
不知道这是否是你想要的,但它是一种简单的方法来为gui添加淡化效果..
using UnityEngine;
using System.Collections;
/**Fade In/Out Instructions:
* 1.Create bool fadeIn. Create float alpha.
* 2.Call Fade() method at start of OnGUI().
* 3.Put 'GUI.color = new Color(1,1,1,alpha)' above the elements you want to fade'.
* 4.To fade in, fadeIn = true.
* 5.To fade out, fadeIn = false.
* 6.To deactivate buttons on fade out, wrap gui in 'if(alpha > 0)'
**/
public class MainMenuGUI : MonoBehaviour {
int buttonWidth;
int buttonHeight;
public float alpha;
public bool fadeIn;
// Use this for initialization
void Start () {
buttonWidth = 100;
buttonHeight = 50;
fadeIn = true;
}
void OnGUI(){
Fade();
GUI.color = new Color(1,1,1,alpha);
if(alpha > 0)
{
if (GUI.Button (new Rect ((Screen.width/2)-50, (Screen.height/2)-(buttonHeight*4/2), 100, 50), "PLAY"))
{
fadeIn = false;
Debug.Log("Play pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight), 100, 50), "SCORES"))
{
Debug.Log("Scores pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight*2), 100, 50), "OPTIONS"))
{
Debug.Log("Options pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight*3), 100, 50), "EXIT"))
{
Debug.Log("Exit pressed");
}
}
}
void Fade(){
if(fadeIn){
alpha = Mathf.Clamp(alpha+0.01f,0,1);
}else{
alpha = Mathf.Clamp(alpha-0.01f,0,1);
}
}
}
祝你好运:)