#archived-code-advanced

1 messages ยท Page 121 of 1

icy smelt
#

It always takes 40 minutes

untold moth
untold moth
#

build report might have more info and actual time metrics

icy smelt
untold moth
icy smelt
untold moth
#

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?

icy smelt
untold moth
#

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.

icy smelt
#

Debug mode insta-compiles it

#

Smh

#

Or maybe it is some cache. Let me see

untold moth
#

Hmm... Perhaps it's doing optimizations. Still weird. If incremental build is enabled, it should check the cache and avoid recompiling stuff.

icy smelt
#

Seems like some cache. It compiled too fast. (Edit: indeed, it was just a cache)

azure moon
#

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.

jolly token
azure moon
#

The spline class, used in the collection of splines for the component or custom implimentations

jolly token
azure moon
#

hmmm interesting, as so this isn't the case with Mono/Scriptable Object references?

jolly token
#

Non-Unity objects are serialized as value

dapper urchin
#

has anyone seen this error before? I've deleted my library as well as root folder C#projects and it still pops up.

frail umbra
worthy lodge
#

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.

regal lava
#

Same idea, iterate through but check for namespace

worthy lodge
silver hill
#

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

scenic forge
#

Any hash gives back a number, so pretty much anything modern works.

silver hill
#

How realistic a 64 bit hash collision

#

Cause I just found out Unity does give you 128 hash

sage radish
#

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.

silver hill
#

Worst case scenario 10k I think

#

But that's an absolutely unrealistic level at which point my other systems will start to give up

sage radish
#

Are the strings known at compile/build time?

silver hill
#

No, dynamically loaded

sage radish
#

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.

scenic forge
#

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.

silver hill
#

My biggest concerns are size and collisions

#

If size wasn't I'd just use a string key notlikethis

#

But unmanaged code can be pretty merciless at times

echo coral
#

whats the umanaged code for?

silver hill
#

Entities

echo coral
#

unmanaged containers/burst is "safe ish" still so isnt bad i think

silver hill
#

Wdym

echo coral
#

ummanaged code is native code not using some runtime and/or gc

silver hill
#

Yeah that's right still not gonna let me use strings though

#

So I have to come up with something

echo coral
#

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*)

silver hill
#

Yeah I was considering to just introduce a character limit

#

But you know ideally I hash it into a number

#

Ideal case scenario

echo coral
#

yea if you know the hash max size then should be fine

scenic forge
#

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.

silver hill
#

Haven't even started doing anything actually just researching

scenic forge
#

I'd speculate this is a non issue ๐Ÿ˜„

silver hill
#

Issue is I have near-zero knowledge about hashing functions

#

SHA1 is very compact though yeah

scenic forge
#

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.

silver hill
#

How hard can swapping a hash function be

echo coral
#

i think pretty much all hashing functions produce a fixed length hash and well google exists to find out quickly

novel plinth
#

I've seen Unity uses their own md5 crypto internally before, not sure if it's available as public api tho

silver hill
#

Didn't have the time to look it up yet, how does it differ from SHA1\murmur?

novel plinth
#

md5 is much simpler that SHAx and should be faster

#

also note thats 128bit not sure if you want that

novel plinth
sly grove
#

do you have special requirements?

silver hill
silver hill
novel plinth
silver hill
#

I'm just researching atm

silver hill
#

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

silver hill
#

I'm gonna dig up the convo, gimme a sec

#

I butchered the terminology, not "incremental" but "sequential"

novel plinth
#

the perfect case to use new string() ๐Ÿ˜„

echo coral
#

im plenty familiar with cpp but dont do much c# -> native interop

jolly scroll
arctic lake
#

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?

thin mesa
#

Not an advanced question. Disabling a component only affects specific unity messages, it does not prevent you from calling methods on that object

sly grove
#

what's the question exactly though?

arctic lake
#

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.

thin mesa
#

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.

arctic lake
#

Hold on, I can provide more screenshots ๐Ÿ‘

thin mesa
#

!code

thorn flintBOT
arctic lake
#

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)

raven ruin
#

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

arctic lake
#

Still kind of am but I'll just mess around with it some more

paper bough
# arctic lake ``` void Update(){ if(player_controls.GetFaceButtons() == new Vector2(0, -1) ...

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

jovial bough
#

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

compact ingot
# jovial bough this is more of a theorical question - but i'm working on generating a map for a...

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.

regal lava
#

Same idea around minecraft. Chunk your stuff and when it's interacted with (WorldToGrid) do you then create that independency for each tile

compact ingot
regal lava
#

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.

exotic leaf
#

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

midnight violet
azure meadow
#

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 ๐Ÿค”

exotic leaf
#
        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

midnight violet
exotic leaf
midnight violet
#

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

exotic leaf
#

What if I delete the whole script... it causes the error again. Could it be a Unity bug?!

sage radish
midnight violet
azure meadow
exotic leaf
tall ferry
midnight violet
#

oh, you were faster ๐Ÿ˜„

midnight violet
trim void
#

Hi

#

Is anyone here?

#

I need big help on solving something

thin mesa
#

!ask

thorn flintBOT
#

: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

opaque pulsar
#

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?

thin mesa
#

unity does not support nuget

opaque pulsar
#

oh
so how do I download that package?

thin mesa
#

google "install protobuf unity"

opaque pulsar
#

oh, considering how much trouble I was looking up problems related to namespaces and packages I didn't expect it to be so easy

exotic leaf
#

and thank you

midnight violet
exotic leaf
midnight violet
midnight violet
#

Is it a desktop or notebook?

exotic leaf
midnight violet
#

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

exotic leaf
midnight violet
#

access to the ram slots on your motherboard

exotic leaf
lofty falcon
#

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?

lofty falcon
#
static LinesManager()
{
    _lineLookup = new NativeHashMap<LineHandle, LineData>(100, Allocator.Persistent);
    _cachedValueArray = new NativeArray<LineData>(100, Allocator.Persistent);
}
midnight violet
#

So you never dispose it?

lofty falcon
#

Only when resizing it

#

well the array, I believe NativeHashMap handles resizing internally

#

so no I don't dispose the NativeHashMap

midnight violet
#

so you are using it in editor and creating it with each unity start?

lofty falcon
midnight violet
#

if you are creating it at runtime, you should also dispose it in runtime

lofty falcon
midnight violet
#

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.

lofty falcon
#

Again this is not for editor code

#

I just have a static class with a native collection

midnight violet
lofty falcon
midnight violet
#

Or is the class not inheriting monobehaviour?

lofty falcon
midnight violet
#

Unless you restart unity

lofty falcon
#

What is weird is I'm not seeing warnings about memory leaks

midnight violet
#

I think it does not fire off right away. Guess there is some kind of threshold or whatever

lofty falcon
midnight violet
midnight violet
# lofty falcon Does it only warn about memory leaks when 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.

lofty falcon
midnight violet
wicked coral
#
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
slim fulcrum
#

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?

tiny idol
#

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

tiny idol
flint sage
#

Have you tried traditional C# sigint handling?

tiny idol
#

Ive tried all of these

NetworkManager.Singleton.OnServerStopped
AppDomain.CurrentDomain.ProcessExit 
Console.CancelKeyPress
OnDisable
UnixSignalHandler
OnApplicationQuit
tiny idol
flint sage
#

Console.CancelKeyPress is the wrapper that C# provides

#

What platform are you running on

tiny idol
#

docker container on a linux server

flint sage
#

But if the others don't work then I wouldn't expect this to work either

#

And if that still doesn't work, use something else as entrypoint and signal unity to shutdown when necessary

tiny idol
slim fulcrum
steady zenith
#

il2cpp crashed at methodInfo.GetParameters()

#

6000.0.32

sly grove
echo coral
dire flume
#

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:

  1. Track leg movement accuracy
  2. Simultaneously track ball movement
  3. Process both on device with minimal latency
sly grove
dire flume
#

Soccer ball

#

basically if they were holding their device like this

sage radish
plain abyss
lament salmon
#

You are doing integer division

#

Do 1.0f / ... if you want a float

silver saffron
#

oml tysm

#

im dumb

onyx violet
#

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

stuck plinth
onyx violet
#

yeah I guess that might be it

stuck plinth
#

yeah, it's just a regular filesystem afaik haha

onyx violet
#

brainfart xD

misty glade
#

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

long ivy
#

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?

misty glade
#

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

long ivy
#

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

misty glade
#

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

echo coral
#

If you have a few components for each section/thing it shouldn't be too bad

lost stag
#

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

echo coral
lost stag
#

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

smoky kite
#

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?

marsh saddle
#

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?

jolly token
#

Are you adding Switch controller support or something

thin mesa
marsh saddle
#

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

jolly token
#

Yeah probably just add some #if guard

echo coral
sly grove
abstract hill
#

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?

sage radish
abstract hill
blazing trout
#

i have come to code-advanced

#

in mind that somebody

#

could help me with

#

Time.deltaTime

#

i have tried adding time.deltatime myself

#

but it just makes my gun have ALLOT of recoil

thin mesa
#

!code
also doesn't seem like an advanced issue

thorn flintBOT
blazing trout
#

only a mastermind can fix this issue my friend

#

i think i got it tho

#

i dont got it

untold moth
silver hill
#

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

compact ingot
silver hill
#

An array per triangle set?

compact ingot
#

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.

silver hill
#

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

compact ingot
#

all this enables you to parallelize your operations and pass on incremental results between operations with minimal overhead

compact ingot
silver hill
#

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

compact ingot
silver hill
#

The ones I described above

hushed fable
#

@old swallow Don't crosspost.

silver hill
#

This is starting to look like a leetcode problem I swear

neat harness
#

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.

echo coral
neat harness
#

Idk if it was just the additive cameras or what but it was bad

echo coral
neat harness
#

I'll do some testing

terse inlet
neat harness
regal olive
#

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 ?

sly grove
silver hill
terse inlet
#

Itโ€™s illegal

short bear
#

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!

regal lava
#

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.

short bear
regal lava
#

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

slate nova
#

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

regal lava
#

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'.

slate nova
#

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

compact ingot
# slate nova yeah, it probably needs to be decoupled more

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.

slate nova
#

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

compact ingot
#

anyway. I think we agree.

slate nova
#

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

compact ingot
slate nova
#

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

echo coral
#

me making things to work with the requirements given to me + what I think it needs to do in future without too crazy ๐Ÿ˜

compact ingot
slate nova
compact ingot
slate nova
#

when the designers and leads did their work well, there is

compact ingot
#

the most knowledge of what should have been done is when the project is over

echo coral
#

requirements always change, pms always change their mind

compact ingot
#

Designers are humans and need to work with limited information, requirements change.

slate nova
#

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

compact ingot
slate nova
#

you did reply with "theres never clarity beforehand"

#

that sounded hyperbolic

compact ingot
slate nova
#

well

compact ingot
#

unless you have precognition

slate nova
#

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

compact ingot
#

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.

slate nova
#

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

compact ingot
#

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.

slate nova
#

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

burnt coral
#

Hey guys

#

I got a problem with my gradle in unity

#

it shows an error

#

anyone could possibly help?

thin mesa
burnt coral
thin mesa
#

this is a code channel

red jewel
#

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
devout hare
#

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

frigid orbit
#

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

echo coral
#

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)

wet sail
#

how do i apply modification to prefab.renderer.sharedMaterials ? (unity editor script)
PrefabUtility.RecordPrefabInstancePropertyModifications(prefab) doesnt seem to do anyhting.

wet sail
#

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

tight ether
#

how could i have possible break my unity so hard that it runs code of a component i delete during runtime

sly grove
#

You'll have to show the specific details if you need more help than that

tight ether
#

even if the reference is missing and the gameobject is disabled?

sly grove
#

Yes that's exactly what Destroy does

#

"missing" means simply that Destroy was called on it

tight ether
#

so its destroyed, gameobject is disabled and its normal for the code to keep running ? huh?? am i missing something here

sly grove
#

The C# half is still there

sly grove
#

If you call a function on it, it will run

#

Update will not run

tight ether
#

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?

sly grove
#

It's normal behavior

#

To stop it instantiating things you should stop calling the function that instantiates things

tight ether
#

thats the only way?

sly grove
#

Yes.

#

If you don't want code to run, don't run the code

tight ether
#

what if its an enemy the player can destroy?

pastel whale
wet sail
#

sorry, the api is little bit confusing obscure with 1mile length function names

sly grove
# tight ether what if its an enemy the player can destroy?

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.

tight ether
#

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

sly grove
#

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?

