Search code examples
androidunity-game-enginedependenciesplatform

When does Unity3D's Plattform dependent compilation work?


I have a small code snippet here from one of my projects. It is used in the script for a drag and drop menu. The script is attached to every item, that is dragable.

public void OnDrag(PointerEventData eventData){
    if (isPlantLocked())
        return;

    #if UNITY_EDITOR
        transform.position = Input.mousePosition;
    #endif

    #if UNITY_ANDROID
        transform.position = Input.touches[0].position;
    #endif
}

I get an exception (every frame i drag the item), that Input.touches.Length is zero, but this code region should only be used on android, and on the mobile version everything works fine.

And now my question is how can i get rid of the exception and when does the plattform dependency work?


Solution

  • If you look at your "Build Settings" window, there is a "Switch Platform" button that'll adjust your current runtime platform and trigger compilation of the respective directives, even while in the editor. This means both UNITY_ANDROID and UNITY_EDITOR can both be true at the same time because UNITY_EDITOR means you're running in the Unity application itself.

    Since you're checking input types and the first one is for a mouse, you might want to replace UNITY_EDITOR with UNITY_STANDALONE and then make sure that when you're testing in the editor, you have the correct current platform set.

    Another option (better if you're never going to publish a standalone build and it's only intended for non-PC platforms) would be to first check against UNITY_EDITOR and then #else if into the other options:

    #if UNITY_EDITOR
        transform.position = Input.mousePosition;
    #elif UNITY_ANDROID
        transform.position = Input.touches[0].position;
    #endif
    

    This way you can be a little more lax with swapping out your current platform setting.