1. 在编译阶段就起作用
void Start()
{
#if UNITY_EDITOR
Debug.Log("这是编辑器模式。。。");
#endif
#if UNITY_ANDROID
Debug.Log("这是安卓平台。。。");
#endif
#if UNITY_IPHONE
Debug.Log("这是iPhone平台。。。"); // 不好听,用IOS代替
#endif
#if UNITY_IOS
Debug.Log("这是IOS平台。。。");
#endif
#if UNITY_STANDALONE_WIN
Debug.Log("这是Windows平台。。。");
#endif
#if UNITY_STANDALONE_OSX
Debug.Log("这是OSX平台。。。");
#endif
}
以测试iOS为例,将Unity中编辑器中的Platform设置为iOS,注意编译后Unity会将非当前平台下的代码置灰,其实就是没有参与编译(Shift+F12找不到相关代码),编译结果与输出结果如图:
2. 运行时起作用
if (Application.platform == RuntimePlatform.WindowsEditor)
{
Debug.Log("这是Windows编辑器模式。。。");
}
if (Application.platform == RuntimePlatform.IPhonePlayer) // 使用Unity切换Platform无法模拟
{
Debug.Log("这是iPhone平台。。。");
}
if (Application.platform == RuntimePlatform.Android)// 使用Unity切换Platform无法模拟
{
Debug.Log("这是安卓平台。。。");
}
注意:运行时判断平台使用Unity暂时无法模拟。
输出结果:
3. 自定义宏
自定义宏需要在Player Settings中添加,例如我添加了自定义宏CUSTOM_SYM
#if CUSTOM_SYM
Debug.Log("这是我自定义的宏。。。");
#endif
输出结果: