#archived-code-advanced

1 messages · Page 113 of 1

silent matrix
#

Plot twist, you argued with yourself about being an alt to gain trust with mods

#

You're his biggest hater and you thought I was harsh? 😄

#

He has a lot of haters

#

More haters than supporters

fast egret
#

i asked so i can know your experience

#

i don't like to name call people

silent matrix
#

I don't like to name call nice people

#

But if you deserve it then you get what's coming to you

#

But I have to stay remotely nice so I stay family friendly

fast egret
#

he has like 300 sponsors on github

#

should be zero of course

fast egret
#

he posted this on his Patreon account, i have seen it

#

it's public

#

btw create a thread here

silent matrix
# fast egret how do you know

Something tells me that when he gets 1 like on his patreon per post (probably his own account) and gets desperate when he can't get a $5/month supporter for his NetworkAnimator, he doesn't have that much support coming in

#

I forgot the reason I actually came here lol

#

I was gonna ask a question

#

I'll be making an RTS next week after my release of the game I'm working on now.

When you are attempting to balance a game with live game stats, for example in Valorant where you have a lot of agents and you want to make sure there isn't an overpowered agent, so you log the wins vs losses and other stats to make sure it's balanced, is there a good BaaS that you can use to track all of these metrics? Or is it better to log your custom stats from your dedicated servers to some AWS EC2 instance, and then to say an AWS RDS so you can view the data in a table of some sort?

fast egret
silent matrix
#

wdym

#

like deterministic lockstep?

fast egret
#

yes

silent matrix
#

Well I'm not worried about the networking part of it, I was more asking about the BaaS

#

I'll figure out the networking lol

fast egret
#

i know

#

lockstep is not really easy nowdays, you need deterministic gameplay, can't use the unity navmesh, physics engine, etc

#

it's the hardest thing, what you are talking about is the easiest thing about an rts or a game in general

#

there are endless ways/services to collect the stats and review them etc

silent matrix
fast egret
silent matrix
#

Oh PlayFab offers that?

#

I didn't even pay attention lol

fast egret
#

they offer a lot of stuff

#

stats is one of them

silent matrix
#

But I'll be abstracting every system so it doesn't matter anyways

#

For prototyping, when a Unit needs to check for other Units or Structures near it, it's just gonna iterate over every object and do a distance check

fast egret
#

i don't know the scope of the rts you are going to make

silent matrix
#

In production, it'll use spatial hashing or something similar

fast egret
#

but i expect years just building the core gameplay

silent matrix
fast egret
#

i honestly think RTSs are probably the hardest type of games to make

#

period

silent matrix
#

Not MMO? 😄

#

or MMORPG rather

fast egret
#

i hate mmos

silent matrix
#

I could be making a mistake on the short deadline, but we are also doing a prototype before announcing a release date, so if it ends up taking longer than we anticipate, that could change a lot of things

fast egret
#
silent matrix
#

But we're also not making a traditional RTS

#

Not gonna go too into detail right now, but it's not the same

#

It's still got the more complex systems and optimizations required, but it isn't the usual RTS

fast egret
#

how many units

silent matrix
#

For a prototype, less than 10 probably

#

Just a handful

fast egret
silent matrix
#

What

fast egret
#

that is nothing

#

how dare you call this an rts

#

lol

silent matrix
#

lol it's a prototype, why would I have 200 different units?

#

Maybe more than 10, I'm not sure

fast egret
silent matrix
#

What takes the longest on an RTS?

fast egret
silent matrix
#

Is it the networking?

fast egret
#

there are other engines than unity people use to make RTSs

fast egret
#

the logic for controlling units and moving them is quite complex

#

it's not just some pathfinding

silent matrix
#

We played a pre-alpha of a similar RTS we are targeting and people loved it

#

It had 1 unit type 🤣

#

and simple pathfinding

#

Obviously our release would have more, but I think we're targeting something a little simpler while still hitting an RTS market

fast egret
#

if your game is nothing like Starcraft or Red Alert

#

then idk, i won't call it an RTS

silent matrix
#

What is your definition of an RTS?

fast egret
#

this is an engine people use to make traditional RTS games

silent matrix
fast egret
silent matrix
#

It's for a different market of players

fast egret
#

mix of rts and fps?

#

that never worked

silent matrix
#

We are trying to design it to have a high APM, but it's not gonna be as high as a traditional RTS

silent matrix
#

I don't think it's for you then unfortunately

fast egret
#

7/10

#

3000 reviews is a failure tbh

silent matrix
#

Right

#

Well to each their own

#

🤷‍♂️

#

I don't know what to tell you 🤣

fast egret
#

good luck of course

silent matrix
#

I mean I think you're a traditional RTS player

#

which is fine

fast egret
#

but tons of people tried to do this

#

it never worked in a way that appeal to enough people

#

but if this what you are trying to do

#

i would just forget about lockstep and all that

#

you can use anything for this

#

it's just an fps

#

with some rts camera and stuff

silent matrix
#

It's not an FPS

#

I just used Silica as an example of how a different RTS can work

fast egret
#

i don't know man, but best of luck to you

cedar cradle
serene pawn
tender crow
#

Anyone here have experience coding dynamic mesh creation / editing via c# monobehvaior or possibly HLSL shaders?

tender crow
violet valve
#

The best answer I can think of specific to RTS is designing systems for efficiency, but if someone isn't sure how they want to approach networking, I can see that being a big hang-up. In my case, I had a very clear idea how I wanted to handle broadcasting actions to groups of units top-down and the networking, replay and user interface piggybacked off that design. I had put a lot of time into figuring that out before actually building a game though. I'm going to be converting my unit logic in DOTS knowing that what I have now is a prototype, so I expect that step to be a big time consumer in my case.

silent matrix
silent matrix
# violet valve The best answer I can think of specific to RTS is designing systems for efficien...

I wanted to abstract a lot of more complex systems. Take unit finding for example. If you have a tank and it needs to find units and structures near it, then ideally something like spatial hashing would be used. However, for prototyping, just an iteration and distance check will work for a small quantity of troops. I would abstract the system into a component like UnitFinder, which handles the logic. When I want spatial hashing and production code, I just change the implementation of that class and it reflects in the build

sterile thunder
upbeat path
#

tbh, imo, automated testing of games is a waste of time, you will never be able to emulate the stupidity of users

sterile thunder
#

It's a balance for sure, testing every last method is def nonsense, but having no tests, it can be a little too easy to accidentally break something when making changes to the code, obviously clean architecture helps with this, but still

dusty wigeon
# sterile thunder Hey all, I'm trying to get some perspectives on automated testing and testable a...

In my opinion, automated test is a lost of time. The only things I would think of automatically test would be engine code but even then. The best, is to define what I call "Gym" where you can manually test each functionality quickly. Additionally, it can be a good idea to test more broadly from time to time. When doing so, keeping track of what has been tested is a most (Quest 1, Combat X, Mode Y, etc.).

sterile thunder
# dusty wigeon In my opinion, automated test is a lost of time. The only things I would think o...

I hear you, manual tests are always going to be needed, and having a "gym" where you have all systems to test in one area without needing to traverse a whole level is def a good shout. The main problem I see with relying on manual tests is that it's unrealistic to do a full suite of manual tests with every change. Sure, you do these tests before each release, or every few days/weeks, but when you catch a bug, it can be tricky to tell what change introduced that bug. With an automatic suite in place, you can confirm your change has broken something before even committing to the repo, which obviously massively cuts down debugging time... I guess the question is how to balance this so you're not increasing dev time by any more than you're decreasing QA time

dusty wigeon
sterile thunder
#

Something to further complicate things in our particular case, we're not really building a game, we're building a unity-based dev tools framework for making games (pre-build player rigs that interface with interaction systems, that sync through a server), so we really want to make sure that all our "customer-facing" functions (e.g, teleport the player to this location, send this message to all players, etc) all behave the same way each release. If something in these functions changes, then we potentially break all our customers' applications

dusty wigeon
#

This is not the same scenerio as building automate test for a game. It is as I stated, if you are building a testing for a game engine, then it makes a bit more sense.

#

Just by that nature of it being an engine and not a game, you have less interdependence and a lot less of non homgenous data.

sterile thunder
#

It still raises the same questions, especially when you're testing monobehaviours, like "should I be injecting dependencies from a higher level service so I can mock them in my tests"

#

I cover some of the considerations to the actual code itself in the post linked above ^

dusty wigeon
#

I believe you should not try to make Unit Test. It is going to increase the complexity of the code for your client.

#

Instead, aim to test from the extern and either use public variable or reflection to test the state of the resulting behavior.

sterile thunder
#

Yeah, I think I agree unit testing maybe seems of less gain here than integration/end-to-end tests

#

It's interesting though isn't it, most software teams outside game dev seem to put the most emphasis on unit tests

dusty wigeon
sterile thunder
#

Interesting, there's some real irony in that forcing in tests led to more complexity which actually increased bugs! Thanks for the thoughts 🙂

scenic forge
#

