Unity(二十) 关于SteamVR里Action的使用

SteamVR封装好了一个事件工具类

public static class SteamVR_Utils
{
	public class Event
	{
		public delegate void Handler(params object[] args);

		public static void Listen(string message, Handler action)
		{
			var actions = listeners[message] as Handler;
			if (actions != null)
			{
				listeners[message] = actions + action;
			}
			else
			{
				listeners[message] = action;
			}
		}

		public static void Remove(string message, Handler action)
		{
			var actions = listeners[message] as Handler;
			if (actions != null)
			{
				listeners[message] = actions - action;
			}
		}

		public static void Send(string message, params object[] args)
		{
			var actions = listeners[message] as Handler;
			if (actions != null)
			{
				actions(args);
			}
		}

		private static Hashtable listeners = new Hashtable();
	}
}

很方便开发者添加事件来驱动

测试如下:

public class MyAction : MonoBehaviour {

    string keyID = "事件的key";

	void Start () {
        Event1.Listen(keyID, Method1);
       
    }
	void Method1(params object[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            Debug.Log(args[i]);
        }
    }
	
	void Update () {
        if (Input.GetKeyUp(KeyCode.Space))
        {
            Event1.Send(keyID, 9,7,3);
        }
      
    }

    private void OnApplicationQuit()
    {
        Event1.Remove(keyID, Method1);
    }
}

 

你可能感兴趣的:(Unity开发,C#总结)