קומפילציה ספציפית לפלטפורמת Unity

Unity מספק תכונת קומפילציה ספציפית לפלטפורמה המאפשרת למפתחים לכתוב קוד שייכלל רק ב-build עבור פלטפורמה ספציפית. תכונה זו שימושית כאשר יש צורך בכתיבת קוד ספציפי לפלטפורמה או כדי למטב את הבנייה על ידי אי הכללת קוד מיותר עבור פלטפורמות מסוימות.

כיצד להשתמש בקומפילציה ספציפית לפלטפורמה

כדי להשתמש בהידור ספציפי לפלטפורמה ב-Unity, השתמש בהנחיות קדם-מעבד. הנחיות קדם-מעבד הן הוראות מיוחדות למהדר שמתבצעות לפני תהליך ההידור בפועל. ניתן להשתמש בהנחיות אלה כדי בתנאי לכלול או לא לכלול קוד על סמך פלטפורמת היעד.

הנה דוגמה כיצד להשתמש בהידור ספציפי לפלטפורמה ב-Unity:

#if UNITY_IOS
    // iOS-specific code
    // This code will only be included in the build for iOS
#elif UNITY_ANDROID
    // Android-specific code
    // This code will only be included in the build for Android
#else
    // Code for other platforms
    // This code will be included in the build for all other platforms
#endif

בדוגמה זו, ההנחיות 'UNITY_IOS' ו-'UNITY_ANDROID' מסופקות על ידי Unity וניתן להשתמש בהן כדי להרכיב קוד מותנה עבור פלטפורמות iOS ו-Android, בהתאמה. ניתן להשתמש בהנחיות זמינות אחרות ספציפיות לפלטפורמה כגון 'UNITY_EDITOR' (עבור עורך Unity), 'UNITY_STANDALONE' (עבור בנייה עצמאית), 'UNITY_WEBGL' (עבור בניית WebGL), ועוד.

#if UNITY_EDITOR
    // Editor-specific code
    // This code will only be included when running in the Unity Editor
    using UnityEditor;
#elif UNITY_STANDALONE
    // Standalone build-specific code
    // This code will only be included when building for standalone platforms (Windows, macOS, Linux)
#elif UNITY_WEBGL
    // WebGL-specific code
    // This code will only be included when building for WebGL
    using UnityEngine.Networking;
#endif

// Shared code that will be included in all builds
public class MyScript : MonoBehaviour
{
    private void Start()
    {
#if UNITY_EDITOR
        Debug.Log("Running in Unity Editor");
#elif UNITY_STANDALONE
        Debug.Log("Running in standalone build");
#elif UNITY_WEBGL
        Debug.Log("Running in WebGL build");
#endif
    }
}

סיכום

על ידי שימוש בהידור ספציפי לפלטפורמה, מפתחים יכולים לכתוב קוד המנצל את התכונות והיכולות של כל פלטפורמה תוך שמירה על בסיס הקוד מאורגן ומוטב לפלטפורמות יעד שונות ב-Unity.