How does Unity package WebGL platform to distinguish mobile terminal and computer terminal

How does Unity package WebGL platform to distinguish mobile and computer complete solutions

Recap

There is a recent project in which there is a function to control the movement of the character. The computer side is controlled by WASD (keyboard), and the mobile phone side is controlled by a virtual joystick.

Since it is a WebGL platform, it is useless to add the following from the C# layer

> void Awake() {
    
    
    #if UNITY_ANDROID
        Debug.Log("这里安卓设备");
    #endif
    #if UNITY_IPHONE
        Debug.Log("这里苹果设备");
    #endif
    #if UNITY_STANDALONE_WIN
        Debug.Log("电脑上运行o");
    #endif        
}

1. Create a new mylib.jslib file

In the project resource folder
1. Create a new Plugins folder
2. Create a new mylib.jslib file The suffix
name .jslib must not be wrong 3. Copy the following code into the newly created mylib.jslib file above

mergeInto(LibraryManager.library, {
    
    
  HelloFloat: function()
   {
    
    
      var userAgentInfo = navigator.userAgent;      
      var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];    
      var flag = true;       
      for (var v = 0; v < Agents.length; v++)
      {
    
            
       if (userAgentInfo.indexOf(Agents[v]) > 0)
       {
    
       
        return 1; //如果是手机端就返回1
         break;       
       }     
      }       
      return 2; //如果是pc就返回2
  },
});

2. Create a new C# layer code

using UnityEngine;
using System.Runtime.InteropServices;
using System;

public class Example : MonoBehaviour
{
    
    
    [DllImport("__Internal")]
    private static extern float HelloFloat( );
    
    void Start( )
    {
    
    
        float f = HelloFloat();
       
        if (f == 1)
        {
    
    
            Debug.Log("移动端");
        }
        else if (f == 2)
        {
    
    
            Debug.Log("电脑端");
        }
    }
}

You can pass simple numeric types to JavaScript in function parameters without any conversion. You can pass other data types as pointers into the emscripten heap, which is just one big array in JavaScript.
For strings, you can use the UTF8ToString helper function to convert them to JavaScript strings.

3. Script mount

Create an empty game object in the Unity Hierarchy window
insert image description here
and attach the C# script we just created

4. Package test

insert image description here
If you want to view the mobile terminal, click here and press F5 to refresh the page.
insert image description here
insert image description here
Now it is the mobile terminal.

Guess you like

Origin blog.csdn.net/weixin_45375968/article/details/127772222