完全に自分用メモです。
はじめに
Unityで開発を進めていると、画像の保存時など端末によって処理を分けるケースが発生します。
今回はその方法を記述いたします。
環境
- Windows10
- Unity Hub 2.4.5
- Unity 2020.3.25f1
- Android Studio 2020.3.1
端末を判定する
今回は端末を判定する方法を2種類紹介します。
1つめの方法
using UnityEngine;
using System.Collections;
public class Terminal : MonoBehaviour {
void OnClick() {
if (Application.platform == RuntimePlatform.Android) {
//端末がAndroidだった場合の処理
} else if (Application.platform == RuntimePlatform.IPhonePlayer) {
//端末がiOSだった場合の処理
} else {
//その他の端末での処理
}
}
}
上記のコードの Application.platform == で判定ができます。
右辺の RuntimePlatform.XXXX は他の端末の判定も可能です。
詳しくはUnityのドキュメントを御覧ください。
2つめの方法
続いて2つ目の方法です。
さきほどより簡単な記述です。
using UnityEngine;
using System.Collections;
public class Terminal : MonoBehaviour {
void OnClick(){
#if UNITY_ANDROID // 端末がAndroidだった場合の処理
// Androidの処理
#endif //アンドロイドの処理範囲終わり
#if UNITY_IOS // 端末がiOSだった場合の処理
// iOSの処理
#endif //iOSの処理範囲終わり
#if UNITY_EDITOR
// Unity上での処理
# endif
}
}
ちなみに以下のように記述することもできます。
using UnityEngine;
using System.Collections;
public class Terminal : MonoBehaviour {
void OnClick(){
#if UNITY_ANDROID
// 端末がAndroidだった場合の処理
#elif UNITY_IOS
// 端末がiPhoneだった場合の処理
#elif UNITY_EDITOR
// Unity上での処理
#endif //終了
}
}
この方法では最後の #endif が必須です。
この #endif がないとエラーになります。
UNITY_IPHONE は非推奨
先程のコードで、 #if UNITY_IOS の代わりに #if UNITY_IPHONE でも動作はしますが、公式ドキュメントでは「非推奨」となっています。