In my game which has a scripting system, the scripting runtime has ~2000 E2E tests (I didn't hand write all those tests though, most are inherited from base class tests). It helped a lot when rewriting from tree walk interpreter to bytecode interpreter. The ability to fearlessly refactor knowing you didn't break something in a hidden way, is very valuable.

#

But it's hard to write good tests for games in general, because of how quickly games iterate and tests break, to the point where you are spending more time fixing fragile tests than the tests save you. Very specific parts of the games though like the scripting example above, can be very good candidates for testing and getting a lot of value out of it.

sly grove
#

TDD is amazing for very specific mechanics or features or tools

scenic forge
#

Your experience with TDD also scales with how fast tests are run/hot reload (which Unity is pretty bad at), and inversely scales with how often requirements change (which change basically all the time in game dev)

sterile thunder
#

A boon we have is that our architecture (so far, we'll see if we can keep it up) handles state in a way where the domain doesn't actually need to reload between runs, so play mode tests should be faster to execute

frail dome
#

let say I have a component called PlayUIClickSFX.cs

There is an Enum shown in inspector to select which type of UI click sound to play.
This script will get the button and automatically registered the onClick to play the sound.

In a normal workflow, I will just Call AudioManager.PlaySound(xxxx)

but since I'm trying to use DI, how can I do this?

Let's say I've already registered the AudioManager in the composition root. And it's available in the current scope already.

But monobeviour is unable to be inject automatically. I need to keep track of every PlayUIClickSFX instance in the scene and manually inject all of them when the DI finish resolving. But that's seems kinda bad? seems extremely bloat way to do thing.

Am I missing something obvious? Or is this just a case where using DI is not a way to do it.

misty walrus
#

I am not sure which DI solution you are using, I haven't used one in a long time. But iirc for Zenject the default workflow would be to create a factory for your component.

frail dome
sterile thunder
#

I'm hesitant to use a 3rd party DI framework, currently I'm just injecting my dependencies in through the constructor, obviously I don't want the higher level classes concerned with all the dependencies of the lower ones, so I'm isolating dependency retrieval in factory classes

#

Oh sorry weren't taking to me lol

misty walrus
sterile thunder
#

But yeah you could have some factory that takes the gameobject your Audio manager sits on (or finds the audio manager through a singleton) and passes it to the dependent component through some Initialize method (or a constructor, if it isn't a mono)

frail dome
#

Which honestly is not great? what if I forget? what if it's destroyed later and some item become null in the serialize list

#

etc etc

misty walrus
#

If one is not included, I would write a simple component that you attach to gameobjects, with a single serialized field allowing you to select the scope(s) to use.

#

Only concern would be the order of execution, you wouldn't want to inject the objects until proper registration is completed.

frail dome
#

I could do LifetimeScope.container.resolve<AudioManager>
but at that point, why not just make the damn thing a singleton right? XD

misty walrus
#

Normally the benefit would be the ability to

  1. abstract the functionality to an interface and register the implementation you wish
  2. have multiple scopes for parts of your code
restive tinsel
#

After i meet with initargs all other dependency injection frameworks feels trash, you can do everything you do in zenject/vcontainer without writing any code with just single click in 1 second. I highly recommend you all

Plus no reflection at all

frail dome
# misty walrus Normally the benefit would be the ability to 1. abstract the functionality to an...

I'm actually doing the first one but using the ServiceLocator pattern. and doing Init() to cache ref to the manager or service myself.
I have my own composition root where I register manager & service.
Then for a local scope(scene) ref I just pass around dependency through method argument.

It's working great. but I'm trying to learn DI and see what's the hype is all about. TBH I still could not wrap my head around it

frail dome
restive tinsel
frail dome
#

Usually, the backgroun jitter because your camera doesn't have interpolation. I assume your camera follow your player right? So if your player jitter, it will also jitter. One way to fix it is to interpolate and gradually follow the player. (Vector3.smoothdamp)

Then the reason your player jitter is because the you only update position in FixedUpdate. It will need interpolation. similar concept to the camera

frail dome
white pulsar
#

What happens in burst when there are multiple assemblies that have burstable jobs? does it just generate one assembly for all of them?

novel cradle
#

guys dose visual scripting good for making games ? im wonder about a package named by game creator 2 which is for visual scripting if i want to create advance level game should i learn these and work with these or not?

jaunty creek
#

Hi! I know that I can use submeshes to add different materials to a procedurally generated mesh, but is there a way to "draw" different materials onto the mesh? Fx. let's say I am procedurally drawing a planet. Would it then be possible to give it a grass material, except some places that should be sand?

regal lava
scenic forge
# sterile thunder Hmmn interesting, did you have much in the way of unit or integration tests?

Not much. Unit tests shine when you have an isolated but complex piece of code to test, in my case the scripting system has a bunch of very simple functions (like addition operator) where they are very simple and rarely ever change so they are not worth testing. Integration tests are great for when you have multiple isolated systems need to be integrated with each other, in my case the scripting system is just one system.

frail dome
#

It's the camera 😶

terse oyster
#

Do you have any suggestions on how I could implement a system for merging player accounts across multiple games? Ideally, a player who creates an account for one game should be able to use the same credentials to access all other games. Currently, I'm using a basic username and password setup. In unity cloud

timid spade
trail spoke
#

What does this error means? and is there a way to fix it ?

#

I think of using unity as a library as a bridge hosted in maui .net8 app then bidirectional methods calls

thin mesa
#

this is not an advanced issue. just because you haven't received the help you wanted in another channel does not make it advanced

floral marten
#

okay am I imagining this or was there a callback/attribute that would run for every scene on build, as well as in editor on entering play mode?

#

there's [RuntimeInitializeOnLoadMethod] but that is executed in builds, not when building scenes

thin mesa
#

there's the IProcessSceneWithReport interface with its OnProcessScene method

floral marten
#

omg that's the one thank you

tender ingot
#

Has anyone done a successful A* Pathfinding ? Having some issues trying to wrap my head around it.

#

I know it's float A distance between the node and starting position and float B distance between the node and ending position and then A+B = total score. But when it gets close to the end position it goes back down in score again so having it sort based on score isn't working as it should do.

sly grove
#

it doesn't know or care about the passage of time or the progress of anything along any of its paths

#

I know it's float A distance between the node and starting position and float B distance between the node and ending position and then A+B = total score. But when it gets close to the end position it goes back down in score again so having it sort based on score isn't working as it should do.
It's not really clear what you're talking about here

#

I guess you're talking about your heuristic function?

#

The heuristic function you use depends on the specifics of your data model and your game

#

a typical heuristic function would be something like "straight-line distance to the destination"

#

but there's no guarantee that a path will always follow a series of nodes where the heuristic score is monotonically decreasing.

tender ingot
#

I know that now as from my testing its not really a clear path. I am trying to follow some tutorials online like from Sebastian to get it working:

https://www.youtube.com/watch?v=dn1XRIaROM4

In this episode we're going to implement some units which can requests paths and follow them through the game world.

Source code: https://github.com/SebLague/Pathfinding

If you'd like to support these videos, you can do so with a recurring pledge on Patreon, or a one-time donation through PayPal. https://www.patreon.com/SebastianLague
https://...

▶ Play video
sly grove
#

Do you have a specific issue you want help with?

tender ingot
#

Mine doesn't follow a certain path as of yet. Its just a train game where there is track and the tracks are the nodes and its supposed to find from one train station to the other as you assign the train to go from one station to the other. Problem is the train starts off where it should then might go across to another track on the other side then back over etc because the tracks sorted by score are not in a certain path due to the scoring issues.

I will have to revisit another way of doing it.

sly grove
#

it shouldn't be possile for it to select unconnected nodes

#

the tracks sorted by score
This is only something you do during execution of the algorithm. Once a path is selected the scores are no longer relevant at all

tender ingot
#

No I did mine different to a traditional A* Pathfinding. I place tracks on the grid and as I place them a reference to that track is placed in a list. I use all the tracks placed in the game as nodes for it to calculate so there is nothing for it to just go directly from a point of map directly down to the other station with out following the tracks. But like I said I think this is not made for what I want it to do so might just try something different.

sly grove
#

I don't really understand what you mean honestly

tender ingot
#

Its all good dw

dusty wigeon
#

Maybe you want to use a weighted A* (It does not needs to be directly on distance.)? Because this is also a thing.

tender ingot
#

I have an idea of what might work instead of A* so will trial it out and go from there.

ruby salmon
#

anyone ever had OnDestroy being called on objects for no reason, even when they are marked with DontDestroyOnLoad ? its so weird

plain abyss
#

DontDestroyOnLoad just means it's not destroyed on load. It can still be destroyed in other ways

ruby salmon
#

hmm like what? apart from manually callling destory is there any other way?

#

seems like randomly some objects are destroyed, never seen it before, only seem to happen with my steam stuff

#

1 week from launch and i find unity doing weird weird shit

#

weird thing is update is still runnning even after the mysterious call to OnDestroy

sly grove
sly grove
#

Make sure you're looking at the correct instance of the script

#

Print the instance id to make sure the one being destroyed is the same one getting Updated

ruby salmon
#

i really wish there was a way to know how things get destoryed, would be ideal if it told you which object did it

#

instead of leaving it completely unknown

#

all i know is ondestroy is being called on objects randomly and not by me

#

this causes steamclient to disconnect and not work

ruby salmon
#

it is definitely happening

#

which means i can reinit from the update, bizarre..

terse oyster
gritty ore
ruby salmon
#

hmm never thought of that, would that work

dusty wigeon
#

As far as I know, it does not because of how unity calls the OnDestroy.

long ivy
#

set a breakpoint/log in OnDisable instead

ruby salmon
#

wouldnt that just tell u when it happens, not how

long ivy
#

you'd have the stack trace and a debugger, so you'd know when and what

gritty ore
#

Should work just fine. I just verified with OnDisable anyway in my own project (because this was convenient). Set a break point in OnDisable, when it was hit, it shows where the disable call came from in the Call Stack window in Visual Studio.

ruby salmon
#

wow thats very cool thanks

#

been wanting that for ages

#

now im intrigued, hehe

#

whats the betting im doing it myself, or somehow im not

#

one of the first times ive used the debugger LOL.

#

doesnt always get destroyed annoyingly

#

hmm the game did not stop at the breakpoint

#

ah it did this time

#

@gritty ore how do i see the callstack?

#

ah got it, doesnt show anythign though, just one line

long ivy
#

what does the debugger tell you about the object to be destroyed? What scene is it in? hopefully you haven't been ignoring warnings about DDOL only being valid on root GOs

ruby salmon
#

all i see is this

long ivy
#

then it's likely Unity is destroying it, which implies it's not DDOL

ruby salmon
#

object is in the unity scene dontdestoryonload, DDOL works in children too doesnt it

gritty ore
#

Well, I actually tested OnDestroy and you are right. You can, however, do the same check in OnDisable and it seems to give an actual stack. OnDisable will be called before OnDestroy in the same process so hopefully works to give you that stack.

ruby salmon
#

good thinking

long ivy
ruby salmon
#

yeh i added it to them all

#

doesnt do anything

#

works on all my other stuff likle my language system etc

#

basically same as ondestory, nothing

#

some invisible force is destroy that obj

#

didnt expect it to work debuggers never show me anything of worth

#

StackTrace stackTrace = new StackTrace(true); may work?

#

yeh nothing, just points to itself, so there is no way to hunt it down i think

#

seems to come from UnloadGameScene

#

but doesnt actually get destroyed

#

should be a DontDestroyOnUnload too

long ivy
#

all signs point to this GO not being DDOL. I don't know how you can conclude it's not destroyed while seeing OnDestroy happen with your own eyes. It sounds like you have a zombie, where the GO was destroyed but you keep references to it from user code

ruby salmon
#

yeh i dont get it either, it is DDOL, doesnt get destroyed, still there, all scripts working

#

in fact i dont need to worry even , SteamClient.Shutdown(); was in OnDestroy() and that was the issue, so i just removed it and put it inside OnApplicationQuit() instead

#

but it is very bloody weird

#

ah what a wasted day, if id known ive have moved shutdown code and be done with it in 10 sec haha

#

completely not consistent too, happens only sometimes

#

is there some sort of limit on how long a static var lives ? thats the oither weird thing, again steam related, one of my static vars becomes null at some point

#

which ive never seen (outside of android culling a host app)

tall ferry
#

The only other case would be if you were recompiling/reloading domain during play mode, where unity would clear the static variables

muted root
#

Hello, I'm trying to load sounds from the streaming assets folder (so that new sounds and musics can be added in mods). I'm using UnityWebRequest and the sound files seem to be loaded properly, but I still get no sound, would anybody know why ?

#
    {
        UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.WAV);
        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.DataProcessingError || request.result == UnityWebRequest.Result.ProtocolError)
        {
            Warning(request.error + Environment.NewLine + path);
        }
        else
        {
            AudioClip clip = DownloadHandlerAudioClip.GetContent(request);

            AudioSource copy;
            if (isSound)
            {
                copy = Instantiate(sound, soundsContainer);
                copy.name = key.Capitalize();
                //Sometimes due to loading time, the same key can be loaded twice at a time
                if (!sounds.ContainsKey(key))
                    sounds.Add(key, copy);
            }
            else
                copy = music;
            copy.clip = clip;
            copy.Play();
            Debug.Log(clip);
        }
    }```
#

Here is my code

#

It's a pretty simple code. I'm just instantiating each sfx individually to keep them as references since they are often played. And there can be only one music at a time on a separate reference

#

I was using addressables before and the sounds and music were working fine

#

    private IEnumerator LoadAudio(string path, string key, bool isSound)
    {
        AsyncOperationHandle<AudioClip> handle = Addressables.LoadAssetAsync<AudioClip>(path);
        while (!handle.IsDone)
            yield return new WaitForEndOfFrame();
        if (handle.Result != null)
        {
            AudioSource copy;
            if (isSound)
            {
                copy = Instantiate(sound, soundsContainer);
                copy.name = key.Capitalize();
                //Sometimes due to loading time, the same key can be loaded twice at a time
                if (!sounds.ContainsKey(key))
                    sounds.Add(key, copy);
            }
            else
                copy = music;
            copy.clip = handle.Result;
            copy.Play();
        }
        else
            AddressableError(path);
    }```
#

This was my code with adressables and it was working fine.

#

Code is almost identical, except for the way I load the audioclip

#

    public void PlaySound(string sound)
    {
        if (sounds.ContainsKey(sound))
            sounds[sound].Play();
        else
            StartCoroutine(LoadAudio(Path.Combine(Application.streamingAssetsPath, "Sounds", "SFX", sound + ".wav"), sound, true));
    }```
#

And here is my playsound method to play a SFX, either from the cache or instantiate a new sfx reference

#

All sounds and music are wav if it helps

#

The unity request is a success, I can see my audiosource with audioclip in them albeit the name is empty for some reason but the field is not null

#

OMG.... I'm dumb... The sounds were disabled in Unity Editor... Dunno why... Well... It works now lol. Gotta love those stupid newbie mistakes 😅

ruby salmon
#

haha

#

the little speaker gets u every time 🙂

cedar veldt
#

Any expert would know how to instantiate on runtime skinned mesh renderers prefabs on player (when the player swaps armor pieces, for instance) ?

cobalt pivot
#

Chat

upbeat path
#

you know the fastest way to NOT get help is to do exactly what you have done

cedar veldt
#

Nobody on earth seems to know because of root bone and bones array problem. Also nobody knows why swapping mesh on component skinned mesh renderer do not work

dusty wigeon
# cedar veldt Nobody on earth seems to know because of root bone and bones array problem. Also...

Your question was not clear, because instantiating a skinned mesh renderer is as simple as instancing a GameObject. If you want armor piece, you can simply export the whole character with it and disable it.

That being said, there is indeed a small twist for adding a SkinnedMeshRenderer on an already created bone structure. As you pointed out, simply changing the root bone is not enough (In fact it has nothing to do with it), you need to change the underlaying root array as well.

tender crow
#

Compute shader (FFTSpectrumViewer): Can't find kernel (0) variant with keywords: CHANNEL_BLUE CHANNEL_GREEN CHANNEL_RED. Does anyone know why I'm getting this error in the snipped code (FTTSpectrumViewer) provided in the hastebin. The error comes from the dispatch line on the computer shader

tender crow
#

the link and the snip are two different things

untold moth
#

Which dispatch is it thrown at?

tender crow
#

First one

untold moth
#

And what is textureConverter? Where do you assign it?

tender crow
#

all the logic for this is around 400 line

#

the other stuff is water simluation; I've tried changing different keywords etc, nothing is null as well

untold moth
#

Is textureConverter assigned in the inspector?

tender crow
#

should be in the constructor

#

it's taking loading a compute shader from a different file, and I debug logged it and it seems correct

untold moth
#

Let's assume that's not the issue, is the shader compiled correctly? Are there any errors if you select it in the inspector?

tender crow
#

No errors in the inspector; clicked on it to make sure and added an error intentionally to test

untold moth
#

Okay. Can you try removing the multi compile options and see if that helps?

tender crow
#

should I get rid of the logic as well?

untold moth
tender crow
untold moth
#

This might imply that the shader is not compiled correctly

timber flame
#

In my 2d project, I have used spine. My question is about how you implement the animation logic and what architecture you choose, I use the built-in spine animation and not animator.
My approach is to define an animation asset and keep all of them in one collection.
Some conditions should be satisfied to play an animation,

public class AnimationDefinition: ScriptableObject
{
    [ValueDropdown("@GetAllNames()")]
        public string Type;

        [ValueDropdown("@AnimationLabel.GetAll()")]
        public string Label;

        public AnimationData[] List;

        public AnimationDirection Direction;

        [Range(0, 1)] public float SelectionProbability;
        public bool ShouldFlipOverridden = true;

        public AnimationGroup Group;
        public bool HasRootMotion;

        public AnimationCondition[] Conditions;
}
obsidian stump
#

can we convert a game object to assetreferencegameobject through code.

dusty wigeon
sly grove
sick flame
#

Hello guys,
Is there any way to disable
UnityShaderCache file under Android storage.
It caches the compiled shader binaries there, but I don't want this thing to happen.

hushed fable
#

Don't cross-post.

coral depot
#

sorry :)

whole plaza
#

Unless you want your game to run at like 4fps

#

Compiled shaders need to be saved for later use and if you would to disable that you would have to constantly recalculate the shaders

sick flame
whole plaza
#

Hmm very specific case, maybe your approaching it wrong ? You shouldnt like need to delete the shader cache, yk

obsidian stump
#

How to find out if there is any script attached to a gameobject when I don't know the name of the script.

sly grove
#

You mean any component?

#

Any monobehaviour?

#

One of a specific subset of scripts you wrote?

#

Can you be more specific and explain what you're trying to achieve here?

#

Every GameObject always has a Transform component at the very least, so there will always be at least that component.

obsidian stump
#

I want to find out if there is any script on a particular gameobject or not.

sly grove
#

Can you clarify as I asked what you mean by "any script?"

#

the answer to your question depends on that.

obsidian stump
#

Any c# script.

sly grove
#

So MonoBehaviour

obsidian stump
#

Yes.

sly grove
#
if (myObject.TryGetComponent(out MonoBehaviour mb)) {
  Debug.Log("There is at least one MonoBehaviour on this object");
}```
#

this isn't very useful though

#

which is kind of why I'm asking what you're trying to achieve here

somber swift
#

Smells a lot like XY

obsidian stump
sly grove
#

Debug.Log(mb.GetType().Name);

#

again

#

what are you trying to do

obsidian stump
#

Just getting a script.

sly grove
#

If you explain your goal, we can try to give the best possible answer here. Otherwise we're just going to give you something that may or may not be very useful or efficient.

obsidian stump
#

I am trying to get the scripts from remote objects like addressable which I don't know and attaching it to new gameobject like addcomponent.

sly grove
#

WHy not just Instantiate the object/prefab you want to copy?

obsidian stump
#

I am working on a vr project remote rendering.

narrow coral
tall ferry
narrow coral
tall ferry
#

No one is gonna fight to help you. Make an effort and describe the issue properly. Narrow down the code too

narrow coral
tall ferry
glacial obsidian
#

So I am working on uploading and testing a jam game. And my WebGL build is immensely laggy after sufficient time playing on OperaGX especially. But also on all browsers eventually. The profiler leads me to the culprit being this call:
SoundHandle.Instance.CreateChannel
Which I assume is the call for requesting an audio clip play. All my audioclips are preloaded, compressed in memory, and a 25% quality already. Im not sure why the audio slowly builds up to immense lag as the game continues, but it consistently lags after about 15 minutes. Im guessing something persists between scenes. Any idea how I can clear this memory or something to prevent lag? Its really killing the vibe as the desktop version is perfect

#

Additional context: Every single spike is just an audiosource.PlayOneShot playing.

Its astonishing really, I have no idea and google isnt yielding me much either.

#

Not that 60FPS is bad, but its also corrupted audio, which is my larger issue

vernal kindle
#

Hello! I don't know if this is advanced enough but i have a problem that i'm struggling to find resources to be able to solve it myself.
I have an app where the user can create cards for a quiz game, They can load a BG image (Texture2D). and customize the card Question and Answer (string) and give the card a score value (int).
The part i'm struggling is in how i should approach saving that card to disk, maybe to a persistent path, and then load that saved data. The image part is where i'm stuck and i need to find a way to make a local copy to store inside the savePath, and then load that copy when the app is launched again.
Where i should look to be able to do this functionality? I need guidance since i'm lost on where to start. Also it's pretty much the first time i've ever interacted with saving and loading files that aren't string or int. Any help is appreciated 🙂

exotic trout
vernal kindle
grand cipher
#

Hi everyone!

I have a question regarding data copying in Unity. Is there a way to copy from NativeList<T> to a standard List<T> in C#? I’m wondering if there’s a method that is faster than traditional iteration and value assignment, which tends to be quite slow.

Thanks for any tips!

stuck plinth
grand cipher
scenic forge
#

I was about to suggest avoid copying at all by changing the consumer to accept IList<T>/ICollection<T>/IEnumerable<T>/etc, then I remembered most of Unity's native containers don't implement any of the standard interfaces.

#

You can still consider that route by having a wrapper class wrapping NativeList<T> which implements whatever interface you need, to avoid copying altogether.

fathom jewel
#

Hi guys, Does anyone here know how to pass data from main scene to an entity sub-scene during runtime in unity ecs?

timber flame
#

I have different skins (made by Spine) for my 2d characters. Each character can move in different directions. There are a different animation corresponding to each direction. I have used on skeleton for all directions. My question is that I need to enable/disable skins by changing the character direction. Is there a better way to handle it?
I think it is better to create different skeleton animation for each direction and set skins for each initially then enable the gameobject based on the current direction :/

sly grove
hazy epoch
#

Okay. I know this is simple, but I'm a bit rusty right now.

private void Update()
{
    Vector3 direction = new Vector3(movementInput.x, 0.0f, movementInput.y).normalized;

    if(direction.magnitude >= 0.1f)
    {
        float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
        float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);

        transform.rotation = Quaternion.Euler(0.0f, angle, 0.0f);

        Vector3 moveDir = Quaternion.Euler(0.0f, targetAngle, 0.0f) * Vector3.forward;

        controller.Move(moveDir.normalized * speed * Time.deltaTime);
    }
}

