Unity3d绑定键盘弹出UI

1.在Fairy GUI里制作UI

2.设置为可导出,发布到自己工程存放UI的文件夹里

Unity3d绑定键盘弹出UI_第1张图片

Unity3d绑定键盘弹出UI_第2张图片

Unity3d绑定键盘弹出UI_第3张图片

3.在Hierarchy里新建一个UIPanel,通过package Name来添加制作的UI;

4.新建C#,fasong 绑定在场景里的任意一个物体上,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class fasong : MonoBehaviour {
    //!!!!定义委托(委托参数要与后面执行函数参数保持一致)
    public delegate void ListenerHandler(Object sender);
    //!!!!通过委托 声明一个事件
    public event ListenerHandler Listener = null;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        //!!!!发送事件
        //if (Input.GetMouseButtonDown(0))//0为左键,1为右键
        //{
        //    this.Listener(this);
        //}
        //!!!键盘A监听
        if (Input.GetKeyDown(KeyCode.A))//键盘按下A,发送事件
        {
            this.Listener(this);
        }
		
	}
}

5.新建C#,Fire 绑在UIPanel上,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using System;

public class Fire : MonoBehaviour {

    public GameObject aaa;
    GComponent _mainUI;
 
	// Use this for initialization
	void Start () {
        aaa.GetComponent().Listener += new fasong.ListenerHandler(noteMe);
        _mainUI = this.GetComponent().ui;
        _mainUI.visible = false;
        
	}
	
	// Update is called once per frame
	void Update () {
		
	}
    private void noteMe(object sender)
    {
        Debug.Log("111");      
        _mainUI.visible = true;
    }    
    
}

调整工程里的UI相机,把UI调整到合适位置

效果:工程运行,UI不出现,按下键盘A,UI出现

7.通过UI中的按钮,控制UI消失,修改Fire:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using System;

public class Fire : MonoBehaviour {

    public GameObject aaa;
    GComponent _mainUI;
    private GGroup _group;


	// Use this for initialization
	void Start () {
        aaa.GetComponent().Listener += new fasong.ListenerHandler(noteMe);
        _mainUI = this.GetComponent().ui;
        _mainUI.visible = false;

        _group = _mainUI.GetChild("ResetBtn").asGroup;
        _mainUI.GetChild("ResetBtn").onClick.Add(() => { PlayUI(_mainUI); });
        
	}
	
	// Update is called once per frame
	void Update () {
		
	}
    private void noteMe(object sender)
    {
        Debug.Log("111");
      
        _mainUI.visible = true;
    }

    private void PlayUI(GComponent targetCom)
    {
        _mainUI.visible = false;
    }
    
}

效果:点击按钮,UI消失;

你可能感兴趣的:(Unity3d)