sly grove
#

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;```
wet sail
#

@sly grove my god yes thank you that was it.

red jewel
# red jewel hi there. i have a problem with coroutine: My game is working well the following...

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.

red jewel
#

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

rare gale
#

- 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);
somber swift
rare gale
#

- The input vector is, anyway

#

omg

somber swift
#

what?

rare gale
#

- It turns out that my script was pausing the play mode, hence halting the update loop, hence not dispatching any mesh rendering calls

somber swift
#

oh...

rare gale
#

- Dang it i hate to feel stupid but i do

misty glade
#

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

bleak citrus
#

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

misty glade
#

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 ๐Ÿ˜

bleak citrus
misty glade
#

hahaha

#

you read my mind

bleak citrus
#

i remember seeing someone have a problem with it being included even after disabling the splash screen

misty glade
#

yep, that's the case here

bleak citrus
#

iirc there was another setting that had to be turned off (that could only be accessed while the splash screen was enabled)

misty glade
#

(wasn't me complaining about it originally)

bleak citrus
#

i do not remember anything more specific

misty glade
#

hm, that's useful though, lemme dig

#

this is already disabled but i'll look for another place it's in the settings perhaps

bleak citrus
#

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

misty glade
#

maybe stripping more code too

bleak citrus
#

so it vaguely makes sense that it'd still be included in the build

misty glade
#

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. ๐Ÿ˜

nocturne ridge
#

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

regal lava
#

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

nocturne ridge
#

I've managed to fix it via another way (that didn't had to do with complexifying the cast process)

nocturne ridge
compact ingot
nocturne ridge
#

CheckSphere for my case would've been sufficient

echo coral
stuck plinth
echo coral
#

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

cerulean sky
#

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?

stuck plinth
#

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

echo coral
#

And as simonp says, if you use async instead its a lot easier to add a fake delay after loading

cerulean sky
#

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

cerulean sky
woven smelt
#

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?

stuck plinth
echo coral
cerulean sky
#

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

echo coral
#

๐Ÿ‘ 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;
}
stuck plinth
#

yeah, async is much easier to compose stuff like this, we avoid using the handles directly in most cases

cerulean sky
echo coral
#

im not returning the handle, its returning the loaded asset

#

Sprite mySprite = await Addressables.LoadAssetAsync<Sprite>("foobar");

cerulean sky
#

๐Ÿค” 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

echo coral
#

Yea this is why its good to start using async as it is more flexible in the long run

cerulean sky
#

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

echo coral
#

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

stuck plinth
echo coral
cerulean sky
stuck plinth
cerulean sky
#

but Task.Run for instance will not do it that way

cerulean sky
thin mesa
#

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

stuck plinth
#

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

cerulean sky
#

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)

stuck plinth
#

isn't this how it works in WPF too, where there's a UI thread with a sync context?

cerulean sky
#

Its a whole different beast than the Unity scheduler but yea it has its own uuuuh caveats

stuck plinth
#

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

cerulean sky
#

confusing and complicated are very different things!

novel plinth
# echo coral this is why we dont use Task

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

novel plinth
stuck plinth
novel plinth
#

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 ๐Ÿ˜…

misty glade
#

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

raw lily
#

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}");
...
bleak citrus
#

Note that this only works in the editor

raw lily
#

Ahh.. thanks!

bleak citrus
#

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

raw lily
#

Yeah I see, hmm.. not quite sure what I prefer, upside is to not to have to manually add them I guess.

bleak citrus
#

Some of my singleton scriptable objects are "catalogues"

#

which just hold a bunch of references to scriptable objects

misty glade
#

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)

pastel whale
#

unity learn ๐Ÿ˜†

teal karma
#

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

echo coral
misty glade
#

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

echo coral
#

I think webgl builds use webasm for code but im not sure how debuggable it is

echo coral
regal lava
#

Usually if I ever have problems related to WebGL, it's usually texture or shader stuff

misty glade
#

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?

regal lava
#

You got it hosted? Drop me a link and ill see how it works with my firefox

misty glade
#

I'm not sure if the webgl builds work with firefox but lemme know what happens

#

wait wrong password i think, sec

regal lava
#

it's webgpu so yeah no firefox

#

even if I enable webgpu on firefox it sucks idk why

misty glade
#

ok

regal lava
#

chromium browsers have it enabled by default

misty glade
#

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

echo coral
#

ill also test on firefox

regal lava
#

chrome loaded it in 5 seconds

misty glade
#

no hiccup on the loading bar?

#

like thereabouts

echo coral
#

mine took ages to load

teal karma
#

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

misty glade
#

i tried it with chrome throttling (3g) and it looks like it's just a download speed thing

echo coral
#

but network took like 3 seconds?

misty glade
regal lava
#

Mine loaded when bar was 1/3rd ;p

misty glade
#

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

echo coral
#

im not sure it is network, it took like 30-40 seconds the first time but my internet isnt slow

misty glade
teal karma
#

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

misty glade
#

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")

echo coral
teal karma
#

I see, why not to the second question?

misty glade
regal lava
# misty glade

Yeah, I see the hanging, but I mean we are downloading 180 mbs here so expected.

misty glade
# teal karma I see, why not to the second question?

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

regal lava
#

loading bar stuff never accurate

misty glade
#

Yeah it was more the 30 second "hang" that I was worried about since my computer and network are both pretty fast

regal lava
#

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

misty glade
#

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

echo coral
#

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

misty glade
#

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)

teal karma
#

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

misty glade
#

i still could, but I didn't wanna deal with the cross origin stuff

pastel whale
#

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

misty glade
echo coral
#

yea was my thought too, perhaps its cached somewhere hence it not happening again

misty glade
#

The uncompressed build is like 175mb

teal karma
#

I see, thanks

pastel whale
#

and the 30sec gap only happens for compressed build?

misty glade
#

yeah, but I can't repro it

#

it just happened once for me this morning, and once for my coworker this morning

pastel whale
#

u cant repro it because it may happen only once then its cached

misty glade
#

but i've tried incognito, clearing cache, etc - can't seem to make it happen again

pastel whale
#

uncompressed once then cached

misty glade
#

i've got this disabled tho:

#

not sure if that's ... doing anything tbh

echo coral
#

could be somewhere else

misty glade
#

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

echo coral
#

Hmm it took about 9 seconds in chrome the first time. May be best!

pastel whale
#

im free after 30 mins, so i can do some tests with plsywright and stealth mode

misty glade
#

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

pastel whale
#

@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

regal lava
#

Probably has to do with compression

#

it's not just downloading, but preloading the first scene

pastel whale
#

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 ๐Ÿค”

misty glade
#

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

olive cipher
#

Do you have it accessible somehwere or is it local?

misty glade
#

yeah, want to try?

#

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

olive cipher
#

not sure whats going on on your side

misty glade
#

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

olive cipher
#

yeah also made sure it wasnt cached

#

got a 200, not 201

pastel whale
#

maybe it depends of the location

olive cipher
misty glade
#

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

misty glade
olive cipher
#

yeah, you can click on the data file there and select timing

#

it shows you a breakdown of what took how long

pastel whale
#

tested now from wsl Ubuntu chrome

misty glade
#

ah, cool.. uhm.. wish i had done that for the 44 sec load

olive cipher
#

should clear your cache

#

otherwise an ingocnito window will help

misty glade
#

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

olive cipher
regal lava
#

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

olive cipher
#

25s for 64mb seems harsh

#

yeah but we are talking about a 64mb data file here

misty glade
#

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

regal lava
#

Still better than most Godot web games I've seen haha

misty glade
#

looks like it must be an itch.io webserver configuration thing tbh

olive cipher
misty glade
#

gig+

#

here's the timing tab after refreshing - 2 sec

olive cipher
#

yeah cause now its cached

pastel whale
misty glade
#

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

olive cipher
#

not itch io cache

misty glade
#

hm? i'm not caching it locally as far as I can see?

olive cipher
#

your browser stores it for however long itch ios cache time is to ๐Ÿ˜„

misty glade
#

("disable cache" at top)

pastel whale
#

cache is disabled but its stored somewhere

misty glade
#

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)

olive cipher
#

oh true, its a 200 response

regal lava
#

itchio does do some sort of initialization for first uploads, but it usually tells you on the window itself

misty glade
#

yeah but ... i can go through that workflow and it still "works" fast (as long as the page has been precached)

olive cipher
#

is it while your game is loading or can you already execute scripts before?

If so just show a loading screen

misty glade
#

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

scenic forge
#

Web frontend has the concept of code splitting, I wonder if Unity can do something similar.

misty glade
#

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?

sly grove
#

You can remove any and all unused glyphs from TMP font assets you're using I think? (not an expert)

bleak citrus
#

I'm still figuring out how to properly profile that

misty glade
#

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?

bitter magnet
#

is there a way to use index geometry types other than triangles?

#

I'm in a specific case where quads are a better pick

frail umbra
#

it's all triangles at the end of the day

bitter magnet
frail umbra
#

yes

#

modern GPU always converts it to tris

frail umbra
#

are you talking about 3d modelling?

#

or using unity's GL?

bitter magnet
frail umbra
#

yep it's converted to tris, there's a documentary about how Minecraft mods optimised cubic mesh generation

bitter magnet
#

doesnโ€™t that take some workload off of the cpu though

frail umbra
#

triangulation is done on CPU unfortunately

bitter magnet
#

ah

frail umbra
#

all the vertices sent to GPU are tris

bitter magnet
#

sad

frail umbra
#

the talk on having GPUs use quads over tris ended a long time ago

bitter magnet
#

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

compact ingot
thin mesa
echo coral
dusk plaza
#

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?

abstract hill
#

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?

bitter magnet
#

oh cool

#

man I really wish unity had proper c++ plugin support

echo coral
#

well you can use cpp code if you build it as a lib but ofc you cant really interact with anything

misty glade
#

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

echo coral
misty glade
#

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

echo coral
#

hmm well when you profile id be intererested to see the gpu memory usage

novel plinth
bitter magnet
novel plinth
#

not sure if enterprise licence covers that, perhaps.

olive cipher
#

yeah thats enterprise

novel plinth
#

aight nice

misty glade
#

is there a way to have packages for one build target but not another?

echo coral
misty glade
echo coral
#

you didnt try yet?

misty glade
#

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

echo coral
#

I dont think its a concern with the memory profiler package it has 1 runtime class

misty glade
echo coral
#

yea you wont get anything useful from a wasm mem dump

misty glade
#

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

echo coral
#

just add it temporarily to test this out and remove later

misty glade
#

reimporting all the (100+) animations with some more aggressive keyframe culling would help but .. probably only a few mb

echo coral
#

you dont have to upload the build to itch io just host locally

misty glade
#

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"?

echo coral
#

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

misty glade
#

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

echo coral
#

Id still aim to get a memory snapshot with the profiler. use a win build if you must

misty glade
#

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

echo coral
#

as it warns you, its not a good representation of the real build

misty glade
#

ah, yeah.. ok i'll do a windows build

echo coral
#

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)

azure moon
#

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

woven smelt
#

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?

azure meadow
#

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? ๐Ÿค”

sly grove
misty glade
#

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?

sly grove
#

Doing it in OnEnable/OnDisable is ok assuming you're not constantly enabling/disabling these things

#

calling the registered delegates doesn't cause GC

echo coral
#

huh didnt know about these problems with when GC can run on webgl but makes sense ๐Ÿค”

azure meadow
regal lava
#

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

misty glade
#

It's entirely likely that an average frame is calling these new()'d up delegates 20+ times per

misty glade
#

(ping me if so - am mobile now but can grab a snippet if you want)

regal lava
#
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

novel plinth
novel plinth
#

or if you insist on using Action, you pass a span on it like so Action<Span<T>>

frigid phoenix
#

is there a discord or channel somewere for A* pathfinding pro?

#

i know he has a forum - but forums are so old fashioned !

somber swift
prisma ruin
#

how to solve this issue? the issue causing a lot of time..

midnight violet
prisma ruin
#

yes

#

but failed

#

do i have to run the unity game on real device instead of trying iOS simulators?

midnight violet
prisma ruin
#

yeah, i updated xcode to the latest version

midnight violet
#

You could try to remove and readd the ios package

prisma ruin
#

alright.

#

is this seem ok for unity 2020 version?

midnight violet
prisma ruin
#

alright. i will 2021 version, then

echo coral
prisma ruin
#

this is 2021 version for another unity project which uses admob too. does it seem ok?

midnight violet
#

So many things change through xcode versions, the very old unity version just might not be able to export correctly

prisma ruin
echo coral
#

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

prisma ruin
echo coral
#

or check the dependencies file for googleadmob adapter

prisma ruin
#

oh, alright

dusk plaza
#

Do anyone know how to calculate the shadowcaster frustrum rect?

#

even if it's just for the main directional light source

dusk plaza
#

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.

dusty wigeon
dusk plaza
#

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.

dusty wigeon
#

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.

dusk plaza
#

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

dusty wigeon
brave cairn
#

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.

mellow plinth
#

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?

woven smelt
#

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?

untold moth
marsh saddle
#

Does anyone know if SteamUtils.IsSteamInBigPictureMode() returns true for steam deck?

dusk plaza
woven smelt
untold moth
woven smelt
#

So you canโ€™t have parallel processed systems?

abstract hill
#

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?

abstract hill
# woven smelt That was just an example, really want I want to see is interaction between Dots ...

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.

untold moth
#

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.

woven smelt
#

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?

echo coral
#

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

untold moth
# woven smelt Nothing you said explains how to actually do it. How do I get access to my TileM...

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.

stuck plinth
untold moth
#

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.

echo coral
#

as a big user of UniTask and async, Task.Run()/UniTask.RunOnThreadPool() are usable for using non unity threadpools

woven smelt
#

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.

echo coral
#

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.

cloud badger
#

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

midnight violet
#

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

cloud badger
#

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

midnight violet
#

Sounds way better ๐Ÿ™‚

echo coral
#

logs are cool but just attach a debugger instead of guessing what you think is happening

untold moth
brisk spear
#

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?

jolly token
#

So you can have pretty road

brisk spear
jolly token
#

No just whole sprite

#

LineRenderer wouldnโ€™t make pretty enough graphic

#

Unless your game is very abstracted

brisk spear
#

ye and i think line renderer would be pretty resource consuming

misty glade
#

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)

echo coral
#

Yea i wouldn't think a few extra line renderer meshes would kill your games perf

slate spoke
#

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

echo coral
sly grove
# slate spoke Idk how to make loading times adaptive to how fast the hardware running it is

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;
  }
}```
echo coral
#

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

