Unity判断当前所属平台
发表于2016-08-24
目标:实现判断当前运行环境是哪个平台,并且可以在脚本中区分开。
背景:我是在做适配的时候遇到这个问题,在iOS和安卓上有不一样的配置,所以需要实现上述目标。
首先我先上了unityManual上找到,如下。
[code]csharpcode:
// JS function Awake() { #if UNITY_EDITOR Debug.Log( "Unity Editor" ); #endif #if UNITY_IPHONE Debug.Log( "Iphone" ); #endif #if UNITY_STANDALONE_OSX Debug.Log( "Stand Alone OSX" ); #endif #if UNITY_STANDALONE_WIN Debug.Log( "Stand Alone Windows" ); #endif } |
// C# using UnityEngine; using System.Collections; public class PlatformDefines : MonoBehaviour { void Start () { #if UNITY_EDITOR Debug.Log( "Unity Editor" ); #endif #if UNITY_IOS Debug.Log( "Iphone" ); #endif #if UNITY_STANDALONE_OSX Debug.Log( "Stand Alone OSX" ); #endif #if UNITY_STANDALONE_WIN Debug.Log( "Stand Alone Windows" ); #endif } } |
并且提供了很多平台的判断,详细可见: http://docs.unity3d.com/Manual/PlatformDependentCompilation.html
看着很简单的,于是我把代码直接贴上去,发现并不能完成目标。
原因:我希望在GameManager中有一个公有变量来对应平台,发现不能直接给我定义的变量赋值。仔细看了一下代码恍然大悟。上面判断平台方法使用了宏定义。于是解决方案如下:
[code]csharpcode:
// C# using UnityEngine; using System.Collections; public class PlatformDefines : MonoBehaviour { void Start () { #if UNITY_EDITOR public static int platformCount= 1; #endif #if UNITY_IOS public static int platformCount= 2; #endif #if UNITY_STANDALONE_OSX public static int platformCount= 3; #endif #if UNITY_STANDALONE_WIN public static int platformCount= 4; #endif } } |
于是问题解决了,我在GameManager下用上面代码既可以获取当前平台,再利用单例模式,所有的适配工作都可以顺利进行了。
但是在我寻找资料的过程中发现另一种方法,贴出来备用。
[code]csharpcode:
switch (Application.platform) { case RuntimePlatform.WindowsEditor: print( "Windows" ); break ; case RuntimePlatform.Android: print( "Android" ); break ; case RuntimePlatform.IPhonePlayer: print( "Iphone" ); break ; } |