创建一个脚本:CombinationKey.cs
1 using UnityEngine; 2 using System.Collections; 3 4 public class CombinationKey 5 { 6 public CombinationKey (KeyCode p,KeyCode a) 7 { 8 PrimaryKey = p; 9 AttachKey = a; 10 } 11 12 public CombinationKey() { } 13 /// <summary> 14 /// 主键 15 /// </summary> 16 public KeyCode PrimaryKey 17 { 18 set { primaryKey = value; } 19 } 20 private KeyCode primaryKey = KeyCode.LeftControl; 21 bool bPrimary = false; 22 /// <summary> 23 /// 附键 24 /// </summary> 25 public KeyCode AttachKey 26 { 27 set { attachKey = value; } 28 } 29 private KeyCode attachKey = KeyCode.E; 30 31 /// <summary> 32 /// 按下组合键后,只返回一次真 33 /// </summary> 34 /// <returns></returns> 35 public bool ClickKey() 36 { 37 if (Input.GetKeyDown(primaryKey)) 38 { 39 bPrimary = true; 40 } 41 if (Input.GetKeyUp(primaryKey)) 42 { 43 bPrimary = false; 44 } 45 if (bPrimary) 46 { 47 if (Input.GetKeyDown(attachKey)) 48 { 49 return true; 50 } 51 else 52 { 53 return false; 54 } 55 } 56 else 57 { 58 return false; 59 } 60 } 61 /// <summary> 62 /// 按下组合键后,一直返回真,直到松开 63 /// </summary> 64 /// <returns></returns> 65 public bool PressKey() 66 { 67 if (Input.GetKeyDown(primaryKey)) 68 { 69 bPrimary = true; 70 } 71 if (Input.GetKeyUp(primaryKey)) 72 { 73 bPrimary = false; 74 } 75 if (bPrimary) 76 { 77 if (Input.GetKey(attachKey)) 78 { 79 Debug.Log("d"); 80 return true; 81 } 82 else 83 { 84 return false; 85 } 86 } 87 else 88 { 89 return false; 90 } 91 } 92 void Update() 93 { 94 ClickKey(); 95 PressKey(); 96 } 97 }
使用该脚本:test.cs
using UnityEngine; using System.Collections; public class test : MonoBehaviour { CombinationKey mKey = new CombinationKey(KeyCode.LeftControl, KeyCode.E); void Update() { if(mKey.ClickKey()) {Debug.Log("Click");} } }
时间: 2024-10-31 09:08:35