unity3d Multiplatform development Organizing platform specific methods to partial classes


Example

Partial classes provide a clean way to separate core logic of your scripts from platform specific methods.

Partial classes and methods are marked with the keyword partial. This signals the compiler to leave the class "open" and look in other files for the rest of the implementation.

// ExampleClass.cs
using UnityEngine;

public partial class ExampleClass : MonoBehaviour
{
    partial void PlatformSpecificMethod();

    void OnEnable()
    {
        PlatformSpecificMethod();
    }
}

Now we can create files for our platform specific scripts that implement the partial method. Partial methods can have parameters (also ref) but must return void.

// ExampleClass.Iphone.cs

#if UNITY_IPHONE
using UnityEngine;

public partial class ExampleClass
{
    partial void PlatformSpecificMethod()
    {
        Debug.Log("I am an iPhone");
    }
}
#endif
// ExampleClass.Android.cs

#if UNITY_ANDROID
using UnityEngine;

public partial class ExampleClass
{
    partial void PlatformSpecificMethod()
    {
        Debug.Log("I am an Android");
    }
}
#endif

If a partial method is not implemented, the compiler will omit the call.

Tip: This pattern is useful when creating Editor specific methods as well.