#archived-code-advanced
1 messages ยท Page 121 of 1
Maybe look at the build report to see what's taking time
This step
build report might have more info and actual time metrics
Not much useful info there, but it took 41m as I said:
Is that from the editor log?
Yes
Hmm... I wonder if it's just doing the same thing over and over again..?
Did you try deleting your library folder and trying to build again?
Yes. I did
No idea. It ends up compiling in the end, tho
Well, then there's not much we can help you with. Unity doesn't really provide much info on it's internal build process.
Maybe try messing with different relevant settings, like toggling incremental build on/off, building non development builds, messing with il2cpp settings in the player settings.
Ah wait. I was compiling in release mode
Debug mode insta-compiles it
Smh
Or maybe it is some cache. Let me see
Hmm... Perhaps it's doing optimizations. Still weird. If incremental build is enabled, it should check the cache and avoid recompiling stuff.
Seems like some cache. It compiled too fast. (Edit: indeed, it was just a cache)
So I noticed splines can be Serialized, and they do maintain data on reload. But the reference doesn't seem saved.
If I cache a spline, and compare the cached value to the original, they are the same.
But if I reload, the reference is lost, and they aren't considered the same anymore.
Could someone explain why this is?
Also I couldn't find a spline specific page so appolgies if this isn't the right space.
Which spline are we talking about. Spline component?
The spline class, used in the collection of splines for the component or custom implimentations
So thatโs plain serializable class, and Unity would create new instance when deserializing
hmmm interesting, as so this isn't the case with Mono/Scriptable Object references?
Unity serialize those as ID while their original exists within scene or asset
Non-Unity objects are serialized as value
has anyone seen this error before? I've deleted my library as well as root folder C#projects and it still pops up.
you may need to change packages.json to remove it completely
I am working on an asset, which needs flexibility.
Normally I could get all child components with GetComponentsInChildren, but that limits the amount of classes I can easily access and requires a lot of upkeep.
Would it be possible to get a list of monobehaviors that are within a certain namespace? This way I could get all scripts that are necessary for me.
Same idea, iterate through but check for namespace
I didn't know you could check if a script is within a namespace, but just found Type.namespace!
Thanks
What hashing function would be the best fit to perform a string -> number conversion? With low risk of collision, speed isn't a super big concern
Murmurhash looks good so far
Any hash gives back a number, so pretty much anything modern works.
How realistic a 64 bit hash collision
Cause I just found out Unity does give you 128 hash
How many unique strings are you working with?
Are there any constraints that you know they will follow? Such as allowed characters, min or max length, human written, random, etc.
Worst case scenario 10k I think
But that's an absolutely unrealistic level at which point my other systems will start to give up
Are the strings known at compile/build time?
No, dynamically loaded
If hash collisions are catastrophic to your application, you'll have to add some kind of check for it, regardless of how unlikely it is, IMO.
If the only thing you care about is just collision and not performance/size/security/etc, just use whatever available and call it a day. SHA1 is built in, a few lines of code.
My biggest concerns are size and collisions
If size wasn't I'd just use a string key 
But unmanaged code can be pretty merciless at times
whats the umanaged code for?
Entities
unmanaged containers/burst is "safe ish" still so isnt bad i think
Wdym
ummanaged code is native code not using some runtime and/or gc
Yeah that's right still not gonna let me use strings though
So I have to come up with something
I don't know exactly what you are doing but could c strings (char[]) be used?
also StringBuilder can be used if you are using native code as an easier to use buffer to write to (e.g. pre allocate 512 and the native function copies a string to the char*)
Yeah I was considering to just introduce a character limit
But you know ideally I hash it into a number
Ideal case scenario
yea if you know the hash max size then should be fine
Are you just speculating that the size of the hash will be an issue, or do you have specific reasons to believe so? SHA1 hash is 20 bytes, that's hardly anything.
I'm usually speculating about everything
Haven't even started doing anything actually just researching
I'd speculate this is a non issue ๐
Issue is I have near-zero knowledge about hashing functions
SHA1 is very compact though yeah
Rather than wasting time now, you can just use SHA1 in a few lines of code and move on, and if you do find it to be an issue later on, the hashing code can easily be swapped out.
Fair. I'm just procrastinating at this point
How hard can swapping a hash function be
i think pretty much all hashing functions produce a fixed length hash and well google exists to find out quickly
why not just MD5?
var test = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("Testing"));
BitConverter.ToUInt128(test);
I've seen Unity uses their own md5 crypto internally before, not sure if it's available as public api tho
Mainly because I just learned of it ๐
Didn't have the time to look it up yet, how does it differ from SHA1\murmur?
md5 is much simpler that SHAx and should be faster
also note thats 128bit not sure if you want that
for what use case?
Is there a reason you can't just use .GetHashCode() on string?
do you have special requirements?
Gotta serialize a bunch of strings for storage in an ecs component (unmanaged)
Mainly because I just learned of it
why wasting your resources for hashing tho?
I'm just researching atm
Can't use strings (well, can, but I'm hesitant) in components, so I'll need to keep reference to them by some key
Incremental integer IDs can be a pain, from what I've heard
So my second guess was to hash it and access via a dictionary
wat
I'm gonna dig up the convo, gimme a sec
I butchered the terminology, not "incremental" but "sequential"
you dont need strigbuilder, bcos at this point you already have the array or pointers so regular string will work just fine
var str = new string(*sbyte //or// *char or char[]);
the perfect case to use new string() ๐
guess what i read was miss informed. i guess then if you make a string with the correct capacity its all good?
im plenty familiar with cpp but dont do much c# -> native interop
Can anyone help answer my friend's code question from here please?
https://discussions.unity.com/t/impossible-to-draw-a-texture-in-sceneview-with-gui-functions/1594136
Hi! I have a question about how code is ran:
I have a function inside of a script (SelectMenuButton) that runs whenever a button is clicked. But for some reason this code runs even if I have the script disabled and I press a button
Does this have something to do with IEnumerators?
Not an advanced question. Disabling a component only affects specific unity messages, it does not prevent you from calling methods on that object
The script being enabled or not is irrelevant
what's the question exactly though?
My question is how am I still calling to this function by accident when my script is disabled?
Notes:
The code to call this function is in Update(), and I'm under the impression if the script is disabled then update should be too
No where else in my code is this function called.
so is this method being invoked by a button or not? if it is being invoked in Update that is not being invoked by a button.
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I call SelectMenuButton inside the code, not outside
void Update(){
if(player_controls.GetFaceButtons() == new Vector2(0, -1) && button_chose && curr_menu_buttons.Count > 0){
print("Run this piece of code");
StartCoroutine(SelectMenuButton());
button_chose = false;
}
}
public IEnumerator SelectMenuButton(){
print(in_fight);
curr_menu_buttons[curr_menu_button].gameObject.GetComponent<Button>().onClick.Invoke();
yield return new WaitForSeconds(0.2f);
button_chose = true;
}
What I do:
Press a button on a controller to trigger the code in Update() so that SelectMenuButton is called--> Invokes a button to disable the script --> Press the same button on the controller --> function in script is called again (should not be happening)
It's because IEnumerator is just something that belongs to C#, but what Unity does with it's components isn't really anything special, so there's no way it could stop you calling it
Well, they could make their own custom IEnumerator which would allow them to control things
Thanks, I was just so lost at how this is running lol
Still kind of am but I'll just mess around with it some more
the way you're invoking a coroutine in the update loop adds a ton of complexity to the logic that I think will make things very difficult to debug down the road
since all you seem to be using it for is to delay setting button_chose, i'd highly recommend making a float timer field and counting down the time yourself in Update(), that way the logic is all contained in the update loop in a more understandable way and enabling/disabling the component will behave more like you'd expect
this is more of a theorical question - but i'm working on generating a map for a 2D isometric city builder. I want to generate ressources on the map right like stone, iron , coal , trees for wood ect.
I use tilemap for stuff like the base ground, hills , rivers ect.
but i'm puzzled with how i'm gonna handle ressources ?
I could use a tile map - but when it comes to interacting with the ressources i'm not sure how it would work and if i want the tree to have somekind of animation for example?
I know i can use prefabs but i also know they might impact performance if we generate for example a massive forrest?
not exactly sure what the best approach would be
This depends a lot on the details of the game design and size of the map. Typically you want to build your systems in a way that you simulate only the minimum thatโs necessary to make the player feel the world is โrealโ and remove anything from the simulation thats just cosmetic or can be faked. Then visualize and detail-simulate only what the player can actually see. Object count is not in itself a problem. Usually itโs all about how many of these objects you are updating and how often. An object that has no active renderer and no component with an update method will only consume memory and can exist โfor freeโ until the time you choose to render/update it.
Same idea around minecraft. Chunk your stuff and when it's interacted with (WorldToGrid) do you then create that independency for each tile
minecraft is a special case that does not generically translate to a city builder.
If you've a forest of 1000 trees, you're not preloading all that as multiples meshes, all each with their own Tree object instance. Even if it's to be interacted with, it should be static beforehand.
I would also expect city builders to combine meshes when each structure is built, but this is 2D so you can probably get away with a lot more things.
hi
i want to use Unity URP's update mode in "via scripting". it works well and i update Volume Effects with script when i need. but when i want to load next scene it shows an error. ChatGPT could not solve my problem ...
Using Unity 2021.3.32
Target Device : Mobiles
Maybe show the code YOU have written
Is there any hack/attribute/message/interface/black magic that I can use to have code be ran whenever any new object is created? Something like a global Awake or Start that fires whenever an object appears no matter who or how it was instantiated ๐ค
I don't think it's from my code, but I'll post the code anyway. I also tried without the code and with the code commented out.
static Camera camera;
public static Camera Camera => camera;
public RenderPipelineAsset urpAsset; // Assign in Inspector
UniversalAdditionalCameraData cameraData;
public static MainCamera Instance;
private void Awake()
{
Instance = this;
camera = gameObject.GetComponent<Camera>();
cameraData = Camera.GetUniversalAdditionalCameraData();
if (urpAsset != null)
{
GraphicsSettings.renderPipelineAsset = urpAsset;
}
}
public void UpdateUrpEffects()
{
if (Camera == null || cameraData == null)
{
Debug.LogWarning("Camera or Camera Data is null");
return;
}
var cameraStack = cameraData.cameraStack;
if (cameraStack == null || cameraStack.Count == 0)
{
Debug.Log("camera stack is empty");
return;
}
foreach (var cam in cameraStack)
{
var camData = cam.GetUniversalAdditionalCameraData();
if (camData != null)
cam.UpdateVolumeStack(camData);
else
Debug.LogWarning("Camera " + cam.name + " has no UniversalAdditionalCameraData.");
}
Camera.UpdateVolumeStack(cameraData);
}
MainCamera.cs
Is the new scene also holding a camera script?
yes... i have checked .. also base camera and cameras in stack have UniversalAdditionalCameraData component
But you overwriting your Instance. I am just wondering, if you still have relations to the "old" camera while assigning the new one in the new scene
I do not think it matters ๐ค
I should also mention that I changed "Script Execution Order" of the script as well.
What if I delete the whole script... it causes the error again. Could it be a Unity bug?!
I assume by object, you mean UnityEngine.Object. This would also include assets such as Material, AudioClip, all Components, etc., not just GameObject. Why do you need to be able to hook into the creation of all of those types of objects?
You should just log every object you touch and see, when the null errors appear in your game loop
good point, I was thinking about GameObjects but I just need to see Monobehaviours.
I need a DelayedStart kinda method. Like start... but after a delay ๐คทโโ๏ธ
I am considering creating my own base monobehaviour and then connecting it to unity's Start. It aint pretty but it should work ๐ค
i just want to use URP in "via scripting" update mode. did i miss something for that? maybe it is the reason of error. i am new to urp
not sure if this is what you're looking for but
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.Start.html
The Start function can be defined as a Coroutine, which allows Start to suspend its execution (yield).
you can write your Start() method also as async or IENumerator
oh, you were faster ๐
Again, you access things that you lose reference to when switchign scenes. Your job is to find out, what object it is. If it does not make sense then, we can start thinking about a bug. But first you really gotta debug that code
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I have installed a package using Nuget (Google.Protobuf) and Visual Studio Code properly shows, checks code and shows syntax errors as if it had the package, however Unity does not recognize the package and shows errors because it does not recognize Google.Protobuf's existence
what do I do?
unity does not support nuget
oh
so how do I download that package?
"install protobuf unity"
oh, considering how much trouble I was looking up problems related to namespaces and packages I didn't expect it to be so easy
Just wanted to say that I fixed that error by updating Unity to the latest 2021 version on Unity Hub. And it seems to be working fine for now...
From 2021.3.32 to 2021.3.45
and thank you
Good to know. Wonder, why you are so far behind in versions. Anything against an upgrade?
I want to be up to date but either Unity is being stubborn or my system is outdated.
Every time I installed higher versions like 2022 or even Unity 6, the "Unity Bug Reporter" page would open when I create new project. some times i create project and crashes few seconds later
Oh alright. Maybe remove it entirely first. But that sounds like a hardware issue probably
Yes maybe...
Is it a desktop or notebook?
Asus x555qg Laptop
You could try to reseat the RAM. That behaviour of random crashes on software happened to me a lot because of RAM back in the days. Not sure if you have access to RAM
How? what you mean exactly from "access to RAM"?
access to the ram slots on your motherboard
I have access to it, and I recently opened the laptop and cleaned it. i have to try that ๐ค
If I have a static persistent native collection, do I need to worry about releasing the memory between assembly reloads in the editor or will the memory be freed automatically?
How are you creating it?
static LinesManager()
{
_lineLookup = new NativeHashMap<LineHandle, LineData>(100, Allocator.Persistent);
_cachedValueArray = new NativeArray<LineData>(100, Allocator.Persistent);
}
So you never dispose it?
Only when resizing it
well the array, I believe NativeHashMap handles resizing internally
so no I don't dispose the NativeHashMap
so you are using it in editor and creating it with each unity start?
No it's for runtime, but I'm just wondering if I need to add some editor code between assembly reloads to dispose of them manually or if all native collections are disposed on assembly reload automatically
if you are creating it at runtime, you should also dispose it in runtime
My point is in a build they don't need to be disposed unless they are resized. Like they exist for the entire application's lifetime. In Editor an assembly reload can occur and I don't know how that affects persistent native collections.
But if the assembly reloads, the nativearray should not be there at all, because playmode end would dispose it. If you dont dispose it but create it again and again on play, this will run into a warning of memory leaks I guess.
I like this approach where you store the values and reassign them with scriptablesingletons https://discussions.unity.com/t/how-to-manage-nativearray-lifetime-for-an-editor-tool/880527/4
Again this is not for editor code
I just have a static class with a native collection
But you are creating it when hitting play, everytime.
Yes and what I want to know is if Unity automatically disposes existing native collections when assembly reload happens
Or is the class not inheriting monobehaviour?
It is a static class
It will not dispose it automatically
Unless you restart unity
What is weird is I'm not seeing warnings about memory leaks
I think it does not fire off right away. Guess there is some kind of threshold or whatever
Does it only warn about memory leaks when using jobs?
No, had the warnings too at some point without using jobs.
public static class FooBar
{
static NativeArray<int> _nativeArray;
static FooBar()
{
_nativeArray = new NativeArray<int>(5, Allocator.Persistent);
}
public static string LogNativeAray() => _nativeArray.ToString();
}
Create a script that logs that LogNativeAray() and you will already get a memory leak warning after starting playmode twice
just to be able to trigger the warning. The reload of assemblies did not affect this or trigger it. And about your Jobs question, it is triggered by the unity internal use of jobs in that case.
Okay yeah I finally got a warning, you're right it really isn't about assembly reloading. It is more about entering and exiting play mode (which triggers assembly reload depending on settings), I will add code that disposes them when exiting play mode. Thanks!
Thats why you had the confusion with me talking about editor scripts, I assume ๐ Great you could reproduce it and got your outcome for it! happy coding!
using UnityEngine;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
public class WaveBaker : Baker<WaveAuthoring>
{
public override void Bake(WaveAuthoring authoring)
{
Entity entity = GetEntity(TransformUsageFlags.None);
using BlobBuilder builder = new BlobBuilder(Allocator.Temp);
ref WaveBlob waveBlob = ref builder.ConstructRoot<WaveBlob>();
BlobBuilderArray<SpawnDataBlob> spawns = builder.Allocate(ref waveBlob.spawns, authoring.waveData.spawns.Length);
for (int i = 0; i < authoring.waveData.spawns.Length; i++)
{
spawns[i] = new SpawnDataBlob
{
isCluster = authoring.waveData.spawns[i].isCluster,
spawnId = authoring.waveData.spawns[i].spawnId,
timeSinceLastSpawn = authoring.waveData.spawns[i].timeSinceLastSpawn,
populationThresholdTrigger = authoring.waveData.spawns[i].populationThresholdTrigger
};
}
BlobAssetReference<WaveBlob> blobAsset = builder.CreateBlobAssetReference<WaveBlob>(Allocator.Persistent);
AddBlobAsset(ref blobAsset, out _);
AddComponent(entity, new WaveComponent { WaveData = blobAsset });
Debug.Log("baking complete");
}
}```
i dont understand why im just ending up with an empty entity without the wave component attached
I'm trying to make an iOS build and I've got this error. Been trying to figure it out for hours. At first I figured maybe there are 2 version of Ruby, but I'm 90% sure that I've got everything up to date. I definitely have CocoaPods 1.0 or higher but it's erroring out when I run the build process. I tried to update ActiveSupport but it states that it can't be updated further until my Ruby is updated, but when I pull latest there are no new updates. Any ideas?
I was wondering if anyone knows anything about calling disconnect functions on unity using SIGINT / CTRL + C, I'm trying to figure out how to process a function when these commands are being called
This is not working unfortunately, Ive also tried on disable, and singal handlers, nothing seems to work.
You mean you run unity from the commandline?
Have you tried traditional C# sigint handling?
from a console command/ server crash
Ive tried all of these
NetworkManager.Singleton.OnServerStopped
AppDomain.CurrentDomain.ProcessExit
Console.CancelKeyPress
OnDisable
UnixSignalHandler
OnApplicationQuit
I'm not sure what traditional c# sigint handling is
Console.CancelKeyPress is the wrapper that C# provides
What platform are you running on
docker container on a linux server
But if the others don't work then I wouldn't expect this to work either
Or you docker container might not be forwarding signals correctly https://hynek.me/articles/docker-signals/
And if that still doesn't work, use something else as entrypoint and signal unity to shutdown when necessary
Thanks a bunch, I apprecaite all the help
Iโll check that out tomorrow
Looks like a null pointer
do you have the whole stack?
Has anyone successfully implemented (or know how) real-time player movement validation using phone's back camera into Unity?
Looking to understand if it's possible to:
- Track leg movement accuracy
- Simultaneously track ball movement
- Process both on device with minimal latency
What are the balls and legs that we're talking about here? Context?
This sort of task can only be done with computer vision. Either you are lucky and a good model for this task already exists and has a permissive license, or you'll have to train one yourself, which requires knowledge on machine learning algorithms and lots of annotated data.
Legitimately look into how VRChat tracks limbs. It requires a few hundred bucks of hardware and is pretty unwieldy but it's basically the most common use case of motion tracking a consumer is going to run in to
Hi there
does anyone have PS5 experience?
I'm trying to write a simple file to /download0 aka Application.persistentDataPath with File.WriteAllBytes( path, bytes )
but keep getting
DirectoryNotFoundException: Could not find a part of the path "/download0/saves/Gloomhole.638743812131054230.pack".
I've set the download area size to 1024MiB
you didn't mention it so i figure it's worth asking, did you do Directory.CreateDirectory("/download0/saves")?
did I have to explicitly?
now that I look at it... the other platforms actually do create directories...
yeah I guess that might be it
yeah, it's just a regular filesystem afaik haha
brainfart xD
I have a UI game object that is quite complex, with a lot of nested images and textmeshprougui objects. I want to monochrome out a portion of it (including a part of a single background image). My first thought was to make a List<Image> and List<TextMeshProUGUI> for each "thing" I wanted to monochrome, and apply a monochrome shader (we have the AllIn1Shader package in our library for shader effects on UGUI objects), but this got super tedious (there's maybe 50 objects that need to be in each of these lists). My second thought was to do recursively traverse the gameobject tree, looking for images and tmpro components, but this didn't work well because I'm building/rebuilding a lot of these objects at runtime, so I'd have to add hooks into any possible place an object was changing and re-crawl the GO tree.
Anyone have any bright ideas for a solution?
Basically, I have this "action card" which I want to monochrome an "action" after it's been used (can only use it once per turn) or cannot be used (player doesn't have dice to pay for the action), and I want to monochrome the entire card when a unit is dead.
(I'm currently just slapping a "USED!" text over the part that I want - I just don't love this solution)
Pretty much everything in the card is programmatically built at runtime based on the ability loaded in from json
dice cost, ability name, text, etc
why wouldn't each action have its own script that controls whether that action was monochrome or not? if your ui is built at runtime, why are there 50 things in the list?
each action does.. just saying, there's like.. a lot of elements in the card that (now) need monochroming-out
For example, the action "roll out" has a tmprougui that has the text "move all units up to 4 spaces" which needs to be gray (including the "4").. the special button has an image that's the background, but also 3 other images (highlighted, pressed, disabled).. the dice icons have a background, icon for dice type, as well as some overlay checkbox icons
The monochrome requirement is a little new, and probably the best approach is to add a monochrome flag to every component in these cards, but .. i was hoping for something a little quicker
it's a pretty big refactor to have every object be able to monochrome itself on demand.. basically I was hoping for a shortcut.. maybe rendering the entire UI object to a render texture and applying the shader to just that, or something.. I dunno..
snapshot of the hierarchy to maybe provide some insight into how many objects are in this stupid thing
and of course, each card has overrides for the layout
if there are some elements that will be monochrome within a card and some that are not, then there is no escaping configuration of some kind. This doesn't seem like a lot to me personally, though; based on your screenshot you have like 10-15 prefabs in total and they need to be customized anyway
K.. you might be right, I might just be overestimating the work and probably just spending more time finding a shortcut than just doing the 'iterate the items and apply a shader on demand' approach
for images you can at least have your own UI shader with a feature to do the greyscale (I guess you could also make a custom tmp shader too)
For UI that I have done we just have a component (named LockedGraphicChanger) we setup to do the material swapping for us for this exactly purpose and we just assign things manually.
If you have a few components for each section/thing it shouldn't be too bad
how do i attach a standard c# (NOT THE UNITY DEBUGGER PLUGIN) to unity? I'm trying to compare the (optimized) disassembly of some code but attaching the unity C# debugger normally causes it to recompile in a non-optimized manner
If you try to "attach to process" on the editor does it work?
it doesn't seem to actually attach a C# debugger, and if i specify a c# debugger none of the options seem to actually find the C# code, so I'm not convinced its attached to the correct thing sanely
Hey guys, how can i integrate github to my unity project that now is on devops? I dont like UVCS for source control at all, would like either Source Tree or GitHub to manage and dealw ith commits, UVCS is way bad. Is there a tutorial for that shift of integration for unity?
I'm getting this error when trying to build for Linux
The type or namespace name 'Switch' does not exist in the namespace 'UnityEngine.InputSystem' (are you missing an assembly reference?)
How can I fix this? Why isn't Switch supported for Linux builds?
Are you using that namespace somewhere?
Are you adding Switch controller support or something
afaik switch controllers don't work on linux without some third party drivers so it's not all that surprising that unity does not support it
Yes, itโs so I can display glyphs for switch controllers
Oh ok, I thought they did, thanks for the help. Iโll remove them for Linux
Yeah probably just add some #if guard
id presume due to it using mono and being old so visual studio cannot actually attach to do managed debugging without the extension.
Hi all, I was wondering if their was a way to lock variables in an IParellelJob, the basic setup I have at the moment is that I am comparing a group of cells to see if their structure matches a pattern within a pre-made pattern library. As of now, I am testing the cell structure against each pattern, then output a NativeArray of bools which contain true or false for if the pattern was matched (some cell structures can match multiple patterns).
Post this job I then iterate over the bool array and find the first index for what pattern to use. I am trying to optimise this specific part by only using 1 variable and setting the lowest index for matched patterns.
However, since just setting the value or something isn't thread safe, I need to be able to lock the value for "patternIndex" read its current value, then if it hasn't been set or its value is higher then the current pattern then to overwrite it.
Since the job system is unmanaged, I can't use lock to stop other threads from accessing the variable, is their any other solutions for something like this?
This sounds perfect for atomic operations. But it seems like NativeArray and Jobs don't have nice support for it, requiring some workarounds.
https://discussions.unity.com/t/solved-atomic-interlocked-operations-on-nativearray/695740/3
Excellent! Thank you, I was actually doing a bit of reading on the Interlocked class as you wrote that https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked?view=netframework-4.7.2 This should work great!
i have come to code-advanced
in mind that somebody
could help me with
Time.deltaTime
heres my script, it is so bad at a low framerate
i have tried adding time.deltatime myself
but it just makes my gun have ALLOT of recoil
!code
also doesn't seem like an advanced issue
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh
only a mastermind can fix this issue my friend
i think i got it tho
i dont got it
Ask your question in #๐ปโcode-beginner with proper explanation and code shared correctly according to the bot message above(use a paste site).
If you think your issue is more advanced than beginner, ask in #archived-code-general
What are some technique of constructing a data structure for a mesh with submeshes WITHOUT using nested arrays?
Once again a restriction of burst. Normally, I'd make an array of lists where X is the material and Y are triangles. Then, when constructing the mesh I'd simply walk through it horizontally and do mesh.SetTriangles(subMeshTris[i], i);
However, since they forbid using nested arrays, I'm kinda struggling
I had two ideas so far, first one to keep a parallel array of size triangles/6 that's gonna be a lookup for what submesh should those 6 triangles belong to, but I have no idea how to transform it efficiently into arrays when I'm setting tris
Another to keep some sort of layout info struct and insert triangles in specific indices instead of appending at the end. So if my info says Material 1 from 0 to 24, Material 2 from 24 to 36 and I need to insert another 6 triangles into material 1, I'd push them after element 23, then update the info struct so that it says Material 1 from 0 to 30, Material 2 from 30 to 42
best way is to keep all datapoints in separate arrays, it is sometimes tedious to work with the various indexes and aligning them but it is the only way to make it performant.
see this library for a nice example: https://github.com/NewWheelTech/geometry4Sharp
I'll check it out, ty. Don't have access to pc rn
What do you mean by "all data points in separate arrays"
An array per triangle set?
no 100% not that
a meshes triangles are just an array of vector3int where the components of the vector are indexes in the vector3[] vertex array.
All other triangle and vertex information is also in such arrays, especially the list of edges, triangle area, normals etc.
Any complex struct you put in such arrays, like edges/neighbours-triangles etc. should use indexes as references to these other elements in an array
do not put any kind of array/set/dictionary inside another, this will destroy your data locality and make everything slow for mysterious reasons.
Right, but Unity's mesh API wants me to provide it with an array of triangles and an integer for which submesh to assign them to
all this enables you to parallelize your operations and pass on incremental results between operations with minimal overhead
unity's mesh api takes a list, an array or a native pointer, which you use depends on what your goals are
My goal is to create a mesh with a bunch of submeshes
Which is where the whole knowing what triangles belong to what sub mesh problem comes from
So Iโm figuring out how to best represent it
probably separate meshes that you combine only for the unity mesh
And the approaches Iโm attempting currently? Would you say theyโre fine?
The ones I described above
@old swallow Don't crosspost.
Hypothetically I could do a vertex pass, record how many quads each material has, then preallocate an array of triangles and offsets and just write directly into the array without moving anything, as inserting in the beggining of the list would move everything. But then I'll have to loop through all points twice
This is starting to look like a leetcode problem I swear
How can I create a curved canvas? I want it to curve around my arm for a watch in VR
Meta has a canvas cylinder but it doesn't render my canvas on the correct side.
The easy way is render a camera (with some UI) to a render texture and plop that on some mesh though events wont work without some extra effort.
With the Quest 2 when I tried using two cameras for rendering it destroyed the FPS
Idk if it was just the additive cameras or what but it was bad
It shouldn't be too bad if one just does some UI only to a non crazy sized texture.
I'll do some testing
Seems like a good starting spot to modify what they have
It's just so bizarre how they never thought to flip the mesh they generated.
I decompiled cities skylines II files with ILSpy (first time doing this) but I can't manage to get a grasp of how the code works for a specific event (like placing roads, buildings, or modifying terrain), am I missing something ? Is there everything in the decompiled files ?
We're not allowed to discuss modding or decompilation here
Oh, ok.
Wait seriously? That's so lame
Itโs illegal
Hi, does anyone have experience building a roguelike upgrade system, like the ones in Hades? For example, upgrades such as โAdd explosive effect to projectilesโ or โYour Special now hits twice in a smaller area and no longer knocks enemies away.โ
Iโve been working on a solution, but itโs not very flexible, and the code is becoming hard to maintain. Iโd love to hear how others have approached implementing this kind of system!
Depends how you're grouping everything. Like each weapon in hades is very unique such that it's hard to create something very modular. However, it doesnt mean attributes like increases to damage cannot be shared with other type of weapons.
Path of exile is a better reference for something that can be considered somewhat modular for an ability system, but even then there's so many edge cases that I do believe each ability in itself is another object type.
Yes, itโs somewhat similar to the system in Path of Exile, or the choice-based upgrades in Team Fight Tactics.
Even though I say each ability might as well be its own object class doesnt mean most of these abilities are re-implementing a bunch of logic that you might have used elsewhere. Things like ProjectileAbility, or AreaAbility can be simply components to these abilities.
E.X. When you cast FireBall -> Invoke ProjectileAbility -> OnHit -> Invoke AreaAbility
I'm doing it on my current project, and it's basically just a matter of making everything as modular as possible.
never assume a behavior is set in stone, everything is parametrized and procedural
expose everything you can as a parameter then just alter them according to stats
it was useful when I was first structuring it to start with a small list of skills that have very different effects or behaviors, melee, ranged, magic, buffs, projectiles, whatever
then try to break them down into as many parameters as possible, grouping whatever you see varying in degree/scale instead of nature (ex: damaging, healing, using stamina, recovering magic, are the same thing, just a resource being altered either up or down)
if you can arrive at a single draft system that covers all that small list without edge cases, it's probably expandable into more
I've tried to do just like a general ability class, but I've ran into some issues when it comes to more unique type behaviours. Even though ultimately it should be possible, I just felt it started bloating up this 'Superclass'.
yeah, it probably needs to be decoupled more
I have a ton of small classes and structs to manage/store specific things, and my main class for skills just alters and points to them
the point is to be data-driven
everything needs to be calculated or fecthed from somewhere, nothing is decided by hardcoding
all parametrized
You can decouple, abstract and parameterize yourself into not getting anything done. Generic systems usually grow out of not having a clear goal. And usually once the goal becomes clear, generic modular system canโt handle it in a comfortable, non-complicated way. โAs modular as possibleโ is an architecture/design smell.
I did say you start with the design, by setting the needs of your system first by having a list of what kind of effects you want the system to achieve
if you dont have a goal for your system, you shouldn't be building it
Fair enough, although I would start with figuring out what the user value is and potentially donโt even build the thing in the first place. Design can be misleading when it is self-defining.
anyway. I think we agree.
yeah we can backtrack that all the way to "should I even be in this career?" but assuming the person wanting to make a system like that knows why they're doing it, I found that doing it this way works well
but it does require an amount of experience
I usually see opportunity to modularize in places where I saw the rigidity being an issue in a previous project
To what end does it work well in your experience? Whatโs the cutoff point where you evaluate that?
that was defined all the way back in pre-production. you have your list of must-go-ins and the system is built around allowing all of those to work without needing to go back into the code to expand it
that initial planning phase is crucial for this
me making things to work with the requirements given to me + what I think it needs to do in future without too crazy ๐
I see rigidity often in two ways; stuff being too scripted, coupled and naive; or, system having an elaborate idea how to properly do the modularity and config and totally missing whatโs actually needed while making changes very expensive
that second one is another issue imo, of planning/project management
that only happens when a programmer sits down to do work without having the demands clear beforehand. that's gonna go wrong regardless of what kind of thing youre attempting
There is never clarity beforehand
when the designers and leads did their work well, there is
the most knowledge of what should have been done is when the project is over
requirements always change, pms always change their mind
Designers are humans and need to work with limited information, requirements change.
if we assume the acceptable way to make games professionally is to just endlessly reiterate on core systems because someone is coming up with new demands I think we'll never agree on anything really
thats just chaos, you cant even talk about "how would you approach x" if thats the expectation
some iteration happens
not this level of not even knowing what your system should be able to do
There is no need to exaggerate
Thatโs just a fact
well
unless you have precognition
if thats your view of project planning
apart from that second case, the first one is the useful one. the one where things are just too scripted and coupled
you built a system for the demands of your current project, its not perfect but it does what it needs, leadership comes with something new a bit too late in and you have to tell them its just impossible because of x an y, but you come out of that discussion thinking what about the current system makes that impossible and how would you do it differently if you revisited it
that kind of accumulated experience is what I find most necessary to build systems like this
Thatโs just my retrospective of whatโs happened in the past. Sure everything could be better, but people are flawed, make bad decisions and we need to be able to deal with that.
I don't conflate "humans need to perfect and infallible" with "theres a minimum accepted level of planning and structure to your production"
I do agree that anticipating these opportunities out of thin air, just gazing into the abyss and seeing the path forward is basically impossible. thats mostly why I think experience in this exact kind of iteration is necessary
this shouldnt be a project for a begginer to tackle
its an useful learning experience, I cant say I havent tried before I could really pull it off and failed miserably
but when you dont know what pitfalls youre trying to avoid by being 'smart' with the system you just over engineer an useless mess not even you can properly use later
Iโve found that even the 10th around the block, you still do stupid things on spec. Nothing is ever right and we can only try to do better next chance we get while guarding against doing worse.
One of those follies is assuming next time we do better by default ๐
I would always assume that โlast time we got luckyโ, otherwise weโd not get the chance to try again.
idk if I find it useful to go with this ptsd-type-talk of "nothing is ever right", mostly because I've felt that for a long time working with games and thought that was just the norm before working in some more organized places that showed me you dont need to accept total chaos, there are better ways of doing this
I think precisely because my experience was horrible that I refuse to accept that as "just the way it is". it was horrible working under those circunstances, I learned mostly how not to do things just by watching projects/people crash & burn, so I try to keep an attitude of "lets try to do our best, entrophy will already add enough chaos"
and there's always enough colleagues that are just straight up bad at their jobs at some level and end up being the source of those issues. its not that common but it does happen, and I found that this kind of talk is their specialty so I avoid it
I had enough producers and leads glady accepting chaos because they werent the ones running around putting out the fires caused by their bullshit, don't wanna sound like them
Hey guys
I got a problem with my gradle in unity
it shows an error
anyone could possibly help?
thx, was kinda not sure if this channel was the place
this is a code channel
hi there. i have a problem with coroutine: My game is working well the following code:
{
yield return null;
// Debug.Log(gameObject.name + ": " + Time.time + " Start Navmesh");
m_EmeraldAISystem.m_NavMeshAgent.enabled = true;
```.
the next fame the Navmeshagent is actived.
Now when the Scene is loaded by the main menu (Continue game) the yield return null completely breaks out of the coroutine. It is simply finished.
Is it not correct to use yield return null?
Thank you very much
Not an advanced issue, but a coroutine is destroyed when the object that starts it is destroyed. If the coroutine is started in the main menu then it'll get destroyed when the scene changes
yield return null
would just halt the execution of things below until the next frame starts
...yeah if it just breaks on loading another scene it's because it get destroyed with the object
yea unity will not continue its execution if the monobehaviour was destroyed. async functions do not act this way and you must stop execution manually when you wish it to (or use cancellation tokens with delays/waits)
how do i apply modification to prefab.renderer.sharedMaterials ? (unity editor script)
PrefabUtility.RecordPrefabInstancePropertyModifications(prefab) doesnt seem to do anyhting.
not working too.
tried it :/
maybe im doing something wrong can someone check please. im stuck here.
// Create materials for the model's renderers
Renderer[] renderers = prefab.GetComponentsInChildren<Renderer>();
foreach (Renderer renderer in renderers)
{
for (int i = 0; i < renderer.sharedMaterials.Length; i++)
{
Material material = renderer.sharedMaterials[i];
if (material != null)
{
string matName = "exported_mat";
string materialPath = Path.Combine(materialsDirectory, matName + ".mat");
materialPath = AssetDatabase.GenerateUniqueAssetPath(materialPath);
Material newMaterial = new Material(material);
AssetDatabase.CreateAsset(newMaterial, materialPath);
renderer.sharedMaterials[i] = newMaterial;
}
}
}
PrefabUtility.SavePrefabAsset(prefab); // i tried many things here
how could i have possible break my unity so hard that it runs code of a component i delete during runtime
Destroying a component doesn't delete the C# object part of it. If you still have a reference to it and call a function, the function will still run
You'll have to show the specific details if you need more help than that
even if the reference is missing and the gameobject is disabled?
Yes that's exactly what Destroy does
"missing" means simply that Destroy was called on it
so its destroyed, gameobject is disabled and its normal for the code to keep running ? huh?? am i missing something here
The C# half is still there
You need to be very specific about what "the code keeps running" means
If you call a function on it, it will run
Update will not run
ye its a function, not Update. I have a script and it Instantiates something, i was testing things, during runtime removed the component in the inspector and noticed it was still Instantiating things
so to confirm, that is normal behaviour ? what would i need to do to stop it from Instantiating things? Disable the component instead?
It's normal behavior
To stop it instantiating things you should stop calling the function that instantiates things
thats the only way?
what if its an enemy the player can destroy?
record changed property after assigning the material, it should mark the prefab as dirty
wdym ?
sorry, the api is little bit confusing obscure with 1mile length function names
I don't know how to make it more clear. Nothing on the Unity side matters here. You have C# code running a method on another C# object. Unity isn't involved. Nothing about "destroyed" or "disabled" is relevant, these are all Unity concepts and the Unity engine isn't even really involved.
If you don't want the code to run, don't run the code.
i think i understand
for me its input related, should probably ask in input for further questions but i was handling input and was wondering how the input was being processed when the component doesnt exist anymore, but if you say Update etc wont run if i delete it, i think it makes sense
Show the specifica details here
which object is hte input handler on?
How did you set it up
Did you forget to unsubscribe your input handler when the object gets disabled?
PLEASE IM LOSING MY SANITY.
You can't do:
renderer.sharedMaterials[i] = newMaterial;```
every time you call renderer.sharedMaterials it creates a new array
you need to store the array in a variable, modify the array, then write it back
Material[] mats = renderer.sharedMaterials;
// modify mats
for (int i = 0; i < mats.Length; i++) {
mats[i] = whatever;
}
renderer.sharedMaterials = mats;```
@sly grove my god yes thank you that was it.
Hi @devout hare , @frigid orbit, @echo coral: thank you for answering. Yes what you say is right and know to me.
I found the root cause of the problem. For some reason during gameplay an invalidAABB object is created (I guess a ragdoll falling through the floor or so). This causes (at my version) of Unity to totally misbehave: coroutines are not working anymore and some other stuff. I have nails this down to this several times in my game but so far i can not create a reproducer for Unity.
If you google for invalidAABB you will find some threads which discuss problems in this direction. The physic engine breaks, at least this is what i understand
- Graphics.RenderMesh doesn't seem to do anything in urp. The only solution available on google didn't help - https://discussions.unity.com/t/graphics-rendermesh-doesnt-work-in-urp/918319. I'm 101% confident that correct mesh, material and rendering layer mask are passed. The meshes also display correctly if i assign them to renderer components instead. The docs on renderparams are as useful as telling me that its constructor is a constructor. What did i miss?
// _material is passed from outside
RenderParams renderParams = new(_material)
{
renderingLayerMask = GraphicsSettings.defaultRenderingLayerMask
};
// down the line after some validation and calculations
Graphics.RenderMesh(renderParams, face.Mesh, submeshIndex: 0, matrix, matrix);
Are you sure the matrix is correct one and doesn't yeet the object somewhere really far or shrink it to nothing for example?
- It's just a translation. Unless something is off with unity's Matrix4x4.Translate() code, it's correct
- The input vector is, anyway
omg
what?
- It turns out that my script was pausing the play mode, hence halting the update loop, hence not dispatching any mesh rendering calls
oh...
- Dang it i hate to feel stupid but i do
If I wanna reduce my webgl build size, is it best to tackle the uncompressed build sizes from the build report? or is there another way to see what's taking up most of the space in the final build?
I did a production build a few weeks ago and it was 35mb zipped. Did one today and it's 75mb zipped - but I can't recall the addition of any substantial sized assets since then. The build report shows uncompressed sizes but I'm not sure if these are the biggest problems
Uncompressed size will unfairly count easy-to-compress objects
I'm not sure how you'd figure out the space taken up by compressed assets
it's a non-trivial question, since if you include 100 copies of the same image, that compresses amazingly
I'm mostly just trying to get the build size down because it's a webgl applet.. I'm already using brotli compression
maybe this should be "disk size"?
-------------------------------------------------------------------------------
Build Report
Uncompressed usage by category (Percentages based on user generated assets only):
Textures 132.6 mb 74.9%
Meshes 5.0 mb 2.8%
Animations 8.3 mb 4.7%
Sounds 25.0 mb 14.1%
Shaders 2.1 mb 1.2%
Other Assets 3.5 mb 2.0%
Levels 0.0 kb 0.0%
File headers 270.9 kb 0.1%
Total User Assets 177.1 mb 100.0%
Complete build size 74.6 mb
Used Assets and files from the Resources folder, sorted by uncompressed size:
Unfortunately this doesn't really tell me enough - I can take care of the worst offenders in the uncompressed size but I don't know if that's actually even helping aside from rinse-repeat-observe (which takes forever for production builds.. like 45min per iteration)
2.7 mb 3.6% Built-in Texture2D: Splash Screen Unity Logo
also this - how can I kill this ๐
we do love the Splash Screen Unity Logo
i remember seeing someone have a problem with it being included even after disabling the splash screen
yep, that's the case here
iirc there was another setting that had to be turned off (that could only be accessed while the splash screen was enabled)
(wasn't me complaining about it originally)
i do not remember anything more specific
hm, that's useful though, lemme dig
this is already disabled but i'll look for another place it's in the settings perhaps
oh yeah
try turning on Show Splash Screen
then uncheck "Show Unity Logo" in there
I believe you can display the splash screen via script
maybe stripping more code too
so it vaguely makes sense that it'd still be included in the build
it was already empty
oh wait, it was enabled! disabled it and then unchecked show splash screen
2mb saved ๐ฐ
I'm removing some possibly-unused packages as well. I have one that's in almost all my projects but I don't think it's in this one. Is there an easy way to see if a component exists on any prefab in the project..?
This seems like it..? I'm just surprised the search was instant, given the amount of prefabs and files in the project..
Yeah, turns out I am using it in the project. Removed it and found out the hard way. ๐
Hey guys!
I'm hesitating of putting this here or in physics, but here I go:
There is a spherecast from point A to B. All the renderers that you see on screen have a properly setup box collider.
My spherecast's radius is pretty small, BUT for this case it looks like it starts inside the ground collider, which makes the cast not hit it.
What would be a good fix? I would very much prefer not having to do a spherecast + a raycast.
And spherecasts are must have for my case
No clue what I'm looking at but you're correct that spherecast will not detect if it starts in the collider, so to supplement it, do an overlapsphere query as well
I've managed to fix it via another way (that didn't had to do with complexifying the cast process)
But you're right, this is a good way, thanks
Overlap capsule is similar to a sphere cast in its effective shape.
CheckSphere for my case would've been sufficient
For some reason the new search does not tell you its indexing so you first get the "no results found" until it can actually search for real. How this was not caught is beyond me ๐
and in the mean time you can put the same query into the old project window search bar and it'll come back instantly most of the time 
another botched feature that doesn't fucking work properly. They need to learn to remove the old shit to make the newer things work better
Hello friends!
I'm testing for race conditions in a project and I need a way to artifically delay addressable loading by any amount of seconds (hence "simulating" slow loading of addressables)
This is a very simple thing to implement everywhere else but for addressables I have not found a proper way yet - I assume it has to be very easy but I'm not sure where to do it. Simply creating a wrapper for every addressable.LoadAsync call is not enough because it returns a handle, which I can't seem to trivially copy (if i wanted to return a "fake handle" with delayed completion events). Is there already a feature somewhere in Addressable to add an artificial delay? Should I be hitting somewhere else, e.g. lower level?
you CAN make your own handle and complete it after a delay but it's a pain, if it's possible to use the Task to wait for loading instead of events that's a lot easier to add a delay to
You can try simulate groups but i've always had it bug out. Else build the content and do "use existing build" to make it take a bit longer.
And as simonp says, if you use async instead its a lot easier to add a fake delay after loading
Unfortunately currently the Addressable Load is called synchronously and is not awaited, the callback is used to trigger the rest of the code, none of the way it's implemented in the project uses the Tasks API
When you copy the handle, do you simply need to reimplement the three events of it, or is there more subtlety to it?
Do I need to do an Authoring or Baking class for every component I use, or can I just have one Baking for a ton of components?
it needs to interact properly with the resource manager/reference counting stuff so you don't accidentally extend the life of the resource iirc, it's been a while since i touched it but it's not trivial
if you use a callback its not synchronous but its certainly harder to add in some delay when its not async already.
Checkout UniTask or Unity's Awaitable (2023+)
Do you have a snippet or something I can look into?
The way I look at it since the handle has its AsyncOperationHandle reference stored internally it's not possible to trigger e.g. the Completed event externally unless using Reflection, this looks like it's gonna be a big mess! ๐
Kinda disappointed because I thought Addressables would have an easier way to inject a delay into it for testing (or to intercept the return events), now it kinda feels like a black box
I suppose there's no way around it and I'm gonna have to reimplement my own struct / return type for Addressable Load async with callbacks and stuff
๐ this is why we use async
public async UniTask<T> MyWrapper<T>(string address)
{
T obj = Addressables.LoadAssetAsync<T>(address);
await UniTask.Delay(250);
return obj;
}
yeah, async is much easier to compose stuff like this, we avoid using the handles directly in most cases
(This is unrelated to what I'm asking...? You're just delaying returning the handle here, you're not delaying the callbacks of loading the actual asset?)
im not returning the handle, its returning the loaded asset
Sprite mySprite = await Addressables.LoadAssetAsync<Sprite>("foobar");
๐ค alright, looking at the signature i thought you were returning a task
Ah yes and then you're awaiting the whole call
Okay yea, I get what you mean unfortunately it's not gonna work on this existing project, callbacks have been used everywhere
If I'm gonna redo the whole implementation of it I might aswell implement delay differently
Yea this is why its good to start using async as it is more flexible in the long run
Although... Maybe I can wrap the call and make it a task call, then switch back to the main thread to send the callback
will look into it
this will be on the main thread when the task completes
UniTask delays are made to work with the player loop events so are also main thread safe
this is why we dont use Task
this is also true of Tasks!
Do task delays use the same thread synchronisation context then? probably not a good idea to use with unity anyway
Depends how you start them ๐ On unity default task scheduler this is true
awaiting a Task always stays on the same thread, it's not about what you await
but Task.Run for instance will not do it that way
That's only true on Unity scheduler - on the standard .Net scheduler, each time a task is awaited it switches thread (new Task() vs Task.run())
Task.Run schedules a task to run on the threadpool so it may run on a separate thread. just starting a task by invoking its method will start it with the current synchronization context
right but we're talking about Unity here, you generally don't switch threads without doing it deliberately here because there is a sync context on the main thread
there's a lot of FUD around accidentally doing something on a background thread with tasks and it's hard to do it accidentally haha
No sorry I didn't mean to spread FUD :P
It's because on the project I'm working on, a lot of Tasks are used but none of them on the Unity scheduler - they're used to e.g. Disk operations or Network operations, and then the result is enqueued on a pump routine that runs on the main thread, started by Unity as early as possible
So we exclusively use the dotnet Task scheduler, and I do find the Unity implementation of the Task scheduler a bit awkward because everything that is true of tasks in any c# project becomes false if you run them on the unity sched, and the other way around. Hence the confusion I think
For instance - new Task() will run on the current thread and will block *until awaited*, but Task.run will run on the task scheduler (on a different thread) and not block even if not awaited
Or - a task started with new Task() and awaited; will always return on the thread of origin, while a task started with Task.run will always switch thread when awaited; because the wait will move the task to another thread as to free the current one. Etc etc
If you mix "unity scheduler" tasks and "default scheduler" tasks on a same codebase it quickly becomes a mess because they look identical but their difference in behaviour will kill you if you don't pay a lot of attention (e.g. if you're used to running tasks on another kind of c# project, like winforms or wpf)
isn't this how it works in WPF too, where there's a UI thread with a sync context?
Its a whole different beast than the Unity scheduler but yea it has its own uuuuh caveats
i don't think the rules of async are that complicated really (and you still have to follow them with UniTask or Awaitables, it's just slightly different), unity doesn't do any magic beyond what C# on its own allows
you can implement a sync context like the unity one in a few dozen lines, i've done it for a non-Unity project haha
confusing and complicated are very different things!
Tasks are fine, you just dont have control of whether it will return on start of frame OR end of frame, it's out of sync.
Making your own dispatcher the poorman's way by doing while(ConcQueue.TryGetValue(out var output)) in Update method is like 5 minutes of work
Or just use the PlayerLoop api, like what UniTask is doing
Unity uses singlethreaded custom syncContext, as long as you await it it will be back to mainthread automagically
Note, that does not apply to Task.Run..
fwiw there's the Awaitable api now for a built in way of waiting for different parts of the player loop like a coroutine, and you can mix and match it freely with regular tasks as needed
yeah, was just saying that the regular Tasks are still usable in Unity
making your own zero-alloc tasks is easy, there's AsyncMethodBuilder then make your custom awaiter be a struct
here for your reference, incase you want to make your own custom zero-alloc tasks https://devblogs.microsoft.com/pfxteam/await-anything/
note, that's using INotifyCompletion, you don't want that, you want the INotifyCompletionCritical for perf and make it struct-based
For the AsyncMethodBuilder sadly this is sort of hidden from the internet, you proly having a hard time looking how to use it, I suggest just go to net runtime repo and look for the impl there
zero-alloc tasks ain't something new outside Unity ๐คค, I'm surprised that UniTask being the 1st and in just recent years ๐
I've got.. a hard to debug issue.
I have a webgl app that we're just about done with (thx for all the help in the last couple months). The dev builds are 175mb and load pretty quick. I just did a full compression build and got that down to 70mb.. the problem is it hangs on the loading for like 30 sec (the dev build loads instantly).
I don't even really know how to begin debugging this one. The browser console is quiet during the burp.
(happy to link to a itch.io build if you wanna .. see if anything is obvious)
That's a snap of my console log. The hang appears before the very first [UnityMemory] line
I typically make a MonoBehaviour to store my Scriptable Objects instances.
Would it be a better practice to load them up directly doing something like this?
List<T> scriptableObjects = new List<T>();
string[] guids = AssetDatabase.FindAssets($"t:{typeof(T).Name}");
...
Note that this only works in the editor
Ahh.. thanks!
I do something pretty similar though
using UnityEngine;
namespace Pursuit.Singletons
{
public abstract class SingletonSO<T> : ScriptableObject where T : SingletonSO<T>
{
private static T _instance;
// only really needed for the editor when Domain Reload
// is disabled.
public static bool InstanceExists => _instance != null;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Resources.Load<T>("SingletonSO" + "/" + typeof(T).Name);
_instance.OnLoad();
}
return _instance;
}
}
public static void ClearInstance()
{
_instance = null;
}
protected virtual void OnLoad()
{
}
}
}
It pulls itself out of a Resources folder
Yeah I see, hmm.. not quite sure what I prefer, upside is to not to have to manually add them I guess.
Some of my singleton scriptable objects are "catalogues"
which just hold a bunch of references to scriptable objects
I did this as well, although we moved away from it .. I can't recall exactly why but something-something-dont-use-resources-dot-load?
Do your singleton SOs need to be in the /Resources folder?
That might have been it - a large dump of files in the resources folder made it so unity automatically packaged them up with builds, even if they weren't being used anymore? Although to be honest, I think even SOs force those resources to get loaded, even if you don't consume them anywhere. (We're actually just going through our project right now and trimming out the SOs that hold references to all the SFX and music .oggs)
unity learn ๐
Bump โ๏ธ
https://civilization-ai.vercel.app/3d
I made this city, i took an asset, bought it and uploaded it to Unity, then i exported it in GLB and placed it in my code.
My goal is to have this city to expand as citizens will start spawning depending if people buy or sell my coin (Yes this is something from Blockchain)
I already have the API that gives me this information
I dont know if is possible to have it directly in unity and somehow show the game live 24/7 expanding
Or to do it separatly and just do it from the Typescript side of things
Civilization AI Dashboard
It could be due to the compression and having to decompress many assets at once?
Could be? How would I debug/investigate that..?
It also loads instantly the second+ time so.. that sounds possible, but I'd like to improve that since obviously the first time load time is the most important
I think webgl builds use webasm for code but im not sure how debuggable it is
check the network tab to see if its actually downloading something?
Usually if I ever have problems related to WebGL, it's usually texture or shader stuff
it loaded pretty fast even though i disabled the cache but still paused about 2 sec
looks like just downloading the wasm and data files - about 4 sec for those
nothing like the first time around though - it literally hung for ~30 sec on my machine
Would anyone be willing to open the network tab and hit my link and snap a shot?
You got it hosted? Drop me a link and ill see how it works with my firefox
I'm not sure if the webgl builds work with firefox but lemme know what happens
https://rsnail.itch.io/mechmice - password "flank"
wait wrong password i think, sec
ok
chromium browsers have it enabled by default
the password is right so if anyone else is willing to have the network tab open for an initial load and lemme know if you have a burp at 80% load - i'd โค๏ธ you long time
ill also test on firefox
chrome loaded it in 5 seconds
mine took ages to load
Yo guys i have a question
https://civilization-ai.vercel.app/3d
I made this city, i took an asset, bought it and uploaded it to Unity, then i exported it in GLB and placed it in my code.
My goal is to have this city to expand as citizens will start spawning depending if people buy or sell my coin (Yes this is something from Blockchain)
I already have the API that gives me this information
I dont know if is possible to have it directly in unity and somehow show the game live 24/7 expanding
Or to do it separatly and just do it from the Typescript side of things and website
Civilization AI Dashboard
i tried it with chrome throttling (3g) and it looks like it's just a download speed thing
but network took like 3 seconds?
Mine loaded when bar was 1/3rd ;p
ok well if it's just network and data transfer.. i guess that's fine, i'll just get back to optimizing the textures to be multiples of 4 on each dimension and so on
im not sure it is network, it took like 30-40 seconds the first time but my internet isnt slow
What's your question?
Yeah I uh.. don't really know how to repro this. My first load took 30+ sec and I have gig+ internet
If its possible to implement live api information being fed into a unity game that will be in the website updating and adding/removing assets 24/7
With animations and everything from unity itself
Is your question "can you call a web api with unity"? (the answer is yes)
Is your question "can I make a game server in unity"? (the answer is also yes but "probably don't")
what format are your textures mainly in? Are most pow2?
I see, why not to the second question?
the biggest are oddball sizes but I'm going through and making them DXT compression capable (mostly just adding a bit of white/black space to the edges of the big ones)
Yeah, I see the hanging, but I mean we are downloading 180 mbs here so expected.
Because unity is a client - all the libraries and stuff are geared towards people interacting with it .. input, sound effects, drawing things on the screen. If you want a server, make a headless C# application to do that
loading bar stuff never accurate
Yeah it was more the 30 second "hang" that I was worried about since my computer and network are both pretty fast
Cool game though. I've been playing around a bunch with webgpu and it's pretty cool what we can do with the browsers nowadays
I shouldn't experience that - and certainly if end users do, they'd just bail and be like "shit's broke"
yeah, thanks .. i'm also impressed with the framerate and stuff.. honestly it's pretty responsive
(i worked a lot on the camera controls but I don't know if they're quite "there" yet - feedback welcomed)
zoom in and out with mousewheel, move camera around with WASD
oh well i give up.. i've reloaded it a few dozen times and load times (without caching even) are <350ms or so which is fine
be glad that unity has good batching. I was doing something in playcanvas (i needed to "port" a unity game to it) and performance was often an issue
Thanks
yeah, I honestly was doing the preload thing (I dunno if you see the error messages in the browser - "preloaded content wasn't called") but it turned out to be mostly unnecessary
I was going to preload the data and wasm files somewhere else (maybe on the main website homepage)
What would to do to implement what Iโm trying to do?
Essentially is a city that will grow based on holders of a token on the blockchain (specifically Solana)
I just want the city to be dynamic and citizens to be shown and added as holders of the token grow
i still could, but I didn't wanna deal with the cross origin stuff
You kind of compress that build right? the 30sec gap may be connected to uncompressing the build or so
dev build runs quick as u said, and its uncompressed
This isn't a code question, let alone a code-advanced question. You want to build a server, google up "how to write a headless C# console server". You'll need to learn about databases, servers, cloud hosting, networking.. all kinds of stuff, completely unrelated to unity.
yea was my thought too, perhaps its cached somewhere hence it not happening again
Yeah, that's compressed
The uncompressed build is like 175mb
I see, thanks
and the 30sec gap only happens for compressed build?
yeah, but I can't repro it
it just happened once for me this morning, and once for my coworker this morning
u cant repro it because it may happen only once then its cached
but i've tried incognito, clearing cache, etc - can't seem to make it happen again
uncompressed once then cached
could be somewhere else
i hate these random sorts of "this thing happened once" issues
anyway, i'm gonna call this one "cannot repro" and move on with my life I think. ๐ Thanks for the eyeballs boys
Hmm it took about 9 seconds in chrome the first time. May be best!
im free after 30 mins, so i can do some tests with plsywright and stealth mode
appreciate it - but just about to head out to pick up kiddos and that's the end of my day.. honestly it's probably fine.. it's just a web demo for a board game, if it works reasonably well and makes sounds and looks like a game, then it's good enough ๐
I won't change the password on the link above though if you wanna try it out - @ me with any bugs/comments
@misty glade didn't had to set up Playwright, the lag comes from downloading, and it just looks like a lag bc the progress bar load slowly for just downloading, i ran it like 10 times, each time on fresh browser instance, its all the same as on video
Preloading it would be good
Probably has to do with compression
it's not just downloading, but preloading the first scene
not familar with web assembly but yes it may be the case, compression require the whole build to decompress but for uncompressed dev build it maybe starts load while downloading ๐ค
Thanks for this video! Yeah - I mean, I don't know that I'll be able to speed up people's download speeds, and we're working on optimizing the data and wasm sizes already .. but that's not exactly the issue I saw.. it was like a 30 second "everything is frozen" when the progress meter was at 80%. It might have been a compression thing? I'm still not really sure, tbh.
The page you're looking at there is the release build (compressed and optimized for disk size)
And yeah, I'm getting the exact same slowness on the initial download
(I did another production build today)
ugh 53 sec
Do you have it accessible somehwere or is it local?
yeah, want to try?
https://rsnail.itch.io/mechmice password is "flank"
I just uploaded a new build but the download for the data.br file is super slow.. I don't know why
44.74 sec for a 64mb file
see yours is instant
i wonder if this is an itch.io thing
(ie, caching a file on their side?)
if i reload the page it's instant-ish as well
2 sec
can you click on the data thing and show me the timing tab?
i think honestly it's an itch.io thing but.. short of reaching out to them and asking details about their webserver configuration, I don't know that I really can repro it (or care?)
i already reloaded the page, unfortunately so all I have is the screenshot above
my 2nd+ page loads are instant now
โ๏ธ this one
yeah, you can click on the data file there and select timing
it shows you a breakdown of what took how long
tested now from wsl Ubuntu chrome
ah, cool.. uhm.. wish i had done that for the 44 sec load
press ctrl + shift + r
should clear your cache
otherwise an ingocnito window will help
it's still instant
same thing - i couldn't repro it this morning
actually lemme try something else - I'm going to replace the build with an older one then see if i can get the slow initial load
standby
can you show me the timing thing on that data.br file?
oh yeah that's another thing. Itchio be limiting the bandwidth. It's crazy how generous they are allowing you to upload/download gigs worth
ok i have a slow load! which is good - now i can at least repro the issue
lemme let it finish then i'll snip the timing tab
Still better than most Godot web games I've seen haha
whats your internet speed?
yeah cause now its cached
probably itch.io server limits downloading speed
ok well.. i suppose that just means all i have to do after releasing a version is just hit it once myself and force itch to cache it
no local cache ๐
not itch io cache
hm? i'm not caching it locally as far as I can see?
your browser stores it for however long itch ios cache time is to ๐
("disable cache" at top)
cache is disabled but its stored somewhere
i mean i could test this by ... releasing a build, having someone else hit the page (and see if it's slow), then release another build, precache it myself, then have them hit it (and see if it's fast)
oh true, its a 200 response
itchio does do some sort of initialization for first uploads, but it usually tells you on the window itself
yeah but ... i can go through that workflow and it still "works" fast (as long as the page has been precached)
is it while your game is loading or can you already execute scripts before?
If so just show a loading screen
i think it's honestly a static content thing on the itch.io side
or maybe their CDN or something
nope - my program entry point isn't hit .. unity/webgl is still bootstrapping during the content download
Yeah, I'm ... done exploring this one. I think I'm just gonna chalk this up to some idiosyncrasy with itch.ios CDN and/or brotli streaming (I don't completely understand why the headers need to be different).. it "works" and it seems to work reasonably well as long as I hit the page once myself to get it to cache for other people so.. yeah. ๐คทโโ๏ธ
again, huge thanks y'all for helping me test
Web frontend has the concept of code splitting, I wonder if Unity can do something similar.
Latest production build is down to 45MB and I think I'm past the low hanging fruit now. I've removed all the unused packages (including unity packages), trimmed all the unused sound and texture assets, made all the largest textures n*4 pixels on a side, and built the app with brotli and optimized it for disk size (it takes 30 minutes to build and link lol).
Any other ideas on optimizing the build size? Googling around hasn't really shown me much aside from the above.
I do see some of the shaders and textmeshpro assets are quite large.. Any optimizations I can do with those?
You can remove any and all unused glyphs from TMP font assets you're using I think? (not an expert)
Shader variants can definitely get really big (it's exponential growth!)
I'm still figuring out how to properly profile that
Hm.. I am not actually sure how to do that. A lot of the text in the game is dynamic, and I have some library that I installed (it's small, like 40kb) specifically to rebuild the glyphs completely.. I probably have too many fonts - I have like.. 6? With a few different variants for different uses.. shadowed, outlined, distance SDF etc
In retrospect maybe I should have enforced a bit tighter design around that
(it's probably too late to change fonts throughout for similar use cases)
-------------------------------------------------------------------------------
Build Report
Uncompressed usage by category (Percentages based on user generated assets only):
Textures 46.7 mb 57.8%
Meshes 5.0 mb 6.2%
Animations 8.3 mb 10.3%
Sounds 15.0 mb 18.6%
Shaders 2.1 mb 2.5%
Other Assets 3.2 mb 4.0%
Levels 0.0 kb 0.0%
File headers 266.7 kb 0.3%
Total User Assets 80.9 mb 100.0%
Complete build size 45.0 mb
The shaders don't seem out of control.. they're just text, too, right? ie - should be compressed really well?
animations seem kinda large
I only have 10 meshes, each with .. 8-ish states? that doesn't seem like it should be that big
ugh.. this one should be fun. Not sure how to debug out of memory errors in the applet. Any tips?
is there a way to use index geometry types other than triangles?
I'm in a specific case where quads are a better pick
because quads get converted to tris anyway
it's all triangles at the end of the day
really? even in like low level OpenGL?
wdym use index geometry types
are you talking about 3d modelling?
or using unity's GL?
well I mean I'd be using them for cubic mesh generation
yep it's converted to tris, there's a documentary about how Minecraft mods optimised cubic mesh generation
doesnโt that take some workload off of the cpu though
triangulation is done on CPU unfortunately
ah
all the vertices sent to GPU are tris
sad
the talk on having GPUs use quads over tris ended a long time ago
one more thing, is there a way to make AssetDatabase.CreateAsset not refresh the database every time itโs called? it makes tasks that need a lot of asset creation take way too long
Disable the automatic refresh in settings, might do it
if you mean you want to stop the asset database from refreshing for the duration of some task that is modifying/creating many assets, then use the StartAssetEditing and StopAssetEditing methods to pause the refresh for the duration so that it won't try to import any of the changes until you are done
oh shoot alright
Seems like you can use the profile with webgl if a dev build + auto connect is enabled. May be your best shot to see what the issue is
I am trying to convert a bunch of Graphics.DrawMeshInstancedIndirect to CommandBuffer.DrawMeshInstancedIndirect, but the CommandBuffer version don't have shadow receive/cast parameters. How do I replicate the parameters?
Hi everyone, this is a bit more of an open ended question but the way I am working on a game with procedural terrain, so far I am genering a bunch of noise on the GPU using compute shaders and then passing these in to the CPU for actually generating the cells that make up the world. However the more I do this the more I'm now wondering if this cell generation should be done on the GPU too.
The problem I have with this is that since the GPU can't do inheritance managing biome logic seems to become harder, right now I am generating the biome through the GPU noise textures and then depending on the result I am calling a overridden method called "SampleBiomeCell" in the biome class, which has specific logic to check what kind of thing should be appearing.
Is this the correct way of doing this, or should I really be doing the whole thing on the GPU? And if so what is the suggested approach given that their will be alot of branches introduced into the code depending on how many biomes exist in the game?
Sure, I recently used this to draw some quads:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Graphics.DrawProcedural.html
This replaces it in newer versions but I didn't use it yet:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Graphics.RenderPrimitivesIndexed.html
well you can use cpp code if you build it as a lib but ofc you cant really interact with anything
I went deep in the google hole last night and learned about the limitations of memory with wasm/browsers.. I couldn't find recent threads but I also could repro my memory issue so.. ๐คทโโ๏ธ
I'm gonna try the unity memory profiler today but I suspect(?) that I won't find much. Cuz you know, my code is impeccably clean and bug free. /s
Its probably graphic memory related. Its actually easy for textures and other assets to never be released from memory (you have to do Resources.UnloadUnusedAssets if not using addressables).
Sometimes managed objects also leak but you will be able to see these in the memory profiler
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Resources.UnloadUnusedAssets.html
Hm.. Not sure that will help my app? I only have 1 level and so "all" the textures are pretty much in use through any session.
I mean, I have 3 levels, but all the units exist on all the levels, so there isn't much loading/unloading going on
hmm well when you profile id be intererested to see the gpu memory usage
it does have native plugin support, thats why a game like Genshin Impact can make their own multithreaded renderer
well I meant more like complete interfacing with the actual engine. also didn't genshin impact literally receive the source code of unity under unity enterprise?
not sure if enterprise licence covers that, perhaps.
yeah thats enterprise
aight nice
is there a way to have packages for one build target but not another?
well you can have define constraints for assembly definitions, could do it via this
It doesn't seem like I'll be able to get that granularity.. from https://docs.unity3d.com/6000.0/Documentation/Manual/class-PlayerSettingsWebGL.html it says I'll just be able to see the wasm heap & used heap sizes
you didnt try yet?
Yeah, I mean, I know about the define constraints but I'm specifically looking at the memory profiler package, which is an editor thing
try what..?
I'm gonna do a dev build with the diagnostic overlay enabled and see what it shows, but .. from the page above, I think I'm only really gonna be able to see a big number of memory used/allocated.. but not much insight into what is soaking the memory
the chrome memory snapshot tools are... cryptic
I dont think its a concern with the memory profiler package it has 1 runtime class
yea you wont get anything useful from a wasm mem dump
for the memory profiler it's more that I wanna aggressively reduce the build size.. i got it down to 43mb but i don't think I can (easily) get it much smaller
just add it temporarily to test this out and remove later
reimporting all the (100+) animations with some more aggressive keyframe culling would help but .. probably only a few mb
you dont have to upload the build to itch io just host locally
i haven't been able to get that to work unfortunately
(i don't have a local kestrel/server instance and the unity "build and run" one's never worked for me)
re: UnloadUnusedAssets() - are you proposing doing that.. at runtime? like, sometime after the game "loads"?
Ideally you use that after you know that many things are no longer used e.g. level change or something else.
Ofc if you load any textures yourself then you should destroy them manually
yeah.. unfortunately there's only one real level and i use all the textures/meshes/models in it (like, even when a unit dies it stays on the field)
although maybe I could try it out after bugs die.. i dunno how much savings I'll get but it's probably worth a shot
Id still aim to get a memory snapshot with the profiler. use a win build if you must
k, i installed the package, i'll do a quick snapshot in the editor
will have to bounce shortly for meetings (joy)
I want to dig into this too - there's a chrome performance profiler where you can load a page and view what's taking cpu/gpu time
in-editor memory snapshot
looks like mostly textures - rendertexture and texture2d
as it warns you, its not a good representation of the real build
ah, yeah.. ok i'll do a windows build
Most i have done with this is investigate when textures are not unloaded on android builds which it can help with.
You can use it also to see when a managed object for an asset is not GC'd (they can leak in odd ways)
Anyone have any idea how to handle 3d unity spline intersecting/self intersecting? Especially with thickness/colliders. Such as pipes or roads?
Trying to block paths for a in game editor. Curious what game devs have used
Has anyone figured out how to work with the new Behaviour Graph and Navmeshes with ECS? Do I make components of everything and sync it with a GameObject or do I use the game object inside a component?
What is the less latency way of getting a tap/click? Unity GUI vs new Event System vs some custom subsystem thingy?
any insights on this? ๐ค
None of them have significant latency
Per https://docs.unity3d.com/Manual/webgl-memory.html at the bottom it says
Note: When you use C# delegates or events such as Delegate, Action, Func, these classes internally utilize similar linear growth allocations as above. Avoid excessive amounts of per-frame delegate registrations and unregistrations with these classes to minimize the temporary memory pressure for the garbage collector on the Web platform.
Anyone know when the webgl GC is run? I occasionally have 10-20 GOs that have a lot of action listeners in OnEnable and OnDisable but can't really tell if it's problematic. I'm assuming there's some time given every frame?
They're saying to avoid registration every frame
Doing it in OnEnable/OnDisable is ok assuming you're not constantly enabling/disabling these things
calling the registered delegates doesn't cause GC
huh didnt know about these problems with when GC can run on webgl but makes sense ๐ค
Might be a bit too technical, but here there is a kinda explanation on when a delegate allocates and when it doesnt
https://www.jacksondunstan.com/articles/3765
(taken from PrimeTweens github)
JacksonDunstan.com covers game programming
See, this is why I pool references over using delegates, not because I'm lazy or anything
actually makes me rethink how I'm using a lot of my tween class. Can't exactly ref values in a coroutine so I'm pumping out a ton of delegates to get some type of return value
This is useful. This project was such a hurried pos that I have some.. stupidly hard coded references to entities that the whole app uses that use find over (admittedly small) collections
It's entirely likely that an average frame is calling these new()'d up delegates 20+ times per
You using your own tweening classes? or Dotween? I have a pattern that's worked pretty well for me for sequences/tweens/coroutines so they aren't left hanging if you want it
(ping me if so - am mobile now but can grab a snippet if you want)
public static IEnumerator SmoothStep(float from, float to, float duration, Action<float> onValueChanged)
{
float elapsed = 0f;
while (elapsed < duration)
{
elapsed += Time.deltaTime;
float t = Mathf.SmoothStep(0, 1, elapsed / duration);
onValueChanged?.Invoke(Mathf.Lerp(from, to, t));
yield return null;
}
onValueChanged?.Invoke(to);
}
Kinda what I do with my util class
I can actually just wrap the value types in a ref type now that I think about it too
just that you can't actually use the ref keyword with how coroutines work
pooling delegate is useless, they're immutable. and you'll always have to to pay for shrunking/expanding the backing array
Action<ref T> is illegal today, but you can roll your own public T delegate(ref T)
or if you insist on using Action, you pass a span on it like so Action<Span<T>>
is there a discord or channel somewere for A* pathfinding pro?
i know he has a forum - but forums are so old fashioned !
that project is a third party one, we don't have specific channel for it here. #๐คโai-navigation is for anything navigation so you may try your luck there. If the problem you are having is very specific to the third party asset, you should seek for help on their own forums
how to solve this issue? the issue causing a lot of time..
Did you follow the link in the log and check those troubleshoots?
yes
but failed
do i have to run the unity game on real device instead of trying iOS simulators?
It does need a working xcode project for both, simulator or real device. So there seems to be something wrong with your xcode. Did you update xcode and your system?
yeah, i updated xcode to the latest version
You could try to remove and readd the ios package
unity 2020? That could just be way too outdated
alright. i will 2021 version, then
no go to 2022 now, 2021 does not get updates anymore
this is 2021 version for another unity project which uses admob too. does it seem ok?
So many things change through xcode versions, the very old unity version just might not be able to export correctly
ohh, alright. i will do so
i get it now. totally get it.
also pod install failure can either be depencencies that could not be resolved or missing cocoapods installation.
if cocoapod install fails the workspace also wont get created fyi @prisma ruin
most common issue for me is updating ironsource/levelplay and not updating google admob to the specific version it wants
but you will see in the error if you experience this
that's the exact problem im going through right now. so much time wasted.. till wasting my time on this issue.
Ha yea its dumb, the error will state clearly for you the version it actually wants so you can update to that specifically.
or check the dependencies file for googleadmob adapter
oh, alright
Do anyone know how to calculate the shadowcaster frustrum rect?
even if it's just for the main directional light source
ye, that's for the camera, I wanted for the shadowcaster
If you go in the frame debugger, you can see how it works
this is the shadow caster, and this is the rendered scene. As one can see the shadowcaster is just a depth only camera facing the same direction of the directional light. But I have no idea how to calculate how wide or how high in the air it should be, or even where the center is.
From a directionnal light, would not that be an orthographic projection ?
yeah, I sorta get somewhat how to get something that might be quite close, but I have no idea how to figure out the finer details
how wide, how high in the air, etc.
I do not believe it is made to be figured out. What are you trying to do in the end ?
Because you might want to actually look into the SRP code and modify what you want there.
I draw a lot with Graphics.DrawMeshInstancedIndirect and use a compute shader to do frustrum culling, of course that don't take into account shadows, so long shadows just disappear out of nowhere. If I had the shadowcaster frustrum, I could just do both frustrums and draw it accordingly
I am using Built in render
I believe you do not want to cull object (from the directionnal) if you are rendering shadow. But I am not that experiemented in Graphics Rendering.
You need to build the shadow volume for current frustum, and test your bounding boxes against it also during visibility determination
Here shadow culling volume is depicted in dark blue. The idea is to find maximum extrusion of view frustum so any potential object inside of it can cast shadow onto camera view. This is basically how big shadow distance is for given light
For point light extrusion need to be performed to the light position. For directional light we are extruding frustum vertices using light direction.
I see there are 3 preprocessor directive for GameCore: PLATFORM_GAMECORE, UNITY_GAMECORE, UNITY_GAMECORE_API. Which one should I use for code that I only want to run if I'm using gamecore?
Does anyone know the steps to take to access a mono behaviour inside an ECS thatโs either burst or a job? It seems to me the moment you want to control the camera or get mouse position (say inside a singleton mono behaviour), you are losing out on burst and/or jobs defeating the purpose of the ECS. Like if I need to read the camera in a job what approaches do I have? Or if I need to modify the camera?
You would need to gather all the required data before starting any jobs. Getting a property/field is not something that benefits from jobs/burst anyway.
Does anyone know if SteamUtils.IsSteamInBigPictureMode() returns true for steam deck?
I see, I think I get the theory, I will have to figure out the math. I think I can go from there, thanks!
That was just an example, really want I want to see is interaction between Dots and Non-Dots ready made stuff instead of remaking it.
More importantly, I want to know how far it can be pushed, I am guessing jobs is out of the question, but can you still make it work with burst?
You can't interact with managed memory from jobs. Can only interact with blittable data.
As for burst, it only improves certain operations, so there's no point in using it with normal code. And the compiler would throw errors if you're using it in unsupported way.
If you want to interact with MonoBehaviours from dots, it would have to be outside of jobs and burst compiled methods.
So you canโt have parallel processed systems?
Hi all, I was wondering is their a way to do mesh instancing / collider instancing with the Physics system like their is for Graphics.DrawMeshNow?
Might not be what your after, but from what I think your talking about is a single source of truth for the data you are using dots on, I've been doing this by using pointers and Unsafe.Malloc, that way outside of the dots system I can read the data directly from the pointer, while when I need to process it I pass the pointer to the job itself.
Their is some extra considerations for making sure your letting things remain thread safe but it is possible.
Wdym? Of course you can. If you structure your systems such that they don't depend on each other.
The way many multithreaded engines work(including unity's internal systems), is that at the start of the frame it prepared the data to be processed in jobs such that computationally heavy tasks can make use of all the CPU cores. The jobs are ordered and synced in such a way that jobs and systems that depend on other jobs are executed later in the frame(when the jobs and systems they depend on are finished executing). You would often have many different systems, that don't need to be synced in real time. For example, rendering and sound could be processed in parallel. AI that doesn't require immediate feedback could also run in parallel to other systems like game logic. Assets/level streaming could be run I parallel to many other jobs as well.
I know how ECS works, Iโm coming from rust so Iโm familiar with exclusive mutable access and what not. Iโm just not familiar with the glue code required by Unity.
Nothing you said explains how to actually do it. How do I get access to my TileMap or anything else that doesnโt have DOTS support today in jobs, and if jobs isnโt possible how do I get in with burst, and if burst isnโt possible how do I ensure that a system can access the data and operate on it async if all it has is read only? Isnโt there like a Mutex or RwLock wrapper for game objects, monobehaviours or prefabs so they can have exclusive access?
the base unity api + its components arent thread safe and prevent use on other threads, therefore you cannot interact with them in jobs (burst or not)
This is why they have made all these packages like mathmatics that actually can be used in jobs and with burst
If you're using ecs systems, you'll access your tilemap(or any other component/object) in the system update or other callbacks by reference. You can get the reference via singletons or authoring components.
Again, burst is only applicable to specific operations.
You don't need to access your components in jobs or burst. You need to access them in system update(for example), prepare the data, execute a job on it, get the results from the job and apply them back to your components if needed.
If you're not using ecs, you can do the same thing in your script.
a lot of it is about putting your data into buffers that can be read from both sides (NativeArray etc), it's a bit like interacting with shaders from the C# side, you have to treat it a bit like a separate environment you're communicating with
You can also just run your own system. Nothing prevents you from running thread pools or some custom jobs system.
Unity jobs just make it easier and handle all kinds of multithreading pitfalls for you.
But there are cases where you might not want to use them.
Such as when you really need to access managed memory/objects from multiple threads.
You'll need to look at the multithreading api that C# provides in this case.
as a big user of UniTask and async, Task.Run()/UniTask.RunOnThreadPool() are usable for using non unity threadpools
But what guarantee do they have for exclusive access? Sounds error prone.
Let me rephrase my question; I want access to something that isnโt a DOTS component inside a query, so how does a component hold a reference to a game object?
Also gotta figure out the same thing with prefabs eventually to turn them into entities that can hold reference to the game object(s) created by said prefab.
unity functions/properties they dont want you using on other threads throw an exception when you try. Most go to native engine code so its not something you can work around.
Hi! I'm very confused on how to go about doing this, hopefully one of you might know:
I have an inventory system that has multiple toggleable UI windows and I'm trying to abstract some repeated code between them. Each window listens for a different static Action from my ControlsManager class and toggles itself off and on when its Action is invoked.
I'd like for them all to inherit from ToggleableUiElement, which should be able to listen to any arbitrary no-arguments Action, but this isn't working. Does anyone know how I could implement this kind of behaviour?
public abstract class ToggleableUiElement<T> : BaseUiElement<T> where T : ToggleableUiElement<T> {
protected abstract Action ToggleAction { get; set; }
private void SetAsActive() {
UiManager.SetActiveUiElement(this, true);
}
protected override void Awake()
{
// Subscribes to open Action and hides UI
IsOpen = true;
Close();
base.Awake();
}
protected override void OnDestroy()
{
ToggleAction -= SetAsActive;
ToggleAction -= UiManager.CloseActiveUiElement;
base.OnDestroy();
}
public override void Open() {
if(IsOpen)
return;
base.Open();
ToggleAction -= SetAsActive;
ToggleAction += UiManager.CloseActiveUiElement;
}
public override void Close() {
if(!IsOpen)
return;
base.Close();
ToggleAction += SetAsActive;
ToggleAction -= UiManager.CloseActiveUiElement;
}
}
public class InventoryUiManager : ToggleableUiElement<InventoryUiManager> {
protected override Action ToggleAction { get; set; } = ControlsManager.InventoryClicked;
}
ControlsManager.InventoryClicked is being invoked, and ToggleableUiElement is subscribing to the ToggleAction, but the functions it's subscribing to that Action (Open(), Close()) aren't actually being called for some reason
There are no logs at all. how do you know about your state of isOpen and so on? Are you sure its not being fired OR just returning because isopen is not correct for some reason?
Its also quite confusing, that you switch between delegate registers when you could just pass in the one, that gets opened and let all that are != the current one close themselves
yeah now that you mention it this is pretty convoluted
this shouldnt be the job of each window my ui manager should be doing this
i'm certain that ToggleAction += SetAsActive is being ran and SetAsActive isn't being called when ToggleAction is being invoked
so i'm doing something fundamentally wrong here
but i think i'll just rewrite this to be done on UiManager
Sounds way better ๐
logs are cool but just attach a debugger instead of guessing what you think is happening
Again, the limitations are that you can't access(or even declare managed type objects in the jobs or bursted functions). That's it. We've been telling you that several times now in different words. What is it that you still don't understand?
how would one approach the problem of drawing road on a hex map? have road sprite for each edge combination or draw them dynamically using line renderer something?
A Civ game 
I think most of those game just have number of road graphics for tiles that you can swap out depending how many road tiles are connected to it
So you can have pretty road
so a dot in the middle and then connecting arms?
No just whole sprite
LineRenderer wouldnโt make pretty enough graphic
Unless your game is very abstracted
ye and i think line renderer would be pretty resource consuming
line renderer isn't resource consuming at all - but you definitely want your own graphics for it @brisk spear
I use a ton of line renderers in my hex based game but it's just for showing temporary arrows for a path
the yellow line is a line renderer with a gradient (alpha at the beginning, color at the end)
Yea i wouldn't think a few extra line renderer meshes would kill your games perf
What's the proper way to set up loading processes for generative terrain? The only way I know to do that kinda thing on a single thread is to pause expensive loops on every frame, but part of my generation code involves going through a dataset with thousands of points, which makes loading comically long.
Idk how to make loading times adaptive to how fast the hardware running it is
what the most expensive part for this? game object/asset creation or loading/processing some data?
Something like:
DateTime startTime = DateTime.Now;
float frameBudget = 0.01f; // max amount of time to do work per frame
// main work loop
foreach (WorkUnit workUnit in allWork) {
workUnit.DoWork();
TimeSpan timeElapsed = DateTime.Now - startTime;
if (timeElapsed.TotalSeconds > frameBudget) {
// reset the start time and wait a frame
startTime = DateTime.Now;
yield return null;
}
}```
I would only do this kind of manual time slicing for unity api specific things, else do as much as you can on another thread in the meantime
yes this would be for indivisible main thread blocking tasks
also a c# stopwatch may be better for this time checking
uh, kinda both? the order of operations kinda goes like this
- Convert a .parquet dataset of about 600k points into a DataFrame that Unity can work with
- Once that's done, start generating low-poly chunks of terrain one-by-one, with height variation determined by perlin noise
- For each chunk, go through the dataset and figure out which datapoint coordinates lie within that chunk
- Put those coordinates into that chunk's indirect mesh renderer so that each of those points can be rendered as a plant in the scene
it's done like this to avoid having literally thousands of gameobjects in the scene simultaneously
(this is gonna be running on a Quest 3, worth mentioning probably)
Hmm you probably want to use Jobs + Mathmatics + Burst then for some parts of this. Ideally you would use jobs to prepare everything before finally creating the meshes
yeah definitely do as much work as you possibly can in jobs/background threads and then only do the final necessary Unity Engine stuff on the main thread
Be aware of the challenges when you use burst with jobs as it restricts the types and methods you can use in a job.
I'm just not sure how many threads I actually have to work with
The job system automagically figures that out for you
When using the unity job system, you can queue many jobs and unity will handle executing them on worker threads for you:
https://docs.unity3d.com/Manual/job-system-overview.html
You will probably want parallel jobs: https://docs.unity3d.com/Manual/job-system-parallel-for-jobs.html
and that'll make sure loading runs smoothly without tanking frames?
well yea as its all executed on worker threads and not the main thread so should have minimal to no impact on game perf
are there any resources that list what those limitations are, specifically?
Yes the unity docs for burst lists the compatible types you can use with burst compiled jobs.
Check here and the rest of the docs for more info
https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-type-support.html
Burst enabled jobs get compiled to native code which makes them faster but means its no longer managed c#
As I said before, the unity mathematics package can be used with burst jobs which is great as it has many noise gen functions
I'm assuming I wouldn't be able to use this for stuff like making KDTrees, then?
Hey, how are you all ? Is someone a timeline expert ? I would like to extend the AnimationTrack (the one who read animation and play them in animator) in order to add a speed curve (like in after effect). The goal is to manage the speed easily without changing game speed. Do someone have an idea about how to do this ? It seems that i can't juste extend the class, and recreate it from scratch isn't the right solution because i will not be able to use the recording solution already existing (first pic is the track i'm talking about, second pic is a time remapping curve from after effects, if you need more details about how it works, i can explain it)
I'm not sure what they are. Give it a try I guess?
A search algorithm, basically. By it's nature it kinda requires a managed type though
my mesh generation is the same way, it uses UnityEngine.Mesh
The mesh generation itself uses classes from ProceduralToolkit
the thing that reads .parquet files comes from https://github.com/aloneguid/parquet-dotnet?tab=readme-ov-file , which uses a ton of its own types and as far as I can tell outputs DataFrame
which is necessary to be able to do things like ElementwiseGreaterThan() and ElementwiseLessThan()
The more I dig through my code, the more I'm finding managed types. You sure Jobs are even an option for me?
What if everything has to be on the main thread?
then you have to timeslice it, but what has to be on the main thread in your case?
I assume everything with managed types
otherwise I'd have to rewrite almost my entire codebase
the managed types restriction is only for burst, you can still use whatever you like in regular C# multithreading, you just can't touch Unity apis
what would be the consequence of not using burst?
burst can produce faster native code, the limitations on it are the tradeoff, and if you just want to make some existing C# code not hog the unity thread, burst is probably the wrong tool
Ahh gotcha. Good to know
Yea the restrictions on types is only when using burst on a job. You can use jobs with normal c# or even traditional c# threads/Task.Run().
Burst is a nice addition for some things if you can plan ahead with it in mind to start
I am already using UniTask like as much as I can
UniTask has a function similar to Task.Run to execute something on worker thread easily so may help.
and ofc with unitask you can await this + switch to main thread via an await too which is convenient
part of me also thinks I'm not using Tasks correctly imo
like literally my strategy has just been to convert basically every function to a UniTask function and await them all
for example,
public async void GetParquetAsDataFrame(string fileName)
{
Debug.Log("Fetching parquet file");
string streamingFilePath = Path.Combine(Application.streamingAssetsPath, fileName);
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
Debug.Log("Detected platform: Windows/Editor");
filePath = streamingFilePath;
#elif UNITY_ANDROID
Debug.Log("Detected platform: Android");
filePath = await CopyParquetToPersistentPath(streamingFilePath);
#endif
df = await ReadParquetIntoDataFrame(filePath);
df = await AddIndexColumnToDataFrame(df);
kdTree = await CreateKDTree(df);
Debug.Log($"Parquet successfully read into DataFrame");
}```
unless they need to wait for some time/frames to pass, wait for an asset to load or say load/download a file then there is no benefit
however there is a benefit to say:
await DoExpensiveWorkOnAnotherThread();
await UniTask.SwitchToMainThread();
//do unity api stuff
they all end up doing that because I'm using functions within functions within functions etc etc
probably fine. I use async functions a lot due to addressable asset loading and things such as animations or waiting for an event/input
what's fine, specifically?
just sounded fine what you described. Just to be clear, doing something like this is pointless:
public async UniTask DoThing()
{
var prefab = GetPrefab();
Instantiate(prefab, transform);
}
I guess I should clarify, using UniTask like I described across almost every function is what I currently have, but I'm also still having huge frame drops
what would the alternative to that kinda function be, though? For a function with the return type of UniTask<DataFrame>, changing the return type to be DataFrame spits out this
well async void is actually using Task so dont be fooled.
if you want it to be async its gonna need to use Task or UniTask
If you have bad performance then you are still doing too much work in a frame so the solution is still to do split it over many frames or do it on another thread
Using async every where is gonna bloat your app with needless state machines. Basically you're gonna be paying for overhead that is lot needed.
related to that, dont use async void but instead use async UniTaskVoid to avoid using Task at all.
As for performance, you should check the profiler.
I think the culprits for this are functions that I can't edit, such as DataFrame's ElementwiseLessThan()
I can't use await unless if it's in an async function though .-.
Don't just "think". Test and profile to confirm your assumptions.
I am using the profiler, I guess I just don't know what I'm looking for
If you're awaiting everything(on the main thread), there's no point in async whatsoever.
It's just gonna add more overhead.
Sort by CPU time, expand the hierarchy as long as it's showing significant time. Read the involved method names. Share a screenshot here if you have trouble understanding.
hmm we are going in circles. I explained that you need to do work on another thread if a few functions are causing the problem
my amazing diagram of doing work on a worker thread and awaiting the result

this is what I mean lmao
@slate spoke plz refer to my shit diagram and research threading ๐
I shall attempt to, though I guess I should ask for recommendations on resources for learning threading properly
also,
1.3 million calls in one frame
Are you actually using async everywhere in your code?
Take a screenshot of the whole profiler window