In that code, if movementInput.x is 0.0f and movementInput.y is 1.0f (basically you're pressing "D" to go "RIGHT" my character right now runs to the right in a wide circle AROUND the ThirdPerson CinemachineFreeLook camera, which rotates to keep its focus on the player. What I want to modify it to do, is have the player just run PERPENDICULARLY to the camera, to their right. What am I missing?

The same result should occur if movementInput.y is -1.0f (pressing "A" to go "LEFT") except the player should run to the left, perpendicular to the camera.

hazy epoch
#

Yes...that's what my code already does. It DOES move in relation to the camera. I just want to adjust it...as described.

dusty wigeon
#

Not sure I understand then

sly grove
#

if you're getting a circle it means the camera is rotating as the player rotates

dusty wigeon
#

Anyone with experience with a crash on a CallStack like the following:

dusty wigeon
sly grove
#

access violation is basically a segfault

dusty wigeon
#

Yeah, but on Unity side.

sly grove
#

yeah inside the C++ side of the engine

#

could be the equivalent of a null pointer exeption...

If it's your fault and not a bug in the engine, it'd be due to you passing bad data into some part of the engine

dusty wigeon
#

It only happens on Switch and it is a 8/10 reporduction rate.

#

Yeah, but what Data.

sly grove
#

Got a full stack trace?

dusty wigeon
#

This is the full stack trace

#

It is during the initial loading.

#

This is the parallel stacks. (What is happening on other threads)

#

While it decompress and read Addressables.

#

From what I understand

azure meadow
#

I have a serialized field that I want to deprecate and migrate to a new one.
I can detect that if the old field has a reference, I write the new field and set the old one to null so it "auto migrates"
Where would that be a good place to do it? OnValidate? 🤔
(I can't use PreviouslySerializedAs since they are different fields, one is a pointer and the new one is a struct)

dusty wigeon
#

OnValidate + Reimport all asset I believe.

#

I'm not 100% sure though

azure meadow
#

makes sense, will try 🦾

dusty wigeon
#

Besure to flag it as dirty too.

#

EditorUtility.SetDirty I believe

patent bear
# dusty wigeon Anyone with experience with a crash on a CallStack like the following:

What is RAM usage like? If allocation fails on consoles, unity generally fails silently and let's the game crash when something is accessed later on. I noticed this is happening in a load, which is why i ask (ram heavy operation).

Alternatively, are you using addressables? It could be trying to load an asset that had been unloaded. I had issues like that ages ago on a project. I thought that had been fixed but it's possible it still exists in some way.

whole plaza
whole plaza
glacial obsidian
#

heres the full set of instructions being called that are taking up now only 28% because deep profiling is also causing immense resource usage

#

A lot of the calls Up until AudioSource.PlayHelper dont mean much as every sound effect causes the lag spike. ANd every sound being played even long form music sounds corrupted

dusty wigeon
# patent bear What is RAM usage like? If allocation fails on consoles, unity generally fails s...

@whole plaza

If it was RAM usage I would have the same issue in a development build given that I do not have any extra memory allocated for dev build.

And yes I do use Addressables. However there is nothing that should be unloaded at that stade of the loading, I could always keep an eye on that though given that it seem to be something akin to MeshFilter being NULL.

At the moment, I'm doing the old delete stuff till it works.

glacial obsidian
#

Additional context to the frame the profiler is on is its loading a 0.2s long footstep sfx. So it realistically shouldn’t eat up 28% of my cpu time

glacial obsidian
#

i mean thats the full stack of calls leading to the huge CPU usage

#

which is all leading to the CreateChannel call for i guess running audio?

#

im wondering if as more sounds are created and played throughout the game if theres some large buffer that needs to be cleared or something to prevent huge processing issues

#

because this consistently happens the longer the game goes on for

#

PlayerLoop is called inside of the camera like FrameRender() something functionlity. But thats everything leading to it

livid kraken
#

In our game the player can upgrade his weapon to have multiple shots and a lot of them. Right now each hit has it’s own light and sound source. Obviously at 50-60 hits this overwhelms the system. I’m looking for a smart way to somehow distribute lights and sound in the total hit area to make sense. Problem is that hits can be different types depending on the material. This only matters for the sfx however.

regal lava
#

Well, pooling the audio and preloading it for starters instead of using one-shots. Not too sure for lighting myself for something that's being generated in handfuls, but usually I just fallback onto investing heavily into emissive shaders.

#

As far as projectiles/abilities go

livid kraken
#

The audio is already pooled. Im looking for reducing the number of sources needed in the first place. Emissive shaders also won’t help Im talking about the actual hit vfx emitting light.

#

What I need is to somehow spatially distribute n light sources and y sound sources to the total hit area

#

But this is complicated since the hits are not always on the same plane… for example

#

Oh and it needs to be both spatial and by type since two different surfaces can produce different audio but be spatially close to each other

regal lava
#

Ah, yeah that sounds complicated, specifically for the lighting. For 3D audio I do kinda check on similar frames if nearby objects share similar audio clips, but this is mostly to prevent overlapping audio and reducing overall loud piercing audio

#

and instead just reduce what is played in that frame

#

The lighting however would probably be more noticeable if not done completely correctly, but similar idea would apply.

livid kraken
#

I mean the obvious solution is to first sort all hits into planes, then cluster them into groups, then subdivide the groups by type and then distribute the lights and sfx but this seems rather computationally heavy so this is why I am looking for a smarter solution.

grand cipher
untold moth
#

Player loop is at the very root of the hierarchy. They just have it in reverse mode

glacial obsidian
glacial obsidian
patent bear
# dusty wigeon <@755084025416253440> If it was RAM usage I would have the same issue in a dev...

Oof, a solid plan but sorry for the tedium. One last suggestion which may not work for you:

If you have any common assets in your addressables, out them in their own group (if the aren't already) and try loading them at boot and never releasing the handle. I've done that a few times to solve similar, though not the same, issues. It will increase team usage since they never get connected but they will also never get released. In my case i was seeing destroyed objects get accessed by engine code that would crash on a segfault later down the line.

bold berry
#

can soembody maybe help i try to install nuget and i got .net 8 but it says version not supported

dusty wigeon
#

I have not test this implementation, but the latest implementation of loading each asset one by one was working (yield each one individual).

bold berry
#

i actually need it for opentk

upbeat path
#

and? does not support means does not support

dusty wigeon
patent bear
# dusty wigeon I have not test this implementation, but the latest implementation of loading ea...

Sounds like deadlock, but it's segfaulting instead of hard crashing? Loading everything/dependencies manually one at a time would be a solution to the fact addressable can only load one thing at a time. I wonder if there is any bundle thrashing, where some bundles are unloading dependencies incorrectly, though I haven't had issues like that for 4 years 😕

Do you have CRC checks disabled on the bundles? That isn't necessary for locally distributed builds. I had a project that went from an almost 60 second load to pretty much instant with that toggled. Might help get your workaround faster if that's not already how you have it set up.

#

There's also a platform thing you can do to speed it up, though that's getting into NDA territory. You might be already doing it, though.

dusty wigeon
patent bear
dusty wigeon
wicked verge
#

don't cross-post and wait for someone to answer

dull spade
#

Sry dude

remote bough
#

What opinions do people have on using ScriptableObject Event system as the one proposed by 'Ryan Hipple' at Unite 2017 (https://www.youtube.com/watch?v=raQ3iHhE_Kk)?
I like the basic idea of using events to help decouple sender and receiver, but wonder if the further decoupling of using a scriptableObject as a middle man has actual value in practise or if it just over-engineered?

Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...

▶ Play video
regal lava
#

I'm a singleton enjoyer so I wouldn't know

devout hare
#

I don't think it ever caught on

dusty wigeon
remote bough
dusty wigeon
remote bough
long ivy
#

opposing view: I like the SO architecture. Avoiding mutable data in SOs is good advice for people who don't understand the SO lifecycle, but we're in code-advanced so it's less applicable

dusty wigeon
remote bough
#

But with regard to using scriptableObject with events would actually make it more immutable in the way you are describing, espeically if they are only set up via the editor.

upbeat path
dusty wigeon
sly grove
#

It's fine if you know what you're doing and generally even more fine if the mutable data in question is not serialized on the SO.

#

Definitely a pitfall for new users though

dusty wigeon
dusty wigeon
regal lava
#

If you could move around POCO instance around the editor we'd just use those honestly

upbeat path
#

prefabs are not data containers nor are they mutable at all

dusty wigeon
#

Prefabs are mutable and they contains data. You instantiate one and you have both, the mutable and immutable representation of your data.

remote bough
#

Ok whilst interesting the whole scriptableObject mutable/immutable is not really the point of what I was asking - it was ( as far as I can tell ) the idea of not simply having events and listeners, but to have a middleman that deals with registering and raising events. That is neither event source nor listener have any knowledge of each other, instead they both commuicate with this middleman class instead.

thin mesa
# upbeat path incorrect

that is correct. prefabs can be changed at runtime. naturally those changes do not persist across sessions in a build like they do in the editor, but it is possible to modify a prefab at runtime

upbeat path
#

if it does not persist then it is not truely mutable

regal lava
dusty wigeon
# upbeat path incorrect

SO is a monobehavior... Not sure how it is incorrect.

My point though is that prefab can be instantiate and it expected to be.

thin mesa
dusty wigeon
remote bough
#

the idea that SO should be immutable is interesting though. The fact that they do not enforce this, make them more problematic. However using them to say hold values for some object, that I can tweak in editor, and then teak later at runtime, does mean that sometimes the values are not what I've expected. I've always taken this just as a 'fact of life' if you are using them that way, but i'd not considered the approach of treating them as immutable - certainly something to think about.

upbeat path
sly grove
dusty wigeon
remote bough
upbeat path
#

no, you could not make a Prefab mutable in a build

dusty wigeon
#

You can though, just save the difference in your prefered file format and load it whenever you start the build.

#

You can modify prefab before instancing.

#

Not that I would do that.

upbeat path
remote bough
regal lava
dusty wigeon
#

At the end, whatever you want to use SO as immutable data or not is your choice.

There is technical implication such as how it behaves in a build vs in Editor.
And there is conceptual different such as how you expect them not to change.

remote bough
regal lava
#

It's common practice, plus you get the benefit of calling it statically

upbeat path
regal lava
#

while you still need that reference to the SO somewhere

regal lava
remote bough
#

Note to self - never ask about scriptableObjects in the future 😉 It would have been safer to ask which is the best game console 😉

upbeat path
#

you can always ask me, I have a much more open mind about SO's than most. Everyone else just seems to spout the party line

regal lava
#

My only major complaint about SOs is they can create a lot of asset bloat

dusty wigeon
#

SerializeReference for the win

regal lava
#

pretty much but no real official support never ever

remote bough
#

I knd of feel i use SO as global variable storage - which is probably bad 😉

remote bough
#

thinking about So being immutable I guess the way to enforce that would be to have private fields marked as serialize and a proeperty getter only that returns the field value?

dusty wigeon
#

You can still change it with function call.

#

Being immuable is a concept. (In this case, given that is mostly impossible to easily make them that way.)

small latch
#

I abuse serialized auto-properties with private setters on all my SOs LUL

remote bough
dusty wigeon
glacial obsidian
# glacial obsidian

Back into this as I have a moment to look into it. I can’t find any documentation online on CreateChannel(). But it seems to (this is an inverted stack) continually become a more and more taxing call as the game progresses and plays more sounds. As if it’s not removing unused resources between scenes. I’d like to look into any documentation or class definitions but i just don’t know

#

So if anyone knows where like, deeply hidden unity code exists that’d be great. It’s closed source so probably no luck.

#

At worst, maybe I can make an official unity post for a unity dev to see. Anybody know how? I’d like to get to the root cause of why playing a 0.1s sfx is taking. 30% of the time for a 5 FPS frame. And why the audio corrupts slowly as the game lasts

remote bough
# glacial obsidian Back into this as I have a moment to look into it. I can’t find any documentatio...

Couple of thoughts

  • does the performance issue exist on other platforms than webgl?
  • Are you (implicitly) creating too many channels?
  • Does webgl have limits on soundchannels (whatever they are in this context - maybe check out FMOD for more info) or perhaps just exceeding the number of channels it can handle.
  • Can you track lifetime of these oneshots? Maybe they are longer, or just sticking around for a long time and over-whleming the audio engine.
  • Can you build a small test project to replicate the issue ( maybe you already have?)
#
  • does the profiling have a useful audio section? Not sure never looked myself
remote bough
# glacial obsidian Back into this as I have a moment to look into it. I can’t find any documentatio...

Could there be memory pressure/limits around webgl builds? - see this https://qa.fmod.com/t/separating-fmod-banks-to-get-around-unity-webgls-2gb-limit/20375

glacial obsidian
#

It could be but I don’t have that many unique sounds. And definitely never that many overlaid at once. Unless there’s some like cache of played audio that isn’t being cleared that slowly builds to a limit.

#

Like in the scene where I typically started to experience lag ~10 minutes in each spike is per a 0.1s step sound. And the only other constant track is a background track that is like a 30s loop

remote bough
remote bough
glacial obsidian
#

I am hammering them in previous scenes

#

But I experience lag independently afterwards regardless

#

Like once the like, idk usage builds, I have constant audio lag throughout and general performance issues

#

The scene that I had to majorly tone down had lots of repeated bush shaking sounds. And then nearing the end of that scene and any scene after that I experience lag

#

And removing those sfx does fix the issue. Adding constant audio sources rather than playclipatpoint didn’t resolve it. Just ditching them for the final jam product helped

#

I’ll try to replicate it tonight. Go home, create a basic scene where I hammer hundreds of quick identical sound effects

#

I can even push it somewhere so that if you want to experience it maybe you can. I’m assuming it’s not a system thing because it happens independent of browser and my pc is kinda a beef cake

remote bough
# glacial obsidian I can even push it somewhere so that if you want to experience it maybe you can....

If its a performance issue then systems will affect it as more powerful ones will take longer to exhibit the problem ( if at all ) and i'd also expect browser builds to suffer more as they appear to limit memory usage and maybe other stuff.
Is there a way to force stop all sounds when you leave scenes?
I wonder what happens if you destroy audiosource?
In the past i've sometimes used an intermediate scene to use unity unload code, but thats not an answer for most cases.
Its hard to know, but it does seem to me you might be abusing the audio system, if you mean you are playing lots of bush sounds at the same time, or overlapping) on the other hand if you mean you just call oneshot many times in a scene, but previous sounds had alawys finished then that shouldn't be an issue.
Final thought do you have any debug code? I'd be checking that any code logici is not literally trying to play the same oneshot every frame or something silly. It can easily happen.

glacial obsidian
#

I tried forcing garbage collecting at end of scenes to little change.

#

I’ll replicate this in a 0 fluff scenario for closer inspection

#

But that’ll be when I come home from work in an hour and a half or so

glacial obsidian
glacial obsidian
#

Recreated the issue in a VERY tiny sense

#

the only files are one script and two audios. One audio is about 0.5s long, the other 9.2s.

I run the code for a few minutes to build up whatever is being built up. And even after wiping the scene which should theoretically make it a clean slate, the lag persists. Heres the short script:

using UnityEngine;
using UnityEngine.SceneManagement;

public class TestSceneManager : MonoBehaviour {
    public AudioClip _clip;
    public AudioClip _longerClip;
    public float DelayBetween = 0.5f;

    private float _timer;
    private bool _paused = false;
    private void Update() {
        _timer += Time.deltaTime;
        if (_timer >= DelayBetween && !_paused) {
            _timer = 0;
            AudioSource.PlayClipAtPoint(_clip, Vector3.zero);
        }
        if (Input.GetKeyDown(KeyCode.Space)) {
            _paused = !_paused;
        }
        if (Input.GetKeyDown(KeyCode.LeftShift)) {
            AudioSource.PlayClipAtPoint(_longerClip, Vector3.zero);
        }
        if (Input.GetKeyDown(KeyCode.W)) {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }
}
#

So like, its not specific to my game jam submission. Regardless of scene switching, if I play enough audio clips at any point ever, it seems to build up to some sort of limitation that causes lag and distortion. And that lag and distortion persists even through the GC runs that happen between scenes. Nothing even gets collected.

#

Here is deep profiler. This is while i have turned off the rapidly repeating sound, and just pressed the singular sound play button right after going to a new scene

remote bough
#

Out of interest what settings are you using for the audio clip importer? Post a screenshot?

#

Also does this happen in a standalone build?

glacial obsidian
#

This happens with build and run for webgl only

#

it doesnt happen in editor or windows builds

#

As for the audio, its default here. No quality loss, decompress on load. But this happens with it set to 10% quality and streaming or compressed in memory. Albeit much slower. That was my first attempt to mitigate it for the jam

remote bough
#

If we’re lucky it’s a bug that Unity can fix, but off hand I can’t see any good reason for this happening, which sadly means no good workarounds for you jam

glacial obsidian
#

I just removed the most commonly played audio from my webgl build lol

#

its been submitted already

#

but id like to know for the future

remote bough
#

Yeah please submit a bug, this seems like a ps good a report Unity would ever get, so hopefully will jump on fixing it

#

What was the jam?

#

Be back later

glacial obsidian
#

Themed Halloween Jam 19 or something akin to that

glacial obsidian
#

It seems to test most strongly in OperaGX

#

or the lag i guess sets in fastest and hardest.

#

it happens eventually on Edge and firefox too though

#

idk submitted a bug report

remote bough
# glacial obsidian the only files are one script and two audios. One audio is about 0.5s long, the ...

Hmm, bad news - I created a test with your code and couldn't see any issue with it running in a browser. Even when i set the delay to be lower than the length of the short audio clip and left it running for 5 minutes, nothing bad happened. Memory went up a bit according to chrome from 318mb to 324mb. That might be a concern, but over 5 minutes with the frequency of clips played every 0.3 seconds it doesn't seem like a memory leak. Plus after 5 minutes it seems to plateau at 324mb.
I tried this with a short clip uncompressed and then with it compressed to 10%.
Did your test use the same project that has the problem or was it in a fresh project? It really should be a fresh as if its fine there then you know there is an issue with your project and probably not with Unity.
Additionally you said the clip was imported with defaults, did you set overrides for webgl? I didn't, but I want to double check.
Almost 10 minutes - no issues still 324mb memory usage.
Build uses 'Code Optimisation = Shorter Build Time'
Publishing settings i'm pretty sure are all default.

EDIT - IMPORTANT
Maybe I spoke to soon - just did a second test as I added a spinning cube to visually check performance. Everything is still playing fine but after 10 minutes the chrome tab went from 156mb to 321mb memory usage. I did do a reload scene after the first minute and this time delay is 0.2 whilst the audio clip is 0.5 seconds long. I'll leave it for another 10 mins and see if there is any change. if there is, then perhaps there is a memory issue, otherwise not sure what is up.
19 minutes and still working fine and stays at 321mb usage - can't go any longer audio is too annoying.

glacial obsidian
#

Fresh project.
I didnt set overrides for the test, but yeah the audio is bad. It could be an opera GX exclusive issue. Or my opera GX exclusive. Because on Edge I saw some performance decrease but not nearly as significantly as I saw it on OperaGX

#

And the build setting was whatever the development build settings are because they become locked

#

I will say that, its nearly exclusive to operaGX. Or not exclusive exclusive, but significantly exclusive.

#

but I have the same hardware acceleration settings on all browsers i tested. So I cant be sure

#

I did submit the bug report with operaGX listed exclusive

glacial obsidian
#

Maybe the lag is related to limited browser resources that I approach by hitting the 321Mb usage limit

#

that it builds up to

#

cant say

untold moth
glacial obsidian
#

OperaGX is chromium

#

so its allegedly supposed to be kinda supported

untold moth
#

Chromium and chrome is not the same thing

glacial obsidian
#

Notes:

The Web platform also supports the latest version of the Chromium-based Edge browser.

#

Ofc its not edge

#

but they support chromium browsers

untold moth
#

There might still be differences in implementation that modify the behaviour.

#

Anyways, I don't think there's much you can do about it without access to unity source code.

glacial obsidian
#

I think opera GX meets the 3 specifications

#

but yeah
The browser is WebGL
2 capable.
The browser is HTML 5 standards-compliant.
The browser is 64-bit and supports WebAssembly.

untold moth
#

Your best bet is to fill a bug report and open a forum post. Then wait.

glacial obsidian
#

i submitted a ticket with opera gx mentioned directly

#

i assume ill get a response saying "not a bug ur browser sucks" if thats the case

#

and if its not the case theyll say something else or nothing

dusty wigeon
# patent bear yup, yup, and sort of. I'm currently trying to debug something similar on PS5 a...

So, yeah, it was a specific asset. I deleted it given that it was not important and it works perfectly fine.

The asset itself was pointing to a considerably large FBX which was not even addressed (causing it to be duplicated).

To find the assets, I just did a binary search on whatever the build crash or not. (Cutting the loading of assets in half each time) It took me pretty much the whole day.

patent bear
dusty wigeon
# patent bear Congrats! Glad you could teach it down. I'm still going to avoid that since the ...

What is your version ? In Unity 2021 or 2022 I believe they sped up building drastically with incremental build. Also, if your project is not badly setup, you could potentially not build everything. Obviously it assume that you do not need it and you are using Addressable.

My project is 4G on Switch and it takes 10-15min to incrementally build on top of it. (With only code modification.)

And if you have stack trace, you could always drop it here. I might know something about by some sort of miracle.

patent bear
# dusty wigeon What is your version ? In Unity 2021 or 2022 I believe they sped up building dra...

We are on 2022 but the game is a large open world game for higher end platforms. The addressables are built programmatically off the open world so they can be streamed in, so splitting up the addressable and content is a bit tricky. Build is at 14gb, but that's with package compression with kraken turned on which is really good on ps5.

I am using incremental builds without addressable build but it's still a 25 minute process, end to end.

I'm trying to solve a different issue where the game has decided to crash at boot, in native vm setup, only in development builds. Once i get those running again I'd be happy to share a trace. I have some platform support, thankfully, but the issues seem unity specific so i don't know how helpful it will be.

dusty wigeon
lean flare
#
            {
                colorAdjustments.colorFilter = nightVisionColor;
            }
            
            if (volume.profile.TryGet(out LensDistortion thisLens))
            {
                thisLens.intensity = pov;
            }

this code only changes post processing volume component values when i make a change in the code and it compiles. in editor when changin the inspector values of this code, it doesnt update. it only takes changes after i change code and it compiles. pain in the ass please help...

patent bear
# dusty wigeon 25min is not that bad. Just enough to want to dual task. It seem strange though...

That's if I'm not rebuilding content and it's an incremental build. Addressable builds bump that to ~2 hours. The groups are divided programmatically (and in a system I didn't write). It's mostly a "do I want to commit time to this over other tasks?" because there are some other deliveries that are higher priority and I'm trying to not fall down a rabbit hole. Lowering the RAM usage overall actually helped a lot with stabilizing things, but I only just wrapped the save system and still have other platform requirements to get in.

I'll do it if it comes down to it but, like always, timelines never quite allow everything to get a "correct" solution.

dusty wigeon
patent bear
#

I love/hate that my reputation is as a fixer that comes in at the end of the project to make things work. It's stressful but I can't say it doesn't keep things interesting.

remote bough
lean flare
robust nexus
#

so source ??= new T(); when T is contrained to a MonoBehaviour in addition to an interface will outright fail or will it still create the type but fail to properly get picked up via callbacks? I don't care about the MonoBehaviour portion here, just the constant details set on the interface portion. I'm mostly curious if we're allowed to do this anyways with Monobehaviours

drifting solstice
#

you shouldn't construct MonoBehaviours at all, they should be made by unity

#

not sure what you mean by "fail to properly get picked up via callbacks"

robust nexus
#

Has the constructor been blocked off at the API level or will it just misbehave if constructed as new() but I attempt to use it's normal lifecycle? Either way this looks like a dead end, I'll have to redo this bit

robust nexus
drifting solstice
#

those aren't callbacks

#

also, UE?

drifting solstice
# drifting solstice those aren't callbacks

huh, nvm, apparently unity does call them callbacks

Event functions are a set of predefined callbacks that all MonoBehaviour script components can potentially receive.
that's not what "callback" typically refers to, but ok, i guess

craggy spear
drifting solstice
#

i guess that makes sense, never heard it referred to like that. seems horribly ambiguous with Unity Editor and Unreal Engine

craggy spear
#

yeah, it's a very very... very rarely used acronym, because 99.999% of people use UE for Unreal

#

but from the context it was used, we know it's not meaning Unreal this time 😄

sharp dune
#

Link to the github gist
Could someone check out this state machine I made, I want to know If I'm going in the right direction and if it's modular enough, because I think it's missing something
I feel like I'm going overboard with the generics.. Could someone plz lmk? Thank you in advance :)

wicked verge
dusty wigeon
# sharp dune [Link to the github gist](https://gist.github.com/blockchain200/6b30768b574f63ed...

Your input should be in its own class.

Your state should not be directly referenciate in the code. (use a dictionnary (<type, state>) (Open-Close principle))
You should not move your character directly in the StateMachine. (Single Responsibility Rule)
There is should never be a situation where the current state is null.
Try to avoid using OnStart, OnUpdate and OnChange and use Enter, Update and Exit. (OnXXX is mostly use with event/callback. Also, it helps to distinguish between if it is a Unity callback or not.)
You might consider making your statemachine as a partial of you Character Class. It makes you able to share private value.
You need a CharacterState somewhere to hold a reference to your character or for other character specific needs.
You might want to not use abstract State or abstract StateMachine. (StateMachine.MoveInputActionValue from CharacterIdleState compiles ?)
StateMachine should not be a MonoBehaviour. It should be driven by a Character or other class.

sharp dune
dusty wigeon
#

StateMachine is usually an extension of the character

sharp dune
#

So i should have a controller class that passes in data to the CharacterStateMachine?

dusty wigeon
#

Having it live by itself is strange.

sharp dune
dusty wigeon
#

And, it is better use

public MyType MyVariable => myVariable;```
dire sparrow
#
    {
        ssCamera.gameObject.SetActive(true);

yield return new WaitForEndOfFrame();

        RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
        ssCamera.targetTexture = renderTexture;
        ssCamera.Render();

        Texture2D endtex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        RenderTexture.active = renderTexture;
        endtex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        endtex.Apply();

        ssCamera.targetTexture = null;
        RenderTexture.active = null;
        Destroy(renderTexture);

        File.WriteAllBytes(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop), "GG.png"), endTex.EncodeToPNG());

        ssCamera.gameObject.SetActive(false);
    }```
#

This works just fine in the editor, but gives a null reference error in the android logcat.

#

Literally no idea why its happening, it was working before

#

It could have stopped working after I migrated the project to unity 6

dire sparrow
#

Along with the info that the problem is in this method

devout hare
#

Make a debug build so that you see the line numbers

thin mesa
#

also consider just printing the state of each of the objects being used in that method so you can see which is null

upbeat path
#

Also this
File.WriteAllBytes(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop), "GG.png"), endTex.EncodeToPNG());
is not gonna work on android

wicked verge
#

probably because it's saving to desktop

#

which definitely does not exist on mobile

thin mesa
dire sparrow
dire sparrow
peak badge
#

I'm trying to write optmized Compute Shader, and I'm noticing a bottle neck... but I am not sure how to identify the cause. Here's my profiler and my command buffer

        cmd.SetExecutionFlags(CommandBufferExecutionFlags.AsyncCompute);
        for (int i = 0; i < 200; i+=2){
            cmd.SetComputeBufferParam(computeShader, 1, "grid", grid);
            cmd.SetComputeBufferParam(computeShader, 1, "output", output);
            Dispatch(1);
            cmd.SetComputeBufferParam(computeShader, 1, "grid", output);
            cmd.SetComputeBufferParam(computeShader, 1, "output", grid);
            Dispatch(1);
        }

i.e. it runs my shader about 200 times per call.
Everything just says "Idle" and "waiting on graphics fence"... but shouldn't it be running async? Why is it waiting ?

#

I call it once per update.

    void Update() {
        Graphics.ExecuteCommandBufferAsync(cmd, ComputeQueueType.Default);
#

Is swapping the buffer actually resulting in a copy? I dunno why else it would need to wait

sly grove
remote bough
#

Also i prefer to group similar operations together such as camera.targettexture and rendertexture.active.
I'd probably also explicitly destroy the texture2D, unless I expect to take alot of screenshots, in which case i'd keep it around at scope to the class.

#
    {
        ssCamera.gameObject.SetActive(true);

        yield return new WaitForEndOfFrame();

        RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
        ssCamera.targetTexture = renderTexture;
        ssCamera.Render();
        ssCamera.targetTexture = null;

        Texture2D endtex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);

        RenderTexture.active = renderTexture;
        endtex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        endtex.Apply();
        RenderTexture.active = null;

        renderTexture.Release();

        File.WriteAllBytes(Path.Combine(path, "GG.png"), endTex.EncodeToPNG());

        DestroyImmediate(endtex);

        ssCamera.gameObject.SetActive(false);
    }```
craggy spear
#

@remote bough read 👇
!code

thorn flintBOT
peak badge
#

I dunno why the CPU thread would be waiting on the graphics fence though. It's all GPU code

untold moth
peak badge
#

yes

#

It just makes dispatching with the right number of threads easier.

#
cmd.DispatchCompute(computeShader, kernelID, dispatchX, dispatchY, 1);
untold moth
peak badge
#

The texture is quite large... and it doesn't seem to like that

untold moth
#

I thought the issue was the CPU side fence after each dispatch..?🤔

peak badge
#

I'm not sure, to be honest.

#

The CPU shows as red... but I don't know what would cause it

untold moth
peak badge
#

It seems to indicate it's CPU bound... but I don't know why. It looks to me like there is a graphics fence, but I also don't know why

#

I think I'm executing it async, so it's weird

untold moth
#

Seems like a new feature in unity 6.
I'd assume that it means that the cpu time is > 16.6, since the target frame time is set to 60 fps.

peak badge
#

exactly

untold moth
#

You'll need to look at the profiler hierarchy properly

peak badge
#

Is the Render Thread running on CPU?

untold moth
#

Yes.

#

On a separate thread usually.

peak badge
#

Why... can't it run on GPU?

untold moth
#

Because GPU is highly specialized for running shaders and similar work. It can't run normal code, like the CPU does.

peak badge
#

But it's rendering?

#

Why does that use CPU

untold moth
#

Rendering is a complex process involving both cpu and gpu

#

GPU runs computationally complex(but specialized for GPU) work that runs on many small threads.

#

CPU runs normal code and controls what the GPU does.

peak badge
#

My command buffer executes super fast... the render loop seems to take all the time (?)

untold moth
peak badge
#

This is from the profiler

untold moth
#

Don't crop out the rest of the profiler out. It's unclear whether it's from the CPU or GPU and player or editor mode.

peak badge
#

I'm running the profiler in Stand Alone mode now, so the editor doesn't impact it

untold moth
#

Ok, so that's the Render Thread

#

I'm not entirely sure what RenderLoop stands for. Is there more info with deep profiling on?

#

Assuming it's the default rendering work that unity does, there are several assumptions that could be made. For example, that the number of batches is crazu high.

peak badge
#

where do you see the batches?

#

basically this image is sampled from a buffer that's about 150 megabytes

untold moth
untold moth
peak badge
#

Ok that's good, that's what I thought. It all fit's in GPU

#

it says 27 batches for 27 draw calls... isn't that just 1 to 1?

untold moth
#

Yeah, that's not much

#

You should try profiling the render thread with deep profiling on.

peak badge
untold moth
# peak badge I don't see any additional info

I don't know if RenderLoop is something that was added in unity 6 or something specific to your project, but when I profile a scene in my 2022.3 editor, there's no such thing. Everything else makes total sense.

peak badge
#

I'm using unity 6, URP

#

I'm not doing anything too unique. I have a shader graph with a custom node that samples my 150 MB texture

untold moth
peak badge
#

Ok tell me if I'm thinking about this wrong:
if I initiate an Async compute buffer, and at the same time, I render a frame that uses that buffer... will it use a graphics fence?

peak badge
untold moth
#

Yes. If whatever the compute buffer is writing to is also read by other shaders later in the frame, it would stall the whole pipeline.

peak badge
#

I thought reads aren't supposed to block

untold moth
#

The reads themselves don't, but any engine would usually add a resource barrier such as to avoid data corruption. You don't want to be reading from a memory that is being written to at the same time.

peak badge
#

Hmm, still doesn't make sense, if the compute buffer time is only about 0.08 ms

untold moth
#

If you really need to both write and read(and you're fine with reading 1 frame old data), then you can make a double buffer setup, where you write to 1 buffer and read from another on the same frame. Then the next frame you swap the two: read from the buffer that was written to the last frame and write to the other one.

untold moth
#

Though, to be fair you had like 200 loops of 2 dispatches there, which would add up to 400 * 0.08 = 32ms, ignoring overhead.

peak badge
#

No I think that's for 1 frame is 0.08ms

#

not per call

untold moth
peak badge
#

"Unnamed Command Buffer" - self time is 0.09 ms

#

I only call the command buffer once, it just contains ~200+ calls

untold moth
#

You're confusing the time it takes to dispatch a command/s vs the time it takes to actually execute it on the gpu. The 0.09ms is the former one, which is not expected to be long indeed.

peak badge
#

Aha... ok that makes sense if it's async

#

it's just so weird. If it's async, I don't know why the CPU would wait to render. Isn't the whole point of an async GPU call so that the render thread doesn't wait?

untold moth
#

Though, it still doesn't explain why the RenderLoop is taking that long. If it indeed is waiting for the GPU, you should be able to see similar time in the GPU module.

untold moth
peak badge
#

I think commandbuffer execution doesn't use graphics fences to wait for itself though

#

in the docs it says you don't need any, it will automatically wait for the first call to finish before the second call runs

untold moth
peak badge
#

That's so weird... I don't think that's how it behaved before

untold moth
#

If you can test in 2022.3 that might provide more clues. Either it doesn't happen, or does and the profiler has more info.

peak badge
#

Ok, I'll try to downgrade

#

The biggest thing I noticed is chaning my .cginc file that I use for my sampler resulted in pretty harsh performance loss (about 50%) when I made a small change. I assume .cginc is all run on GPU

untold moth
#

cginc are just include files for shaders, so yeah, obviously they run on gpu

peak badge
untold moth
peak badge
#

Well it does say it ran out of memory, let me try to get a spike from before that

#

it's mostly "semaphore wait for signal"

untold moth
# peak badge

This seems to be waiting for the GPU to complete rendering the frame.

peak badge
#

Ok, I think I have an idea. I don't think it needs to wait, it's just something about the way it's sampling.

#

It's sampling this 150 MB texture, but what if I sampled it myself to a smaller size, first

untold moth
peak badge
untold moth
peak badge
#

If so, I guess I can only optimize away about 6% through being clever...

untold moth
peak badge
#

It's doing computation

untold moth
#

Then perhaps that's what you should focus on omptimizing.

peak badge
#

The computation right now is actually very simple

#

it's just taking a simple average

#

of neighboring cells

untold moth
#

the fact that it takes 7ms on GPU definitely doesn't align with "very simple"

peak badge
#

it's running on a 6000x6000 matrix

#

I dunno why it's slow, tbh

untold moth
#

presumably, you're running that "very simple" computation for every pixel in that 6k x 6k matrix?

peak badge
#

yeah

untold moth
#

And then you're doing that 400 times per frame

peak badge
#

yep

#

I'm assuming it's just memory bound

untold moth
#

That's a hell of a lot of computations

peak badge
#

it fits in the GPU ram, but I'm guessing it just takes a long time to load them into the cache

#

actually no it's like 400x per second, not per frame

#

closer to 200 per second right now

untold moth
#

Gpu, while has a lot of processing blocks, they are a lot slower than CPU cores. And it doesn't have 6000x6000 processing blocks either. So it has to process these in batches while loading in and out of internal caches.

untold moth
#

In update or something?

peak badge
#

Yeah but really I just want it to run as fast as possible

#

Right now it's dispatching 2 at a time, instead of 200 at a time

untold moth
#

You should spread the workload across frame. Maybe make one of these dispatches every frame.

peak badge
#

the only difference it makes is the visuals lag less

untold moth
#

Another thing to consider: do you actually need to run this computation that often on that much of data?

peak badge
#

yep

untold moth
#

Can you not just cache it and only compute again when there is actually a change or something.

peak badge
#

It's for procedural generation, so yes, it can be cached when it's done. But if it's faster it's better

untold moth
#

I don't know the whole context, but it feels like you're trying to run some kind of simulation that is really not fitting something like a realtime rendering application like a game.

peak badge
#

yeah it's simulation stuff

untold moth
#

Like, does the player actually see the result of all of these 6000x6000x200x2 computations?

#

every frame?

#

There's probably not enough pixels to fit it all in one screen.

peak badge
#

it's not necessary, of course, to show every frame. But not showing every frame would only save the 0.5 ms

#

that's the render time

#

the compute time wouldn't change

untold moth
#

Well that's what I'm saying: the compute time is the problem. Not rendering. You'll need to think of a way to optimize it or fake it.

peak badge
#

I can just reduce the render size. For actual gameplay purposes, I may only use e.g. 1024x1024... but during gameplay, I would also have more than one "layer" of computation

#

so I'm using a very big texture to stress test

untold moth
#

Then there's need for more optimization.

#

Also, the difference in performance with the real life scenario might not be linear. You should actually test the real life scenario instead of some hypothetical assumptions.

peak badge
#

Yeah that's fair. I think I learned what I needed to, which is that I think it's running into an actual GPU bottleneck, not just that I coded the async wrong

#

enjoy a small gif

#

Do you think there would be a performance difference in something like unreal? Or is it simply the GPU?

untold moth
peak badge
#

Unity only works with fullsize floats, and halfsize would be fine for me

untold moth
untold moth
peak badge
#

you can't by default, which is the problem

#
        grid = new ComputeBuffer(resolution * resolution , sizeof(float));

ComputeBuffers must allocate 32 bits at a time.
All read and writes are 32 bits at a time

untold moth
#

This is not inside the shader.

#

But I don't think memory is relevant to the issue.

peak badge
#

I think memory is the problem because just loading the memory into the registers takes time. The computations aren't hard, it's bounded by loading

untold moth
#

It would have to load it into the registers all the same.

#

It's not like the number of registers would double.

peak badge
#

Right but if the data is half size, it only needs half as much memory

untold moth
#

It doesn't matter though. The other half would just remain empty and unused.

#

Unless you do some kind of packing of parameters.

peak badge
#

yes, I do that already

#

I made a fake halfsize and I pack it 🙂

untold moth
#

You should be looking at macro optimizations before you look at the micro optimizations.

#

There's no guarantee a microoptimization would help, and in the worst case it might even hurt.

peak badge
#

Yeah, using my fake type didn't help.

dreamy basin
#

Pls is any free texture download either from browser or asset store safe from copyright can I use it to publish my game

somber swift
fossil pine
#

Hello! Apologies for the meaty post, but I'm hoping someone can help me with this, because I'm at my wit's end with this one:

I use scriptable objects as states. The actual states are classes which inherit from the scriptable object SO_State, and these states are then instantiated as clones on game start, so that they can freely communicate with an instance of NPCController and NPCPossessed without messing anything up.

My issue is that the references to both of these script instances is spontaneously lost within the state clone, and I have no idea how. Here's how it works:

NPCController calls this:
foreach (SO_State state in states)
{
state.Initialize(this);
state.InitializeSpecific();
}

... which results in this method running in SO_State:
public virtual void Initialize(NPCController cntrl)
{
controller = cntrl;
npcBase = controller.transform.GetComponent<NPCBase>();
}

... and this method running in Possessed_State_Idle:
public override void InitializeSpecific()
{
npc = controller.transform.GetComponent<NPCPossessed>();
}

Through debugging I know for an absolute fact that each instance of Possessed_State_Idle has a valid reference to both controller and npc at this point. However, almost directly after this, Enter is called on the currentState (e.g Possessed_State_Idle):

public override void Enter()
{
npc.agent.SetDestination(npc.transform.position);
npc.timeToRoam = Time.time + Random.Range(standDurationMin, standDurationMax);
}

... and at this point, it has no reference to either controller or npc. There is literally no code that touches these references inbetween InitializeSpecific and Enter.

#

I'm just wondering if anybody has any clue as to what's happening here? Does it have something to do with instances of scriptable objects? Because this issue didn't exist back when I was using the original scriptable ojects themselves instead of clones.

I would be incredibly grateful if someone could offer some insight here. Thanks!

#

This is made even stranger by the fact that in the inspector, the clones literally show that these references are correctly assigned:

upbeat path
#

It's impossible to advise based on the information you provide.
Please do not remove Debugging information.
I also recommend debugging the instance id's and names of all objects involved so that you actually know you are referring to the objects you think you are.
Once you have done this please post your amended code correctly along with the debug output

teal needle
#

Weird, got a new macbook air m3 and all my projects fbx files refuse to load with an error that an fbx reader wasnt found.
Unity 6 for MacOS doesnt come with an fbx reader?

teal needle
#

Tried installing the exporter since it seem to have a formats.fbx package

#

or depend on

#

Did not work

drifting solstice
#

you'd need an importer, not an exporter

teal needle
#

I know but i was hoping it would add the missing fbx reader

#

although it doesnt seem like a common problem on macos , cant find many results about it

modest yoke
#

Need some help, Im making a game and I want to have destructible buildings similar to teardown, but I want it to be optimized for quest 2 so having 3000 rigidbodies is not gonna cut it, Im trying to figure out if there is a way to cut holes into objects during runtime, can somebody help me?

sly grove
#

You will probably have a hard time reproducing teardown in Unity

modest yoke
#

yeah

#

I decided to use a diffrent system

remote bough
# fossil pine Hello! Apologies for the meaty post, but I'm hoping someone can help me with thi...

Going to be very difficult to help with this as there is just so much that could be happening in your project or code. Perhaps if you are lucky someone ran into a similar issue and give you a hint. So in cases like this, I’d sugggest the best advice is to populate every part of you code with debug statements ( unless you can step through the code in debug mode) and if the project is already complex, to create a new stripped down version of the state machine from scratch, testing as you go.

fossil pine
# remote bough Going to be very difficult to help with this as there is just so much that could...

That's good advice for the future, thank you! However, I did end up finding the problem. As I use instances of scriptable objects, I neglected the fact that each state instance allows for transitions to other states, and these states references never ended up being replaced by references to their clones, and so pointed back to the original state objects which never assigned the missing references in question (as well as causing other issues). I'm relatively inexperienced with working with instances of originals in this manner, so I guess I had to learn that the hard way. Thanks either way!

remote bough
# fossil pine That's good advice for the future, thank you! However, I did end up finding the ...

Nice catch. If I understand you correctly, yeah, this can catch you out and not just with scriptableobjects, but also with say duplicating objects in scene. It can be very easy to overlook and not obvious to find unless you are looking for it. One piece of advice now you have found the problem is there any form of logging/debugging code you can add to catch this situation, or even just add some comments? It may seem pointless after the fact, but you'd be suprrised how often you can get caught out by the same problem in the future and completely forget how you fixed it.

dusty wigeon
dire bobcat
#

Hello. I'm part of an indie team developing a game. None of us are professionals and my job is to manage the code base. Now I'm reading Unity's eBook about SOLID in Unity and I'm enjoying applying the concepts. But I'm struggling with one specific thing. Managing dependencies. I want to give you an example from the project. I have a Tutorial Manager script, that manages the flow of the Tutorial. In the process of the tutorial, the player picks up weapons. So each time an Interaction is triggered the Tutorial Manager is notified by an event and the Tutorial Manager should call the AddWeapon(); Method on the player. So the Tutorial Manager somehow needs to have a reference to the player. I don't want to use a serializefield as that would cause Problems when changing the Player Prefab. The only other things I can think of are 1. using a DI Framework, which I was told in many tutorials, not to do unless we have a very big project (which we don't) or 2. To use something similar to the service locator pattern and to have the Player register itself on Awake. I even use an Interface for the player. But here again I was told it's an anti-pattern and I'm not supposed to use it. Any suggestions? I'm really struggling with finding any tutorial on this

dusty wigeon
# dire bobcat Hello. I'm part of an indie team developing a game. None of us are professionals...

You can use what we call SubPub pattern in this particular situation.
https://en.wikipedia.org/wiki/Publish–subscribe_pattern

That being said, having a sort of registry is a good idea. Instead of subscribing to the TutorialManager directly, I usually like to have a separate Script (Depending on the code quality, a simply static list), to manage all the reference to the given object.
https://www.geeksforgeeks.org/registry-pattern/

Simple implementation of Pub/Sub. There is multiple way of doing it, depending on your needs and wants.

    public class EventChannel<T>
    {
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
        private static void Init()
        {
            instance = null;
        }

        public delegate void EventChannelHandler(T evt);

        private static EventChannel<T> instance = null;
        public static EventChannel<T> Instance
        {
            get
            {
                if (instance == null)
                    instance = new EventChannel<T>();

                return instance;
            }
        }

        private List<EventChannelHandler> subscribers = new List<EventChannelHandler>();

        public void Susbribe(EventChannelHandler subscriber)
        {
            subscribers.Add(subscriber);
        }

        public void Unsubcribe(EventChannelHandler subscriber)
        {
            subscribers.Remove(subscriber);
        }

        public void Publish(T evt)
        {
            foreach (EventChannelHandler handler in subscribers)
            {
                handler?.Invoke(evt);
            }
        }
    }

    
cursive horizon
dusty wigeon
# dusty wigeon You can use what we call SubPub pattern in this particular situation. https://e...

Implementation of a simple registry.

public class AgentRegistry : Manager<AgentRegistry>
{
    private List<AgentEntity> agents = new List<AgentEntity>();

    public void Add(AgentEntity agentEntity)
    {
        agents.Add(agentEntity);
    }

    public void Remove(AgentEntity agentEntity)
    {
        agents.Remove(agentEntity);
    }

    public AgentEntity GetByFaction(FactionType faction)
    {
        return agents.FirstOrDefault(x => x.Faction == faction);
    }
}
dire bobcat
dire bobcat
late hinge
#

hey !
Do someone is familliar with addressables in unit test ?
Addressables loading does not working in unit test , event with [UnityTest]

wooden vigil
#

Does anyone know a sane, burst/job friendly way of zeroing out a NativeArray<int>?
Feels like I am missing something, I can't find an equivalent of Array.Clear() or Span<int>.Fill(0)
I -could- do NativeArray.AsSpan.Fill(0), but spans are a no-no in burst.

#

I've looking into unity's code and I could do something with pointers, but it's weird that there is no safe API for this.

sly grove
#

are you wanting to do this as part of some other job?

wooden vigil
#

yeah, at start of the job I want to zero out memory instead of allocating new, it's fixed size and needs to be updated when something else changes.
it definitely feels like an overkill, Unity does this internally:

public static unsafe void MemClear(void* destination, long size) => UnsafeUtility.MemSet(destination, (byte) 0, size);

wooden vigil
#

when you first allocate it

sly grove
#

at the start of what job? What kind of job is it?

sly grove
wooden vigil
#

yeah, buffer is shared between job runs

#

I could allocate a new one every time, but that's also a waste

sly grove
#

which you can schedule in the job system nicely

wooden vigil
#

int[] and Span<int> have normal Clear() methods, I would expect NativeArray<int> to have it too

upbeat path
#

Arrays do not have a Clear method

wooden vigil
#

Array.Clear is a static method

#

so you can do Array.Clear(myIntArray)

scenic forge
#

How big is this buffer? I doubt it's big enough that you can do something better than memset.

sly grove
#

which would be the same as UnsafeUtility.MemSet

wooden vigil
#

yeah it's all the same
just Unity didn't make a normal safe API for this

#

apparently

scenic forge
#

Zeroing out some memory is like one of the most frequently done operations, in any program. I highly doubt memset isn't already very well optimized.

wooden vigil
#

of course
it's just that there is no non-unsafe way of invoking memset on NativeArrays apparently

#

I will probably make an extension method for this

upbeat path
#

Considering everything to do with NativeArrays is Unsafe anyway, I wouldn't fret it

wooden vigil
#

Ha, look like burst doesn't complain about Span<int>, so myNativeArray.AsSpan().Clear() is the way to go
Burst complains about spans if you try to pass them in, so this is a no-no

    [BurstCompile]
    public static void DoSomething(in Span<int> mySpan)
stuck plinth
#

ugh, i was just converting some code to use Awaitable instead of Task and found out the hard way it doesn't continue on the calling context automatically, apologies to whoever i was telling the opposite to a while ago in here lol

#

i guess there's still reasons to use Task...

sharp dune
#

Not sure if i should put this in #archived-code-general or #archived-code-advanced but:
FallingCharacterState.cs
JumpingCharacterState.cs
WalkingCharacterState.cs
IdlingCharacterState.cs
CharacterStateMachine.cs
CharacterState.cs
StateMachine.cs
State.cs
Character.cs

Ive updated the FSM i made previously, I want to know If I'm going in the right direction and if it's modular enough

The general architecture is:
StateMachine is a generic class that handles the transitioning between the states and holds a reference to every state and also holds a reference to a class for context, each states type is the generic type. the class for context is another generic type
State is a generic class that holds methods for Enter, Update, and Exit state, and it has a constructor where you must pass in a class for context, via the generic type
Character is the class for context which holds a bunch of useful variables and properties to pass into the State and StateMachines

dusty wigeon
# sharp dune Not sure if i should put this in <#763495187787677697> or <#885300730104250418>...

Seem like a really strong base.

The only comments I would say is to let's the state decide whatever they want to run (It is basically what you are already doing, it would just make it more specific):

_isGrounded = Physics.CheckSphere(_groundCheckPosition + transform.position, _groundCheckRadius, _groundCheckLayer);
_characterController.Move(new Vector3(_movementX, _movementY, _movementZ) * Time.deltaTime);

I would create function such as :

public class Character 
{
  public void IsGrounded ...
  public void Move() ...
  public void ApplyGravity() ...
}

For IsGrounded, you can use lazy evaluation instead of actively doing it and you can cache the result base on the frame count (Time.frameCount).

#

However, it is worth mentioning that usually you should do Physics Check in a FixedUpdate and because of that it would be better to that what you previously did for the ground check (In FixedUpdate).

sharp dune
dusty wigeon
#

But, as I pointed out, it really is minor.

sharp dune
#

For IsGrounded, you can use lazy evaluation instead of actively doing it and you can cache the result base on the frame count (Time.frameCount).
You mean something like this?

if (Time.frameCount != lastCheckedFrame)
{
  isGroundedCached = CheckIfGrounded();
  lastCheckedFrame = Time.frameCount;
}
dusty wigeon
#

And in this case, it is even justifiable to do this way you did.

dusty wigeon
sharp dune
sharp dune
#

Thanks for the feedback, much appreciated

dusty wigeon
#

And, if you ever increase the complexity, you might needs different movement logic.

#

By example, if you want to handle swimming.

sharp dune
#

And that extra logic might be extra overhead

dusty wigeon
sharp dune
#

Because as of right now, my controller is simple

dusty wigeon
void bronze
#

Hi, hopefully a quick one. I have a native c++ .so file which I'm trying to load in my unity project. I also have the exact same native plugin as a .dll which works fine on my windows builds, however looking at my logs I keep getting this exception: DllNotFoundException: Unable to load DLL 'nestopia_libretro'. Tried the load the following dynamic libraries: Unable to load dynamic library 'nestopia_libretro' because of 'Failed to open the requested dynamic library (0x06000000) dlerror() = dlopen failed: library "nestopia_libretro" not found

I've read through the docs and done a lot of searching online. As far as I can tell I'm doing things the correct way. I've placed my plugins under Assets/Plugins/Android/libs/arm64-v8a or Assets/Plugins/Android/libs/armeabi-v7a etc. depending on the architecture. In my C# file I load the dll like this:

    [DllImport("nestopia_libretro")]
    public static extern void retro_init();
stuck plinth
stuck plinth
# void bronze You mean this?

well that looks OK, might be worth poking around in your android project/build files to make sure the SO is actually there and has the expected name?

void bronze
subtle spindle
#

What do you use for mocks?

void bronze
subtle spindle
#

Second one

#

Moq works for me, but I've seen comments of people complaining about some errors

void bronze
#

I use it and seems to work fine for my setup. What errors?

subtle spindle
ruby prairie
#

have someone here already made a don't starve like game (2,5D with 3d map & 2d sprites), im having problems with an 2d sprite that looks like its moving everytime the camera moves around, is this a problem with how the sprite is being rendered or a problem with the camera itselfe? call me on my pv if you need more info, i wish i could send a video right now, but i cant currently

sly grove
#

but you'd have to share some details

#

certianly not a code issue it sounds like

spring holly
#

not sure the best way to phrase this, but lets say that you have an object with a collision box, and an object slams into it. is it possible for that collision the record the amount of velocity the slamming object had, and turn it into an interger within a script?

sterile thunder
#

I'm struggling to understand how to properly manage state when disabling domain reload... the docs say you need a method like this to reset any static data

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void Init() { Debug.Log("Counter reset."); counter = 0; }

But in my own testing, a regular OnEnable method seems perfectly fine, and there's no need to use this obscure attribute on a static method... I'm using Unity 6, has something changed in the most recent version around domain reload?

#

Also, I'm struggling to understand what "Disable scene reload" does in enter play mode settings... I thought it was something to do with reloading my scene from disk when I enter play mode, but even when its disabled, unsaved changes at edit time seem to still exist in play mode (ie, if I move a cube in edit mode, don't save, enter play mode, that cube is still moved).... likewise, any changes to the scene made in play mode are still reset when I exit play mode, regardless of whether scene reload is on or off, any idea this actually does?

long ivy
#

OnEnable is called any time the script becomes active, so if you want to reset statics it's the wrong place to do it because "whenever the script becomes active" is not the same as "resetting play state". It'll work, but it's a code smell imo. Also it will only work for MonoBehaviours obviously; anything with a different life cycle (static class, SO) would need another object to reset them which would also be a code smell for me.

Scene reload is explained here: https://docs.unity3d.com/6000.0/Documentation/Manual/configurable-enter-play-mode-details.html

sterile thunder
#

Right I see, you might want a monobehaviour that turns on and off at runtime but still persists its internal state, resetting the state in OnEnable works for domain reload, but would break things if the mono wants to persist state between different enabled/disabled's without the domain reloading, makes sense

Yeah, I've read through that docs page already, still not understanding.... it says the steps of "Destroy gameobjects" and "recreate from temp backup" will be skipped, but I don't know what this tangible means, what effect does this have on my scene? I'm not able to see any difference in behaviour between the two options

long ivy
sterile thunder
#

"ScriptableObject and MonoBehaviour fields that are not serialized keep the values assigned to them during Play mode on returning to Edit mode"

So, if I have a field that isn't serialized, and it changes in play mode, next time I enter play mode, that value will persist?

Thing is, that doesn't seem to be what happens

`public class ReloadTest : MonoBehaviour
{
[System.NonSerialized] private int _nonSerializedCounter;

void Start() => Debug.Log($"Start called - non serialized counter = {_nonSerializedCounter}");

void Update() =>  _nonSerializedCounter++;

void OnDestroy() => Debug.Log($"OnDestroy called - non serialized counter = {_nonSerializedCounter}");

}`

With this script, with domain and scene reload off, let it play for a few seconds, you'll see OnDestroy log out a non-zero value for the counter, enter play mode again, and the counter will have reset back to zero

upbeat path
sterile thunder
# upbeat path Did you not read to the end of that paragraph? `This is why private fields you m...

Yes, I did.

"Note that private fields are not serialized as part of the regular build pipeline but are serialized as part of the Editor’s hot reloading of scripts. This is why private fields you modify in Play mode might reset to their original values on exiting Play mode even when scene and domain reload on enter Play mode are disabled."

I also read that link, which says that if you add the [System.NonSerialized] attribute, it stops that serialization process. Which is exactly why I added that attribute in my snippet above.

sterile thunder
# sterile thunder "ScriptableObject and MonoBehaviour fields that are not serialized keep the valu...

I thought maybe the difference would be that the value would persist from play mode into edit mode, but not back into play mode again, but that doesn't seem to be the case either.

public class ReloadTest2 : MonoBehaviour
{
[EditorButton(nameof(LogValue))]
[SerializeField] ReloadTest reloadTest;

private void LogValue() => Debug.Log("Test value: " + reloadTest.NonSerializedCounter);

}

Entering play mode, letting my counter tick up, going back to edit mode, and then logging the value out in edit mode, still shows the counter has returned to zero. Even when the counter isn't serialized, and when reload scene is disabled

timber flame
#

Guys, could you help me for this problem?
I have different skins for each direction. I have used one skeleton for all animations.
I think there are two major approaches to tackle it
1- Create different gameobjects for each direction and set the skins related to that direction initially, then switch between them based on the current direction (caching)
2- Create just one gameobject then update skins based on the direction (performance issue)

void bronze
carmine lion
#

why this listener dont adds to the button even if all conditions true

carmine lion
carmine lion
dusty wigeon
#

Then debug it.

carmine lion
#

please

dusty wigeon
#

Could be somethine like a RemoveAllListeners somewhere you forgot about.

#

Or the button is not the one you expect.

#

There is a lot of possible causes. One of them is that you are not utilizing the API correctly, which I do no think is the case here.

regal olive
#

How do i compile script in unity project to dll ? I created a library in unity which uses unity. However, the internal method, class, etc were visible to script outside the library because they are in the same assembly as other script in unity project. So i wanted to compile the library to dll so that the internals is not visible to script outside the library.

austere jewel
regal olive
regal olive
#

Any good tutorial how to create asmdefs

regal olive
upbeat path
austere jewel
regal olive
upbeat path
regal olive
#

I created two assembly definition in separate folder. Then in one of the assembly definition, i added reference to the other. However, when i try to reference the class in the other assembly definition, it is still not visible, and visual studio or unity didn't throw error when i save the cs file

#

Why is that ? I dont understand

upbeat path
#

is the class marked as public?

regal olive
#

Yes

#

I even try to access internal class in the other assembly, which should throw error, but visual studio and unity didn't throw error when i save the file

upbeat path
#

can you see the asm def'd projects in VS

regal olive
#

im not familiar with that

upbeat path
#

whatever you called them

austere jewel
regal olive
upbeat path
#

probably need to switch on Player Projects in external tools and regerate project files

raw dew
#

Anyone know how I can start learning about game AI and training machine learning modules in unity?

upbeat path
#

it generates project files.
asm defs should show as seperate projects in your solution explorer

regal olive
#

Ok try to do that

upbeat path
regal olive
#

It did nothing.... except that now it has Assembly-Csharp.Player in solution explorer

#

The class or namespace still not visible

stuck plinth
#

what's in your asmdef?

raw dew
stuck plinth
regal olive
#

Okay wait

upbeat path
regal olive
stuck plinth
#

try regenerating your project now? that should mean it's usable from assembly-csharp

raw dew
regal olive
#

Okay wait

raw dew
upbeat path
regal olive
#

I just want to hide the internals why is this thing so hard 😭

stuck plinth
raw dew
regal olive
stuck plinth
upbeat path
raw dew
stuck plinth
# raw dew I'm confused 😦

that's the kind of thing you use for game ai, the behaviour you program into enemies, not the buzzword tech thing

regal olive
stuck plinth
raw dew
regal olive
#

What is going on

raw dew
stuck plinth
#

make sure it's marked to be included in editor!

regal olive
#

ooh

#

Wtf i thought it was include

stuck plinth
#

the UI is kind of unclear on that option

raw dew
regal olive
#

i selected the platform thinking it was target platform, not exclude 🤣

misty glade
#

I'm setting up a 3d volume (in space) where I'd like a combination of background stars (I can just use a skybox) and interactable "real" stars. The idea is that you'd be able to select some of these stars, and see some popup UI in your ship. Alternatively, you'd be able to plot a course several star systems away (think EVE or NMS) and be able to view some HUD elements connecting the dots in space to your destination.

I'm wondering if there's a good approach to this. Part of me is thinking that I'll just render a very tiny mesh, so I'll have a lot of control over aspects of it (color, brightness, maybe some particle effects), but then part of me is worried that's gonna be a lot of triangles for what are essentially points on a skybox.

Any thoughts?

misty glade
#

Followup / different question - if I want to use System.Numerics.Vector3 - is there a way to make that play nice with Unity, or am I going to need to qualify those Vector3 uses in each and every place in my code as either System.Numerics.Vector3 or UnityEngine.Vector3

untold moth
raw dew
#

do I need to downgrade my python version for ml-agents cause there's so many errors rn?

terse inlet
#

I would just create a static extension method that is -> numericsV3.ToUnityVector() and vice versa and I would define a line in your code where you fully convert and use one or the other

#

If its in hotpath/needs to be fast you can probably write a memory reinterpreter in unsafe code to go between the two.

stuck plinth
misty glade
#

Yeah, it's bothersome to qualify them all, but in most places I'll be using them I'll need to be converting back and forth.. I suppose I could... "hydrate" the numerics vectors at the boundary (networking packets and deserialization coming in) into unity types, but that feels like a pain.. probably the least painful way though

ruby prairie
terse inlet
ruby prairie
terse inlet
#

uhh i dont know the rules but here is fine

pliant cypress
#

I'm attempting to make an RPC interface using attributes, similar to how Photon Fusion works, like this:

[Rpc]
public void RPC_Test()
{
    Console.WriteLine("Received RPC");
}

My main goal has been to make this portable so I can use it unity, or any other c# project I do. At first, I was using PostSharp to inject code to handle encoding, sending, and receiving. But I realized pretty quickly that PostSharp isn't compatible with unity. I've been shopping around and it looks like reflection methods are rarely very compatible (Castle DynamicProxys, IL stuff, unsafe function pointer manipulation). Does anyone have any suggestions or leads I could look at for this?