sly grove
#

yes this would be for indivisible main thread blocking tasks

echo coral
#

also a c# stopwatch may be better for this time checking

sly grove
#

possibly/probably

#

this was just to get the idea across

slate spoke
# echo coral what the most expensive part for this? game object/asset creation or loading/pro...

uh, kinda both? the order of operations kinda goes like this

  1. Convert a .parquet dataset of about 600k points into a DataFrame that Unity can work with
  2. Once that's done, start generating low-poly chunks of terrain one-by-one, with height variation determined by perlin noise
  3. For each chunk, go through the dataset and figure out which datapoint coordinates lie within that chunk
  4. 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)

echo coral
sly grove
#

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

echo coral
#

Be aware of the challenges when you use burst with jobs as it restricts the types and methods you can use in a job.

slate spoke
#

I'm just not sure how many threads I actually have to work with

sly grove
#

The job system automagically figures that out for you

echo coral
slate spoke
#

and that'll make sure loading runs smoothly without tanking frames?

echo coral
#

well yea as its all executed on worker threads and not the main thread so should have minimal to no impact on game perf

slate spoke
echo coral
#

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

slate spoke
fallow sentinel
#

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)

echo coral
slate spoke
#

my mesh generation is the same way, it uses UnityEngine.Mesh

#

The mesh generation itself uses classes from ProceduralToolkit

