[Unity Game to Windows Store] Compile error- missing namespaces/classes

如以下,在 Unity 中 Switch Platform 至 Windows Store Apps 後 “Build”:

image

出現的錯誤訊息為: “error CS0103: The name 'File' does not exist in the current context”。

Unity 上開發的遊戲 porting 至 W8/WP 平台時,第一個也是最常遇到的問題,即是有某些 namespaces 及 classes 在 Mono run-time 中可以編譯,但卻因不存在於 W8/WP 的 run-time 中,而造成 Compile error 的情形。

我們先直接來解決它,之後會有較詳細的說明。

如何解決?

[以下環境以Unity 4.3.3 + Windows 8.1 + Visual Studio 2013 作說明,解法適用於 Windows Store App 及 Windows Phone 8]

步驟1: 請至https://aka.ms/UnityPortingSamples 下載位於 GitHub 中的 UnityPorting (C#) 專案 (Download ZIP),這個專案實作了許多 missing namespaces/classes,只要在 Unity 中的參考加入此專案建制出來的 .dll 檔即可解決這個常見的問題。

1-1. 解壓縮後,雙點位於 \UnityPorting-master\UnityPorting-master\PlatformerPlugin 目錄下的 PlatformerPlugin.sln (會以 Visual Studio 2013 開啟)。

1-2. 刪除方案中的 Facebook 資料夾;「只」重新建置 MyPluginUnity 這個專案,因為我們僅需要其 MyPlugin.dll 檔! (建置後會在 \UnityPorting-master\UnityPorting-master\PlatformerPlugin\MyPluginUnity\bin\Debug 目錄中)

imageimage

步驟2: 將 MyPlugin.dll 檔加入 Unity 的參考 (references) 中:

[2014/2/24更新] 用滑鼠把 MyPlugin.dll 檔拖拉至 \Plugins 資料夾中即可:

image

回到 Unity ,點擊錯誤訊息,於發生錯誤的 .cs 檔案加入以下 Using directives,同時並記得將既有的 Using System.IO 移除。

 #if UNITY_METRO_8_1 && !UNITY_EDITOR
using LegacySystem.IO;
#else
using System.IO;
#endif

image

請各位以所缺少的 classes 所在的 namespace 作相對應的修改;以上是以 System.IO 中所缺少的 classes 為例,以下則是缺少 System.Net 中的 Sockets 之例:

“error CS0234: The type or namespace name 'Sockets' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)”

image

存檔後回到 Unity 重新 Build 即可發現錯誤已解決;若無其他錯誤的話即會發現在所選資料夾中已成功編譯出一個 Windows Store App 方案,點擊其 .sln 檔即可以 Visual Studio 開啟編譯。

原因及說明:

此問題發生的原因其實很簡單,Mono .NET 及 W8/WP .NET 這兩個 run-time 雖然都是屬於整體 .NET run-time 的子集合,但是兩個子集合圈圈之中,會有 namespaces/classes 不在交集內的情形 (藍色半月型區域):

image

MyPlugin.dll 這個檔案即是我們在以上步驟中的重點,在其中已實作了許多出現在 Mono run-time ,但卻未出現在 W8/WP run-time 的 namespaces/classes。 因此 Unity 開發者只要直接 Using 進來,即可在不更動既有的 classes 名稱下,編譯出相容於 W8/WP run-time 的遊戲;而又由於所有的 classes 名稱都沒被更動,因此不會影響遊戲在其他平台 (iOS/Android 等) 的相容性。

詳細來說,於步驟1所建置出來的 MyPlugin.dll 之中,至少實作了以下的 namespaces/classes:

- System.Collections 之中的: Hashtable, ArrayList, OrderedDictionary, SortedList, Queue, Stack and a few others.

- System.IO.File, System.IO.StreamReader, System.IO.Directory, etc.

- System.Net.TCPClient using Windows.Networking.Sockets WinRT namespace:

- System.Threading.Tread

- (optional) Facebook plugin

亦即若您的 Compile error 是因為找不到以上的 classes,那以上步驟都可以解決您的問題。

以上步驟的詳細說明請見這份 Unity3D/Microsoft 的官方文件Porting tips for Windows Store (813 KB) 中的第4 ~ 6 頁。

另,線上課程 (英文) Porting Unity games to Windows 8.1 & Windows Phone 中的 Module 3 就特別討論到 Duel Runtime environment ,建議一聽。

更完整 porting 至 W8/WP 平台的文件可見: https://unity3d.com/pages/windows/porting