作者littleshan (我要加入剑道社!)
看板GameDesign
标题Re: [请益] unity 按钮跟时间的问题
时间Wed Sep 4 13:12:32 2013
※ 引述《flyfeather92 (老娘)》之铭言:
: 小妹不才 目前是unity新手
: 我想写一个在特定秒数会跳出button的装置
: var mySkin : GUISkin;
: var myWeapon : GameObject;
: var WeaponClosed : boolean = false;
: var btnTexture : Texture;
: function OnGUI()
: {
: print (Time.time);
: // Waits 6 seconds
: yield WaitForSeconds (6);
: GUI.skin = mySkin;
: if(GUI.Button(Rect(400, 40, 160, 30),"O"))
: {
: }
: else if(GUI.Button(Rect(400, 80, 160, 30), "X"))
: {
: }
: }
: 可是在GAME里面连BUTTON都跳不出来
: 之後也想请问各位大大 如果我在if里面要移动特定的物件该怎麽做?
OnGUI 是 Unity 处理 GUI event 时的 callback function
每个 frame 可能会呼叫它许多次
这意味着 OnGUI 必需在一个 frame 以内结束,否则整个程式会卡住
所以遇到超过一个 frame 的动作必需用另外的方法处理
比较无脑的方式是设一个时间变数
我比较熟 C# 所以下面是用 C# 当例子 (没实际跑过,小错误请见谅)
class ButtonGroup : MonoBehaviour {
float myElapsed =
0.0f;
void Update()
{
myElapsed += Time.deltaTime;
}
void OnGUI()
{
if(myElapsed <
6.0f)
return;
if(GUI.Button(...)){
...
}
}
}
至於移动特定物件,用 coroutine 比较方便
IEnumerator MoveObject(GameObject obj, Vector3 dest,
float duration)
{
Vector3 delta = dest - obj.transform.position
float elapsed =
0.0f;
while(elapsed < duration){
elapsed = Math.Min(duration, elapsed+Time.deltaTime);
obj.position = dest - delta * (
1.0f - elapsed/duration);
yield return null;
}
}
void OnGUI()
{
if(my_elapsed <
6.0f)
return;
if(GUI.Button(...)){
// 在 3 秒内把 myWeapon 移动到 myDestination
StartCoroutine(MoveObject(myWeapon, myDestination,
3.0f))
}
}
但这样写有个问题
如果玩家重覆点击同一个按钮
就会造成两个 coroutine 更改同物件的位置,结果通常不是你想要的
所以这边还要加个 flag 来检查物件是否已经在移动了
最後
其实 OnGUI 的设计根本就很难用
然後 Unity 的 coroutine 功能也很弱
当你的 UI 元件愈来愈多,整个 code 会变得非常杂乱
因此最好还是建立自己的 GUI 和 coroutine 系统
但这就没办法用一篇文章讲完了
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.135.3.139
1F:推 chenglap:每次我看到 onGUI 就在想 unity 团队有多仇视 2D 09/04 13:32
2F:推 changyin:推~StartCoroutine真的要避免出现在Update 或 onGUI上... 09/04 13:41