18 April 2019

Unity Platform Specific Object

This MonoBehaviour allows for any game object to be disabled or destroyed when enabled on a platform it's not needed on. An example of this would be when using on-screen controls for use on mobile devices. Attach the script, select the platforms the object should be allowed on and done.
// PlatformSpecificObject.cs

using UnityEngine;

namespace FallingSloth
{
    public class PlatformSpecificObject : MonoBehaviour
    {
        public bool destroyObject = true;
        
        public bool android;
        public bool ios;
        public bool windows;
        public bool mac;
        public bool linux;
        public bool webgl;

        void OnEnable()
        {
            #if UNITY_ANDROID
            if (!android) Execute();
            
            #elif UNITY_IOS
            if (!ios) Execute();
            
            #elif UNITY_STANDALONE_WIN
            if (!windows) Execute();
            
            #elif UNITY_STANDALONE_OSX
            if (!windows) Execute();
            
            #elif UNITY_STANDALONE_LINUX
            if (!linux) Execute();
            
            #elif UNITY_WEBGL
            if (!webgl) Execute();
            
            #endif
        }
        
        void Execute()
        {
            if (destroyObject)
                Destroy(gameObject);
            else
                gameObject.SetActive(false);
        }
    }
}

No comments:

Post a Comment