I’m somewhat of an amateur when it comes to Unity, and there’s one issue I’ve been trying to work through for two days now. I have a game made that is fully playable in browser (WebGL), no issues or anything, but I’d like to add a detection function that activates if the user is on a phone or tablet while playing. I’ve tried several different options, including creating a .jslib plugin, but the documentations are outdated and cause instant crashes as it seems the build files have been overhauled recently. I’ve found a few people talking about this in
and
but playing around with index.html to find somewhere for the javascript to interact with unity code has gotten me nowhere so far. Right now I’m trying to just have the SendMessage function work at all, but it doesn’t affect my unity script at all. From what I understand, the function is supposed to work if you put it here:
var script = document.createElement("script");
script.src = loaderUrl;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
unityInstance.SendMessage("isitaphone", "IsPhoneFunc", 5);
loadingBar.style.display = "none";
fullscreenButton.onclick = () => {
unityInstance.SetFullscreen(1);
};
}).catch((message) => {
alert(message);
});
};
document.body.appendChild(script);
</script>
</body>
</html>
This is what my unity script looks like, attached to gameobject isitaphone (the bool is currently unused, tried that before I attempted adding a number to see if anything changed):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class SprayClick : MonoBehaviour
{
public GameObject phoneRef;
public GameObject phoneRef2;
public bool isTouchies;
private int num2;
private void Start()
{
if (num2 == 5)
{
phoneRef.GetComponent<Gameplay>().isPhone2 = true;
phoneRef2.GetComponent<StartMenu>().isPhone = true;
}
}
public void Update()
{
if (num2 == 5)
{
phoneRef.GetComponent<Gameplay>().isPhone2 = true;
phoneRef2.GetComponent<StartMenu>().isPhone = true;
}
}
public void IsPhoneFunc(int num)
{
isTouchies = true;
num2 = num;
}
}
I’m wondering if there’s any easier way to pass information from index.html to unity, or if my code is wrong somewhere. I thought perhaps the function being called too early, before gameobjects are loaded, could also be the reason it doesn’t work, but in that case, is there a workaround? Greatly appreciate help.
Edit: Before I forget: yes, I do upload the project (to itch) for playtesting, and yes, I am tired of exporting and editing the build files every time I do this.