#🌐┃web
1 messages · Page 6 of 1
For instance, a new project, first time build, with a release build, set to gzip, is likely a 20min process. Subsequent builds are less. Debug builds remove stripping and build even faster. Removing gzip is also even faster. You should be able to get that down to a 3 or 4 minute build during development in most unity versions for small (<40mb) projects. Not that 20mins is really all that bad, given you really shouldn't be building often in practice for webgl. Forever to me is hours.
But, no sense going into all of that if you don't really care about the what or why. And I don't really love unity enough to defend it :D. If possible, for web, I usually recommend other web based engines. Just because of the unnecessary loading times and download sizes for the web.
Morning all
Getting an error on load of my WebGL game, it happens on two browsers (Edge + Chrome)
It's saying something to do with memory allocation, happens when I run in my VM i use for work and outside of the VM too
I've tried enabling/disabling decompression fallback, even tried with/without the appplication/wasm header
A lot of the information like file paths and URL's are omitted for confidentiality
1st screenshot is the error
2nd is the nginx proxy
3rd is the publisher settings
4th is general build settings
Can anyone offer a pointer on what's causing this please?
TIA
nvm got it sorted now
hi, so i have a for loop (tried foreach too) to iterate through my array and instantiate some prefabs on a leaderboard.
i've had this working fine in editor, but when building + running it refuses to run the for loop.
i've even tried to just have a basic Debug.Log in there to see and it doesn't show either
again, works fine in editor, absolutely does nothing when running as a WebGL game.
is there something i'm missing for it to like my loop?
for (int index = 0; index < scores.Count; index++)
{
Debug.Log(scores[index].Score);
GameObject entry = Instantiate(leaderboardEntry,
GameObject.Find("LeaderboardBody").transform, true) as GameObject;
entry.transform.GetChild(0).GetComponent<Text>().text = scores[index].UserID;
entry.transform.GetChild(1).GetComponent<Text>().text = scores[index].Score.ToString();
}```
i've also had the spawn in worldspace as false too and still doesn't work
I'd try checking deeper. Changes are there is an error in the console for Web, but if not, try testing it end-to-end in editor (like right from the loading scene).
i sit watching that console like a hawk and nothing comes up
it's just refusing to acknowledge that loop and never shows anything, even when I had a debug log in it
Chances are there is a singleton, non-web friendly network request or some other problem causing the issue.
Which may only appear when you go through the whole set of scenes end-to-end in the editor
But the loop in of itself doesn't have anything obvious for an issue to me
i can go through my games whole loop, loading + playing + submitting score + restarting the game perfectly fine in the editor
from what I can see, the only way that wont execute is if there is an error, the script is missing, or scores.Count is 0.
but this is the thing, there's no errors, the scripts there, and the score count isn't 0
Actually - that's my guess. Add a ebug log before the for loop that does Debug.Log(scores.Count);
That'll at least (hopefully) show a bit more of what is happening
if that is zero, then we need to see what Scores is (and make sure it isn't something like a scriptable object, etc). If it doesn't run at all, we know something is happening earlier in the script.
trial and error is fun 😄
From what I encountered it is quite common that order of initialization is different. So my guess you Score list is not ready yet on webgl. try to create it in awake instead of start or create it if it does not exist yet. Also GameObject.Find is very slow, I would never suggest using find instead of referencing it.
Hi
While I was making a WebGL build of my game, I encountered a problem; In one of my scenes, I use two cameras to achieve a split screen effect but when I build the game in WebGL, it skips the first display where I have set up split screen and moves to the second display where a third camera is rendering.
I checked building it for windows and it works just fine, the problem only persists for WebGL builds. And NO I cannot edit the index.html file because I'm making my game for another public game site and they only require the build folder
Does anyone no a solution to this?
Does all cameras have Main camera tag?
I had cameras problem when I had multiple cameras and used MainCamera tag to select camera. Because both cameras had same tag, it selected first one. And the first one was different on PC and WEbgl
so My guess that you using somekind of search/select method and the cameras list is in different order even if they all starts at the same time.
I refer to the cameras as objects by dragging them from the hierarchy into the slot on my script; I am not using tags
but it might be because I'm manually changing the display and rect transform of the cameras
if yes then it should work fine if I don't however I am high doubts about this; it won't work but I'll check anyways
Okay it actually worked but confused a bit
welcome to WebGL, confusion here is common feeling 😄
I made another scene where i set the cameras to split horizonally(wide cameras; one on top and the other on bottom) and it displayed correctly but in the original problem i had set the cameras to split vertically (one on the right and the other on the left).
It's still confusing tho but I confident that I'll be able to solve it now
Thank you so much @astral wave
glad to heart that you found where to start! good luck!
thanks 
Solved it!
I was changing target displays to switch between split screens and other displays as
camera_01.targetDisplay = 0;
camera_02.targetDisplay = 0;
camera_03.targetDisplay = 1;
But we don't have target displays in WebGL, so I have to render all the cameras in one display and handle accordingly.
Why this happened: I developed the game first in Windows Standalone Platform then switched to WebGL
Hey folks! I've hit a lot of bumps on the road of game development. So, I decided to do something different: I’m open sourcing my casual multiplayer web game Crayon🖍️.
It's plug-and-play🔌 ready for Unity game engine, and I’m excited to see how you'll turn it into something big. To help you get started, I've also included the handwritten blueprints on Crayon's design.
https://madhavagar.gumroad.com/l/crayon
A web-based multiplayer coloring game for team building and friends-hour built on Unity. The source files are distributed under the MIT license. You can download the unity package to dive into the C# code, learn behind-the-scenes of game development, or even make your modifications to publish elsewhere.ALSO INCLUDES- The game designer's original...
hi all, back again
don't know if i'm being a dumbass, but having an issue with JsonUtility on my WebGL build
Below is the json string i have
{"scores":[
{"scoreId":5,"userId":"abc","score":3590},
{"scoreId":4,"userId":"abc","score":130},
{"scoreId":2,"userId":"abc","score":120},
{"scoreId":3,"userId":"abc","score":120},
{"scoreId":1,"userId":"abc","score":110}
]}```
this is my C# code```cs
public void UpdateLeaderboard(string scoresJson)
{
try
{
string json = "{\"scores\":" + scoresJson + "}";
ScoresData scoresList = JsonUtility.FromJson<ScoresData>(json);
int destroyed = 0;
foreach (Transform child in GameObject.Find("LeaderboardBody").transform)
{
Destroy(child);
destroyed++;
}
Debug.Log("Removed " + destroyed + " items from leaderboard");
Debug.Log(scoresList.scores.ToString());
for (int index = 0; index < scoresList.scores.Count(); index++)
{
Debug.Log(scoresList.scores[index].score);
GameObject entry = Instantiate(leaderboardEntry,
GameObject.Find("LeaderboardBody").transform, false);
entry.transform.GetChild(0).GetComponent<Text>().text = scoresList.scores[index].userId;
entry.transform.GetChild(1).GetComponent<Text>().text = scoresList.scores[index].score.ToString();
}
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}
}
[Serializable]
public class ScoresData
{
public List<Score> scores { get; set; }
}
[Serializable]
public class Score
{
public int scoreId { get; set; }
public string userId { get; set; }
public int score { get; set; }
}
```now, the problem here is that this works completely fine in the editor with the same string, but when it's built and running, the same string refuses to parse. I don't get any error unless i try to do something with the scoreList.Scores property.
i've read up on it a few times and looks like WebGL hates threading, but nothing here is being threaded, the only thing I can think that's different is the fact that the API calls to fetch the data are handled via JS because there's some info the calls need that can only be grabbed via JS
is there something with WebGL and Json parsing I'm missing, or something i've missed in general?
the other potential solution i can see is returning the needed info from JS and make Unity do the API call, but this was blocking the game before (was just UnityWebRequests), i'm assuming it hated because of threading?
I want to open webpage inside unity, Is there any way to do it?
for "unity embedded browser"
do you have a walk through video of some sort on youtube?
Selling it on gumroad for $50 isn't quite the same as just open sourcing it. And if you really wanted to go down that road, you could just sell it as a project on the Unity asset store.
At any rate, selling something on here is very much promotional and would belong somewhere akin to #1080140002849214464
@fallow hill if you go to the gumroad link, you shall find a YouTube video attached in there
Ahh, thanks for sharing your thoughts @charred briar! I appreciate it 🙂 Considering #🌐┃web games are a niche among Unity devs, I felt it would be best to put it here.
I understand your point about open source, which is a common misconception we make in equating open source with all free. However, as you would see, open source refers to the license under which the files are distributed, in this case the MIT license, which is indeed free. And while similar for-profit source codes cost significantly more, the modest price floor I have set is just to cover the time and effort invested rather than earning a profit. Cheers 😄
Sorry, maybe I wasn't clear in what I was trying to say. Selling things on #🌐┃web is not the appropriate place. This is for getting help with unity for the web.
If I was to say, create an asset pack for sale, posting it in here is a no no
Even if it's web related
I'm sure if it was a github thing saying hey I posted the code for X, I'm sure no one would care particularily. But saying you want money for source code (advertising) is against the conduct and belongs elsewhere i.e. #1080140002849214464 - the two places advertising is allowed per the #📖┃code-of-conduct is two archived channels. You could maybe toss it in #1180170818983051344 but that's really not for advertising either.
Ahh, right! Again, selling hasn't been my focus. I'm sorry if my message felt that way. Just wanted to put a word out there in case anyone is struggling with multiplayer setup(which I myself struggled immensely with and wasnt clear until I visited some source codes) or any aspect of C# code that they may think they could take cue of from this project.
But i understand you, and feel my messaging could have been more clear and directed towards aspects of code that maybe of direct help, instead of looking like an advertisement. Thanks for pointing that out @charred briar I'll take care of that.
Saying you open source your game is fine. Linking to a gumroad purchase is monetizing (not just open source).
Sorry I didn’t see this. I’m just saying in context to test on mobile devices, I have to build it so 20 minute builds for testing stuff is jarring. I need to look into the methods you mentioned…
https://paste.ofcode.org/NaschTgJRLLqCXwbG5YAsP. Hello friends I am using Application.runInbackground = true; and i want to kepp this coroutine countinue and finish in background but its pause while web app is running in backgound, I am using WebGl build
Found a strange bug on calling a method from the side front-end to the unity webgl app, it gets executed correctly but at the end I get an "undefined", as u can se I've just put a debug.log("END"); at the bottom of the method to check if the undefined was something left in the code but it was not...any idea on what it could be?
Ok I get undefined if the method that I call has not code in it 🤔
and its a void so it doesnt return nothing
That's how the console works. It prints the value of the last line after it's been evaluated. The value of a function call that returns nothing is undefined
so I can consider it normal?
yes
@quartz goblet !collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Hello, Im trying to host a webGL Build on a react.js website. any one have any tips?
If you're having problems with it, describe the issue and ask a proper question. Random tips aren't going to be helpful
Is it possible to modify the index.hmrl in order to have 1 (or 2) gifs when loading the webapp?
Sure, the sample template shows you a single one. No reason you can't use it as a reference. There are more templates from unity you can use to build something custom quite easily.
Hello friends I am using Application.runInbackground = true; and i want to kepp coroutine countinue and finish in background but its pause while web app is running in background, I am using WebGl build
Ah okay
I hope someone will know better than me, but you will run into alot of problems when Tab is not active. Websockets dies, connection breaks and etc. And you can control most of those things, as it is up to browser to control your tabs processes. And what most browsers do? deactivate not needed tabs to save power and resources. So only way is to have the tab active, sorry. I also had tons of problems with that, and did no find any universal solutions. But maybe I am wrong or dont know something.
tho some people says they have better results if they lock their Application.targetFrameRate = 30; but that just make it less visible, but don't solve the problem fully.
@astral wave thanks for the answer! I will try this Application.targetFrameRate = 30;
@astral wave Application.targetFrameRate = 30 is not working for me, I keep the Application.runInbackground = true and when i am on the browser but in different tab runinbackground not working but when i switch to another application like filemanager or other runinbackground working fine.
from what I understand in different tab application is either pauzed or reduced to to super low frame rate. But you can't control it unless you control browsers code.
yes exactly I have timer in my application so its slow down when i'm on other tab
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Any idea on what could be the reason for this artifact?
Device is Mac (OS Sonoma 14.2.1)
I've tested my webgl app on other Mac devices and didnt had problems...
MY guess is scaling. As on webgl it gets random scaling of weird resolutions it runs at. try set same resolution on editor and see if it still acts the same.
thats not open source?
Its also pretty unattractive. It's a neat idea, but the cleanup involved to make it look good enough for commercial use isn't trivial.
hi, new here, new to unity and absolutly cluesless on to why my web.config isnt working when i try to host my webgl game on azure (it needs to be azure). gzip compression not working and unconpressed isnt building right eather. I am doing something wrong, thats for sure, not alot of "explain it to me like im five" tutorials out there that arent outdated, i think. Please help me. Thanx in advance! ❤️
You're probably better off asking on an Azure or devops server. After a WebGL game has been built, there's nothing special about it from the server's point of view. It's just a standard website.
I'm getting this Wwise+Unity error, but googling it results in only one result, and it's a forum post with no responses. Anyone know what's happening?
WwiseUnity: A class has not been registered for the reference platform: Web
UnityEngine.Debug:LogError (object) AkWwiseInitializationSettings:UpdatePlatforms () (at D:/Users/Aryo Nazaradeh/Misc/Work/Games/2024/GGJ 2024 Impact/Impact/Impact_Unity_Game/Assets/Wwise/API/Runtime/Handwritten/Common/AkWwiseInitializationSettings.cs:448) AkPluginActivator:Update (bool) (at D:/Users/Aryo Nazaradeh/Misc/Work/Games/2024/GGJ 2024 Impact/Impact/Impact_Unity_Game/Assets/Wwise/API/Editor/AkPluginActivator.cs:693) AkWwiseWWUBuilder:Populate () (at D:/Users/Aryo Nazaradeh/Misc/Work/Games/2024/GGJ 2024 Impact/Impact/Impact_Unity_Game/Assets/Wwise/API/Editor/WwiseWindows/AkWwiseWWUBuilder.cs:143) AkWwiseWWUBuilder:Tick () (at D:/Users/Aryo Nazaradeh/Misc/Work/Games/2024/GGJ 2024 Impact/Impact/Impact_Unity_Game/Assets/Wwise/API/Editor/WwiseWindows/AkWwiseWWUBuilder.cs:84) AkWwiseWWUBuilder:StartWWUWatcher () (at D:/Users/Aryo Nazaradeh/Misc/Work/Games/2024/GGJ 2024 Impact/Impact/Impact_Unity_Game/Assets/Wwise/API/Editor/WwiseWindows/AkWwiseWWUBuilder.cs:330) AkWwisePostImportCallbackSetup:PostImportFunction () (at D:/Users/Aryo Nazaradeh/Misc/Work/Games/2024/GGJ 2024 Impact/Impact/Impact_Unity_Game/Assets/Wwise/MonoBehaviour/Editor/WwiseSetupWizard/AkWwisePostImportCallbackSetup.cs:166) AkWwisePostImportCallbackSetup:RefreshCallback () (at D:/Users/Aryo Nazaradeh/Misc/Work/Games/2024/GGJ 2024 Impact/Impact/Impact_Unity_Game/Assets/Wwise/MonoBehaviour/Editor/WwiseSetupWizard/AkWwisePostImportCallbackSetup.cs:140) AkWwisePostImportCallbackSetup:CheckMigrationStatus () (at D:/Users/Aryo Nazaradeh/Misc/Work/Games/2024/GGJ 2024 Impact/Impact/Impact_Unity_Game/Assets/Wwise/MonoBehaviour/Editor/WwiseSetupWizard/AkWwisePostImportCallbackSetup.cs:67) UnityEditor.EditorApplication:Internal_CallDelayFunctions ()
The people on game audio related forums/servers were also unsure about this
Everything I see online about this just says that Wwise doesn't support WebGL
Greetings folks, i am currently having issue getting audio to work for my Brackey's Game Jam project made in Unity 2022.3.20f1 for WebGL. Made a thread below detailing the issue as well as the steps i took thus far in solving the issue.
an error text would help more. But most likely you webserver is not setuped to support gzip or/and wasm. As at least AWS was not by default. so you need first.
https://docs.unity3d.com/Manual/webgl-server-configuration-code-samples.html
this is not azure, but you can find same elements.
Thanx for the guidance , as i suspected me beeing new to this it took some time to figure out simple stuff but i got to work now. In the webgl build i chose the Gzip compression but with decompression fallback checked, this then requires you to add .unityweb files to the mimeMap on the wen.config file. The same file from the uncompressed WebGL builds example on the unity Server configuration code samples page. This might be to obvious to many but im attaching it for the noobs (like me!) with simular issues 🙂
hi all. I've been trying to build my scenes for WebGL, everything including the game object animations look fine in the build however my videos won't play back. The videos plays back fine in unity but they don't play in the built webgl version. I'm a noob so this is probably something very simple but I can't seem to figure it out. (made my videos by creating a videoplayer and drag and dropping it onto a gameobject -a cube)
https://docs.unity3d.com/2023.1/Documentation/Manual/webgl-video.html this is worth checking for if you using unity 2023.
and another thing is how you load your videos. Is it URL? or from video file? are you loading from streaming assets?
As with webgl there is a lot of things to consider. CORS (when you load from url that dont have same domain), loading from streaming assets, where it recomended to uiser webrequest to load video.
What is more widely supported for webgl, urp or standard pipeline? I am looking to maximize the number of devices this works on.
Also, I saw a lot of conflicting information regarding whether webgl works on phones. I saw it works on high-end ones, does it also work with low-end mobile phones
Thanks 
URP, mainly couz you will ant to work with most recent Unity version, as it provides way more control over webgl. URP is just better, tho you will need disable features you dont need. And for performance it really depends on your game. For me biggest problem was memory usage, as expecially iPhones have super small limits (~300mb) after which it will keep restarting or not load at all. Phones after iPhone X have way less problems. But if you want it to run on as many devices as possible you will be better with PlayCanvas or Three.js, or babylon.js as their performance is way better than Unity webgl (also memory limits is higher for some reason there as well).
In short: if amount of devices matter, don use Unity webgl. If quality and content matters, use Unity and URP.
Hi.I have video playback problem on webgl.I did almost everything but the video was not played at all.I changed the video codec to H.264 or webm or reduced the size of the video to KiB .Also I always use URL option,but still the video did not play.Please help me I really don't know what to do.
turn off autoplay and add button to play video. As autoplay does not work unless audio is muted (and sometimes dont start at all) without user interaction. Browsers thingies.
URL option is also scuffed. as there might be problems of CORS, aka loading video from different domain will be a big NO NO.
also:
also video clips are not supported at all.
No, I test locally and the play on awak option is disabled, and I have to play the video code from the Start method. It also works correctly in Unity.
void Start()
{
_videoPlayer = GetComponent<VideoPlayer>();
string videoPath = System.IO.Path.Combine(Application.streamingAssetsPath, videoName+".mp4");
_videoPlayer.url = videoPath;
_videoPlayer.Play();
}
it will not work. Play needs to be called after user interaction with your application ( touch, click). Well if it is muted then it should work on chrome.
So I will test this
There is only one more thing that is not bad to say. The video plays, but with a lot of lag. So that if the video should be 10 seconds, it takes an hour to finish.
what resolution of that video? WebGL videos is very demanding. but it should not be that bad. On player settings did you enable Run in the background option?
720 * 480 . and yes Run in the background is enabled
Its size is 52 kb
ooooooooooo mannnnnnnnn.It was fixed by user interaction and the video works very well. Thank you very much for this valuable advice
thanks for your response. loading from video file not url, which maybe is the issue? I’ll try to redo with streaming assets and report back✨
is there any way to limit the editor to single thread to simulate the browser so i can test there instead building to webgl each time only to realize the methods don't work 
I don't think so. How many non working methods are you finding? Should be generally fine as long as your code is IL2CPP compatible and doesn't use stuff relying on System.Threading, like some of the task APIs as far as threading is concerned.
i learned that the hard way with using Tasks setting up an http handler a while ago (atleast i learned something) , but strictly stick to coroutines now to avoid this
it's mainly my primetween methods
UniTask might be a nicer alternative
private IEnumerator AnimateValueChange(float start, float end)
{
yield return new WaitUntil(() => ReelsController.Instance.AllReelsReady());
Sequence colorSequence = Sequence.Create(cycles: -1, CycleMode.Yoyo).Chain(Tween.Color(_userBalanceText, endValue: Color.yellow, duration: 0.1f, ease: Ease.Default)).Chain(Tween.Color(_userBalanceText, endValue: Color.white, duration: 0.1f, ease: Ease.Default));
animateTextIncrease = Tween.Custom(start, end, duration: animationDuration, onValueChange: newVal => _userBalanceText.text = newVal.ToString("F2"))
.OnComplete(() =>
{
colorSequence.Complete();
_userBalanceText.color = initialColor;
_userBalanceText.text = end.ToString("F2");
});
}
in editor it works great, but in webgl does nothing
...
PrimeTween doesn't use threads, so tweens can be awaited on all platforms, even on WebGL.
https://github.com/KyryloKuzyk/PrimeTween?tab=readme-ov-file#asyncawait
PrimeTween is truly multiplatform with no exceptions. ...
Should be fine.
thanks i'm trying that out now, if it doesn't work hopefully i won't have to spend all of tomorrow hunting down what's causing it 😅
that looks awesome btw. when i'm done building the basics i'm definitely saving that to use in refactor.
after a bunch of Debug.Logs to browser console i tracked it down to event not firing when it's supposed to like it does in editor ... atleast i can go to sleep now knowing where to look tomorrow . thanks !
Pretty sure you can limit it via windows task manager.
This would just limit where your threads can run on the CPU, not whether you can use threads.
There might be a preprocessor directive somewhere which you can toggle, but not sure what effects that might have in editor.
Yeah and looking it up, I think it's a request to use a single core, it doesn't mean it'll listen either
I did, too, but only one or two videos can be played at the same time, and when I want to play the third video, the videos all stop.
i finally found the culprit... i'm so confused on why it happens . for some reason this setter method doesn't work in webgl (it works in editor though)
[System.Serializable]
public class Result
{
public static event Action<float> OnPrize;
public ExitStorage exitStorage;
public IProcessedLine[] lines;
private float _prize;
public float prize
{
get => _prize;
set
{
UnityEngine.Debug.Log($"Result.prize, value = {value}");
_prize = value;
if (_prize > 0) OnPrize?.Invoke(_prize);
}
}
}
[System.Serializable]
public class Result
{
public static event Action<float> OnPrize;
public ExitStorage exitStorage;
public IProcessedLine[] lines;
public float prize;
}
this works though 🤔 🤷
someone's workin at IGT lol
I have used UniTask in the past successfully to port over multithreaded code to use unitask instead. We might not have to worry soon since Unity is totally going to support multithreading for webgl sometime this decade maybe
Awaitable also works great as a replacement for task<T> on webgl if you just want async and await not actual threads.
Question about multi threading… who here has multithreaded a heavy web app in emscriptem c++ or JavaScript and how well does it work on chrome on an average PC (or on a phone?)
I mean… we’re talking about web browsers, which aren’t primarily focussed on high performance compute. Assuming unity DID fix webgl c# multithreading to the maximum extent oosssible, do we know that that extent is equivalent to multithreading code ina native app (similar possibility of. Umber of worker threads, timeslice etc?) or is it more like “chrome only lets you use 4 physical cores no matter your PC core count” etc
I’m thinking about doing rhe test myself but wanted to ask first.
What number of batches should I be looking at with webgl?
Also, static batching vs gpu instancing
What is this error in Unity when building for webgl and how can I solve it:
Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js: undefined symbol: ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEC1ERKS5 (referenced by top-level compiled C/C++ code)
I found out that there is a way to run Java code even when the Chrome browser tab is disabled.
However, I found that in the Unity webgl build or the 2023.3 version of the web build, no update works when the tab is disabled even though RunInBackground is turned on.
Is there any way to solve this? I would like to modify framework.js but it is too complicated.
Why does runInBackground not work for web builds, even though it obviously has a way to run Java code even when the tab is inactive?
Trying to load textures into my Character Select Screen but doesn't load them in WebGL. It's a custom character animator that uses Coroutines to animate characters through a list of PNGs. It looks through a folder in Assets that has these PNGs and loads them in the game.
In the picture I manually put a button with no character. In the editor it shows both the manually button and the character but in webGL it's having trouble loading my character in my Asset/Characters/ folder.
Does anyone know what's wrong here and why it's not loading the character PNG in web.
You most likely don't have such folder in your build
Addressables or streaming assets is probably what you are looking for
https://docs.unity3d.com/Manual/com.unity.addressables.html
https://docs.unity3d.com/Manual/StreamingAssets.html
I'm hoping someone can help me with some confusion regarding WebGL and multi-threading. My understanding is that code using System.Threading will not work, and Jobs may or may not work (which is it?).
However, I am using Parallel.For and several IJobParallelFor structs in some code (compiled into a DLL), and when I build to WebGL everything works fine. My use of Parallel.For is very simple; does Unity somehow convert the code to a normal For loop, which is why it works (which I would be fine with)?
My test was on 2020.3.37f1 if that matters
I believe jobs will fall back to running on the main thread. Still not super sure if these are considered to be "engine threads" or not.
That makes sense and would be fine in my case. Do you have any knowledge of Parallel.For? I've tried googling and searching this channel; everyone seems to say that it should not work (since it is in the System.Threading.Tasks namespace).
I don't have specific knowledge. I would not expect it to work. Did you validate that it actually does run? I believe these things can fail silently
Yes, I have confirmed the code is executed, as the game would not work if it did not.
Hello ! I'm finishing my first game that I would like to put on a web page. However, I don't know much about cybersecurity at all and I'm afraid some of my friends will try to cheat/break the game. Is it possible to break a unity game via web or you have any recommendations for minimal protection?
Just worried about game cheating? Is this a multiplayer game? Does their cheating actually matter?
There's just a leaderboard, I looked up a youtube video to do it (I'm a total beginner) and I'm worried if its possible to send requests to cheat (sorry for my english 🥲)
I doubt that there is limit of 3 videos. maybe something with video start is the problem? like your code?
You out of luck. Only way to protect directly is to have full server authority over all clients actions. But there still a ways to make it secure, mostly to create some specific checks if that update is possible. For example you can see only score in leaderboards, but when you send new score you send duration of session as well. And on API you check if that score is even possible with that time. Aka dirty methods.
But more about your question: is webgl easy to hack? never tried, dont know. But it is harder than PlayCanvas or native JS libraries as most of code is translated in not so user friendly machine coding. But I know that with chrome dev tools you can do quite a lot. For example intercept websocket message. And with some coding you can send fake messages which API or what ever is your server is easy to trick. But as first game I would not think too much about it.
Te problem is it will run the code, but will never finish the task. I strongly recommend use UniTask. It have almost same syntax as other multithreading solutions, but on webgl is friendly to run on main thread without asking questions. So if unity multithreading will become available you will be able easy move to it.
How can I solve the microphone error in Unity WebGL when hosting through AWS? I encountered this problem; while hosting locally, no error occurs, but it arises when hosting through AWS
Where is entry point for 'update' runtime in the web build's framework.js?
How can I obtain the framework.js file?
first of all open browser console, for more accurate error code. Second of all, make sure your AWS is https, as without secure connection you wont be able to use any devices. Local host is exception for that rule. framework.js wont be readable, it is mostly generated machine coding. If you want full stacktrace errors handling, set build to develop mode and on publish settings changes logs to full stack trace.
what you are trying to do? you cannot access code like in PlayCanvas or three.js directly, so framework wont give you any good.
@astral wave I Thougt problem is web is not secure i am i right?
yes this is not secure. on not secure website webgl will not let you access microphone or other devices.
Okay thank you for Clarification
Just want to keep update when browser tab is disabled
If framework.js is using for updating runtime, then i can fix it to keep update when tab is disabled
on Player settings -> resolution and presentation you need to check run in background. Browser controls what runs and does not run when tab is disabled. So you cannot actually control that 🙂 with this option at least it will run at 1fps or whatever browser want it to run.,
I already tested it, and it didn't work in all browsers. I can easily find out by taking a log of the update function.
No logs were recorded while the tab was inactive.
Write logs you want in update function in your code. Build developer mode, enable full stack trace in logs and maybe that will help whatever you want to see.
have you enabled Run in background? And once again, browsers control what run in disabled tabs. most of them brutally pauses all proceses there. others reduces it to extreme low frame rates. yet you cant control that.
Yes that's what I'm talking about. I wrote a log in the update function and tested it. And no logs were recorded. Have you ever tested it? In update, add the variable by 1, remember the number before deactivating the tab, and then come back after deactivating the tab and check the recorded number.
Even if it lower the frame rate to an extremely low frame rate, if no logs are recorded even after 10 seconds, it means that it is not working.
just make sure: have you enabled Run in background?
Yes I said
I already tested it
I did all kinds of testing
From changing browser settings to modifying JavaScript.
As a result, I was able to send a message to Unity using JavaScript in the unityframework loader part of the html, but there is a problem with this.
Only this method could update Unity update, fixedupdate, etc.
So I think framework.js among the web build files created by Unity can solve this problem.
Okay there is one more workaround that helps some people. Set target frame rate at 30 or lower. Some browsers then lets you run it. But this is just workaround. short anwser: different tab = dead tab
And have you ever logged the update function in a Unity web build? Did it work well in the disabled tab as well?
The target framerate is 30 by default.
And I wonder if you've ever done the test I mentioned. If you are sure that runInbackground = true solves this problem, you should at least test it.
I also tested with other players to see if this was just my problem, but the results were the same.
There is some code in framework.js that is responsible for updating something. The problem is that it works with setInterval, and I remember it didn't work well when the tab was disabled.
you clearly know it better than me. I am not here for fighting. If you want change how Unity webgl and browsers tabs works you are free to do so.
I'm not trying to fight, but I was wondering if you've tested it.
Even the Unity guys here are confident that runInbackground will solve it, but as it turns out, it hasn't solved the problem in over two years.
Since Unity has decided to support web in the next version of Unity, this problem will definitely be resolved then.
But what about older versions of Unity?
But thank you for your help so far.
It is not UNITY PROBLEM. Play canvas works exactly the same. The tab is inactive, update does not work. It is browser problems and you cant change it. so my answer from the start you are out of luck and cant run logs on update. As how it works it differs from browser to browser. Some browsers stops it completely. Other reduced frame rate to super low. all for better performance.
nad yes I tested all debuging for it for 3 years now. WebGL sucks as you need to follow more rules than any other platform.
I jsut gave you solutions that helps with some of problem regarding that.
I don't know much about js. Is Play Canvas used in Unity rendering?
For example. Audio works only if you press run in background. but update functions don't work. Or some coroutines can work in background. For example if you have coroutine to run code every 10 seconds you will get response ONCE. it will finish but never start again until you will make tab active again.
PlayCanvas is different engine based on JS. Has nothing to do with unity. But behavior is the same.
However, I have already succeeded in sending messages to Unity in the background at a certain period of time. What this means is that the Unity team can call update in the same way.
fixedUpdate, which runs during the same cycle, can definitely be solved this way.
I implemented this in the Unity load section of index.html and was successful. However, there was a bit of a sync problem with Unity's actual fixedupdate function call.
So I think this was clearly a problem that could have been solved.
The sync problem occurs because the call cycle of unity's fixedupdate and the call cycle of fixedupdate that I executed by sending a message through index.html are different.
What is certain is that update and fixedupdate can be called as messages through JavaScript in index.html, and this fact alone does not mean that Unity's disabled tab problem is an unsolvable problem.
Hello! My Unity code makes a request to access an online leaderboard. However, the issue is that users can see the URL request on the site using the inspector. Is there a way to ask Unity to hide it?
No. Unity is not showing the request, the browser is
there is no way to hide it in the browser?
correct
ok ty
for Streaming Assets, Directory.GetDirectories wouldn't work right? what would be the equivalent to that? Also is this correct on what I'm trying to change?
//filePath = Application.dataPath + "/Characters/";
filePath = Path.Combine(Application.streamingAssetsPath) + "/Characters/";
string[] characterDirectories = Directory.GetDirectories(filePath);
for (int i = 0; i < characterDirectories.Length; i++)
{
CharacterSelectButton spawnedPrefab = Instantiate(buttonPrefab, contents);
spawnedPrefab.Intialize(characterDirectories[i]);
}
On WebGL, Application.streamingAssetsPath returns a HTTP URL that points to the StreamingAssets/ path on the web server. For example,
http://localhost:8000/unity_webgl_build/StreamingAssets/is returned when your application is running against a local development server.On Android and WebGL platforms, it’s not possible to access the streaming asset files directly via file system APIs and streamingAssets path because these platforms return a URL. Use the UnityWebRequest class to access the content instead.
I doubt Directory methods will work and I'm not sure if you can get directory/file listings without some sort of additional mechanism on the web server. Managing your own list of paths is probably the most portable way to do this.
hi guys. for some reason i cannot see my webgl output in chrome console, any ideas?
What is "webgl output"?
like debug.log
Show a screenshot of the console
Yes but the screenshot shows if you have something disabled there or something else out of the ordinary
also check that the player log is enabled in WebGL build options
i dont see that option
never had this issue before, always worked.
oh i just remembered i removed logging from logging.js!
because it was spamming console lol
Hi guys I need some help with building webgl. it started failing recently with an error that i have never seen before. emmscript python.exe failed to run a command. has anyone experienced similar issues? I can provide logs if necessary
the logs would help a lot. There can be tons of reasons. Maybe you have an error in code, which during compile fails. Maybe you have added js code and it is incorrect, maybe it just compiler problem and you need to remove Library folder from your project and let unity to remake it.
Hey guys, curious if anyone has integrated a web wallet with webGL game, would love to see some examples or hear recommendations. I'm interested in allowing a player to claim an NFT at the end of a level, using Needle Engine.
From testing a bunch of shared materials vs a bunch of different materials, gpu instancing seems to be a clear winner. Not sure of the technicalities of it all, but even saving 400 calls out of 1000 with static batching ran pretty terrible.
shouldn't the comparison be between bunch of shared materials on GPU instancing vs bunch of shared materials on static batching?
Yeah, I've been testing both situations and I still get a bit more juice from gpu instancing.
I'd assume gpu instancing is the clear winner over dynamic batching in this regard
what we were doing was static objects went with static batching. Dinamic ones got gpu instancing and srp batcher was on on quality settings. Or you are working not on urp?
tho cant remember why this decision was made, as it was quite long time ago. well for me 350 batches is quite too much for webgl. but just my personal opinion.
I've got a few extra cameras and some stenciling so I've got some extra rendering going on, but just trying to see how well webgl holds up
Anyone know what this WebGL error is trying to tell me?
RankException: Only single dimension arrays are supported here.
at System.Array.Copy (System.Array sourceArray, System.Int32 sourceIndex, System.Array destinationArray, System.Int32 destinationIndex, System.Int32 length) [0x00000] in <00000000000000000000000000000000>:0
function _JS_Log_Dump(ptr, type)
{
var str = UTF8ToString(ptr);
if (typeof dump == 'function')
dump (str);
switch (type)
{
case 0: //LogType_Error
case 1: //LogType_Assert
case 4: //LogType_Exception
console.error (str); <== THIS IS WHERE THE ERROR IS POINTING TO
return;
case 2: //LogType_Warning
console.warn (str);
return;
case 3: //LogType_Log
case 5: //LogType_Debug
console.log (str);
return;
default:
console.error ("Unknown console message type!")
console.error (str);
}
}
Is this from Unity? The error is point there just because that's where the console log is.
But it's saying to use a single dimensional array SomeArray[] not a multidimensional array SomeArray[][]
Yeah. This is from unity WebGL build.
I don't even know where to start looking.
try building in dvloper mode and on publish settings select full stack trace. Then in browser console error will show which script causes it. At least will give you place to start.
Thanks.
Why does there seem to be no option for async loading with webgl? I just want a responsive loading screen instead of my whole program locking up for multiple seconds.
private IEnumerator LoadSubstringBundle()
{
#if UNITY_WEBGL && !UNITY_EDITOR
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(assetBundlePath);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError(request.error);
}
else
{
// Get downloaded asset bundle
bundleRef = DownloadHandlerAssetBundle.GetContent(request);
}
#else
var assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(assetBundlePath);
yield return assetBundleCreateRequest;
bundleRef = assetBundleCreateRequest.assetBundle;
#endif
}```
Actually, that seems to work, I'm just not too sure why. I guess the files are loaded after the web request?
I expect to need LoadFromFileAsync but you cant use that with webgl
https://i.imgur.com/cV502DH.png
Can anyone tell me how to rid of this bottom padding? I've tried completely wiping out the style sheet and it continues to show on the player. It'll even add the text of the build in the space if I were to do that as well which is worse.
you can use async and all those thingies with wbgl if you will use UniTask libray. If you want task and oter threading features usee that.
Failed running command "C:/Program Files/Unity/Hub/Editor/2019.4.39f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" -E "C:/Program Files/Unity/Hub/Editor/2019.4.39f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc"
I get this error when building for WebGL anyone had this issue? this also happens on completely clean project Reinstalling unity changing unity version and deleting tmp and libraries did not help
I looked into uni task but it seemed like I was running into similar problems
I guess the problem mostly is that stuff that you cant naturally yield with via coroutines isn't possible with unitask
like zipping methods
async should work without uniTask. But Tasks them self does not finish up on webgl. but I Have not met any problems on UniTask yet. maybe yours is very specific task that fails. In general webgl is just traps field 😄
ah, is that the problem? I don't care about multithread, I was just looking for a way not to block the main thread but also loading my files.
cant yield when using methods like ZipFile, so that was making it tricky. In the end, I should just be using asset bundles anyway since it just makes more sense.
there is no such thing as multithread in WebGL. unless you will use native c++. UniTask is just creates virtual threads and emulate it. But in reality you cannot do multithreading on webgl 🙂
you can UniTask.Yield. unless ZipFile use external library of some kind. but I see where you have problem. I can just offer my moral support for u
<@&502884371011731486>
what do you mean?
You'll find out soon enough
this is not the place for job search. Please check: #📖┃code-of-conduct message
by activating the stacktrace for errors as in the image below, are the performance of a unity webgl build worse with the console closed compared to not activating the stackatrace at all? Thank you.
by saying activating the stacktrace you mean this?
Regardless all console data is performance not friendly and is still producing logs regardless console is open or not. So for best performance you dont want logs. but if something breaks you will be in bad spot, as you wont know what broke. so having as little as possible logs is the best in my opinion.
Thank you
Im trying to convert my game in WebGL, but I keep getting this error and my player settings wont show, any tips?
Alt+printscreen 😄 I can't read a lot of that, it's too blurry. So I'm not sure what's up
Well if you have problems when converting to WebGL.... Are you using VFX or Threading? If yes, then you will need to rework your code. and wen you get this error? On play? or just when open the project you get tons of errors? or when you switched the platform?
I only seem to get an issue with my video player starting off black and starting slower on Firefox, it seems to be okay on chrome and edge. Would anybody happen to know if there's some kind of secret to Firefox optimisation?
In general video on webgl is .. well special. But it can also be caused by different order of execution, similar like there are cases when game works differently on different pc depending on your code. Expecially when you have find functions or alot of stuff happening on start which depends on each other. Another of causes with black screen especially, that your screen does not get dirty tag at the start. In order to solve that, when video actually starts you need to make texture dirty so it can correctly update (as sometimes if you start video, but video data is not ready yet, it will become black screen and even if on next frame there is video data it will not update. you only need to do it once after video start, after it video gets dirty status correctly.)
Also it could be like one of 9000 other webgl problems 😄
Wait how do I convert my HTML game into a unity game.
I tried my own coding for once that loads .html code but. Still dont work
using UnityEngine.UI;
public class MonkePaint : MonoBehaviour
{
// Embedded HTML content
private string embeddedHTML = @"
<!-- Testing the loader -->
<div>
<h1>Test</h1>
<p>Test.</p>
<p>Test.</p>
</div>
";
public Transform parentTransform;
void Start()
{
GenerateUI(embeddedHTML, parentTransform);
}
void GenerateUI(string htmlContent, Transform parent)
{
}
}
``` (Quick hint im tryna make my .html game into a game in unity)
You will need to be more specific. as now I am not sure, are you chasing something that is completely impossible, or something that is plausible
You don't. You convert Unity games into "HTML" (WebAssembly and WebGL/WebGPU, on a canvas). You can include your own regular HTML stuff on the same page and have interactions between that and the exported Unity game.
Aww how did my friend do it might ask him for the code.
Well can we do it with websites? Ill put the code onto the website.
What do you mean? It's still unclear as to what you are exactly trying to do.
Unity build exported to web techs will run on a webpage in a regular browser. You can include whatever you want on the same page.
My friend challenged me to make my drawing website into a unity project and doing the unity project can also make it possible to make it a .APK so I can upload it to the play store.
To do that you'd rewrite it completely using C#.
Although there are far easier ways (than recreating it in Unity) to build and publish a web app or service into mobile.
Alright thanks
You can package web services and web apps into APKs without Unity if you want.
Yea but I don't really trust those websites. I have very bad trust issues
Hah no worries, I meant you could either just create a web view app in android/xcode. And point it at your site.
Or package it as a chromium app
There are third party plugins you can also buy in the asset store to.let you create an embedded browser view in Unity. But it would just be a really ugly solution that way
I am build and running my webgl project and I keep getting this error and my Textmeshpro text wont load anyone have any idea why this happens or how to fix it?
MORE CONTEXT
It seems that it is the text that is causing the issue, I am using a custom font but its the text that does not load. Anyone have any clue why this would be?
Hey, I'm having trouble while using the controller that only happens in WebGL. No input is working, it's as if the controller is not detected at all.
No issues with standalone builds.
Any insight on what could be the problem? I'm using the new input system btw
Unity needs to use Web APIs for this, so there most likely will be differences. I would look for lower level APIs in the new input system to see if it detects any potential devices in the first place. What controller are you using?
I have no idea how to do that =(. I'm using a Xbox one controller
are you using new input system or old one?
The new one
What do you mean by lower level API? different methods in the new input system?
I would have told you if I had the APIs on the top of my mind, but Gamepad.current or Joystick...current? .. would be one step below the Action system, but there should be a more raw list of input devices that the input system doesn't necessarily have a sensible mapping available.
The new input system was designed to work with devices which the input system doesn't necessarily have mappings available, but the developer can provide for. It's not necessarily something you want or need to do, but the point is that the input system exposes a lot of information that could be helpful for input device debugging.
Manual has several mentions specifically for WebGL input support.
Thanks for the info, sounds like a hassle to redo everything I think I'm gonna let it as it is
Hello, I am trying to use this javascript function to print the Useragent information that the browser has for me. My function looks like this GetUserAgent: function() { var UA = Pointer_stringify(navigator.userAgent); return UA; },
Note: UTF8ToString(message) also not working.
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
I do believe you need to follow these documentation. Also have in mind, you cannot run Javascript code on unity editor, so testing only possible on build version.
also if you build lib file, make sure it is enabled on webgl platform and disabled on others
Thank you, and actually I've taken these steps and unfortunately I'm still having an issue, only with navigator.userAgent, i have other functions working, but this one is giving me an issue, I've been doing research on what may be the issue, and i think its passing a string like such to C#, im still lost.
it might be not pure string, so you will need either prepare correct buffer to it, or hange it into JSON, and then send as string.
I Tried JSON.stringify(), i think i might be doing something completely wrong, would you like a closer look at my project on the unity Website forum ?
If so you can follow this link, and id appreciate any feedback! and thank you for responding
https://forum.unity.com/threads/c-function-to-print-useragent.1564369/
it seems unity have similar function of it self:
string platform = Application.platform.ToString();
Debug.Log("Platform: " + platform);
You can use it as last resort if wont find the solution to your problem.
also you can try making sure to use same approach as https://docs.unity3d.com/Manual/web-interacting-browser-js.html
just maybe "```c
autoAddDeps(DeviceInfo,'GetUserAgent')
autoAddDeps(DeviceInfo,'GetScreenWidth')
mergeInto(LibraryManager.library, DeviceInfo);
and for running on Editor, you will need to use conditional coding and exlude it not to run on your editor at all:
https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
as js will not run editor.
@astral wave I wasn't aware, and I'll probably use it, however, figuring out how I might troubleshoot the issue.
autoAddDeps(DeviceInfo,'GetUserAgent')
autoAddDeps(DeviceInfo,'GetScreenWidth')
doesnt do this, ive tried taking away the 'GetScreenWidth' function from both the c# code and the plugin
Yes, i'm aware of the Preprocessor directives, they didn't change the results either 😦
I did some reading and I was trying to figure out things such as how I would see if this plugin is making this GetUserAgent Result, an environment variable somehow that i can make use of in unity C#, because i was reading something about C/C++ interop and i probably read it incorrectly but learning something along that line so i can pinpoint the issue past i cant print the information is what im looking for
I'm hoping that it isn't C# posting it in some odd format or characters that are there but i can't see.. which is unlikely because its unity C# so im not banking on that, but right now, im almost convinced that Java Is returning something that Unity cant use in the manner that im trying to use it, but i REALLY want to know why badly.
.jslib is something i haven't had very much fortune with finding out information on. But im hoping everything im doing in that file is correct because my "GetScreebWidth is printing properly
My next read is going to be WASM Forums 😵
New information from me.
i know its Unity C# that is not allowing me to Call the Function now. Because i see this function in my browser, as what i think is an environment variable.
I also did some research on string Marshalling.
(Solved.. I Indeed just needed to read and follow simple instructions Better. )
autoAddDeps(DeviceInfo,'GetUserAgent')
autoAddDeps(DeviceInfo,'GetScreenWidth')
were actually necessary
However, in the docs, it says you handle string in this manner:
StringReturnValueFunction: function () {
var returnStr = "bla";
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
}
where my string would be navigator.userAgent instead of "bla".
the first time i failed to understand what I was being told because, i've never read ANYTHING about buffers, so my **** *** just looked at this like, I don't even know what this thing is saying, and didn't do this. A worthy punishment for failing to read thoroughly.
I noticed WebGL apps, when loaded on android will ask to install, but when it does, it uses a generic icon. Any idea how to change it?
Hi guys.
@glacial yacht Has nothing to do with Unity
Hello Everyone,
I need help regarding an issue I'm facing.
I'm creating a webGl game for Smartphones, and I want to add a Full screen function when the user clicks for the first time. But the unity's full-screen button is not working in IOS Smartphones and I also tried different methods, but there is still no progress.
Can anyone please help me with this?
Thank you
iOS Safari doesn't support fullscreen
Is there any way to work around it?
no
Well, if the user makes a desktop link with the the "Add to Home Screen" feature then the website can run in fullscreen. But the website itself can't initiate fullscreen
Okay, thanks for your help
Do you know any Documentations or Tutorials on how I can achieve this?
Google for "ios pwa tutorial"
:(
@orchid bridge just embed the index.htm unity page gives u in the iframe
where are you trying to add this webgl
that doesn't answer
the body of the script
huhu? what script ? and why is it hta?
HTA (Application in which you can program using HTML).
no idea why you would use that
idk how to program apps..
why do you need to "program an app"
also do you know where i can report this?
some kid kept saying godot is better.
For a team called Onyx. I need a app
When I try to publish my game, it loads to 90%
But I have used https://forum.unity.com/threads/fix-for-unity-2020-webgl-build-stuck-at-90.949254/ this to help me. It worked for a bit until now and its still on disabled
Check browser console for errors
How do I check for console errors?
Depends on your browser. I would look it up.
Hello i'm new to unity and i just basically started creating stuff by following the unity course online, i just finished lessons on how to make audio tracks play in the bg and generate 3d sounds. after all that, the course asks me to build it with WebLG and then publish it online by using the WebLG publisher. The project i've made is a 3D Cross-platform URP as requested, and i've everything i had to and i had no problems with that BUT, when i build it, if I select build and run the project works perfectly fine in the site but, if i close that window and try to open it again with the index.html inside the folder i've built that in, it doesnt work and it gives me an error which is:
"Failed to download file Build/Dududu.data. Loading web pages via a file:// URL without a web server is not supported by this browser. Please use a local development web server to host Unity content, or use the Unity Build and Run option."
i have no idea how i can fix this problem, i tried to use different approches like, building another scene, clean building it multiple times AND even redoing all of that project from scratch and rebuild it again but nothing has worked.
i am sorry if this sounds like a dumb question but i'm not even that good with compsci overall, im still in hs and i just started using unity for fun and i'd like to continue obviously but i still have no idea what is wrong with that build because i dont think i've made anything different from the last time i published a project making it work in any scenario.
I hope that someone will be patient enought to help me out with this 🙏
WebGL build requires a server to run. Unity creates a virtual one for you when you use build and run option. Easiest way to deploy for testing without Unity is on Itch.io
yeah ty i managed to fix that by publishing it onto unity but still the game gets to around 90% and then stops loading giving me more errors such as:
idk it these errors are correlated with the build or smthing like that
Unity's site is somewhat weird, it breaks on first run. Try refreshing the page with Ctrl+F5 .
If that doesn't fix it look up what those errors mean
nothing
i moved on, it's surely a bug correlated to me importing some other assets that are probably not public so ill avoid that and that it
Hi guys. Anyone get copy and pasting working on webgl?
It requires special support. There are third party solutions or this. https://github.com/Trisibo/unity-webgl-copy-and-paste
Support Copy and Paste in Unity WebGL. Contribute to Trisibo/unity-webgl-copy-and-paste development by creating an account on GitHub.
Thanks man
im having some webgl lighting issues everything is much dark on the built webgl deployment, any ideas?
issues happened when i switched to urp
switching it self might have cause several problems. First I suggest delete library folder and start project again, it will regenerate premade settings. Also are you using some handmade shaders?
Yeah I had to delete all the materials because although they were converted they weren’t interacting with the light unless I use different shaders
i am getting this in local server no water or grid ..?
is there any error on browser console? are you using something like VFX?
no error on browser console. and only water surface turns like this grid is still rendering
Maybe your water shader uses feature that WebGL dont support. I had tons of problems with water shaders as well. Is it your personal water shader or you using some assets?
as if shader would not be compiled correctly during build, it would be invisible instead of totally black
Hello guys, I was wondering if there is a way to make the webgl build always use the same local host port as I can see that sometimes it varies slightly, and I need to save and retrieve local data from the browser. Thank you
I m using Aqus lite asset from store
You can use python py -m http server it always gives 8000 local port
Mmmh interesting that's the only thing I haven't looked at, but is there by any chance a setting in the unity editor it self
Idk abt that but yeah this is two step process. U have to build it and run the command inside the build. But yeah it gets ur single port
Kk thanks dude I will look into it
oh so you working not on URP? maybe you need to enable depth buffer in project settings or something? Common error is that webgl by default uses different rendering settings profile (you know, low, medium, high), which might have disabled feature that shader uses, like depth buffer or others. Try setting same default quality for all platforms.
hi there
does anyone know how my webgl build wouldn't have the Builder.loader.js file without any errors?
it's complete gone on build, but I get no errors during the process and the file is necessary
Ah thanks! But yeah I'm working on a built in pipeline and that asset was webgl supported idk why but some changes in hierarchy does the job
Which type of compression ur using ?
Hello everyone, my team and I are encountering challenges with our Unity WebGL build. Our aim is to develop a build suitable for running on both mobile and PC browsers. We're utilizing Unity version 2022.3.5f1.
Presently, we're encountering inconsistencies upon launching the application. At times, we encounter prolonged loading screens, while in other instances, certain in-game scenes fail to load. Additionally, we've noticed visual glitches where our canvases fail to render properly until a page refresh.
We've conducted tests across various devices, platforms, and browsers, yet we're still experiencing inconsistencies across builds.
If anyone within the community has insights or advice on this matter, we would greatly appreciate it.
Running both mobile and pc is challenging. Unity webgl havee very limited memory usage on mobile devices (350~mb RAM regardless on device memory), expecially on iPhones. Which forces to use a lot of optimisations on that end. For example making sure all images is encoded in ASTC if you want it to run on android and iPhones (https://docs.unity3d.com/Manual/class-TextureImporterOverride.html) , or pack textures separately for each device. Aggressive memory management with Adressables also helps. Visual glitches on UI also appeared on our project when project was running at the edge line of memory limit (we were using uitoolkit) expecially on iOS devices.
In short it is hard and have tons of limiations. If mobile is your main focus, maybe switching to Playcanvas or other native methods are better. But if main focus is PC, I wish you best luck and stay strong with Unity!
Good day
Anyone experienced with
Module.dynCall_viiiii is not a function
at XMLHttpRequest.http_onload
error on unity6 webgl build , webassembly is enabled?
What code are you using to trigger this? Make sure to use Unity's WebRequest facilities or implement your own through https://docs.unity3d.com/6000.0/Documentation/Manual/web-interacting-browser-js-to-unity.html.
Good day, thank you for the reply, can’t get thru the game, but when I disable the web assembly 2023 build settings, it goes thru
Hello! I have a 3D game that I published to Itch in a WebGL format. This game is running very poorly and I was wondering if anyone had any tips and suggestions to optimize my game
Compress all textures with unity compression tools. It save quite a lot of VRAM. Bake occlusion culling maps and use that. Install addressables and load only things you need, not every single scene into memory. Check models to be as low triangles count as it can be to fit your quality requirements. Play with quality settings (also suggest leave only one quality setting for webgl, otherwise shaders are compiled for all quality settings.). Play with quality and render pipeline settings (reduce shadows or disable them at all). and finally, dont use webgl :DDDDDDDDDDDDDDDDDDDDD
Thank you so much. I usually prefer not to use WebGL; but sadly I’m in a circumstance where it must be played on the browser. Thanks for the help!
depending on devices you want it to run and project I would recommend reading a bit about WebGPU then. I do believe it will be available in Unity 6, at least as beta.
I'm facing a problem with the WebGL Build, when I run the game on Unity Editor, the text "Fill The Bowl" is positioned exactly within the position where I wanted to but after Building WebGL, and when I play in the Unity Play, the text's position initially when I run the game is positioned wrongly and when I play the game and return to home screen, the text is aligned properly. Can someone please help me fix this issue?!
could you show the inspector for the fill the bowl text?
the one that looks like this
Here you go, I've been trying to fix it for quite sometime now...
I set the Rect Transform position to top, and then again I positioned the text, and play tested after WebGL build but still facing the problem
I see that your text is floating up and down, how did you set the position of your text?
First in the script Start method, I've set the position of the text to it's current position and then from the current position to Make it floating, below is the code snippet
void Start()
{
initialPosition = fillTheBoxText.transform.position;
{
void FloatFillTheBoxText()
{
if (initialPosition == null)
{
Debug.LogWarning("initialPosition is not initialized yet.");
return;
}
float yOffset = Mathf.Sin(Time.time * textFloatSpeed) * textFloatHeight;
fillTheBoxText.transform.position = initialPosition + new Vector2(0, yOffset);
}
And I've used the FloatFillTheBoxText() in Update method to make it flow
the problem here is that using transform.position to set the position does not scale with screen size, so users with different screen sizes may see different things
one sec
i was thinking that you can make the title text a child object of another object, then use transform.localposition instead
But, if you look at the video I shared, as soon as I load the game the text is not aligned properly but when I play the game and return to main screen, the text is aligned properly.
webgl things 😵
you could make a quick patch where the game starts off in another scene, and have it immediately load in the title screen
But that's a patch 😢 can't we fix this issue? If you look at the play button, I've used a similar method but to zoom in and out and it's working as I wanted, the problem is only with the text😭
void Start()
{
initialPosition = fillTheBoxText.transform.position;
buttonInitialScale = playButton.transform.localScale;
{
void FloatFillTheBoxText()
{
float yOffset = Mathf.Sin(Time.time * textFloatSpeed) * textFloatHeight;
fillTheBoxText.transform.position = initialPosition + new Vector2(0, yOffset);
}
// Method to perform zoom in and out animation for the play button
void ZoomInAndOutPlayButton()
{
float playButtonScale = Mathf.Sin(Time.time * buttonZoomSpeed) * buttonZoomAmount;
playButton.transform.localScale = buttonInitialScale + new Vector2(playButtonScale, playButtonScale);
}
If you look at the methods above, they are almost same but the way they function differs and there's no issue with the Button at all as it's showing in the position as intended
whats the canvas scaling mode?
if its scale with screen size make it biased to height instead of width
"Scale with Screen size"
In the sense?
Just a noob so have lodz of questions, how will this help fix the issue? Because, as you can see, the issue I'm facing is only upon loading the game, the issue is getting fixed upon playing the game and returning to menu screen. I'm wondering what could be causing the issue here
2022.3.22f1 LTS
I would try to delay grabbing of the initial position to see if it's some execution order issue with Canvas layouting. Modifying RectTransform's anchored position might also behave better. Could also try keeping track of just the offset and add/subtract it from whatever the current position is to play nicer with canvas scaling.
You can test some of these behaviours better in editor if you set your game view to free aspect and resize the window in play mode.
Thanks for the info, I've actually set the screen aspect to 16:9 since it kind of makes it look like a mobile view
Any result yet?
So, I just built and run the Windows version of the game and it's completely working fine without any issue, the problem seems to be with the WebGL
@sweet oriole @edgy mulch Just a heads up, I removed the floating function and tested again, the text's position is aligned properly. So the issue strongly I suspect is with the Time.time since WebGL takes a while to load and that could be causing the issue. Thanks to both you for all the help guys, means a lot to me 🥹
I'm gonna share this game project here in the respective channel in sometime, please do play the game, and share your feedback and any suggestions on it. I never worked on pure 2D game before and this is my first ever attempt without taking a proper 2D course as well so your feedback and suggestions can help me a lot🙏
In sometime, I will have the game shared here in the respective channel as said, please do visit once later, play the game and share your inputs 🥹 🙏
🎊
I also have a couple of questions that I need answer for related to Game Dev, is it okay if I can DM you, please do let me know...🙏
Oo alright go ahead
Not the right place for play testing though, I think you want #1180170818983051344
Glad it's running though:)
Failed to download file Build/Build.data.br. Loading web pages via a file:// URL without a web server is not supported by this browser. Please use a local development web server to host Unity content, or use the Unity Build and Run option my unity webgl build is giving this error
Run it on a web server
There's different ways to run it on a webserver
You could have it up on unity play or run it locally
"Build And Run" button in Unity will spin up a temporary web server for you.
Does anyone know how to hide the last updated status on itchio?
Why would you want to hide that? Breaking a gamejam rule or something?
More like school deadline 😅
It was due a week ago but I figured no way they’ll check it that soon so I just made the project without uploading anything yet. But of course at the bottom of the page it now says last updated a few hours ago
I'm pretty sure that's unchangably in there for game jam purposes. I don't think they would allow or want you to be able to change that
Or people would cheat at game jams which is itch.ios bread and butter
Makes a lot of sense
hi, a cold build for webgl for production, using brotli and LTO, is 1 hour normal for a 200MB game?
yes
It also greatly depends on the project
expecially if you have multiple quality settings and it needs to compile shaders for all of them.
Is there anyone here who has an idea to combine blockchain and the world of Game
!warn 1167721012201275472 Don't troll or spam on the server. Read #📖┃code-of-conduct
james03520 has been warned.
I haven't used blockchain in a Unity project a while (7 or so years back). But if you have questions or issues you are stuck on, just ask, and I'm sure someone can help
thank you for answering.
im a blockchain developer, currently learning unity. feel free to ask about any blockchain question 👍
https://theportal.to/
you can search inspirations there.
hey, do u know how to link a token to an ingame currency?
erc20 token? how do you plan to use it in the game?
nope, its on the solana blockchain
but nvm I think we ll go with an easier way
Hello. Trying to make a web build so I can eventually upload this small game on itch.io. I have resolution settings set in game view, canvas, and player settings as you can see. For some reason, my web build is still way different than in my scene/game views. Any ideas?
I was able to figure it out for everything but the bottom right bubble. I have it anchored bottom right. What seems to be happening is the default 0,0 x,y pos is being defaulted to whatever anchor point I set it on, and ignoring any values I put in x,y to make it actually appear on screen
deleting the old parent and creating a new one seemed to work even though the values didnt change, hm
Has anyone worked in Nvidia CloudXR?
If, please guide me to developing a VR app for oculus quest ?
What should I do if the game in webgl on the iPhone does not work?
give up on iPhones. Jokes aside, check console what error it gives you. (f12 for chrome to open console). But most likely it is running out of memory that iPones gives you to use on webgl. profile your game on browser and ask this question again if it will not work when your game is using less than 300 mb RAM.
How can we implement screen sharing in Unity WebGL
I think fmetp or whatever it is supports webgl
I set the webgl build settings to less than 300 MB and my game stopped running on all devices
that setting is not optimization. it sets limit after which it will crash. So you actually need to optimise game and use profiling to test memory usage.
https://docs.unity3d.com/Packages/com.unity.memoryprofiler@1.0/manual/index.html
Have in mind if you have a lot of textures or load textures in runtime, the correct compression format makes huge difference (up to 4x).
https://docs.unity3d.com/Manual/class-TextureImporterOverride.html
does anyone know why chrome's webgl performance is SOOO bad compared to firefox? I haven't tested any other browsers except from chrome mobile which also has far better performance
Hello,
Does any one have idea about gamelift + mirror on webgl??
I have a server deployed on aws gamelift.
I developed a build which is working on desktop, but the same build not working on webgl platform
well webgl you gotta use websockets for one
in one loads levels additional, feels like it slows down, to new input system with csharp events, but still a bit chrome slowdown, what do you have special in your game that can cause slow? (chrome update fails needs to reinstall, but have to check the about:gpu about:flags gpu=hwAcc , than compare webgl2 use free gamer browser: Opear GX )
im using the new input system for 1 button and being able to remap it, but that wouldnt make sense considering webgl runs perfectly smooth on firefox or on chrome mobile
Is your Chrome install stock? Addons and settings could be messing with performance.
the performance is the same on incognito, but that might not be how that works
unity is not packaging my scriptable objects correctly
it messes up strings
2022.3.19f1
Did you write that text in code editor or inside unity editor?
I would check files encoding options on your editor of choice. Make sure that files encoding is UTF-8 just in case. I had similar problem when file was changed on another editor and its dfault encoding was different than project.
Another idea is if you using textmesh and not legacy text elements: as you sure that your font have correct information for your text?
Reason: on editor, if font is not find for letter, it goes to system fallback font and displays it. On web there is no such system fallback logic. but in this situation characters should not be displayed at all.
Have you tried different Unity editor version? 2022.2.13 I am sure it works well ready data from scriptable objects.
I'm using tmpro but The text in the rest of my game are working fine
My school computer doesn't allow us to install other unity versions 😦
Another thing is that I'm using Master build mode if that affects anything
Another long shot: are you typing into scriptable object field, or copied and pasted the text? Try writing manually one field and check if it is parsed correctly in you webgame then. it seems some people have that kind of problem.
I tried both actl initially I copy pasted everything and saved it
And checked GitHub to see the changes reflecting
I also manually typed everything
Both doesn't work
In fact it seems like some of the texts are merged
This might be a bit time consuming, but I think it would give you a lot of clarity. Create new project and try reproduce this behavior oh it. Make it as minimal as possible. If you are able to reproduce it, then you can calmly report as a bug. This will also help you to see where this data got corrupted. As if it a bug and you cant change version then you will need to create totally new workaround. Like creating script with all text you need and have it will some type of identifier for a workaround.
I also would debug.log all text into console on places you displaying it, so you could see if there is differences? maybe some parsing problems.
of course we can wait for someone else that had this problem. if they had
Hi i have a problem with my webgl export.
i upload it on my personal website. The first time the game started well. but now it doesn't load at all. when i open the console i have all those errors
is there someone to help me ?
Well you in luck, as problem most likely not that big. The problem is you Index.html. When you build your webgl build it changes the names of files depending on directory you built. In this case FMVTest.data is not found. So when you change build folder, you need update index.hmtl as well to load correct files. Most likely if you will start page in incognito mode (aka remove cache) it should work.
OR
so i just have to rename my index.html ?
in your index html there a part where FMTTest.loader and other 3 files are loaded. you need to update that place or you need to make sure you always build in same folder.
that assuming you change all files
okay thanks you i'll try this and post the result 🙂
update it now happens on all paltforms
i will move this to another ch 😦
it seems okay by default
i don't understand what i should write
check Build folder if file names are correct. Then check FMCTest.loader.js if names are correct. and try opening in incognito window. as if you update the index html it does not mean it wont be loaded from cache on browser.
i think it works ! thanks 🙂
I think if you upload to itch, they are the ones hosting your game on their server. No need for a certificate unless you have an external server it has to talk to
I have a virtual machine on AWS that runs my dedicated multiplayer game server
Mixed Content: The page at '<URL>' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws:<URL>/socket.io/?
This request has been blocked; this endpoint must be available over WSS.
this is the error
Ah, do you know where it's creating the websocket?
You'll have to change any ws:// urls to wss:// AND have a certificate associated with it. It can be a self signed cert for testing purposes. Otherwise you'll have to generate a csr for the server listening for the websocket connections and get it signed and then attach it to that server
with my certificate self signed on the server, should the server be able to receive sockets from https://thiago.itch.io/forkant ?
Browsers won't accept self-signed certs
It depends on the environment, you very well might be forced to actually get a signed cert rather than a self signed cert, depending on the environment. If you are hosting a "front end" on itch and having it talk to YOUR backend server over a websocket, I definitely would not roll a self signed cert.
Namecheap has them for $6/year
Let's Encrypt certs are free
AWS-issued certificates from Certificate Manager might also be free, not sure about that
certs can be a pain, good luck!
Yes. I have the certificate from AWS Certificate Manager
but this certificate I obtained with my domain, playforkant.com, but the domain is trying to acess my backend server is itch.io
I actually did not understand well yet
this is my case:
"If you are hosting a "front end" on itch and having it talk to YOUR backend server over a websocket"
your domain should point to your AWS instance, and your backend certificate should be tied to that domain/subdomain running the server on playforkant.com
you'll have to reupload your itch webgl build after changing the ws:// call to wss://XYZsubdomain.playforkant.com
Hey there mates! I used the SimpleWebServer to test a WebGL build locally on localhost:8017, how can I stop the server from running?
how to faster load the WebGL build, it sometime takes too much time to load with same build
Has anyone worked with discord API in webgl?
It needs both dlls but absolutely hates that they have the same name
kill the process running it--is it the node.js executable?
It was a PWA template, so I had to unregister the service worker on browser inspector
the first one takes foreever. others takes less. Also it depends on how many shaders it needs to compile and etc
optimize game? expecially textures. Is it on local machine or on web? regardless check your build report, how much textures and others things takes. And what does taking too long means to you? and what machine are you running it?
I would also hate of there would be several objects named the same way. you sure there you need both of them named the same way/
That's how discord SDK is by default
Renaming or deleting them breaks it
And building it for windows let's you keep both
correct me if I am wrong, but that sdk is c# for unity right? isn't it by default will not work on webgl?
Yes and no
It works on windows and breaks when building for webgl
When I build it for webgl it throws an error - 2 DLLs with the same name
If I remove any of them build is successful but it throws an error (referenced DLL is missing)
I even tried renaming the dlls
Hello everyone, I'm a total beginner in Unity, but I saw some things on YT and wanted to confirm the feasability of an idea. I want to create an augmented reality app that won't need to be downloaded (so web hosted), and that coulb be used with iOS and android. The thing is, I've heard that since I'm developping in a windows environment, I couldn't make it work for iPhone users. Is it true or is there a solution ?
Only true for native apps, not web apps. Thankfully Apple hasn't found a way to restrict iPhones to browsing only websites that were made with Macs
That's good news ! Now, I browed Unity tutos to learn how to create the said app (that would basically be a viewer that would display a 3D object according to a QR code), but it seemed their courses are "native apps oriented" not web app. And I can't figure if I can follow the same tuto to create a web app or if I need to find a totally different way to work.
Mostly you can follow native app tutorials. There are some things you cannot do and some things are done differently on webgl. Main difference how you load files (I would assume you will not have all 3D objects in build and will need to download them). Aslo webgl dont support VFX at all. If you use external plugins, you cannot use c# dlls and etc. Memory manangment needs to be spot on, or you will have crashes on iOS (tarrget about 350mb RAM for older iOS). No compute shaders. No HDRP. Accessing devices can be more complicated (like camera or gyroscope).
https://docs.unity3d.com/Manual/webgl-graphics.html
https://docs.unity3d.com/Manual/webgl-develop.html
But I fully see you creating that kind of app on webgl. Tho have in mind Unity have quite high overhhead, so project size and performance won't be too good. Minimum 4 times worse than native app.
Thanks a lot for your answer. If I understand everything, my projects will be slower, but cross-platform, and if I want it to be faster I have to create two apps (and buy a Mac because I wouldn't be able to deploy for iOS)
Yes if performance is the issue, I would recommend either native app or something like PlayCanvas or Three.js. But honestly working with unity is a pleasure on development side, so try it first 🙂
I understand ^^ thank you very much !
Out of the box, unity can't do AR over web. But there are some expensive add-ons in the store that can help you do that. Personally, I use the package with mindar in it the most and it works well for me.
But usually when I'm doing webxr of any kind, I'm not using Unity. You usually use aframe or something else to do that.
Hello pretty people, would anyone know why the shadow works fine on edito playmode and is cutted off on webgl build on browser?
Hard to tell from those photos what the problem is, but you might want to take a peek at the Quality settings tab. It has shadow length and showadow caster properties per platform.
My friend that has more experience said it is probably a unity bug, he was able to reproduce even on u6
why are web builds much smaller than desktop builds? my current desktop build is 1.7gb but the web build is only 300mb
compression isnt enabled
you can check it while investigating build report. Which will show exactly what takes what space? you eiter can use unity package for that, or just by opening editor logs after you build:
most of my space is textures
some of the maps are almost empty and are very compressable
but i didnt enable compresison
by compression enabled what do you mean? there are like 3 compression options. YO utalking about brotli/gzip? are you talking about textures compression options?
what does your build report says?
Does your WebGL and PC builds have all quality settings enabled?
or you talking about default setup on webgl player options;
Can someone help me how to use opencv in webgl build for free in unity
is it possible to use webgl for submitting form online? I have html form and want to require user to beat game/ win simple game for form to submit
I think you are looking for youtube
Sure, you can pass info back and forth between the html site and the webgl package. You can also use webgl friendly networking and submit the surveys directly. It's up to you on how you want to do it
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
This is what you looking for I guess. There is no out of box solution, but it is simple to create it.
Hello, have a bit of a wierd question, currenlty have a game thats working all fine on web no issues. but for testing purposes we tried to run the game on android google chrome and everything works fine apart from the saving to clipboard.
this is the c# func
[DllImport("__Internal")]
private static extern void CopyToClipboardImpl(string text);
public void OnCopyAddress()
{
var textToCopy = DojoEntitiesStorage.currentAccount.Address.Hex();
#if UNITY_WEBGL && !UNITY_EDITOR
CopyToClipboardImpl(textToCopy);
#else
GUIUtility.systemCopyBuffer = textToCopy;
#endif
Debug.Log($"Copied: {textToCopy}");
}
this is the js end
CopyToClipboardImpl: function(textPointer) {
var text = UTF8ToString(textPointer);
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
},
i am guessing it has something to do with permissions but i am not too sure.
Edit: so it turns out it actually works fine, but to make it work i would first have to click on a textfield input, exit such textfield input and then the copy code works fine... still this is not really the meant behaviour
I am still having issues with my WebGL going to 90% when I try to play
I was told by classmate that they are able to play my game, but its nor loading on my end
Hi, I have a WebGL build, and I want to detect if a user opens the other Tab through the script, Is it possible to do?
You can check if they lost focus? You won't know for sure if its another tab though. If it is from your own page that you want to monitor, you can do it web side, and then feed it to Unity:
https://stackoverflow.com/questions/54040065/how-to-detect-new-tab-is-opened-from-current-page
@charred briar I have already implemented the Lost Focus but it is also called when the other dialog appears or just leaves the app in the background. No, the other tab may be anything like the new tab or other they are not from my page.
I don't think you'll be able to do that unfortunately (privacy concerns), I would expect that to be prevented at the browser level
@charred briar yes, I think the same way. thanks for answering!
I'm running into an odd issue and wanted to see if anyone else has experienced this:
Running a WebGL build on a specific device (Galaxy Tab A) in the past worked without issue.
Now however it just shows a black screen. If I enable the splash screen, it works fine.
If I press the full screen button it will show a black screen.
This build works fine on other android devices in the browser.
This has been tested with Unity 6, 2023, 2022 on an empty project.
This also only happens when building with URP, built-in works fine.
Do you have any post processing or anything of that nature happening? Could be not enough memory, or vulcan incompatbility.
Sounds a little like this:
https://forum.unity.com/threads/webgl-black-screen-on-mobile.1537309/
Hey, thanks for the response, it definitely does seem related to the issue I am having.
In my test project, I do have all post processing and other rendering features turned off.
I took a look at the link and tried setting the texture compression to ASTC, however it did not seem to make a difference 😦
Ok, this is odd, I set it to gamma color space and it worked 🤔
I know linear lighting doesn't work on all platforms so that makes sense
does anyone know how to fix ERROR:root:emcc: cannot find binaryen js libraries (tried: ('/usr/bin', '/usr/share/binaryen'))?
Unity 2019.4.40f1, arch linux-lts
solved: copied unity's version of binaryen entirely into /usr/bin
I have the binaryen package installed
well I got past that.. but what the heck does this mean?
It seems to be happening when gzipped file contents are expanded in the virtual fs
It seems to happen when it tries to load music_assets_.bundle, which is 455mb, and probably above what the virtual "memoryFS" can handle
firefox has a completely different issue, where it will just OOM instead :c
about:performance says it is using ~5gb when oom happens, which seems insane because the entire game is 1.4gb
Ah yes, Exception: Files.
I integrated a WebGL game in a mobile app through a webview. The issue is that on some devices the unity part boots up but I get a black screen on the first seconds before going back to normal. Has somebody any idea why this could happen?
guys, can webgl work on all mobile devices by registering touches as inputs?
For example, Lets say we have virtual joystick on screen for movement that would be used on android and IOS devices in general, but could webgl do it the same if it is run on mobile? 👀
So webGL and await async is not working?
async and await does work. Tasks and threading does not. I strongly suggest using UniTask plugin if you want to use tasks and etc. Have in mind it will not be multithreaded, it will just fake it, but at least code transition is easy.
If you use new input system then there is no big problems regarding to controlls. Tho there are some problematic things with multitouch. But having virtual joystic is not a problem at all.
thank you, the thing is async await is in the Unity Multiplay and server hosting docs so I don't wanna mess around with plugins that much, I would rather just use coroutines, but it seems this standard async await works, Tasks like delay dont work so it aint a problem
btw if someone knows how to update old code so that I dont get "runtime.dynCall is not a function" errors when I am using webassembly 2023 option in unity?
oh that..... well that is most likely because you using some plugins. You will need to update them and hope developer updated it for new Unity Versions. It depends on plugin you are using there.
"Runtime.dynCall" -> "dynCall"
in others plugins different changes needs to be done
yes I am using Solana SDK from magicblock, thanks for info
Hello everyone,
I recently found a bug in my application related to the screenshot capture system. Has anyone else encountered this issue before?
My app is developed with WebGL and the WebGPU option enabled in Unity(2023.3.0a14)
Here is my method:
`IEnumerator TakeScreenShot()
{
if (!VirtualVisitManager.Instance.player.activeSelf)
{
UIManager.Instance.HUDState(false);
}
yield return new WaitForEndOfFrame();
// Log to ensure we are capturing at the right time
Debug.Log("Attempting to capture screenshot...");
Texture2D tex = ScreenCapture.CaptureScreenshotAsTexture();
if (tex == null)
{
Debug.LogError("Failed to capture screenshot texture.");
}
else
{
byte[] bytes = tex.EncodeToPNG();
string stringifiedPNG = Convert.ToBase64String(bytes);
this.Emit("screenShot", stringifiedPNG);
Destroy(tex);
}
if (!VirtualVisitManager.Instance.player.activeSelf)
{
UIManager.Instance.HUDState(true);
}
}`
Here is the error i have :
I havn't found a lot of topic about that on web maybe it happened to one of you ?
Maybe WebGPU do not support WaitForEndOfFrame anymore ?
@cold frost um why did i get banned i was at shopping and i just got home like 10 min ago and my brother was at home but sometime i let him play roblox on my pc.. did he got on my discord? but i saw on your DM so that wasn't me and i did told him not to get on my pc.. so can i get a chance to be unbanned or ban appeal?
but i wish it has a warning instead ban
Are you sure you even have the right discord group?
well im talking to uv of his discord name Learn unity
i dont think uv can see my message because he blocked me
Trying Unity 6 preview, is WebGPU not yet available?
Navigate to an existing Unity project and open the ProjectSettings.asset file (located at <project folder>/ProjectSettings/ProjectSettings.asset) using a text editor.
Search for a setting titled “webGLEnableWebGPU”:
If found, change the line to “webGLEnableWebGPU: 1”.
If not found, add a line “webGLEnableWebGPU: 1”. (This line can be added anywhere in the file, preferably next to other web-related settings.
Open the project in the Unity Editor, using the latest 2023.3 release.
WebGPU should now be available in Graphics APIs. WebGPU support is experimental.
These imports worked in Unity 2019 but no longer work in 2022 which i had to upgrade to:
[DllImport("__Internal")]
private static extern void ShowMessage(string str);
[DllImport("__Internal")]
private static extern void ProgramStart();
[DllImport("__Internal")]
private static extern void ProgramEnd();
[DllImport("__Internal")]
private static extern string GetWCFURL();
[DllImport("__Internal")]
private static extern string GetUploadURL();
Unfortunately i cannot provide any more context or in information than that as it's a project i'm jumping on and there's no individual or documentation to consult.
Does any of that look even vageuly familiar to anyone?
This is in a script called JSBridge for some kinda javascript stuff apparently
So thier referencing some internal functions in unity which i have no idea how to check to see what has changed or been removed between versions
Narrowed it down tom these two:
[DllImport("__Internal")]
private static extern string GetWCFURL();
[DllImport("__Internal")]
private static extern string GetUploadURL();
ShowMessage, ProgramStart and ProgramEnd work
Well there isn't anything we can help with this kind of information. At least error message would help. As it can be anything there inside. it could be Runtime.dyncall problem, which were changed in new unity versions. It could be some kind of depreciated code and using Pointer_stringify instead UTF8ToString (tho this still should work). Or it could be any changes with Emscripten version changes. The most generic solution, if this is third party plugins, check maybe update for them already exists.
Thanks so much for the feedback @astral wave, i can provide a bit more feedback now after debugging last night and it looks like all those extern calls are referencing a .jslib file in the project and this is what the contents of that file looks like:
mergeInto(LibraryManager.library, {
ShowMessage: function(message){
window.alert(Pointer_stringify(message));
},
ProgramStart: function(){
sessionStorage.setItem("UnityState","Started");
},
ProgramEnd: function(){
sessionStorage.setItem("UnityState","Finished");
},
GetWCFURL: function() {
var returnStr = sessionStorage.getItem("WCFURL");
if (!returnStr) {
console.error("GetWCFURL: No WCFURL found in sessionStorage.");
returnStr = ""; // Handle the case where returnStr is null
}
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
},
GetUploadURL: function() {
var returnStr = sessionStorage.getItem("UploadURL");
if (!returnStr) {
console.error("GetUploadURL: No UploadURL found in sessionStorage.");
returnStr = ""; // Handle the case where returnStr is null
}
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
},
});
So the GetWCFURL and GetUploadURL functions there at the bottom return values in Unity 2019, but null in Unity 2022
I've made a script to enstablish a websocket connection with a remote service, it works perfectly on editor but on webgl it crashes.
Any idea on why and how to fix it?
Is this true?
"WebSocket-sharp does not export (in a working condition) to WebGL.
You need a JS library to integrate the browser WebSocket API for Unity."
WebGL does not support c# or other languages for websockets or networking. You are stuck with JS solutions. well technicly you can use c++ somehow, but in general JS is only way
I solved by switching Websocket-sharp with NativeWebSocket
NativeWebSocket is definitely the best way to do it. Still uses unmanaged JS under the hood, but it's not too bad
Why is there no exact implementation of OnApplicationQuit in 2024 ._.? Even the Unity documentation itself didnt mention about how to integrate OnApplicationQuit, why am i supposed to use SendMessage which is really similiar to 90's web solution
When would you send OnApplicationQuit?
I would like to be able to implement that method for every MonoBehaviour instead of restricting the event by SendMessage(object, method, arg). I understand there are workarounds for integrating OnApplicationQuit() and i believe it is the simplest solution but i suppose it should have been a part of Unity already somehow and just yelled... Therefore, the same issue goes to OnApplicationFocus/OnApplicationPause because of every web browser's different systems even some share the same base 'Chromium'
Not sure if there is a real workaround. Seems like platforms aren't keen on apps doing bunch of stuff when user wants to close them.
What are you trying to do?
I was going to use these methods for cleanup of a MonoBehaviour(dependency chain). But now, i will be going to create a singleton(depends on platform i build) that holds the IsPaused, IsGoingToQuit, IsQuitting and IsFocused.
Personally, i hate singletons they are hard to manage sometimes if it didnt planned correctly...
I am uploading my game on Unity Play, but the screen stops here. It shows no errors and does not proceed further. If anyone knows why this happens, Please help me.
Did you check your browser's console for potential hints?
Hi All
I'm trying to get webGL working
I am very close, my game runs, only issue is my buildings dont load 😦
I think its a texture format issue, I see GL_INVALID_OPERATION: Mismatch between texture format and sampler type errors in the console
I am manually creating some textures in the editor as TextureFormat.RGBA32 I'm trying other formats but no idea what to use
These files are put into a addressable bundle... maybe thats an issue too?
This is what im seeing on WebGL with RGBA32 and RGB24
The blocks seem to be receiving shadows but no color is loaded 😦
Turns out it's the shaders
I have a dual project addressable setup and for some reason only in webgl the shaders built in my content project don't work
I've copied them into my main project and replace the loaded ones and it seems better
Hi there people. I'm trying to do a test WebGPU build from the new unity 6. When I hit build and play it works, however I triend to set up nginx so that other people on the local network can test and there I get the following error
at ShaderLab::Pass::ApplyPass(unsigned int, ShaderPropertySheet const*, DynamicBranchState*, ShaderPassContext&, keywords::LocalKeywordState const&, Shader const*, int, int, ShaderLab::GrabPasses const*, ShaderLab::SubPrograms*, DeviceRenderStateBlock const*, ShaderLab::Pass const*, ShaderLab::Pass const*) (http://192.168.0.55/test/Build/web.wasm)
at ApplyMaterialPass(SharedMaterialData const&, ShaderPassContext&, Shader const*, ShaderLab::Pass*, int, int, ShaderLab::GrabPasses const*, ShaderLab::SubPrograms*, DeviceRenderStateBlock const*, ShaderLab::Pass const*, ShaderLab::Pass const*) (http://192.168.0.55/test/Build/web.wasm)
at Material::SetPassSlowWithShader(Shader*, int, ShaderPassContext&, int) (http://192.168.0.55/test/Build/web.wasm)
at Material::SetPassSlow(int, ShaderPassContext&, int) (http://192.168.0.55/test/Build/web.wasm)
at DrawQuad(RectT<float> const&, float, Texture*, ColorRGBAf const&, RectT<float> const&) (http://192.168.0.55/test/Build/web.wasm)
at DrawSplashScreen(bool) (http://192.168.0.55/test/Build/web.wasm)
at MainLoop() (http://192.168.0.55/test/Build/web.wasm)
at dynCall_v (web.wasm:0x36d187f)
at web.framework.js:897:22
at web.framework.js:1835:24
at _JS_CallAsLongAsNoExceptionsSeen (web.framework.js:1835:39)
at UpdateUnityFrame() (http://192.168.0.55/test/Build/web.wasm)
at dynCall_v (web.wasm:0x36d187f)
at web.framework.js:897:22
at browserIterationFunc (web.framework.js:6146:51)
at callUserCallback (web.framework.js:5423:9)
at Object.runIter (web.framework.js:5479:11)
at Browser_mainLoop_runner (web.framework.js:6117:26)```
obviously since the build and run option works something is wrong with my nginx conf but I did copy the conf from the documentation.
did you config nxginx .wasm or what ever is needed for webgpu correctly? And do you have enable fallback feature enabled on build settings? It could be that it does not have correct config on ngxing and then tries to load fallback build, which does not work unless it is webgpu
Does anyone know if you can run async/await/tasks methods in a webgl build?
you can use async and await (with some limitaions). Tasks are impossible in webgl. If you want to use tasks, use UniTask (https://github.com/Cysharp/UniTask). In short, webgl does not have multithreading and everything will work on main thread. I wont go too more details.
Ok thanks for answering,I think I can avoid tasks and do everything in async/await so I should be ok
hey. i hosted a unity webgl server with python -m http.server and it runs fine on all platforms except for iOS. any idea how I can fix it?
the error invisible, the page simply goes to unknown error screen after the initial loading is finished (assets are downloaded)
Welcome to iOS. The land of wonders and secrets. What you need to do is to check errors on console. You can do that by opening separate tab "chrome://inspect" (if used chrome, different browsers have different ways to do it) then turning on logs tracking. Then open your app in another tab and check what the logs says. Or you will need to connect device to your Mac device and get logs from there. As no error can mean anything.
HOWEVER, depending on your device, the most common problem is memory usage. As unity webgl have very strict memory usage on iOS devices, especially a bit older. If you application uses more than 300-350 mb RAM, it is totally possible that it will just crash on iOS devices because you run out of that memory limit. Yes, it does not matter how much memory your device have, it just hidden limitations that you need to follow. (surprisingly PlayCanvas don't have that strict limitations, so IDK from where it comes, but they just there). In this case you would want to connect Unity profiler to your project to see memory usage and more precise logs for that. Also have in mind, that memory usage on iOS can be up to 4 times bigger than other devices, depending on what textures compression you are using (https://docs.unity3d.com/Manual/class-TextureImporterOverride.html more about it here).
Or it could be easily some kind of rendering feature that iOS just dont support. But that is way harder to find, and connecting your profiler is only way to find it I think. Or make multiple builds, like with only one scene or etc, to make is as small a possible and keep adding features and quality settings until you find the culprit,
In general i dont really believe that is problem with your web server if other devices are running fine on it.
Thank you for your thorough information! The game did start throwing error after I added a new set of UIs, so the memory limitation issue seems most likely. I also remember seeing some alloc in an error message once or twice (sometimes it shows a web assembly error before crashing). I tried narrowing down the issue by using various git tools, but I totally disregarded the new UI elements since I thought it unlikely that a series of textures would cause an unknown error crash, but that's probably the error.
Thanks again!
hey sorry for the ping but i was messing around looking through stuff and saw in the ProjectSettings.asset theres a webGLThreadsSupport that can be set to 1, wanted to ask if this is worth messing with?
also i forgot to mention that all my async operations are not in game, its doing stuff in the lobby like fetching lobbies, joining a room, etc, and i did test it as a Task in a browser and it seemed to execute fine, dont know if its because its just doing such little or what tho
Afaik webGLThreadsSupport only affects engine threads, so native and (I believe) Job threads. My understanding is that C# threading support is not offered at all until they have a way to gracefully fallback to no threading support.
Tasks might work until some API invokes something relying on threads (it's not always obvious), in which case it might just silently fail. I would use UniTask or other equivalent solution to use Tasks safely.
ok i can try out UniTask, is it like a well known thing and trusted to work?
Cysharp has a long history of creating some pretty amazing stuff. UniTask has been around for a while and relied on by many.
From what I understood that webGLThreadsSupport enables threading only for C/C++ code and also browser needs to support that. Multithreading C# code is not yet available. (https://docs.unity3d.com/ScriptReference/PlayerSettings.WebGL-threadsSupport.html)
I used UniTask on webgl project, it is really well made. Maybe you wont win performance, but it is way more convenient to use. Also it have similar grammar as unity tasks, so it would be easy to transfer if WebGL EVER would start supporting C# threading. So no downsides pretty much.
Thanks for the insight :) I’ll give it a try
that was really easy to implement, thanks for all the help guys @astral wave @sweet oriole
When i run my unity project in web i got this error ```UnityLoader.js:1
Failed to load resource: the server responded with a status of 404 (Not Found)```
- make sure your server setuped correctly. support wasm, brotli, giz depending on your build. (follow unity documentation how to do it)
- Make sure the files have correct names. When you build webgl and change build folder, names changes accordingly. so if you keep old index.html or UnityLoader.js it will fail to find assets or load old ones if you have them
@astral wave Hi, I have successfully uploaded my Webgl to the server, I transferred my Unity WebGL build from Unity 2019 to 2022, and when I uploaded it to the server this new version of the build took of time to load, previously On Unity 2019 it loaded so fast. here are my Webgl settings.
and also get this warning when start my webgl app
follow @amber ginkgo link. Most likely what happens is your server is not setup for wasm correctly. I also would recomend use compression like brotli for better loading. Just dont forget to setup server to support compression format!. Good luck!
anyone else having general audio issues with web builds on unity 6? e.g. AudioSource.time and AudioSource.timeSamples are desynced, looping audio suffers a slight silent period, and AudioSource.PlayScheduled() plays stuff immediately instead of at the scheduled time.
this is my first message here so i'm not sure this is the right spot for this stuff, please lmk if its not
Hi, I transferred my project from Unity 2019 to 2021 I built for WebGL, and in the 2019 version there is a UnityLoader.js file created inside the build folder but in 2021 there is no such file UnityLoader.js which necessary for upload my build to server, help me
here is a difference of the build folder of two unity versions
most likely what you need is Proslat.loader.js. In ne Unity it is beeing renamed depending on your build folder. So I assume you build it in Proslat folder. Or you can just update your index.html with new template for loading you project instead of using UnityLoader.js. Also why not ugrading to unity 2022 or 2023? the later the version the more webgl improvelements there is, from more memory control to... well.. there were more stuff there I am sure about it
Update to 2022 and make some changes in index file now its works fine, Thanks @astral wave
Hi, I use react-unity-webgl, and have event that will send devicePixelRatio to adjust performance, but when i update it it don't change resolution.
const [devicePixelRatio, setDevicePixelRatio] = useState(
window.devicePixelRatio
);
useEffect(() => {
addEventListener("SetDPR", (dpr: any) => {
setDevicePixelRatio(dpr);
});
return () => {
removeEventListener("SetDPR", (dpr: any) => {
setDevicePixelRatio(dpr);
});
};
}, [addEventListener, removeEventListener, setDevicePixelRatio]);
return( <Unity
id="unity-canvas"
tabIndex={1}
unityProvider={unityProvider}
className="h-full w-full outline-none"
style={{
visibility: isLoaded ? "visible" : "hidden",
}}
devicePixelRatio={devicePixelRatio}
/>)
If I use matchWebGLToCanvasSize={false} and manually set canvas width and height it works but image is shifted and buttons in game are not clickable
const canvas = canvasRef.current;
if (canvas) {
var width = window.innerWidth;
var height = window.innerHeight;
canvas.width = width * devicePixelRatio;
canvas.height = height * devicePixelRatio;
}
I'm trying to reduce my build size and I'm wondering if anyone has insights into what this Unknown stuff is?
ave you tried checking build report it self manually (aka logs file), maybe there will be more information?
Checking log files does not add any more info to this unfortuatly
dont mind the source assets. the main stuff is in the output tab
also, in the logs look for the exact words "Uncompressed usage by category (Percentages based on user generated assets only):" and check the sorted list out
will see something like this
-------------------------------------------------------------------------------
Build Report
Uncompressed usage by category (Percentages based on user generated assets only):
Textures 2.8 mb 94.2%
Meshes 0.0 kb 0.0%
Animations 0.0 kb 0.0%
Sounds 0.0 kb 0.0%
Shaders 6.8 kb 0.2%
Other Assets 1.3 kb 0.0%
Levels 0.0 kb 0.0%
Scripts 137.5 kb 4.5%
Included DLLs 0.0 kb 0.0%
File headers 29.3 kb 1.0%
Total User Assets 3.0 mb 100.0%
Complete build size 68.9 mb
Used Assets and files from the Resources folder, sorted by uncompressed size:
2.7 mb 3.9% Built-in Texture2D: Splash Screen Unity Logo
128.2 kb 0.2% Built-in Cubemap:
7.4 kb 0.0% Resources/unity_builtin_extra
0.4 kb 0.0% Built-in Sprite:
0.2 kb 0.0% Packages/com.unity.test-framework/UnityEngine.TestRunner/NUnitExtensions/Runner/RestoreTestContextAfterDomainReload.cs
0.2 kb 0.0% Packages/com.unity.visualscripting/Runtime/VisualScripting.Core/Listeners/UI/UnityOnScrollbarValueChangedMessageListener.cs
0.2 kb 0.0% Packages/com.unity.visualscripting/Runtime/VisualScripting.Core/Listeners/UI/UnityOnScrollRectValueChangedMessageListener.cs
0.2 kb 0.0% Packages/com.unity.visualscripting/Runtime/VisualScripting.Core/Listeners/UI/UnityOnInputFieldValueChangedMessageListener.cs
...
Anyone got recommended settings/workflow for publishing webgl builds on itch.io? Specifically confused about the resolution and what to set on itch.io, seems a bit weird.
I kind of found someone setting 960x540 in unity and on itch game page settings the size to 960x590 so the fullscreen button is visible which seems to work but is it the correct way?
hi. has anyone had experience deploying a build to apache2 server with the correct .htaccess config?
I followed the official docs and configured the following
# This configuration file should be uploaded to the server as "<Application Folder>/Build/.htaccess"
# NOTE: "mod_mime" Apache module must be enabled for this configuration to work.
<IfModule mod_mime.c>
# The following lines are required for builds without decompression fallback, compressed with gzip
#RemoveType .gz
#AddEncoding gzip .gz
#AddType application/gzip .data.gz # The correct MIME type here would be application/octet-stream, but due to Safari bug https://bugs.webkit.org/show_bug.cgi?id=247421, it's preferable to use MIME Type application/gzip instead.
#AddType application/wasm .wasm.gz
#AddType application/javascript .js.gz
#AddType application/octet-stream .symbols.json.gz
# The following lines are required for builds without decompression fallback, compressed with Brotli
#RemoveType .br
#RemoveLanguage .br
#AddEncoding br .br
#AddType application/octet-stream .data.br
#AddType application/wasm .wasm.br
#AddType application/javascript .js.br
#AddType application/octet-stream .symbols.json.br
# The following line improves loading performance for uncompressed builds
#AddType application/wasm .wasm
# Uncomment the following line to improve loading performance for gzip-compressed builds with decompression fallback
# AddEncoding gzip .unityweb
# Uncomment the following line to improve loading performance for brotli-compressed builds with decompression fallback
AddEncoding br .unityweb
</IfModule>
which compiles to just
AddEncoding br .unityweb
(as you see, i commented out everything that does not correspond to my build setup, which is brotli with fallback)
but I still get the error message
"You can reduce startup time if you configure your web server to add "Content-Encoding: br" response header when serving "Build/webgl.wasm.unityweb" file."
(I have placed the .htaccess to the /Build folder relative to index.html file
(also worth noting that apache is indeed reading those configs, because I accidentally commented a line with ; instead of # and it gave me syntax error:
[DATE] [core:alert] [pid PID:tid TID] [client PUBLIC_IP:0] /home/admin/web/DNS/public_html/Build/.htaccess: Invalid command ';', perhaps misspelled or defined by a module not included in the server configuration, referer: https://DNS/
``` *(uppercase words are censored)*)
in case relevant, here's the config code related to serving the website in the first place
...
<Directory /home/admin/web/DNS/public_html>
AllowOverride All
Options +Includes -Indexes -FollowSymLinks +SymLinksIfOwnerMatch
</Directory>
...
(uppercase wors are censored)
well I'll be damned. I re-tested several times and it finally worked 😅 maybe apache2 was using cache? (i know i deleted the website's cache on browser through edge://settings/sitesettings)
Newb question. What is your go-to method for profiling Unity heap usage in the browser. Specifically the Unity heap allocated by WASM.
I'm finding it difficult to find resources specifically to view the WASM heap and chrome doesn't seem to display WASM heap usage in the memory profiler.
https://docs.unity3d.com/Packages/com.unity.memoryprofiler@1.1/manual/index.html
I would mark autoconnect profiler when you click build and run. Then open memory profiler, it gives quite accurate data about a lot of things.
Browser will not give you exact values, as it is not JavaScript and quite closed enviroment to get data from. And different browsers handle that differently. Some even limits memory differently;
does LevelPlay/Unity Ads work for webGL builds at all? Is there any solution for in game ads in WebGL?
well i found this but it's 3 years old https://forum.unity.com/threads/recap-the-greatest-secret-never-told-monetizing-unity-webgl.1182106/
would like to hear from anyone about more recent info on WebGL monetization
Hi guys, this is a recap post: after active searching for around 3 days about unity WEBGL monetization here is what I have found:
Unity Ads: WEBGL...
WebGL builds are websites, so you can just use regular website monetization methods. Some web game portals want you to do ads through their SDK, but the ads are still most likely ads from big web ad networks like AdSense.
Having the game up on your own website with ads allows you to use the same setup across multiple web game portals (there are hundreds) through iframes. You also don't need to worry about updating builds across multiple websites or maintain multiple SDK integrations. Some of the big web game portals really want you to use their SDK since they can take a cut and control the experience. How much say you end up having depends on how much those portals want your game(s) on their site.
hey does anyone have any clue why my webgl addons arent installing? it just stays like this for hours with no sign of progression
There are !logs you can dig through, but I would just restart the process if it appears to be stalled.
I have a question, if publish a simple unity game with webGL. Can I add a c# file which help user to play only 1hr in 24hr time. I heard about concepts session or cookies to take record which device accessing service.
You can store the time the player has played to PlayerPrefs. Note that there is no system that would actually stop the player from clearing browser data and playing more apart from using user accounts, and even then you can't prevent them creating multiple accounts (other than in very restricted situations)
Does anyone have any idea why Audio is not able to playback if loaded via AssetBundles in WebGL? This has apparently been an issue in various Unity versions for sometime now. https://forum.unity.com/threads/audioclip-in-assetbundle-for-webgl.1261610/
Hello, I'm having a problem getting audioClips in an assetBundle to work for a WebGL build,
i have exported the assetBundle for WebGL and im testing...
I know that some of FOD problems were fixed in 2023. But cannot say if this is one of them. If they backported to 2022 maybe this doesnt matter, but I would still test just in case.
Are there more performance improvements for WebGL in 2023? I prefer to sticking to LTS but if there are significant performance boosts already in 2023 then hmmm may consider trying it.
I've been waiting for WebGPU to be fully ready before I moved to the next version.
I don't remember exact reason why we moved to 2023 now, it was so long ago. But some bugs and some memory managment improvements were one of the reasons why. But 2023 at that moment had some problems as well, so it is a trade off. But it was quite stable otherwise.
As I know WebGPU will certainly be a game change if they manage to add support for the new resident drawer for example.
yea...... tell that to apple that you waiting for it for web :DDD
and I doubt you will ignore all iOS and Mac users.
Ops I was confusing 2023 with Unity 6 😅
OK, if no work-arounds come up then I'll try exploring 2023 for hopeful fix of this Audio + AssetBundle issue
Hello
My build is 40MB right now but if I can split my scene and offload the audio assets into the second scene, it cuts my initial build size by 50% which is ideal for WebGL game. Although hmmm I wonder if 40MB is really that noticeable of difference to end-users these days with such fast internet speeds we have
So I need some help with unity, where do I go?
It also depends on the game and demographic/ region a lot
40 mb as for unity webgl is super nice! good job! Are you using addressables for spliting content?
aparently the global average download speed is 45Mbps / about 5MB so that would be 8s download or less if speed is higher, but yeaaa I imagine not everyone has 45+ Mbps
40MB is total size of start menu scene + game world scene together. Game world is about 500 units in size. It was originally close to 100MB before, but in Unity 2022 LTS using LTO Build compression it shaved off 60MB magically!! Totally blew my mind 😅
its not...
ideally you'd go as low as 4MB (with Project Tiny and DOTS you can go even lower I believe, but I haven't seen proof of it yet)
a lot of the things will be stripped out when you use the high stripping settings. And all assets should be asset bundles; no exceptions except for the initial loading assets if you want
a quick way to reduce tons of build size is to remove big 2D arts (any texture, not just 2DTexture) from the build and have the player download them instead. this is a pretty quick fix, as it doesn't require any change anywhere in your system except for your image displayers
*so instead of assigning Sprites manually, you'd assign some custom type, say, GenericSprite instead, which accepts some asynchronous operation in which it'll decide whether to load the asset from local database or from remote. so like
background.Sprite = myManifest.rareCardBackground)codes would be similar to something like
myManifst.rareCardBackground.GetAsync(sprite => background.Sprite = sprite);*
Yea project tiny and other super stripping projects can become small, but you strip pretty much everything even some features, and in reality it is rare project that will spend so much time doing that. So 40 mb is great, I do not take my words back. I was able to strip it to 15mb, and then load all other 150 mb little by little when needed. While doing same project in playcanvas with all the same assets total size of everything is 40 mb. where 5mb is initial load almost without any optimisations. So 40mb for unity webgl is great, and it is hard to make it lower, and it should be celebrated.
I would ideally love to go smaller than 40MB... and I can if I can fix this stupid Audio issue not loading in Asset Bundles.
I do believe initial load time of a game is critical to help ensure a low bounce rate.
Although, I'd argue that this may not be an issue if players are actually excited about the game they are going to play. So yes, they will wait an extra 10 seconds or more for it.
I say this based on what i've seen with a popular .io game built with Unity known as ZombsRoyale for example. This game is 2D and is 100MB if not more at initial load, and it's one of the most successful .io / Unity WebGL games to date. The developer earned millions $$ off this game.
So yea... I'd say that it really all depends on the game. ZombsRoyale already had a massive following due to the success of Zomb.io, so in this case it was a no brainer for players... they'll wait for that 100MB download in the browser 😄
For other games developed by unknown / new developers and pushing a large build size like this... i'd argue the marketing of said game is what will help determine if players will be willing to stick around for it to load or not.
That's for sure 👌
Yeah definitely 💯 lowering the size takes a lot of effort and in the end it might not be worth the time. Might be something to consider in later stages after the game's success.
It's not...
I made a premature judgement there, my bad! :p
If you want to get the smallest possible packages sizes for web, I'd recommend looking outside of unity entirely. It's great for cross platform though, and does an excellent job of webgl support. But it's always been a bit of a hack job.
By It's nature, web auto compresses at the server level and feeds you content as you need it. In theory you should never need to see a loading bar or directly manage compression and upload gzipped binaries.
But you trade size, control and loading for a more robust and complete engine. There are a ton of other webgl engines worth checking out though when trying to stay small. Also, last I checked project tiny was killed off paused in favour's of building out things like AI tools on a subscription
Yea I would have totally gone with Playcanvas if I wasn't already a long time Unity user. I'm just comfortable with it, and well the productivity is much higher at least for me going with Unity based on the type of games I like to make. I'm a web developer by day and love all things JS, but JS engines are still way behind Unity. So ya I prefer the complete engine, and all the resources that come with Unity in comparions to other solutions. I'm not entirely worried about keeping my build size extremely small.
Yeah that's what a lot of NFT games do too, but they're usually not complex games. Unity+AssetBundles is really fine. The initial size 3.5MB so the rest is really up to the assets you use; and unity has some really amazing asset compression features.
Complexity plays the major part in this choice. The hamster game would probably lose a lot of users if it used Unity and required webgl and a seconds long initial loading
It's not so much "if you can" compress unity down, but just doesn't compare imo. Aframe is ~268kb (and one line to load a 3D model). three.js is ~100kb (and also one line to load a 3D model) when gzipped. It may not seem like a big difference, but we it is a ~92 to 96% smaller size.
Don't get me wrong, I use Unity for the web all the time, and we do some amazing stuff with it. It's just that if package size is really cruicial, there are way better tools for most small-use applications.
If size isn't a major concern though, it's going to be hard to beat Unity for what Unity can do with the web though 🙂
And having singular code bases is a great thing, as long as you don't mind vendor lock.
I uploaded my WebGL build to the server, and it works on Firefox but on Chrome something is weird with the text there are squares instead of texts. see images with the same URL, left Firefox and right Chrome. Could you help me to resolve this issue? also works when using an incognito tab in Chrome that suggests something about cache issue.
if it orks on chrome incognito, clear your cashe, or hard reload page and check if it still works. My guess is that font asset fault (maybe corrupted or old font assets are loaded). what are you using for font? legacy or textmesh pro?
works when hard reload, but i don't understand why this build use cache when i disabled the Data caching in player settings.
@astral wave
Wwhat I can say, webgl is magical beasts. As data caching also depends on browser settings, and you not always can control it. While on development state, it is really not important to fix this, but later in production you could just change files names to have version numbers to it, that way it will always load new files ignoring cache.
You are lucky you dont need Asian fonts, then webgl becomes even more magical 😉
Also you didnt answre about which text asset you are using. Legacy wont have this problem, as it will use fallback browser fonts on problem like that. but it is way less performant and not recomended in general.
I changed the product version, in the index.html file but that is also not working properly. for text I use legacy texts
you need to change also files names as well as index.html. YOu mentioned that after hard reload it works right? how you make it not to work again? or now we just talking about caching?
I am building for a client and their users, they may not know how to hard refresh after each update on the server. I'll try to change the file names as you said.
What do you mean you changed the version in the index.html? The project version can only be changed from the Project Settings in the editor
Whenever you up the version, Edge will redownload the data without cache. I don't know about chrome but it should be the same story
you can use small version numbers for each build, like if you're on
0.1, you can add a sub for the build number like0.1.b3, indicating it's the 3rd build
i am going to learn webgl multiplyer
any suggestions please let me know
i saw in YT there are many way to do this , which one is preferable ??
Most of the multiplayer frameworks you would use for other platforms also work on web with a WebSocket transport. Photon's offerings seem pretty good.
Yeah, using Photon Fusion on a webgl game, the library works like a charm and the community is responsive
Yeah essentially (disclaimer: my opinion is shared a lot but do your own research for sure):
- Photon is kind of the gold standard, but their licensing isn't great (especially once you move away from games).
- Normcore is second place for me but you have to do a lot to share sldata (like create 3 or 4 files just to share a score value) and lacks a lobby and relay.
- Mirror is pretty good (and in my opinion, underrated and easiest to sync values), but you'll need to setup a relay. At least it supports a self hosted one. Each relay is a bit different though, so it's not simple to do match making sometimes.
- Fishnet is supposed to replace mirror but... doesn't... as it is only compatible with commercial third party relays, all of which require you creating a developer account (epic, steam) or paying a service. It also takes a lot of work to just share a score between users. It relies heavily on free EOS, so if epic ever adds a dollar value to their relay, it's going to hit them hard.
- There is the Unity service. But I don't know what it supports, their pricing model is all over, documentations pretty bad (but improving...), and then you are vendor locked to them. I love the engine, but not the company, and dont trust them with account management. Being baked in though it's slowly pushing the others out.
- I'm currently using Nakama (self hosted, free and open source) for a large number of projects (Unity, godot, webgl and unreal) and quite happy with it. It includes a relay, user accounts, leaderboards etc. But you'll need to write a fair amount of code yourself. I have some tutorials coming 🙂
- Dark Rift 2 is another open source one (not really maintained anymore), relay built in iirc - but convoluted process for variable sharing
- Edgegap (relay only) is worth mentioning, trying hard, and priced more fairly than most. Documentation is very sparse.
- Colyseus is another self hosted open source option. But it's documentation is almost non existent and is from web devs trying to make unity multiplayer. They seem to have treated data sync as an after thought.
- Forge Networking, no longer update, authoritative. But a lot of potential. Self hosted and open source.
- netick, makes some large speed promoses, but hasn't gained commercial interest. Requires authoritative. Doesnt support relays.
You may also find this valuable
https://github.com/StinkySteak/unity-network-library-benchmark-on-bad-network-condition?tab=readme-ov-file
It should also be mentioned photon & normcore have voice built in. And some have different network transports for web vs desktop and mobile.
Not that relays are only needed for non authoritative servers. Some like nakama also do chat, user accounts, leaderboards etc. Some do voice. Some support webgl. Some are open source... your milage may vary
I have created an open-world third-person game, but I am facing issues with deploying it as a web-based application through WebGL. I tried to deploy the project in an AWS S3 bucket, but the output is not good, and the file is almost 1 GB. I need your assistance with this.
Wow this should be pinned! Thanks a lot! I wasn't even looking for new solutions but Nakama seems the ideal I had given up looking for!
Nice Review! @amber ginkgo agreed this should be pinned 📌
Mirror + Edgegap user here, i'm pretty happy with my setup. Although I do agree getting setup with Edgegap was not the easiest. As you need Docker running on your PC and have to do a bunch of steps, but I've managed to create a batch script to help automate the deployment process. Edgegap does have a Unity Plugin that supposedly makes deployment easier now. I don't use it as I have a particular deployment process that won't work with their plugin.
I do have mirror running with the lightweight mirror relay at the moment, I've been benchmarking it this week. I was tempted for edgegap relay support because it is quite affordable. It's an interesting combo, I need to figure out matchmaking with it still.
My main reason for nakama is we rely on its user accounts, chat and leaderboards already, so getting the multiplayer going has been a high priority for me
ah nice! I heard of Nakama but I never knew they offered all those BaaS features. I tried LootLocker, and had a horrible onboarding experience so I ditched it and rolled my own Login System & Leaderboard System with Firebase + Firebase Auth. For LobbyServer (match making) I also rolled my own using Websockets and Node.
I have to go down that path too for our non-game side 😄 it's going to be fun hah
You'll get a whole lot more control creatingnit yourself too though
Yea, it has certainly made development progress slooower having to build all this out, but now that it's all done I feel better about it. As if something breaks I don't have to wonder if it's one of the third-party services and when they'll resolve the issue. Depending on third-party services for certain things have been a nightmare for me. At least with all of these systems. Edgegap I don't mind becaus it's pretty agnostic, meaning i'm not really locked in as all it's doing is spinning up docker images of our server. So that can be replaced pretty easily compared to having codebase tighly coupled with a third-party login system, lobby, etc...
I guess my login system is kinda coupled with Firebase lol... but ahhh we can swap that with SQL if worse case if they ever go down. But it's a Google Service so I don't think they are going anywhere anytime soon.
Supposesly SupaBase is a good open-source replacement for Firebase.
Yeah database switching and relay switching seems like a reasonable risk and work
**[ HELP ] **
So i'm currently having an interesting issue where after my player logins in and we pull PlayerPreferences from database passing that to Unity Instance from the front-end using unityInstance.SendMessage it works OK, but ONLY if I reload the page 😅 !!
So what I tried to do in Unity is call PlayerPreferences.LoadPlayerPrefs(); in Awake or Start and set the Script Execution Order to the #1 on the list. But that is still not working...
Note in the console we can see the player preferences have loaded when I logged in... but it doesn't display the changes in the scene. Only if refresh the page will it load on the second run. PlayerPreferences.LoadPlayerPrefs(); is a custom function that is communicating with the front-end which has the player's state. Front-end responds with callback sending the state back to Unity Instance.
nvm fixed!!! It seems there was a race condition between LoadPlayerPrefs and when my Character Customizer fetching the prefs 😅
The UI caught my eyes, it's so nicely web-looking!
Thx!! I'm using Nuxt UI https://ui.nuxt.com/
eventually i'd like to replace all of the in-game UI with this.
for now it's a blend of Unity UI and the above
that is a nice UI, does the UI look good on mobile too? I find my Unity UI just get's ruined when run on mobile browsers
i guess i just need 2 different UI's one for mobile and one for desktop, but I wonder if Nuxt manages stuff like that better
Yes, I would say something like Nuxt UI will work better on Mobile. Most Front-End web frameworks these days are mobile-first solutions, so they support mobile out the box. My game currently doesn't run in mobile browser, it just crashes due to memory limitations i'm pretty sure.
I believe Unity's UI Toolkit is suppose to be based on standard web technologies so that may improve things. Although in the documentation it states there are some limitations when compared to current Unity UI. A big one for example is no support for World-space (3D) rendering.
So guess that means no name tags or health bars over the head of your players and NPCs.
ah cool, good to know that
i think u can more or less convert world space to screen space, but it will always be on top
Hello everyone!
Word space logic is currently in progress, so it will appear sooner or later https://unity.com/ja/roadmap/unity-platform/ui. I personally liked UI toolkit as it makes it simple to create good looking UI. Bit harder to connect Code With UI, but still quite nice feature. I totally agree with you about everyting tho :D.
It's harder to connect code to the UI with Toolkit really? Like in comparison to Unity UI where they allow you to hook into a method easily through their drag & drop editor interface? Can you at least do that in Toolkit?
When talking about Photon does everyone use Fusion these days or is PUN2 still fine for a new projected if it worked on your previous ones (but you are starting from scratch)? Historically I've always used PUN because it just works, and whilst extra replication control sounds great, stability is king. But maybe Fusion is now rock solid and their primary API?
Yeah the downside is PUN2 is now deprecated. That said, I've found Fusion to more or less be the exact same
The plus side imo, is because all they've done is multiplayer engines for the last 15 years, is it is very well documented, battle tested, and reliable as can be.
@charred briari looked into a lot of those before starting and your information seems incorrect. maybe your data is outdated? according to this chart several of the frameworks you mentioned arent even updated anymore.https://docs.google.com/spreadsheets/d/1Bj5uLdnxZYlJykBg3Qd9BNOtvE8sp1ZQ4EgX1sI0RFA/edit?gid=127892449#gid=127892449
not to mention every single networking library in your list requires a relay or dedicated server. photon, normcore, mirror, fishnet, forge, literally all of them require you to run a relay or dedicated server. how else do you get your game online?
I should preface this by saying it's not really a chart, more just a few bullet points to help people get started. Photon has its own relay (they even sell it as a service), Nakama (and netick, forge & dark rift too I believe) all have it built in with their self-hosted authoritative - although Nakama is probably the most flushed out in that regard. Mirror, Normcore and Fishnet do not have a relay built in (although Mirror at least supports a self-hosted relay option - and all three could be used as a relay with an authoritative configuration). Fishnet specifically relies on EOS a lot, which I'm also not a fan of. That said, I think people should do their own research on them and use that only as a starting point. As for what is updated, I believe I pointed out which ones aren't being updated, but feel free to share a list if you like (I'm not an authority on any of this, and do not want to be). Good catch on normcore - you are right, it has no relay, I've updated it.
I should add that I like to go against the grain on this and strongly recommend self hosting a dedicated server over a cloud service (especially early on). We've run thousands of CCU's across dozens of games on our servers, and the cost is around 35/month. There isn't anything wrong with using cloud services. I think most interesting to people is which service include voice, relay, cost and self hosted. But again, it's all just personal preference.
Personally I don't like to give my data and money and control over my databases, user accounts and multiplayer to third-party companies. And some companies (like Unity) have even accidentally disabled our company accounts before because an employee hit the wrong checkbox on our account after checking our compliance - it took them 10 days before they even tried to correct it (fortunately, other people at Unity stepped in and fixed us much much sooner). I can't imagine what would have happened if we were using their ad systems, user account system and networking when that happened. But that's another story 😄
Anyway, all of that to say, I strongly recommend posting a list of your own and digging into more specifics.
I am hoping to get some time over the next month to post walk-throughs for a few of them, the how-to of setting up a self hosted server, setting up a relay, and getting going with it. Probably the most interesting one for people will be the nakama, and I'll post my server scripts and sample projects - so it'll be really easy to kick off a VR project and own all your user data on your own systems. At least, that's the one I'd be most interested in, as it comes with leaderboards, chat, user accounts, commerce options, and authoritative. Right now, there aren't many options that can block a user from joining based on a user account (maybe UGS). Photon and Normcore for example people tend to use Playfab for user authorization. But regardless of the user being authorized or not, the servers are separate, so someone could force the connection anyway (and inject an unfavourable username). But that's another long story I suppose.
pretty sure none of those rely on eos and can all be client authoritative or server authoritative. im a big fan of independence which is why i dont use photon but i understand their all in one alure. its risky imo to put all your eggs in one basket
you can authorize prior to access im pretty sure on any of the frameworks you listed too
the main difference is yes photon has all that built in but at a price
Oh yeah, and I totally agree that they don't, I just mean that Fishnet (the team) specifically strongly recommends EOS for being free and cross platform. But isn't really taking into consideration the effort of creating an epic account, and that epic could inject a monetization blocker tomorrow if they wanted.
My issue with Photon isn't the game pricing, but we have a lot of non-game clients. Which makes Unity want to charge me 5K/year/license for industry, and Photon wants 500/m/developer or something crazy for industry. So I'd rather avoid both in our non-game stuff.
oh maybe they have a preference towards eos then? im certain its not dependent on eos at all. my goal was to use steam but i was on the fence between dedicated servers or their relays
Oh yeah, it has two very solid relays for Steam. I can't remember but there is a platform it doesn't support that we use so I didn't add that one
With us being VR focused, Android and PlayStations important for us
Which only leaves us with EOS or a custom relay if we were to use fish-net.
I suppose this is more of a #archived-networking discussion though I suppose 😄
i do not know anything about normcore netick and a couple others you listed but the ones i do know of the tldr is to use photon if you want an all in one but be ready to commit to their eco system, or mix and match third party services with others. commiting to fusion means increased costs if your game is successful. doing it yourself means cheaper costs and experience but also more time. i suppose if someone were a very beginner id tell them to use photon so they do not stumble over other steps.
yeah you are right!
I havent touched it for a while, but it was quite tedious, no such thing as drag an drop. You needed to use queries to find element by name and assign that way. Linking data also was kinda ... meh... I know they were working on it, especially on linking data, so idk how it is now.
Positive aspect of this kind of workflow, is that UI is totally separated from code, decoupled you could say. So it is better work flow in a long run, where changing one thing wont break everything 😉
ah OK, thanks for the heads up... I'll keep any eye on it for the future! 😃
Hi, Netick creator here. Just wanted to make a few comments.
Netick does not make any "big claims". I believe we discussed this before and came to an agreement. Both benchmarks you linked prove the "claims" you are talking about. It's the highest performing solution, in addition to the only free solution that handles bad network conditions (proven by the benchmark you linked), out of all these (included in the benchmark) options you mentioned. We are proud of that and we love to advertise this fact.
Also, server-authoritative games are the way to go now, making games that get filled with cheaters day one is a guaranteed suicide. Netick makes it as easy as client-authoritative. Free anti-cheat for all games.
Also, your analysis is subjective. Not everyone looks at solutions in terms of what relays they -currently- support. That's just one way to look at them for one specific use case. Most people are doing dedicated server games anyway where relays are completely irrelevant. And in the end making an integration with a specific service is not the hardest task ever, in fact it's relatively simple, at least with Netick.
Based on your reply, I'm thinking you maybe misunderstand what I wrote, as that's pretty much what I shared.
I've derailed #🌐┃web it would seem, but it's always good to get a creator to share on their passion project.
It would be nice if Unity recognized the need to have a real server-authoritative net solution that isn't a bundled solution. NGO is great, but trying to hamstring it into a server auth solution is painful
Hello folks ! Maybe some of you guys know more about how can I handle the microphone and sounds when switching tabs?
I have the wishes that I can still listening to my other friends when playing on a match when my focus tab is on other one that is not the actual game
you will need to use javascript solution for audio chat then. For example Agora audio chat works on different tabs both listening and capture of mic (regardless of active tab).
I am not sure if that is possible with native WebGL of unity tho, sorry.
Thanks for that ! Will take a look at it 😄
Just wanted to check I dont see the Unity 2022.3.2f1 generating .unityweb file anymore even if the Compression Format is set to Gzip and Decompression Fallback is set. Any idea how to generate this file?
Don't set it to gzip. If you do that it'll zip the .Unityweb file and run a script to manually uncompres it at runtime
It's (in my personal opinion) bad practices for unity to be zipping or generating gzip files anyway. If it's supported on your server, it should do it on demand. Making you do it manually is backwards. But if you want more information on the process and the way it should work and ways to handle it, this is a great guide:
If you ever exported and tried to publish a WebGL game made with Unity, you were probably bombarded with really confusing settings and some esoteric configurations in your server. Let’s explore how stuff really should be done
It's bad practices for unity to be zipping or generating gzip files anyway.
This guide also suggests precompressing large files, which makes sense. Benefit of this guide is the ability to support multiple compression formats without a slower (and larger) JS fallback.
Thanks for the response.
is there any way that someone playing webgl unity game and and this game can be stream to other website ??
Fmetp would probably do it. Can also try manually here
https://getstream.io/resources/projects/webrtc/platforms/unity-streaming/
@umbral oracle Don't post off-topic on the server and don't spam that drama here.
can you atleast get rid of the shady af guy with his prolly stolen networking solution ?
!warn 755084025416253440 Stop posting off-topic here. Don't spam the channel.
elry.moe has been warned.
Hi, sorry but just wanted to report this person/account. This person spammed my server and another server with the same messages, my Reddit posts and even our GitHub repo.
Edited: Important to mention this person is affiliated with the scandalous FishNet developer.
They were warned here. Report them on appropriate platforms.
Hello, just wondering if anyone can help me understand webgl builds a bit better - Mostly interested how small can you make a webgl build, what are the common sizes and how to verify that (is the build size same as the resulting build folder on disk)? I tested building an empty 2D URP project and it seems to give me build that is around 8mb in size.
the base webgl build is 17mb
as of unity 2022
without compression set up
thats probably as small as you can get it
https://github.com/JohannesDeml/UnityWebGL-LoadingTest
You most likely shouldn't be shipping without compression.
I was actually just browsing through this one
so if I read this right, you can get it around 6mb with URP as a starting point?
..or actually more like 7mb
Correct. 2D template is probably adding slightly. You can reduce the build size a bit by removing unused packages (even from the minimal builds on that github page).
That github page is measuring "default" configurations with various settings, so you technically can go slightly lower.
Your build will still end up being many MBs either way.
Browser native engines (PlayCanvas, Cocos Creator) and frameworks can do a lot better, but few extra MBs can be relatively reasonable for what you get and the benefits when shipping on other platforms.
What is considered a large webgl build size?
Depends a bit on the devices/platforms (instant games) you are targeting. Looking at bounce rates for website download sizes and download time calculators at various speeds can give some indication.
Make sure to evaluate on demand downloading (at least for the initial screen) like Addressables if this is something you are focusing on.
still keeping things relatively simple so I doubt I need addressables yet 😅
but this has been helpful so far so thank you!
if you will have more than one scene, you will need addressables for sure for webgl. As without it, you download and load everything at the start, which will be undesirable in most cases (especially if you want it work on mobile web as well).
does webgl load all the scenes in memory on webgl?
ah nvm, read your comment again and now understand your point 😅
hello im trying to get a token-exchange from the api of unity bit every time it send an error 400
$credentials = base64_encode("$keyId:$secretKey");
$url = 'https://services.api.unity.com/auth/v1/token-exchange';
$data = [
'scopes' => ['live_ops.leaderboards.scores.get', 'live_ops.leaderboards.scores.list']
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Basic $credentials",
'projectId' => '',
'environmentId' => 'd',
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
// Specify the path to the CA certificate bundle
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/cacert-2024-07-02.pem');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo json_encode(['error' => curl_error($ch)]);
} elseif ($status >= 400) {
echo json_encode(['error' => "Server returned HTTP status $status"]);
} else {
$decodedResponse = json_decode($response, true);
if (json_last_error() === JSON_ERROR_NONE) {
echo $response; // It's valid JSON.
} else {
echo json_encode(['error' => 'Invalid JSON response from server']);
}
}
curl_close($ch);```
this is my code (i removed my project id and environementid to show it but they are set)
No details with the error?
Do you get the error in a simple curl? (400 means your request syntax is invalid)
Had a question regarding intuitiveness of devops in webgl.
Do you guys find addressables easier to use in a webgl project that needs ~weekly devops? Or do you find AssetBundles better for the web? (Given addressables' RAM peak when loading as well as the inability to load from bytes)
the real question is... is scarf on the character is cloth physics or just animations?
Yeaa it's animations... using this awesome asset that simulates physics: https://assetstore.unity.com/packages/tools/animation/fleximotion-243310
does photon pun 2 work in webgl ??
cause mine not working , did i need quantum 3 for that ??
Yep it does!!! I'm sure the documentation has some examples of how to configure it... or maybe try asking in the Photon Discord?
yup got to know that they both connect to different region
thats why i think its not working
Thanks for this mate
does anyone know how to embed an unity game onto an html page
Building with the minimal HTML template in Unity and looking at the HTML output is probably the most straightforward way to start
do I have to have a functioning website before I can embed one or any is fine
The output files are valid to host as is.
what is a good database solution for non-local storage? I was about to use Firebase real-time database but then learned that it isn't really compatible with WebGL (there is an old unity package someone made with webGL support but its not been updated for 3 years and i don't see much signs of life there)
What we were using as any database with API that controlls incoming data. And data was simply send using unity webrequests with POST, GET requests. Worked without any problems. If you want some kind direct implementation, sorry I do not know.
hi
hi
I've found that apparently dynCall is deprecated and I should use makeDynCall (ref: https://docs.unity3d.com/Manual/web-interacting-browser-deprecated.html) however, makeDynCall ain't a thing
<@&502884371011731486> this looks shady AF...
ignoring my comment just makes this even shadier...
!ban 1237086828364828694 Some weird bot messaging?
rex12__23 was banned.
🦾
Hey Team,
I am using web gl build, and i am using asset free outline shader.
This only happens on webgl, but not in desktop build.
Any advice idea how to solve this ui glitch?
how should it look? 🤔
Does WebGL have a light count limit even when using deferred rendering?
i dont see how there would be a limit
i guess it just depends on what the machine can handle
Just confused - I ran into the 8 light limit with forward rendering in the editor, so I switched to forward+. But WebGL doesn't support it, so I tried deferred. It looks good in the editor, but the web build looks a lot like the 8 light limit I had first.
if you are using more than 8 light sources on your webgl project, you already doing something wrong. Reason is that webgl is very performance not friendly, and calculating lights is quite expensive, if not the most expensive thing to do. I strongly suggest bake lights, and have max 1 real time lighting in the scene if any. also have in mind Webgl dont have global illumination what so ever, so if you set that, editor and build will always looks different.
While webgl 2 supports differed rendering pipe line, if you some why running webgl 1 it will automatically run in forward renderring instead. And if I remember correctly differed is less performant than forward, unless there specific scenarios present.
Another tip if you insist in running a lot of lights, you can cheat in cutting objects in smaller pieces, as 8 ligths limit is per object. So as long one object is not effected by all lights, it will be fine.
does asset states that they support webgl? if not, you should search for another asset. Reason is it really depends how they created shader, and gussing how to fix it might be complicated. In the end you might need to create outline effect by your self, in URP there are multiple ways how to do it. Sorry I know it not big help, but webgl is very sensitive to a lot of things and hard to say where it went wrong. Next time you also could name asset name for more info. Some asset owners have quite decent support.
webgl can not support 4000 basic cubes? why is the game failing to load with no EM_asm constant found
Hey
I added a button on my WebGL app but I can't communicate with it, I can't write in it. Why ?
<div>
<div>
<label for="session-id">Session ID:</label>
<input type="text" id="session-id">
</div>
<div>
<label for="lap-number">Lap Number:</label>
<input type="number" id="lap-number">
</div>
<div>
<button onclick="SendMessage('APIManager', 'LoadLapData', '')">Load Lap Data</button>
</div>
</div>```
Conflicts with Javascript from Unity ?
If yes, how can I fix that ?
Thank you. It's the first time I've tried a WebGL build, but also the first time doing any real work with lighting. The limitations weren't described very well, but if I had known that I'd have done things differently 🙂
basic cube from unity
That wasn't the question you asked originally that they answered.
You can't just call SendMessage, you'll need to reference the Unity Instance chained with the method
Like shown here: https://docs.unity3d.com/Manual/web-interacting-browser-unity-to-js.html
now the tricky thing is even if you did that directly on the onclick I believe you may get an error because the Unity instance hasn't loaded yet.
So in the order of things... HTML elements load first and if onclick is referencing an undefined instance of an object it will error!
So you'll need to create a let variable in global scope of your javascript where you'll later assign the Unity instance to once it's available.
then you need another function in your global scope that serves as a wrapper function that handles the send message on the unity instance.
function SendMessage() {
unityInstance.SendMessage()
}
finally when you pass arguments to the SendMessage, Unity is very sensitive about what you pass it. So if you have nothing to pas in the third argument, don't include it.
If you just want to call a C# function on Unity object then just call it like this
unityInstance.SendMessage('object', 'function name')
If all the above doesn't make sense to you... share your webgl build with the web content on a site like https://codesandbox.io and I can then help edit it for ya and show you how to set this all up
can i share my off topic project here?
There's no off-topic. If it's made with Unity you can post it in #1180170818983051344
its not made with unity
Then find any non-dedicated-Unity game dev community to post it in?
why dont have a off topic channel
ok thats a good reason to dont have off topic channel
You can share it in the reddit gamedev discord though, lots of other sections there, and post it under share your work 🙂
There is the indiegames discord too that's smaller but growing.
any idea where to set the USE_THREADS flag in webgl builds? 🤔
If I want the unity window embedded into a website to be rounded, can I make it directly by its build index.html?
This was done but nothing changed for the input field
😔
what do you mean nothing changed for the input field? You can't type in it?
Nope
I can select it but when I type in it, nothing happen and nothing is displayed
If I comment the canvas, I can. So I thought it's because the key inputs are for the unity app
can you upload a copy of the build to codesandbox.io and share the link I'll have a look
Unity WebGL has a known issue with capturing keyboard inputs... that can be solved in 1 of 2 ways if it's related to capturing input.
I'll share the 2 things you could try
Thank you 🙏
as you can see in the second sentence of description You need to disable this property if you need inputs to be received by other html input elements.
I'm actually toggling this on and off at certain points in my game as well
I believe main menu it's set to false
then in-game I set it to true
Oh, thank you a lot, it worked
I didn't know that and I didn't found that on internet
I forget how I found it... but yea I struggled with this before!! so happy it worked for ya
go to your project folder->ProjectSettings-> open ProjectSettings.asset with any text editor and set webGLThreadsSupport to 1. Start your projet you will see that there will be now threading supported. Please have in mind, that this threading is just for c++ and not for c#. So just enabling it wont make everything just work.
Thanks!
I dont need any threads myself, I just wanted to see if unity would behave better while loading addresables 😅
it will should not effect any default behavior, as everything is single threaded anyways. But testing your self always is a good practice 🙂
what is the best texture compression to use for webgl? I'm interested in the least loss of quality and small size and that it is supported on all devices
Answer "there is none" that is the best for all devices.
https://docs.unity3d.com/Manual/class-TextureImporterOverride.html
Each device supports different compression, and if it fails it fallbacks to back to RGBA. Ideally you would want to have separate build of each of device like it is done here, but well in more complicated way:
https://docs.unity3d.com/6000.0/Documentation/Manual/webgl-texture-compression.html
If you want to stick with one compression format I would go with ASTC6x6. It is bit bigger than ETC2 or DXT, but it will work on iPhones and Android. Well PC will have to fallback to RGBA, but PC have most free resources so it can suffer a bit. Enjoy webgl suffering 🙂
Im trying to test different background musing for my webgl game, I have a simple ui panel that changes the audioclip of an audiosource by pressing different buttons.
The problem is that on WebGL (and not in editor) the music takes quite a while to start
Can I somehow remove this delay?
Hi guys,
Has anyone here ever successfully modified the AudioContext in WebGL through a JSLIB for audio mixing?
I've tried to capture the context with a JSLIB but because Unity creates what seems like a hardcoded context object with no exposed API to use it, it seems like I have to modify engine level code to reach it?
Any help or pointers would be appreciated!
It really depends on compression you choose when importing songs. I cant remember which one is the fastest now, but you can play with settings on music file. Offcourse fasteres music will requare preload to memory and etc, so give and take situation.
I might not help a lot, but from hat I know you are pretty much right, you cannot reach audio context from JSLIB. I saw plugins that was able to do so, but they used c# code to parse information between Unity and external calls. For example webrtc voice chat plugin. There are a lot of reason why Unity does it this way even if that is inconvenient. I would suggest either handle all audio that needs JSLIB access outside of unity in js code (just call js code from unity and trigger unity code from js). Or you will need to write elaborate plugin your self. If that plugin is core part of your project, I might even move to PlayCanvas to hav easy access to all audio from JS
Thank you for the additional information @astral wave 🙂
I'll fiddle around and see what I can come up with.
For context, all I wanted to do was have the Low pass filter work in WebGL because it's a really cool sound effect haha
Template variables, macros, and conditional directives
During the build process, Unity pre-processes template files and evaluates all macros and conditional directives included in those files. As part of this process, Unity finds and replaces all macro declarations with the values the Editor supplies. Unity automatically pre-processes all .html, .php, .css, .js and .json files in the template folder.
https://docs.unity3d.com/Manual/webgl-templates.html
Do we know what template language/engine unity is using? 🤔
I get we can use #if and {{{ STUFF }}} but do we have other tools?
Quick look at \Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Preprocess.js suggests acorn? Looks like the template stuff is done in JS, so it seems like something easy to mess around with.
you are right 🥲
it's done in javascript...
it's not using any of the javascript templating libraries
mustache, handlebars, dot, ejs, nunjucks, underscore, pug, hogan, and many more...
NOPE, just a regex locals.output.replace(/{{{([^}]|}(?!}))+}}}/g, ...
Anyone got any ideas about this?
Long error pops up starting with "
"An error occurred running the Unity content on this page. See your browser JavaScript console for more info. The error was:
RuntimeError: indirect call to null""
It all worked fine earlier
It's just a generic error. It could mean running out of ram or even a null ref call in some cases. You'll need to trace the error deeper in the debug console etc.
It could really be a lot of things
I'd also do a debug build with development logging of everything enabled etc.
Damn Idk how to do that. It was fine earlier today. Works fine in the editor
How do I do that?
You'll need to go through the build settings and player settings and just turn on max logging, development mode, and uncompressed.
Basically anything that will give you more info
On it
Man this sucks lol
The other levels work
Actually idk how to do that and I don't wanna mess things up more than they are rn. I'll try it fresh tomorrow
Fixed! It was some weird script I had checked
Excuse me! 🙂
deleted it.
Im trying to build my game to HTML5 for the gmtk jam and there is a bug that seems to only affect the web version where when i go into fullscreen, all the text in the game goes invisible.
it only happens when i attack an enemy, and the only code todo with text is this:
GameObject popupGUI = Instantiate(player.damagePopup, new Vector2(UnityEngine.Random.Range(position.x - 0.30f, position.x + 0.30f), position.y + 0.5f), Quaternion.identity);
popupGUI.GetComponentInChildren<TextMeshPro>().text = popup;
popupGUI.GetComponentInChildren<TextMeshPro>().faceColor = color;
popupGUI.GetComponentInChildren<TextMeshPro>().color = Color.white;
yield return new WaitForSeconds(0.84f);
Destroy(popupGUI);
why is this happening? ive been trying to fix it for a few hours now
Any idea why my WebGL is build is freezing up the whole browser on Windows, but is fine on Linux?
Hi! I'm trying to do a WebGL build and i'm getting this error - IL2PP error for method '...' System.NullReferenceException: Object Reference not set to an instance of an object. There are no compiler errors and everything runs fine in the editor. Could someone please suggest any fixes? I wasn't able to find a lot online
Show the full error message
This is the full debug
I have two video players in a scene. If I play both only one player is rendered. Other one is definetly playing because I can hear the audio, but not rendered. If I pause the first one, second is rendered. If I play the first one again, second stops rendering but still playing. In standalone/editor everything works properly, this happens only in WebGL. Do any of know why this is happening ? I use RenderTexture and assigning it to a material which is assigned to mesh in which the video is rendered. I create the RenderTexture runtime and instantiate the material runtime too.
Are you sure you using separate rendering textures and not the same. And separate materials or separate material instances? As it sounds like you render both on the top of each other, and just one which is rendered later wins the video texture.
Yes I printed the videoplayer.targettexture.getinstanceid(), it's different. And both renderer use different materials with different shaders.
What Unity version are you using? As I can confirm that on 2022 that wasn't a problem. It could be bug as it happens only on webgl. You don't have any conditional code dependant on platform?
Yes this happens only in WegGL, in other platforms my setup works as expected (Standalone windows/meta quest android). Unity 2022.3.31f. I also want to find out if there is already a known limitation or bug in WebGL regarding this.
Hi
I'm using JS Vibration API for haptics in WEBGL
Is there a way to adjust the strength of the haptic, not just its duration?
Maybe someone uses some other plugin, I use VibrationWebGL (https://assetstore.unity.com/packages/tools/utilities/vibrationwebgl-201020?srsltid=AfmBOopi3KKKwAYk8DMh6MmtQZmiLZNTreVa4mMWqEmRAy4UJQearSTF)
I'm getting a strange error trying to deploy my project to WebGL. Has anyone else encountered this?
when I encounter weird errors like that, first step is close project, to delete library folder, open project again and let it regenerate library. If that don't work I would check logs file, sometime there is more information. I haven't seen error like that yet. does other platforms builds work?
I just fixed this a little bit ago. The issue was an api mismatch. I will have to look at the project when I get a moment and find out which I swapped to in the player settings.
I have a full screen Canvas, can I still set something like max Resolution, because I dont need it to run on 4k, it is enough to be FullHD and then scale. Is there an easy way I am missing?
How to remove unity logo from WebGL build??
I remove checkbox from Show unity logo and use Default WebGL template
you can try using the unity build and run option, as they mentioned - this makes unity host the game for you
Okay I will try
you basically need a web server to run a game, and right now you have none
Unity can kinda act like one for the purposes of running the game
Itch?
itch should work too, yeah
but I'd use build-and-run as a sanity check first
are you bothered by the background on the menu text?
or are you just happy it worked xd
yeah the scaling is not good until i make it fullscreen
I think the both
ah so the issue is the scaling? Did you put the anchors properly?
we should move this to #📲┃ui-ux
okay
it really better to check browser console for more detailed error message. Most likely it just null reference somewhere in your code.
Hello gm
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
wasn't a code issue turns out, the windows build worked fine
webgl just doesn't work with HttpClient in .NET
it's fine, didn't really need webgl as a target
Unity provides its own crossplatform HTTP APIs
how to fix this parse error?
Did you check the string to see if it matches the way you are trying to parse it?
we only caught this on one device on one browser
for example this strings
so i was trying WebGPU for the first time and tried to build an empty scene but after the build i get dark screen then nothing
when i reload the page, the unity logo loader show up but then the dark scene again and nothing
Probably a good idea to check the console for errors
Trying to Build and Run my WebGL game I get a gray screen, just like the last message above, here's my console log, I searched a few of the errors without success, anyone knows what it could be?
1.framework.js.gz:10 RuntimeInitializeOnLoadManagerInitializer: Failed reading 'ScriptingAssemblies.json'
1.framework.js.gz:10 [Physics::Module] Initialized SinglethreadedJobDispatcher.
1.framework.js.gz:10 No GlobalGameManagers file was found at , quitting player!
1.framework.js.gz:10 Failed to initialize player
1.loader.js:1 [UnityCache] 'http://localhost:58401/Build/1.data.gz' successfully downloaded and stored in the indexedDB cache
Full version with mostly non-errors: https://hastebin.com/share/yawahivese.vbnet
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What's weird is that when I read online, people will usually have some other error causing theses, or am I missing something?
Turns out I could enable more stack traces in build settings and then that all made sense
Anyone have IAPs on iOS/android who has a good solution for either letting people buy iaps in a self hosted web version of the game (stripe??).
Code/selfhost answers only, eg not revenuecat.
Stripe and Xsolla at least used to be pretty popular.
WebGL will only garbage collect at the end of the frame - it can't do so mid-frame. That's fine, but... if I turn my expensive loop into an async Awaitable, and periodically
await Awaitable.NextFrameAsync()
Can the garbage collector run then and clean up all the garbage from previous iterations of the loop? Because on WebGL it doesn't look like it is... (Previously there were problems in Unity with using Task.Delay() etc not allowing the garbage collector to run on any platforms - you ended up having to use coroutines. It looks like Awaitable has fixed that, but not on web...)
Im building for WebGL and it works fine on all platforms but reloads twice on iOS then nothing happens. The first time it loads, it will load the first (loading) scene, but the moment it should transition in to the main scene, it will reload. Anyone experienced this before? I read about a 500MB limit for RAM, but it does load the first scene, and sometimes (rarely) the full scene too, and it will vary between 500MB and 1.5gb in JS memory through checking the console.
Which is also weird, how wildly it can vary..
Again, works on all platforms except for iOS
Welcome to webgl iOS hell. iOS have a lot of hidden rules that are not obvious. Are you using addressables or other assets management tool? As by default even if you load only first scene, everything will be loaded to memory regardless of scene loaded. My guess would be memory limit, most likely it gives too low start memory, then reloads and gives more memory then it works. You can play with ho memory is increased in newer Unity versions. But iOS, depending on device have memory limits for UnityWebgl, for example iOS 10 will have start weird behavior at around 400~mb RAM (if you use UI toolkit the ui starts blinking), then around 500 MB starts restarting or doesnt load at all. On never devices it is bit better, but still you must be VERY carefull with memory on iOS. Surprisingly PlayCanvas don't have this memory problem, but that is not Unity fault, iOS is just.... well.... hell to develop at.
the thing is a previous build i made works, and if i go in to memory profiler on safari, it shows as using 1.5gb, then some other builds i do dont work, but use like 300mb memory. Also it changes upon every reload of the page. Some times its using 300mb, sometimes 600mb, somtimes shoots up to 1.5gb. There seems to be no consistency when checking the memory profiler in the inspector :/
Anyone know why my game crashes on mobile webGL? My build is kinda big could that be a reason? If you need more info tell me.
Prob the same thing as me above... I assume its only really happening on iOS devices?

