#archived-code-advanced
1 messages · Page 113 of 1
You're his biggest hater and you thought I was harsh? 😄
He has a lot of haters
More haters than supporters
lol
i asked so i can know your experience
i don't like to name call people
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
how do you know
he has like 300 sponsors on github
should be zero of course
he posted this on his Patreon account, i have seen it
it's public
btw create a thread here
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?
not an answer but I'll be making an RTS next week after my release of the game I'm working on now.
lockstep?
yes
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
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
I've never had the need to use one, that's why I'm asking lol
Yeah I'll have to see what are the best solutions for each problem and system at hand
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
i don't know the scope of the rts you are going to make
In production, it'll use spatial hashing or something similar
but i expect years just building the core gameplay
3-6 months, simple stylistic art
i hate mmos
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
have you tried to make an rts before?
In Age of Empires the time to complete each simulation step varies greatly: the rendering time changes if the user is watching units, scrolling, or sitting over unexplored terrain, and large paths or strategic planning by the AI made the game turn fluctuate fairly wildly. A few quick calculations show that passing even a small set of data about ...
No
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
how many units
what?
What
lol it's a prototype, why would I have 200 different units?
Maybe more than 10, I'm not sure
a prototype means you know you can make the game
you test the worst case on a prototype, not some optimistic case
What takes the longest on an RTS?
a traditional RTS like Starcraft or Red Alert is not a simple game by any measure, not with unity at least
Is it the networking?
there are other engines than unity people use to make RTSs
everything
the logic for controlling units and moving them is quite complex
it's not just some pathfinding
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
What is your definition of an RTS?
A game like Starcraft or/and Red Alert
this is an engine people use to make traditional RTS games
What if it's not a traditional RTS game
then you need to explain what the gameplay is like
I'll put it this way. It's first person, so immediately if you're a hardcore RTS player, it's not for you
It's for a different market of players
We are trying to design it to have a high APM, but it's not gonna be as high as a traditional RTS
good luck of course
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
i don't know man, but best of luck to you
thats roughly 100k sales, I wouldn't call that a failure
maybe its a failure by his standards because all of his games make at least 10 million sales
Anyone here have experience coding dynamic mesh creation / editing via c# monobehvaior or possibly HLSL shaders?
I don't really have a particular question in mind rn 😄
I'm working on an RTS game that is somewhat in the vein of StarCraft. Your question about "what takes the longest" is incredibly vague and I'm not sure if anyone is going to provide a useful answer to you. True of just about any game, whatever takes the longest is whatever you choose to put the most time into.
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.
I was just trying to see where his head was at given he’s saying it would take years to make a game like the one I am making, but I’m not making a traditional RTS so really the question wasn’t even practical
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
Hey all, I'm trying to get some perspectives on automated testing and testable architecture, was going to post here but it's a chonky question so dumped it on the forum, would love any insight 🙂 https://discussions.unity.com/t/where-to-focus-automated-tests-and-how-to-architect-for-them-coming-from-corporate-to-game-dev/1541564
tbh, imo, automated testing of games is a waste of time, you will never be able to emulate the stupidity of users
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
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.).
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
In theory, automate test are wonderfull.
In practice, in video game development, they are a nightmare. This is due to multiple factor (Lot of interdependence, lots of non homogenous data, etc.)
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
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.
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 ^
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.
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
I struggled a lot because of that when I studied in IT. It made little to no sense to me doing all those tests in the context of what I was doing. I tried really hard to figure out how to apply what I have seen during my learning time, but everything felt wrong. Making things long to develop, more complex and it increased the number of bugs because of that.
Interesting, there's some real irony in that forcing in tests led to more complexity which actually increased bugs! Thanks for the thoughts 🙂
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.
TDD is amazing for very specific mechanics or features or tools
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)
Hmmn interesting, did you have much in the way of unit or integration tests?
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
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.
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.
I'm learning VContainer.
but that means I can't attach the script to button in the scene right?
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
Normally if the script is in the scene there might be some helper components in the library that injects any injectibles on the gameobject.
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)
https://vcontainer.hadashikick.jp/resolving/gameobject-injection
Have you checked this portion of the documentation?
yup. But it's ugly, let's say I have this script scattered all over the scene (because I have many button) I have to serialized them in the list of AutoInjectGameObject
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
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.
I could do LifetimeScope.container.resolve<AudioManager>
but at that point, why not just make the damn thing a singleton right? XD
Normally the benefit would be the ability to
- abstract the functionality to an interface and register the implementation you wish
- have multiple scopes for parts of your code
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
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
sounds too good to be true. must have some catch right? I'll check it out though.
Just check comments in asset you will see but its paid
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
WOW, This looks SO GOOD. I'll try it. Thanks for the rec
What happens in burst when there are multiple assemblies that have burstable jobs? does it just generate one assembly for all of them?
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?
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?
I think what you're looking for is how to texture blend a single shader
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.
It's the camera 😶
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
That's very similar to OAuth system in some forum engines
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
this is not an advanced issue. just because you haven't received the help you wanted in another channel does not make it advanced
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
there's the IProcessSceneWithReport interface with its OnProcessScene method
omg that's the one thank you
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.
A* is a "point in time" kind of algorithm
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.
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:
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://...
Do you have a specific issue you want help with?
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.
The only nodes in your fringe should be those directly connected to the current node (the neighbors) or a previously explored node
it shouldn't be possile for it to select unconnected nodes
If you look at the pseudocode for the algorithm:
https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode
The only time members are added to the open set is when they are neighbors of the current node
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
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.
I don't really understand what you mean honestly
Its all good dw
Obviously, if you are not correctly implementing A* and expect it to works it won't.
Maybe you want to use a weighted A* (It does not needs to be directly on distance.)? Because this is also a thing.
I have an idea of what might work instead of A* so will trial it out and go from there.
anyone ever had OnDestroy being called on objects for no reason, even when they are marked with DontDestroyOnLoad ? its so weird
DontDestroyOnLoad just means it's not destroyed on load. It can still be destroyed in other ways
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
Like destroying its parent
Or a particle system component destroying it
Pretty much zero chance of that, it would be a very serious bug
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
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
good idea thanks
it is definitely happening
which means i can reinit from the update, bizarre..
And how do I do that?
Can't you use the debugger and look at the call stack?
hmm never thought of that, would that work
As far as I know, it does not because of how unity calls the OnDestroy.
set a breakpoint/log in OnDisable instead
wouldnt that just tell u when it happens, not how
you'd have the stack trace and a debugger, so you'd know when and what
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.
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
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
then it's likely Unity is destroying it, which implies it's not DDOL
object is in the unity scene dontdestoryonload, DDOL works in children too doesnt it
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.
good thinking
Children of a DDOL'd object will live only if the root GO is DDOL. Calling DontDestroyOnLoad for GameObjects with parents is a no-op and prints a warning to the console
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
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
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)
No, as you've stated this is related to some other code. The fundamentals of code dont change here
The only other case would be if you were recompiling/reloading domain during play mode, where unity would clear the static variables
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 😅
Any expert would know how to instantiate on runtime skinned mesh renderers prefabs on player (when the player swaps armor pieces, for instance) ?
Chat
you know the fastest way to NOT get help is to do exactly what you have done
If here people doesnt know, why on earth people on beginners lvl would know?
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
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.
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
What code..?🤔
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the link and the snip are two different things
Is it a runtime error?
Which dispatch is it thrown at?
First one
And what is textureConverter? Where do you assign it?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
Is textureConverter assigned in the inspector?
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
Let's assume that's not the issue, is the shader compiled correctly? Are there any errors if you select it in the inspector?
No errors in the inspector; clicked on it to make sure and added an error intentionally to test
Okay. Can you try removing the multi compile options and see if that helps?
should I get rid of the logic as well?
Not if it compiles correctly.
Here's new error: (Happening on same dispatch line)
Interesting. Is there a shader compile error now?
This might imply that the shader is not compiled correctly
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;
}
can we convert a game object to assetreferencegameobject through code.
It depends what you meant but, you should head to #📦┃addressables.
You mean like, get an asset reference back to the prefab it was created from?
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.
Don't cross-post.
sorry :)
Bad idea
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
I know, but I am intercepting the shaders during runtime and every time I would like to run my algorithm, I need to reinstall the whole game. Is is there any way to disable it?
Hmm very specific case, maybe your approaching it wrong ? You shouldnt like need to delete the shader cache, yk
Maybe ask in #archived-shaders to why you need do what youre doing
Thanks, I will ask there!
How to find out if there is any script attached to a gameobject when I don't know the name of the script.
For what purpose? What do you mean "any script"?
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.
I want to find out if there is any script on a particular gameobject or not.
Can you clarify as I asked what you mean by "any script?"
the answer to your question depends on that.
Any c# script.
So MonoBehaviour
Yes.
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
Smells a lot like XY
How to get the name of that script.
Just getting a script.
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.
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.
WHy not just Instantiate the object/prefab you want to copy?
I am working on a vr project remote rendering.
Could someone take a look at my code please? I'm trying to make my slopes snap at 90 degree angles on the y axis and rotate them to face away from the player: https://pastebin.com/tG6rWv14
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
This is not an advanced issue. #💻┃code-beginner or #archived-code-general
You also are going to need to specify what code you're even referring to or what's not working. This is 300+ lines, people arent gonna go through all that logic without even knowing what's wrong.
No one responds to me in general, i've asked many questions there and never get a response. The issue is what I stated, the slopes aren't being rotated correctly
Consider that in the message you're replying to, I told you exactly why no one responds exactly. If you insist on not specifying further then you'll continue to see the same results.
No one is gonna fight to help you. Make an effort and describe the issue properly. Narrow down the code too
it's the snapGhostPrefabToConnector and AlignSlopeWithPlayerFacing methods. The slope snaps correctly at a 90 degree angle, but if you wiggle the mouse around a little bit then the slope starts rotating on the wrong axis and not in 90 degree angles
One thing you should really do, especially for these math related issues, is debug every step and see where values are no longer correct. One possible issue I see is that you're reading and using the .eulerAngles of a quaternion. There are many different euler angles that would equal the same rotation. Theres no guarantee you're getting the euler angles that you expect
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
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 🙂
Might wanna look at AssetBundles
I'll look into it
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!
Show me from deep profiler
with bounds checking on looping over the native collections can be surprisingly slow, ymmv but if you're able to use a C# array instead of a List you could try nativeList.AsArray().CopyTo(theArray) which might end up being faster
Thanks, I’ll test this solution. I’m currently making a system reactor and the other components are using the list. I wanted to use the jobsystem but it will probably be slower.
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.
Hi guys, Does anyone here know how to pass data from main scene to an entity sub-scene during runtime in unity ecs?
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 :/
#1062393052863414313 but typically just by setting some value on a component
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.
Yes...that's what my code already does. It DOES move in relation to the camera. I just want to adjust it...as described.
Not sure I understand then
what you're missing is making your camera not adjust itself to turn with the player
if you're getting a circle it means the camera is rotating as the player rotates
Anyone with experience with a crash on a CallStack like the following:
what's the error?
access violation is basically a segfault
Yeah, but on Unity side.
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
Got a full stack trace?
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
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)
makes sense, will try 🦾
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.
Could it be that youre overloading the ram ?
You only like have 3gb of ram useable
Oh... yeah shouldve scrolled down first
Hey, sorry. Had to work and then i prioritized just preventing this lag from too many sounds by removing a lot from my webgl build
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
@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.
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
That is the full stack ?
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
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.
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
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
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.
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.
is there anything below PlayerLoop?
Player loop is at the very root of the hierarchy. They just have it in reverse mode
Yes but it’s just the render stack. Like the things that are 100% of the cpu time because they own are above every other call every frame
Yeah it’s inverted because it was way easier to find the function I needed that way lol
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.
can soembody maybe help i try to install nuget and i got .net 8 but it says version not supported
I already do that.
Strangely, I tried to show out every Asset that is being loaded and the error went away.
I have not test this implementation, but the latest implementation of loading each asset one by one was working (yield each one individual).
unity does not support nuget
i actually need it for opentk
and? does not support means does not support
And this implementation does not work...
Strange, waiting on each individual object does work though. But it takes considerably longer to load.
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.
And yes, it is a segfault, mostly a one cause by accessing an array that is null.
You mean CRC disabled ? This is what I am doing at the moment.
Otherwise, I believe you spoke of the CPU boost for the Switch.
I'm still trying to found what could be the cause, it seem to be crashing relatively at the same moment I might be able to find what asset does the crash.
yup, yup, and sort of. I'm currently trying to debug something similar on PS5 and would really like to avoid an asset hunt due to the project size, so if you figure out a better way to debug this kind of issue, I'm all ears.
don't cross-post and wait for someone to answer
Sry dude
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...
I'm a singleton enjoyer so I wouldn't know
I don't think it ever caught on
Terrible. Always, always use ScriptableObject as immutable data. There is multiple consideration to take otherwise.
Interesting, I don't think i've ever used scriptableObject as immutable, its always to provide data, but often the whole point is that data can be changed. granted sometimes that might only be settable at load time, but often its useful as a in editor means to view data and that data wants to change.
It should not change. If it does, you need to consider that it behaves differently in an Editor and in a build.
Ok I can see you point here, that while in the editor the values can be changed and will be saved, whilst in build they can be changed but not explicity saved. However theuse of a scriptableObject to hold data that can change is still important abiity
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
If the idea is to use scriptable object to hold data that change during the execution of a good. Terrible idea.
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.
nonsense, SO's is the ONLY data container that Unity provides, making them mutable at run time is fairly trivial
You usually need to have a state for such system. (Subscribers) So, I would consider them to be mutable.
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
This is not true, there is other alternative. I'm not saying that it is impossible also, but that it is usually a pitfall that I prefer to not get into.
name one
Prefabs
If you could move around POCO instance around the editor we'd just use those honestly
prefabs are not data containers nor are they mutable at all
Prefabs are mutable and they contains data. You instantiate one and you have both, the mutable and immutable representation of your data.
incorrect
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.
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
if it does not persist then it is not truely mutable
I prefer singletons for the managers. The whole argument about the talk is how you're bound by a single instance, but most of the time you only want one instance anyway
SO is a monobehavior... Not sure how it is incorrect.
My point though is that prefab can be instantiate and it expected to be.
oh of course. then nothing is mutable except for anything that you save to disk. silly me
If you want to define it that way, than SO are not even mutable in a build...?
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.
no, they are in Editor and, as I said, making them mutable in a build is fairly trivial
the difference comes in with what the state of serialized data in the SO is after playtime ends.
In the editor, serialized fields will be saved when changed at runtime and playmode stops
In a build, they will not.
Everything is trivial to make mutable
I think we may be talking about different things. At 27 mins, they talk about using scriptableObject Events - i.e the SO is an event listener that can be registered with.
no, you could not make a Prefab mutable in a build
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.
only to a certain extent, many things in a prefab cannot be changed
True and is how i've always used them, but as @dusty wigeon points out that can lead to case of data not being what you expect. As I said i've always used them with what you say in mind, but I do think its interesting if you were to treat them as immutable , might make them less useful though
Right, and that event listener needs to live somewhere if not on the scene. This is useful because when you change scenes, you don't need to worry about the SO being cleaned up, but similarly you can just use something like a singleton and control its lifetime instead.
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.
Interesting. I guess the real selling point is that it allows manipulation of events/listerners in the editor interface, with a singleton you'd have to write an editor inspector. Other than that there is no difference - but in regards to my question then would you think a singleton class that acts as a middleman for events and listenrers is a good idea or getting overengineered?
It's common practice, plus you get the benefit of calling it statically
tbh, in this case there is absolutely no difference
while you still need that reference to the SO somewhere
also very much this
Note to self - never ask about scriptableObjects in the future 😉 It would have been safer to ask which is the best game console 😉
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
My only major complaint about SOs is they can create a lot of asset bloat
SerializeReference for the win
pretty much but no real official support never ever
I knd of feel i use SO as global variable storage - which is probably bad 😉
may I DM you?
sure ... ? but i need to refill my coffeee brb
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?
It would not be enough.
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.)
I abuse serialized auto-properties with private setters on all my SOs 
when someone says immutable I think of it like a struct, which sure its truley immutable, but you have to go out of your way to change it.
Yes, a struct is immutable. And this is what I mean. It should behave the same way. (Without the copy bit, you do not want to copy the SO as they represent a singular concept)
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
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
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
Hello! Recently, I posted this topic, and while my initial question has been answered, after some further reading I realized that the problem I’m trying to tackle is much bigger than I initially thought. Context HTML5 builds in Unity are not only single-threaded, but they also have a limit of 2GB of usable memory. To get around this, I figure...
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
ok well thats weird, from what i remember of your other posts i just got the impression you were hammering audio oneshots. If that is not the case then its really weird. I still think a new simple testbed project and checking what profiling/debugging information unity supply for audio running in webgl might be a good starting point.
Also what if you disable audio in the project, does it still exhibit issues over time? Might have to let it play for longer than expect to be sure, there isn't a memory issue elsewhere.
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
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.
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
Additionally. Half of my sounds are permanent audio sources and half are temporary ones spawned by PlayClipAtPoit
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
Ouch, this seams bad. Having dinner atm ,but I’ll see if I can test here later, if you could upload a webgl build somewhere that would be easier. But yeah unless you can find some reason why the number of clips playing is exceeding some documented value, I’d submit this simple test case as a bug to Unity
Out of interest what settings are you using for the audio clip importer? Post a screenshot?
Also does this happen in a standalone build?
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
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
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
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
Themed Halloween Jam 19 or something akin to that
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
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.
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
But does it not - not reset when you switch scenes? Isnt it weird that that memory usage never returns to normal?
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
I'd point out that nowhere in the unity docs is it mentioned that opera is a supported browser.
https://docs.unity3d.com/Manual/webgl-browsercompatibility.html?utm_source=perplexity
Chromium and chrome is not the same thing
Notes:
The Web platform also supports the latest version of the Chromium-based Edge browser.
Ofc its not edge
but they support chromium browsers
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.
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.
Your best bet is to fill a bug report and open a forum post. Then wait.
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
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.
Congrats! Glad you could teach it down. I'm still going to avoid that since the project I'm on is massive and takes a couple hours to do a content build on (assuming shaders are already built 😐)
My current plan is to update the engine (which needs to happen anyway to update platform sdk versions) and crossing my fingers. Not the most technical of plans, to start.
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.
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.
25min is not that bad. Just enough to want to dual task.
It seem strange though that you would not be able to pin it down given that everything is pretty much already divided.
{
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...
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.
Oh, I do know about the whole priority list. The previous issue I had could have been prevented if we had a better assets management.
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.
use sharedprofile instead? Also if using profile you need to handle destroying it if I remember correctly.
However I recently did this and i'm sure using profile worked as you expected. Does it maybe only work if you have the values overriden property enabled in inspector?
nightVisionColorAdjustments.colorFilter.Override(camcorderManagerData.nightVisionColor); this is the solution. the override method is necessary to change the values
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
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"
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
The UE api callbacks (Start, Update etc)
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
Unity Engine..
i guess that makes sense, never heard it referred to like that. seems horribly ambiguous with Unity Editor and Unreal Engine
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 😄
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 :)
I swear nobody interprets "UE" as Unity Engine
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.
Thanks for the tips!
But I dont see why StateMachine shouldnt be a MonoBehaviour
At least, it should not be driven itself.
StateMachine is usually an extension of the character
So i should have a controller class that passes in data to the CharacterStateMachine?
Having it live by itself is strange.
That makes sense
You can serialize the state inside the character if you want to have serializable value on it. That being said, the Speed or InputAction could directly be on the character
And, it is better use
public MyType MyVariable => myVariable;```
{
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
Can’t give any other details cuz this is literally what Logcat tells me
Along with the info that the problem is in this method
Make a debug build so that you see the line numbers
also consider just printing the state of each of the objects being used in that method so you can see which is null
Also this
File.WriteAllBytes(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop), "GG.png"), endTex.EncodeToPNG());
is not gonna work on android
they have allegedly ruled that out as the issue
#archived-code-general message
Yes Im aware I commented that before building
Didnt know this ty
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
Are all the dispatches independent? I think the command buffer is probably inserting graphics fences because you're using the results from one shader call in the next perhaps?
You are not releasing your RenderTexture, but just destroying. Not sure if that could be responsible for null reference though.
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);
}```
@remote bough read 👇
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
It's just supposed to run one after the other
I dunno why the CPU thread would be waiting on the graphics fence though. It's all GPU code
What does Dispatch do? It is your own method right?
yes
It just makes dispatching with the right number of threads easier.
cmd.DispatchCompute(computeShader, kernelID, dispatchX, dispatchY, 1);
Hmm... In this case it's really hard to tell without knowing what unity does under the hood.
Maybe use something like PIX to see what actual commands are issued to the GPU.
Also, I don't remember if compute shaders appear in frame debugger, but if they do that might provide some clues.
The shader code actually seems to run fine... the problem seems to be in the renderer code which is sampling my computed texture
The texture is quite large... and it doesn't seem to like that
I thought the issue was the CPU side fence after each dispatch..?🤔
I'm not sure, to be honest.
The CPU shows as red... but I don't know what would cause it
wdym shows as red?
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
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.
exactly
You'll need to look at the profiler hierarchy properly
Is the Render Thread running on CPU?
Why... can't it run on GPU?
Because GPU is highly specialized for running shaders and similar work. It can't run normal code, like the CPU does.
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.
My command buffer executes super fast... the render loop seems to take all the time (?)
What is the context of that screenshot?
This is from the profiler
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.
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.
where do you see the batches?
basically this image is sampled from a buffer that's about 150 megabytes
In the rendering stats profiling module
Just sampling an image/buffer wouldn't be expensive regardless how big it is.
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?
Yeah, that's not much
You should try profiling the render thread with deep profiling on.
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.
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
Does the RenderLoop time go down if you disable the object that renders with your shader graph?
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?
Yes, that's the object that's running the script
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.
I thought reads aren't supposed to block
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.
Hmm, still doesn't make sense, if the compute buffer time is only about 0.08 ms
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.
Well, I'm not saying that it's the cause of the issue. Just that it would indeed block.
Though, to be fair you had like 200 loops of 2 dispatches there, which would add up to 400 * 0.08 = 32ms, ignoring overhead.
Where do you see that number?
"Unnamed Command Buffer" - self time is 0.09 ms
I only call the command buffer once, it just contains ~200+ calls
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.
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?
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.
Normally, yes. But if you are using the result of that operation, then it needs to wait somewhere. Usually that's just before using that result.
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
Again, the wait is probably during the rendering of the scene where you access one of the resources that you write to in the compute shader.
That's so weird... I don't think that's how it behaved before
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.
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
cginc are just include files for shaders, so yeah, obviously they run on gpu
I downgraded but, huh... I'm still not sure what to make of this
This seems to be unrelated to rendering at all. Something about modifying the pointer data of a pointer event.🤔
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"
This seems to be waiting for the GPU to complete rendering the frame.
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
Did you have a look at the GPU module in the profiler yet? Because so far it's all speculation.
I'm not sure how to interpret it. Is it saying that 7.8 ms is my script, and 0.5 is the sampler?
Yes. The compute shader dispatches take around 7.5 sec to process.
If so, I guess I can only optimize away about 6% through being clever...
I don't know. Dispatching 400 compute shaders in one frame sounds excessive to me in the first place.
It's doing computation
Then perhaps that's what you should focus on omptimizing.
The computation right now is actually very simple
it's just taking a simple average
of neighboring cells
the fact that it takes 7ms on GPU definitely doesn't align with "very simple"
presumably, you're running that "very simple" computation for every pixel in that 6k x 6k matrix?
yeah
And then you're doing that 400 times per frame
That's a hell of a lot of computations
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
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.
Well, don't you dispatch them per frame?
In update or something?
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
You should spread the workload across frame. Maybe make one of these dispatches every frame.
the only difference it makes is the visuals lag less
Another thing to consider: do you actually need to run this computation that often on that much of data?
yep
Can you not just cache it and only compute again when there is actually a change or something.
It's for procedural generation, so yes, it can be cached when it's done. But if it's faster it's better
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.
yeah it's simulation stuff
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.
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
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.
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
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.
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?
It is the GPU and what you're doing with it.
Is there a way to get native halfsize support?
Unity only works with fullsize floats, and halfsize would be fine for me
native halfsize?🤔
I think you should be able to use 16 bit precision in the shader just fine🤔
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
This is not inside the shader.
As for the data stride in the buffer, it does seem like it's limited to 4 bytes min indeed.
https://docs.unity3d.com/ScriptReference/ComputeBuffer-ctor.html
But I don't think memory is relevant to the issue.
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
It would have to load it into the registers all the same.
It's not like the number of registers would double.
Right but if the data is half size, it only needs half as much memory
It doesn't matter though. The other half would just remain empty and unused.
Unless you do some kind of packing of parameters.
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.
Yeah, using my fake type didn't help.
Pls is any free texture download either from browser or asset store safe from copyright can I use it to publish my game
Read the license, it will tell you
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:
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
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?
Tried installing the exporter since it seem to have a formats.fbx package
or depend on
Did not work
you'd need an importer, not an exporter
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
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?
Teardown was built using a custom built voxel engine specifically for that purpose
You will probably have a hard time reproducing teardown in Unity
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.
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!
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.
I've dealt with system similar to that. If I remember correctly, we used weak reference instead of hard one. (Serialize the ID of the ScriptableObject, than use a look up table to find the correctly one.)
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
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);
}
}
}
I wouldn't stress too much about it unless it's a persistent problem. It's totally fine to have one static reference to your player, or do a Find behind a load screen or whatever works. The player is special and it's ok to 'break the rules' for them
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);
}
}
I guess that makes sense. I could even use a tag to get it. But I want to use this case to learn for different situations as well.
Thank you. I will look into that#
hey !
Do someone is familliar with addressables in unit test ?
Addressables loading does not working in unit test , event with [UnityTest]
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.
maybe overkill but you could do an IJobParallelFor that writes 0s in
Kinda depends on your requirements for the thing here
are you wanting to do this as part of some other job?
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);
but where do they run that
when you first allocate it
at the start of what job? What kind of job is it?
so are you allocating it in the main thread?
yeah, buffer is shared between job runs
I could allocate a new one every time, but that's also a waste
so either do this on the main thread OR make a job that sets it all to 0 in parallel
which you can schedule in the job system nicely
int[] and Span<int> have normal Clear() methods, I would expect NativeArray<int> to have it too
Arrays do not have a Clear method
How big is this buffer? I doubt it's big enough that you can do something better than memset.
that's equivalent to just Array.Fill though
which would be the same as UnsafeUtility.MemSet
yeah it's all the same
just Unity didn't make a normal safe API for this
apparently
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.
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
Considering everything to do with NativeArrays is Unsafe anyway, I wouldn't fret it
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)
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...
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
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).
Seem like a really strong base.
Thanks!
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):
You mean make eachStatehandle transitions for other states, and not theStateMachine?
That's true
Nah, I meant instead of always doing a move and deciding whatever it should move or not base on the _movement variable, have the state directly call Move.
But, as I pointed out, it really is minor.
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;
}
And in this case, it is even justifiable to do this way you did.
Yes, something like that. Inside the IsGrounded property.
Eh, it sounds kind of unnecessary
👍
Thanks for the feedback, much appreciated
It sounds strange to always move the character even when it shouldnt. If you are state without movement, you are essentially doing:
Move(0,0,0) each frame.
And, if you ever increase the complexity, you might needs different movement logic.
By example, if you want to handle swimming.
I get your point, but i mean its unnecessary in terms of the performance change
And that extra logic might be extra overhead
How would you implement Swimming, Flying or even RootMotion ?
Thats true, but when the time comes, then itll be more necessary
Because as of right now, my controller is simple
This is usually the best way to approach such design. I believe that stating that was a most though, given that would be easy to continue on the same line which would eventually make things really ugly.
Makes sense
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();
first of all i'd check the import settings, make sure it's enabled on all the platforms you're trying to load it on
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?
Yeah, that was one of the first things I check and they're defiently there
What do you use for mocks?
Is that question directed to me or are you asking what library people use to mock classes for testing?
Second one
Moq works for me, but I've seen comments of people complaining about some errors
I use it and seems to work fine for my setup. What errors?
This, but I use it for runtime tests and have no errors
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
most likely a trick of perspective or something
but you'd have to share some details
certianly not a code issue it sounds like
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?
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?
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
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
https://docs.unity3d.com/6000.0/Documentation/Manual/scene-reloading.html "effects of skipping scene reload"
"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
Did you not read to the end of that paragraph?
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.
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.
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
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)
I figured out the issue, so I'm positing here in case someone else has recently had a similar issue. The .so file needs to explicitly contain a lib prefix. My .so file was originally just nestopia_libretro.so and after renaming it to libnestopia_libretro.so it works.
why this listener dont adds to the button even if all conditions true
If you expect to see it in the editor you probably will not.
https://docs.unity3d.com/ScriptReference/Events.UnityEventTools.AddPersistentListener.html
but button with this didnt call listener method
when clicked
Then debug it.
Use the debbuguer, add logs, reduce functionnality to the simplest.
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.
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.
Why not make a package and use assembly definitions?
look at asmdefs in unity
ah i didn't understand asmdefs which is why i want to compile it
Any good tutorial how to create asmdefs
Hmm txn for answer, i guess asmdefs is the correct way to do it
creating dll's external to unity and bringing the result into a Plugins folder is not hard, it's just not 'normal' Unity workflow
The docs are fine https://docs.unity3d.com/Manual/assembly-definition-files.html
If you're stuck on something specific we can help, but general tutorials are difficult to recommend as I never learnt using any of them
i just wanted to hide the internals from script outside the library, nothing else
google has lots of results for you
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
is the class marked as public?
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
can you see the asm def'd projects in VS
Which one is it
im not familiar with that
whatever you called them
Screenshot your asmdefs I reckon
Weird, when i open the file in visual studio, it is not visible in the solution explorer, but i can open it
probably need to switch on Player Projects in external tools and regerate project files
What does it do ?
Anyone know how I can start learning about game AI and training machine learning modules in unity?
it generates project files.
asm defs should show as seperate projects in your solution explorer
Ok try to do that
code monkey has a pretty good tutorial
It did nothing.... except that now it has Assembly-Csharp.Player in solution explorer
The class or namespace still not visible
what's in your asmdef?
yeah I saw it but I'm looking for something for more of humanoid characters
turn on auto referenced
Okay wait
the concepts are identical, extrapolate
I turned them on in both of asmdf, did nothing....
try regenerating your project now? that should mean it's usable from assembly-csharp
yeah but someone once told me to learn something about state machines and allat
Okay wait
would I need this for animations and all?
state machines have nothing to do with ML
It did nothing....
I just want to hide the internals why is this thing so hard 😭
is unity showing a compile error or is it just visual studio not showing it properly?
wait what I swear someone here told me to learn those and path finding algorithms.
None of then show compile error
that's for real AI, not ml nonsense lol 😛
Indeed you need those but, as I said, they have nothing to do with ML
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
What else should i do, i regenerated my project but it did nothing
if there's no errors, do you have code referencing the types in the main assembly? if so it sounds like it's working and it's just a VS problem? 🤔
Ohh so those aren't machine learning concepts just regular game AI concepts?
yeah look at #1202574086115557446 for the ML stuff
I just removed a semicolon from a code and neither unity nor visual studio throws error...
What is going on
I wanna work on the ml stuff tho, teach two humaniod characters to play tag
oh wait, i misread your photo, you have EXCLUDE editor turned on, not include editor
make sure it's marked to be included in editor!
the UI is kind of unclear on that option
I just have no idea where to start and it's driving me insane
IT WORKS TYSM
i selected the platform thinking it was target platform, not exclude 🤣
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?
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
Yes, you'll need to qualify which one you are using every time. And you'll need to cast it to unity Vector3 when interacting with unity API.
do I need to downgrade my python version for ml-agents cause there's so many errors rn?
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.
if the verboseness is bothering you, you can write an alias like using UnityVector3 = UnityEngine.Vector3 or whatever name you prefer
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
do you think if i sent a video of the bug it would help?
Wouldn’t hurt
can i sent it in the chat? or you prefer if i send to you through your DM?
uhh i dont know the rules but here is fine
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?
Roslyn code generators