在前面的討論中,咱們介紹瞭如何在Unity3D for WP8中使用高於.Net 3.5的第三方庫,傳送門:http://www.cnblogs.com/zhxilin/p/3311240.htmlhtml
在Unity3D和WP8的交互當中,若是要使用第三方插件(dll),一般的方式都會想到直接在Unity3D的Assets中添加一堆Plugins。可是這種作法的侷限性很是明顯,就是隻能添加基於.Net3.5的dll。若是第三方插件是基於.Net 3.5編寫的徹底沒有問題,但使人頭疼的是大部分第三方插件都不是基於.Net3.5來編寫的,至少使用了.Net 4或.Net 4.5,若是再以Plugins添加到U3D的Assets中是根本編譯不經過的。所以纔有了咱們前面那篇文章的討論,藉助UnityPlayer中UnityApp類的SetLoadedCallback來回調操做。session
在實際的開發需求中,除了經過回調來調用第三方庫的方法,還能經過消息機制通知Unity3D一些值的變化。每一個Unity3D的腳本類都繼承了Component類,Component類實現了幾個向game object發送消息的方法,包括BroadcastMessage、SendMessage以及SendMessageUpwardsthis
在Unity的API文檔定義以下spa
方法 | 描述 |
BroadcastMessage | Calls the method named methodName on every MonoBehaviour in this game object or any of its children. |
SendMessage | Calls the method named methodName on every MonoBehaviour in this game object. |
SendMessageUpwards | Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour. |
舉個例子,假設在一個MonoBehaviour中,須要使用到OpenXLive提供的PlayerID,前面提到,OpenXLive是基於.Net 4.5的第三方遊戲社交平臺,咱們沒法直接將OpenXLive.dll做爲Plugins的形式導入Unity工程,因此咱們無法直接在MonoBehaviour裏取到PlayerID。可是咱們能夠利用消息機制,很好地將須要的值從WP8中傳遞給Unity。pwa
假設咱們建立了一個C#腳本叫MyScript.cs,定義一個UsePlayerID方法插件
using System.Reflection.Emit; using UnityEngine; using System.Collections; using System; public class MyScript : MonoBehaviour { public event EventHandler GameCenterButtonPressed; public event EventHandler SubmitScoreButtonPressed; void OnGUI() { if (GUILayout.Button("Game Center", GUILayout.Width(300), GUILayout.Height(40))) { if (GameCenterButtonPressed != null) { GameCenterButtonPressed(this, EventArgs.Empty); } } } void UsePlayerID(string Id) { // Use the player id here. } }
那麼在MonoBehaviour中就能夠隨處調用GetPlayerID方法拿到玩家的ID,然而它的值從何而來?3d
將Unity工程導出爲WP8工程並打開,在MainPage.xaml.cs中,能夠看到DrawingSurfaceBackground_Loaded方法中UnityApp.SetLoadedCallback(() => { Dispatcher.BeginInvoke(Unity_Loaded); });code
在Unity加載完成後就通知了這裏的Unity_Loaded方法,完成加載後就能夠取出Unity中的腳本對象:htm
private MyScript script; private void Unity_Loaded() { script = (MyScript)UnityEngine.Object.FindObjectOfType(typeof(MyScript)); script.GameCenterButtonPressed += script_GameCenterButtonPressed; } private void script_GameCenterButtonPressed(object sender, EventArgs e) { this.Dispatcher.BeginInvoke(delegate { OpenXLive.Features.GameSession session = OpenXLive.XLiveGameManager.CreateSession("xxxxxxxxxxxxxxxxxxxxxx"); session.CreateSessionCompleted += session_CreateSessionCompleted; XLiveUIManager.Initialize(Application.Current, session); session.Open(); }); } void session_CreateSessionCompleted(object sender, OpenXLive.AsyncEventArgs e) { this.Dispatcher.BeginInvoke(delegate { if (e.Result.ReturnValue) { script.SendMessage("UsePlayerID", XLiveGameManager.CurrentSession.AnonymousID); } }); }
調用SendMessage方法,將PlayerID做爲UsePlayerID所需的參數傳遞過去,通知MyScript對象執行UsePlayerID方法。對象
以上,介紹了在WP8和Unity3D之間進行值傳遞