#

which is necessary to be able to do things like ElementwiseGreaterThan() and ElementwiseLessThan()

slate spoke
slate spoke
stuck plinth
slate spoke
#

otherwise I'd have to rewrite almost my entire codebase

stuck plinth
slate spoke
stuck plinth
#

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

slate spoke
#

Ahh gotcha. Good to know

echo coral
# slate spoke 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

slate spoke
echo coral
#

and ofc with unitask you can await this + switch to main thread via an await too which is convenient

slate spoke
#

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");
    }```
echo coral
#

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
slate spoke
#

they all end up doing that because I'm using functions within functions within functions etc etc

echo coral
#

probably fine. I use async functions a lot due to addressable asset loading and things such as animations or waiting for an event/input

echo coral
# slate spoke 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);
}
slate spoke
#

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

echo coral
#

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

untold moth
echo coral
#

related to that, dont use async void but instead use async UniTaskVoid to avoid using Task at all.

untold moth
#

As for performance, you should check the profiler.

slate spoke
slate spoke
untold moth
#

Don't just "think". Test and profile to confirm your assumptions.

slate spoke
#

I am using the profiler, I guess I just don't know what I'm looking for

untold moth
#

It's just gonna add more overhead.

untold moth
echo coral
#

my amazing diagram of doing work on a worker thread and awaiting the result

slate spoke
echo coral
#

wtf is that alloc WHAT ARE YOU DOING

#

slap a stopwatch start/stop around it instead

slate spoke
#

this is what I mean lmao

echo coral
#

@slate spoke plz refer to my shit diagram and research threading ๐Ÿ™

slate spoke
#

I shall attempt to, though I guess I should ask for recommendations on resources for learning threading properly

#

1.3 million calls in one frame

untold moth
#

Are you actually using async everywhere in your code?

slate spoke
#

basically yes

#

I'm not sure where I wouldn't be

untold moth