#archived-code-advanced
1 messages Β· Page 109 of 1
Non Unity C# questions are out of scope for this server
Do you have the link to the server ?
(And frankly... your question there is going to be met with a similar toned response.. you'll need to scope down your question and ask more precisely)
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Thanks
I wrote a custom editor window instead of the already existing custom inspector and presented a demonstration in it for editing.
But while editing, the problems I said appeared, the system is actually editing an already existing SO file.
!ban save 293392938623565834 Slurs
1x5x7 was banned.
Anyone have a reasonably good implementation of PriorityQueue<T> for unity (ie, before MS built a proper version in .net6)? The only one I came across is functional but not fast, basically just sticking an element onto the end of a list and iterating the entire list every time I want to Dequeue()
Maybe this? https://github.com/BlueRaja/High-Speed-Priority-Queue-for-C-Sharp (Has anyone used? I was looking for something a little less enterprise-y but... this seems like it hits all the requirements I didn't know I had)
Using this one without issues. Itβs not overly complicated in its implementation
I'm wrestling with it. π
It doesn't look like I can configure the weight of the queue, and I want to use it for A* pathfinding, which means I want a ... "de"priority queue π
If you use the Simple version itβs trivial to use.
(ie, best is lowest value)
You could extract the queue from A* pathfinding project lite
I am also unsure if I need to implement IEquatable to check if a node exists in the queue
is that um.. victor's project?
I forget his name or the project, I recently saw it in the C# discord, and it was nearly perfect but had some new C# language features that didn't work in unity out of the box
but I have a bug in my own implementation of A* and i'm close to reaching the limits of my ability
If you want speed with complex types you certainly want to custom implement all the compares
This one https://arongranberg.com/astar/
Itβs the most scalable and real world usable turnkey pathfinding solution
cool, i'll check it out after I finish this at-bat with blueraja's implementation
i'm currently trying inverted weights (ie, negative) so that I don't have to change any of his underlying code
but i've got a low level of confidence it's gonna work
LGTM? π€·ββοΈ
Ended up implementing my own wrapper data structure with a dictionary and priorityqueue because neither data structure did it all .. it was getting to be a huge pain in the butt to get items out of the queue
Just a recomendation, but if you want your Priority Queue to be faster for A*, you should find an implementation that doesnβt create seperate objects for each node but stores them all in a list. A priority queue is just a heap so you could implement this yourself
That is, if your node is a class, make it a struct so you get more cache hits
Now that Iβm saying it, this is actually kind of too picky for your caseβonly really matters when your trying to boost performance
So afaik there isn't any C#-native way of getting a folder or some other path from a System.Assembly. However, in Unity, is it perhaps possible to get the path to an .asmdef file from an Assembly?
Need an unity wizard to go trough with me and figure out why my game only works properly in play mode except for some pcs.
The line underlined doesn't work in build
I'm sure it works, just not as you expect it to
If you can reproduce the issue, just debug it.
why does it only work in playmode
I tried debugging a dev build
the values are still correct
im so desperate to fix this
debugged both playmode and build, values are correct
playmode works
build doesnt
If they're correct at that point, then something is modifying them later on.
The most common cause of such issues is dependency on execution order.
And many things are executed in different order in the build.
and its random too, some pcs work fine
I have tried a shitty laptop, a high end pc, just mine doesnt work
Yep, sounds like an execution order issue
hmm, what should execute first? I had the level manager with priority didnt work, removed it didnt work
You should find the cause first.
Anything that is moving or could be moving the character. Just log or breakpoints everywhere that touches the position.
i don't think there's a convenient way but you should be able to calculate it somehow, the first thing that comes to mind is you can look at the types in the assembly and find the corresponding assets (MonoScript.FromType should do it?), and from there you can look for asmdef/asmref files
Ah! MonoScript.FromType looks like it'll do it! Thanks a lot
Well uh... MonoScript.FromType doesn't exist? Plus MonoScript doesn't have any sort of reference to the file path...
ah my bad, Rider was showing me internal methods haha! but MonoScript assets do have methods to get the class/assembly they contain, so you can still search through the project for MonoScripts and compare the type yourself
MonoScripts are also assets so you can do AssetDatabase.GetAssetPath on them
how can I have breakpoints on something that run every frame? I want to debug dev build and I have a bind to skip level but you know, cant actually press anything if its in the breakpoint π
Doesn't the issue occur at the very specific timing(level load)? Why would there a be a problem to move until that point?
Also, there are conditional and log breakpoints.
You can also disable breakpoints and enable them only after that method is called.
I disabled them and reenable them but I dont think thats very reliable
Why not? Also console logs are an option too.
does it go to appdata player.log?
If you have the debugger connected you can see them in the output tab
the game is still running in the time i disable and enable them how can I ensure the frames that i missed didnt mess up
Or you can connect the unity console to the build and see the output in there
how can I do that?
Well, don't enable them when the game is running.
Break in your method, and enable the breakpoints durring that time.
I see
I also tried brute forcing all possible combinations for script execution, still nothing
the player only gets moved in the level manager and player controller
so I messed with those two
Check the attach-to-player section:
https://docs.unity3d.com/Manual/Console.html
Also, the player movement is not necessarily limited to just your code.
A CharacterController, for example could cause issues with movement.
oh and how can I debug that?
This kind of things you just have to know usually. But if there are no other causes, there's a possibility it's one of the unity components.
Another possibility is that you're not moving the correct object.
At least when the issue occurs
that can't be, the reference is never changed
its called on awake and never again
its a private variable so nothing can change it
are the level manager and player DDOL?
no, but its in a scene that doesnt get swapped out
its all in a scene and the levels get loaded on top
Okay. If it's a character controller, you can try disabling it before setting the position and reenabling after that.
holy shit I think that was it
yeah its fixed now, thank you so much
I still don't understand why it would work in playmode but not in build. Honeslty, don't care, just care that it's finally working after 3 days
Probably has to do with the timing. CharacterController is a pretty bad controller to be honests, and I wouldn't use it for anything beyond a prototype
what's a DDOL btw?
Don't Destroy on Load. You can google that.
in unity context..
If you want to look up something about Unity why would you not make Unity your first keyword? Do you think google knows you want Unity related results without you telling it
I didn't even know it was related to something Unity-specific in this context
We're in unity discord. Everything here is unity related.
And if not, then it's off topic.
sheesh guys u better not be roasting everyone over questions of this type lol
You're in advanced-code channel. Of course you'll be roasted over these kind of questions. π
think of it as a learning experience
it's amazing how much easier life becomes when you learn to google effectively
I'll stop this here to avoid further spam, but yeah I don't think roasting is productive in a learning discord lol. Not that I felt pressured but I'm sure new people in this discord would
Hello, pardon my wording but any pointers on how to implement runtime updates to the game? Like i have launched a new character in the game with new powers and everything, user can just download all the data without redownloading the app?
I'll try to research on it but I don't even know what "this" is even called 
So any pointers pls, thank you!
Addressables or Asset Bundles
I read somewhere addressables don't allow to add scripts in it so how would that work?
For anything that doesn't use code, you can use Addressables. For code-related stuff, you can setup some DLL loading system.
neither will allow scripts, you cannot update scripts without an update of your game. Well you can but it's a very complicated procedure and fraught with danger
Mind that DLL-based patching can introduce vulnerabilities, so be careful how you distribute your game.
(e.g.: tell players to only download patches from the official link etc)
I see 
as for "this", it's called "patching" π
So all the logic needs to be done beforehand , and can only send out the assets at runtime? ;-;
yeah, and for security reasons this is the best course of action by Unity
what you can do with addressables (not with asset bundels) is include scriptable objects with new data, so that is one way of doing it as long as your original SO code supports it
Like imagine if you didn't know it could introduce vulnerabilities but you still released your game that allows all and every Addressable + New Code (mods) to be loaded.
This could easily become a nest for community-made viruses or something along these lines. Whereas locking to non-code makes you pay attention to it.
(either by manually designing modkits, or by taking the risk on your shoulders to create your own DLL-loader)
Makes sense
DLL-based patching is fine, imo (assuming carefully designed), but for modding it's extremely dangerous and you shouldn't ever do it
Of course that only works with a Mono build, for IL2CPP you do not have that option
Thanks for the advice! I'll drop the idea for now and plan out better next time 
pretty sure you can load and execute code from DLLs in IL2CPP (?)
Don't really have a need to import new assets yet so yeah
Is it technically possible? Yes, Do you even want to think about doing it, most definitely not
lmao all-in-one patching solution costs $200 per seat π https://assetstore.unity.com/packages/tools/utilities/patch-updating-system-plus-46639
hmm? How come? I'm not aware of any actual differences past the runtime
that is exactly the problem, IL2CPP builds do not use the Mono runtime, an external DLL will require it, so you have to ship the complete Mono runtime with your game
That looks good on paper 
oh interesting.. yeah that makes sense.. I am under the impression I loaded some DLLs in IL2CPP but thinking back it's very likely they were included in the project, therefore precompiled
DLL's build into IL2CPP are no problem becaise they are decompiled into CPP source and compiled back into CPP obj's
Sadly mobile platforms not supported 
not a chance
patching an apk is really really hard
yeah if you notice even top-tier apps like Google Chrome force you to download the whole thing all over again
XD
True
But man Google is an indie company, cut em some slack~
for mobile games though patching can be simplified (by separately storing the tons of assets)
aka if you use ship your game without assets (just scenes & prefabs & code), and link to addressable download from (your) server
assets downloaded via addressables will be stored on separate folder than the apk, so your apk file can still be quite small
I have tonnes of questions regarding what you just said but someday later xD
alright xD
Asset bundles is just how you do live update with assets, that's the entire purpose of it.
You can't live update code, especially not on mobile, iOS App Store forbids it. Design around it or give up, there's no other way.
Yep gave up half an hour ago 
maybe a decent alternative if you're willing to go down this route, visual scripting graphs are just assets so as long as you don't try to add any totally new nodes, you can update those without a new install
in a runtime executable?
what do you mean?
what you are saying is that the graphs themselves are built into the executable and turned into IL at runtime. I'm just querying that
no, they're just assets, it's an alternative to actually updating the game code
so how would they run then?
it's all based on reflection
as long as you don't try to use anything that was previously stripped by the linker, it should be OK to update them
Nah, I cannot see that ever working
why?
because a graph is not IL and reflection would have nothing to do with it
The issue is not technical, I mean you can always embed an entire Lua/JS/whatever runtime you want. The issue is iOS App Store does not allow apps to do that (even though there are still apps that do, that's a separate conversation though), and that's why all iOS browsers are just reskinned Safari.
well that's the point lol, it's a way to arbitrarily update the game's behaviour without modifying any actual code. i don't know what apple makes of it policy wise but it's bascically a fancier version of making a bunch of scriptableobject building blocks you can combine in different ways
Visual scripting is something only my dead body would use 
This is really driving me nuts. MonoScript could have worked, but I'm dealing with files with mostly POCOs, so MonoScript.GetClass() doesn't really work. I've managed to get a list of UnityEditorInternal.AssemblyDefinitionAsset for the asmdef's in my project, but those seem to know nothing about the actual assemblies, so it's another dead end. So, I'm asking once again: does Unity provide a way to get a file or path or asset from a System.Type/System.Reflection.Assembly?
C# does have System.Collections.Generic.Dictionary<T, U> (?)
myDict.Add(typeof(MonoBehaviour), myAssetRef); and it's associated (?) π or what do you mean
ah you mean get actual assembly classes out of an assembly if you know its asmdef
for plain old C# classes there's not much special support for this kind of thing that i can think of, the asset database only cares about things it can serialize as assets really
technically var asm = System.AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.Contains("AssemblyName")); -- then you can get all classes from it etc
I'm not sure what you are trying to do here. You can get all loaded Assemblies and itterate them to get the Types they contain
Well, I'll try to actually explain my purpose.
I'm generating some files in an editor script (mostly because Unity doesn't like generic MBs), and I'd like to place them in the same assembly as another type, since that way the end user can't possibly break stuff unless he tries to
If you don't find a solution, a surefire hack to group types by assembly could be this:
var assemblyTypesMap = new Dictionary<Assembly, List<System.Type>>();
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (var asm in assemblies) { assemblyTypesMap.Add(asm, asm.GetTypes().ToList()); }
Uhh? That wouldn't help at all... I guess I still haven't made myself clear, I'll try again
why wouldn't that work? π If you find types on some place they shouldn't be you can detect which file they're in and move it to the location you want them to be in (effectively controlling the assembly it'll be in)
Say I have the following folder structure:
Assets/
βββ SomeFolder/
β βββ SomeSpecialScript.cs
β βββ SomeAssembly.asmdef
βββ ScriptGenerator.cs
ScriptGenerator finds some special types (as System.Types) and creates some code. I want to then be able to save that code in a file in the same assembly as the special type. So in this case if SomeSpecialScript.cs contained a special type, the generator should create a file in SomeFolder/. That is why I want to find a folder based on a Type or Assembly.
that's some nice ASCII
not gonna fly, the Assembly is created in the Library folder not in your Assets folder and an assembly does not contain the file names of its component types
How about something like this?
var allAsmdefs = Directory.GetFiles("Assets/", "*.asmdef", SearchOption.AllDirectories); // Also the root for new scripts
var allFiles = Directory.GetFiles("Assets/", "*.cs", SearchOption.AllDirectories); // All scripts, raw, without grouping
var groupedTypes = // your algorithm to group the cs files by asmdef if you want (Potentially unnecessary)
foreach (var filePath in allFiles) {
var fileText = File.ReadAllText(filePath);
foreach (var specialTypeString in specialTypesToPathMap.Keys) {
if (!fileText.Contains($"class {specialTypeString}")) { continue; }
var correctRootPathPath = specialTypesToPathMap[specialTypeString];
if (filePath.Contains(correctRootPath)) { continue; }
File.Move(filePath, $"{correctRootPath}/{Path.GetFileName(filePath)}");
}
}
I ended up getting a list of asmdefs from the AssetDatabase and comparing their name's to the type's assembly's name. Not ideal and not bulletproof, but it might work
Can't believe the functionality for scroll view mouse drag is built in, and locked away, because somebody didn't want to create a toggle.
Am I going to get an army of lawyers at my door for removing that single check so I can enable this feature?
Taking the silence as a no army of angry lawyers.
Anyone know how I'd go about making quadtree LOD for meshes?
what kind of meshes?
cubespheres
so you want to make planets?
yes
i followed sebastian lagues tutorial on creating the cubesphere,
i just need the LOD part now
and I have no idea how to go abouts this
Like a distance based LoD system?
yes
The baseline would be: you define a coarse sphere at the lowest LOD resolution, then subdivide its quads in view N times to the appropriate LOD level based on distance or pixel error. Next step is subdividing/merging the boundary quads between different LOD levels (which have a small number of variations if you only go between adjacent levels).
Subdividing boundaries is what's usually very annoying for LoDs, good luck
a proper LOD system would generate details based on how much variance is in the sampled surface elevation data at a given tile (like the unity terrain). This is a quite a bit more complicated in regards to tiling and boundary matching.
here is the original article on how: http://tulrich.com/geekstuff/sig-notes.pdf
for 3D games where I DO want custom physics, ON TOP of the existing physics, is Kinematic RB + Reinventing dynamic physics the one way?
You can use the velocity of the rigidbody to make a lot of "custom" physics.
actually answers for 2D are acceptable as well -- just specified 3D because kinematic Rigidbody (3D) doesn't even support .velocity, so I'd REALLY need to re-invent everything.
you should know better than to cross post
wait, you moved it, ok
don't be that guy. I deleted my message from -general to let the other dude get help
Explain what you want to do, 99.9% of physics can be customized
hmm simplest example is: I haven't managed to pull off a controlled-velocity bounce after collision with Dynamic Rigidbodies when it should have been as simple as
void OnCollisionEnter(Collision collision) { rb.velocity = -rb.velocity; }
You should use a "velocity" variable that you change and you update the rb.velocity to be that each fixed frame.
That being said, the actual collision will be made with the physic engine you are using, you can only modify the after effect.
In case of an exagerate bounce, it should be more then enough.
You can also look into physical materials
Which are the way to customize the bounce for the phyisic engine
I can't deal with just physics materials -- I definitely need actual custom physics. And sure .AddForce and direct rb.velocity = help,
..but if I have to make a motor that updates the velocity to my desired one just to handle the collisions, thinking I might be better off with a Kinematic RB
Kinematic RB is not a necessity, you can mostly do what you want till you find out that you need it to be kinematic all the time.
But, for most effect that are extension of the physics engine, you can use AddForce or other means of velocity.
If you want to have the best control, you can use Kinematic + own velocity
Usually, you end up with kinematic for important elements of the game anyway.
thanks, I'll go with Kinematic after all as I always did lol.
was just curious coz I always go with Kinematic since I find it easier to implement existing (needed) physics on demand (e.g.: Motor, Velocity, AddForce, Collisions)
rather than make the Dynamic viable for custom and controllable physics
Usually dynamic is more for non important object
Even the CharacterController is not using rigidbody.
And the moment you have navmesh it breaks everything
hmm? Everything nav-mesh related breaks without a rigidbody? How so?
The navmesh agent drive the object, trying to use a rigidbody dynamic with it does not work correctly.
You need to use alternate method to use both of them.
Does Microsoft.Data.SqlClient work with unity or am I stuck using deprecated system.data.sqlclient
It's not built-in with Unity's references, but you probably can import the dll add it yourself.
I have an architectural problem with unity π
I am trying to make an strategy pattern where each strategy is a scriptable object.
I need to find a way to assign a configuration (strategy) scriptable object to a static / global / singletonish class.
I have this problem in pretty much all my managers, but lets make an example of a "savedata manager"
The static class has two simple methods: Save(stuff) and stuff = Load(). This static class doesn't have an implementation on how to actually save data, it instead asks the strategy scriptable object to actually do the saving.
My problem comes now... how do I tell the static-ish class which strategy is the current one?
My current solution is to have an scriptable object instead of the static class, but now I need to drag the scriptable object from the editor everywhere I need to Save(stuff)...
Is there some unity black magic I am missing? (I am trying to avoid loading from resources, hardcoding paths, etc if possible π¬ )
π¦ unlucky its like 12 dlls lmao
yeah π
we are going to need more info to really answer your question but id use reflection to populate my references personally. The static class/singleton pattern you're using is terrible in design. It produces clunky code that you can't really unit test properly
oof long questions like this are hard to read by ESL people like me :/
tldr; If I am doing a strategy pattern in unity, how can I set the strategy globally?
Dependency Injection is the standard -- and the cheaper version is System.Action (/delegate) composition
use reflection or addressables or asset bundles
you can build the scriptable objects out to asset bundles then load them from Application.streamingData path
maybe I am getting something wrong, but with dependency injection if I skip the injection step (say, a bootstrap scene) the system falls appart π¬
and during development, you skip your bootstrap scene a lot π
ah, you seem to have missed RuntimeInitializeOnLoadAttribute π
public static class ConfigurationManager {
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod] public static void ConfigureDebug() => SaveSystem.SetStrategy(Resources.Load<SerializationStrategy>("A"));
#endif
}
this makes ConfigureDebug() get called as soon as you hit play
There are a bunch of options for the attribute: https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
@azure meadow is there a reason you're preferring to make this class static? is it just so its easy to call from anywhere or what?
yep
the only static part is the "save system" which is a strategy manager π€
@azure meadow would this not work for you as a DI solution?
i dont see why it wouldn't
and yes, I am using Resource.load which is eeeviiiiiil π
but I am doing it on UNITY_EDITOR so I don't really care π
save the scriptables to asset bundles and load t hem from bundles instead
Resources.Load is fine afaik π
Addressables and web builds and stuff breaking π₯²
hmm... neither web builds
addressables have been buggy for years
bundles been around since unity 3? and have always just worked
for web builds they are a godsend compared to bundles π¬
I couldn't get bundles to lazy load on web builds
lazy load?
I managed to punch addressables into shape
load them as you try to enter the scene that needs it
oh
a web game should ideally load in less than 5 seconds
unity runtime is like 20 mb
we can't afford to load all the assets after those 20mb
π
assetbundle.loadasync?
that wont stall the web build from loading
also
asset bundle loadscene thingy downloads all needed addressables
no it doesn't
it only downloads it if you make it download it
you can ship the bundles into your game directory directly and they dont have to download anything
yeah
addressables are like one of those typical unity solutions
works great for prototyping
not so g reat in production
i shipped a game using adressables and the first update stripped them out and I replaced them with my own system i wrote around asset bundles
what problems are you finding about addresables in prod? π€
(oh, also, I am not doing the hotpatching of the addressables, not yet anyways)
users are somehow causing redownload of assets they dont need to
and bandwidth isn't cheap
but yeah the solution @hardy sentinel posted would work great but if you dont want to use resources your only other options im aware of are bundles/addressables or maybe you can mess around with tags
would you recommend CharacterController over Kinematic RB + Motor for non-complex entities? (e.g. projectile)
a super-barebones motor would be just this
CharacterController is only for prototyping in my opinion. Also, for projectile you wouldnt want to use ChracterController as it is made for character (Grounded entity)
For projectile, I would use rb kinematic or no rb at all.
I share your opinion lol. But again, I was stuck with the practice of Kinematic RBs almost since the beginning, so was hoping to find easier alternatives this go.
With Overlaps or other manual collision detection
Physics.OverlapX OP
The issue with what you have could be that you will only update in FixedUpdate it will look like it lags.
Given that your refresh rate will mostly be higher then the fixed update, some frame the object will not move.
I was under the impression this makes it emulate the inb4 frames?
nah it can still be jittery
From my experience, it is suppose to be but it does not always result in good results.
Also, you are not using the rb.velocity of the rigidbody.
tbh the first go I was so frustrated at built-in physics I went up with completely custom physics system lol (including collisions)
I suspect it might not work as intended because of that.
great point, I am usually more concerned about the game loading fast and not losing players to the loading screen
somebody else paids the bills π
but maybe in the future I will need to make my own loading system π
I'll check closely and let you know.
the game may load faster using bundles t han not using bundles there was a time where the resource folder increased load times.
i personally created an editor script that builds my assets bundles and also generates json files based on the data inside so I can use them inside of my zone server that doesn't run in unity
I will look into spinning my own "per scene loading" system then π€ π
its really not that hard feel free to shoot me a dm if you have any questions or ping me on here
my editor script has certain assets tied to certain scenes I created a wrapper class around scene manager so when I load/unload a scene it loads/unloads the bundles
use assetbundle.loadfromfileasync to avoid long wait t imes
are you like trying to do bullet ricochets?
not trying to achieve that per se, but I indeed want that in my game π
for now I'm contemplating on how I'll go about the physics.
well i mean you should be able to make a projectile bounce off a wall pretty easily with the default physics
you shouldn't have to use kinematics or custom physics or nothing like that, what problems are you having thats making you contemplate using kinematic rigidbodies for this?
well the bullets shouldn't need to be dynamic anyway -- I'm planning ahead about the rest of the physics entities (characters, movable/immovable objects, etc)
although dynamic bullets with bounce=1 would save some trouble π€
you shouldn't make bullets with rigidbodies
high speed projectiles can sometimes not detect collison
fiiiiiine I'll write custom transform-based physics again...
just use raycasts?
yeah.. issue is I'll need to do it for any and all physics entities
you're worried about performance?
what? no, not at all xD I'm worried about the scope
can you elaborate?
well making a custom physics engine will be time-consuming no? And bugs will be constantly be detected along the way
well that's a custom physics engine π
you say custom physics engine
and I think you're talking about writing something like bepu
but with that in mind no using raycasts wont be more time consuming or buggy than trying to get rigidbodies to work as projectiles imo
it's kinda like that except I'd be using UnityEngine.Collider and UnityEngine.Physics(/collision-detection methods) as bases
the real question is: are you 3000% sure you want a bullet object and not just instant hitscan damage?
don't be stuck on the projectiles xD
very fast and very small moving objects are the bane of any physics engine
writing your own won't magically fix that π
that's why we fixate on projectiles π
imagine handling Character->World collision with raycasts etc.
yeh, my player character usually does that... but with the unity physics engine π
at that point id just use a quad tree
well oct tree in your case since its 3d
I don't know why everyone assumes raycast means infinite range and instant hit. You can raycast in steps, as far as the projectile will reach in each fixed frame. Then you can have perfect collisions that will never miss and even implement ricochets, bullet drop, etc.
yep i have a full fleded projectile system that is as realistic as escape from tarkovs entire thing is less than 1k lines of code
high-quality collision detection can be easily handled like so: if (Physics.Raycast(position, vel * Time.deltaTime, out var hit)) { ... }
one issue is if you want the movement to stick to the 'wall' (/hit object) after a collision it becomes complex in 3D
.. coz the simple position = Vector3.MoveTowards(position, position + vel * Time.deltaTime, hit.distance); would not try to move across the normal
so yeah, for a custom physics system we'd want to first notify callbacks, then calculate adjusted position across the normal without overlap,
then cross-check with other moving objects that could potentially occupy the space between, cache overlaps, readjust, and finalize
collide and slide β’οΈ ?
yeah π must-have in a physics engine imo
unity... has one?
I wrote my own π₯²
collide-and-slide β’οΈ
look for the "collide-and-slide" algorithm
it's a whole paper and all π
or maybe unity has one and I reinvented the wheel
I'm not trying to do anything xD I'm just explaining why it needs to be a fully-fledged custom physics engine if I don't use rigidbodies at all
Unity has Physics.ComputePenetration for 3D
Physics2D.Distance for 2D.
If you're not using Rigidbodies and you want physics of course you need a custom physics engine, that does not explain why you are not using rigidbodies in the first place
because you shouldn't use rigidbodies for projectiles
why not? It is common practice
put a rigidbody on anything that moves
sometimes collision events wont be fired if the projectile hits between fixed update frames
slow moving projectiles are fine
but bullets? they will not work correctly
then you need code to compensate. You don't throw the baby out with the bath water
no you just use raycasts instead
no, you use BOTH
why?
because a raycast can be used as predictive technology
and what exactly is the point in using a rigidbody at all when you can just raycast it?
because the rigidbody technology will run a damn sight faster/more efficiently than your C# coded raycast technology
do you have a benchmark or is this speculation?
you can do batched raycasts and jobified raycasts now so I really dont see how youll run into any perf issues with raycast
common sense, rigidbody tech is running in native code
'just' ? That covers a multitude of sins
calling c# methods is a sin?
dang I better switch to unreal im not trying to burn in hell for my actions
no, it's cosines
ik im jokin xd
no, using words like 'just' is a sin when it comes to software development
the benchmarks prove otherwise
Hello Guys I have question I am learning game development I want to know do I have to learn the full C# language for unity scripting? Or can I learn C# basics and then simply learn unity scripting? already learned C# basics from Brackeys series do I have to learn more?
either ones fine just chose whatever one you think will keep you interested long enough to not give up
Yeah imo unity scripting keep me interesting long enough, Btw can I ask what you did when you started?
i learned how to code like 15 years ago modding grand theft auto lol
Oh that's Cool!
i personally would try to stay away from video tutorials and instead look at stack overflow/forums/discord when you are trying to figure something out
most of the unity tutorials are just like "hey watch me code this thing and follow along while you learn nothing"
Thanks for your advice dude, I will follow your advice π
Yeah for real bro, I am just learning the basics from YT but I don't copy from the tutorial after I learn something new I ask chatgpt to give me some challenges that include using of that feature like if else statements,loops etc. Then I try to make at least 2,3 small programs entirely myself.
Keep in mind, that brackeys course is... not great.
Also, definitely do not use GPT as a beginner. oh, just for giving you a challenge? That actually seems like one of the very few good uses of it. Nice
You should do !learn
And if you want an actually decent c# course
https://www.w3schools.com/cs/index.php
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Also, none of this is an advanced question. It would belong on #π»βcode-beginner
Alright But there unity documentation is too big i am confused where to start,
Yeah i only uses it for giving me challenges not for coading.
Thanks i will look it out!
Go into the pathways section. Start with essentials, then junior programmer, then perhaps common core
(That is not the documentation btw)
Alright I will keep it mind but i thought in the #π»βcode-beginner There were beginners only i want to ask some experienced developers how they started.
Can i ask how you started?
YOU are a beginner, so you ask in #π»βcode-beginner
The people who ANSWER are not beginners
Hope that makes sense
Alright Thanks!
Sorry my bad.
Okay Cool! I will keep in mind.
!code
No worries! Best of luck with everything
π 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.
Can you answer this in #π»βcode-beginner If you want to?
Thanks dude π
public void GetLeaderboard(string publicStringKey)
{
LeaderboardCreator.GetLeaderboard(publicStringKey, ((msg) => {
int loopLength = (msg.Length < names.Count) ? msg.Length : names.Count;
for(int i = 0; i < loopLength; i++)
{
names[i].color = Color.white;
rank[i].color = Color.white;
scores[i].color = Color.white;
rank[i].text = msg[i].RankSuffix();
names[i].text = msg[i].Username;
float retrievedTime = msg[i].Score;
scores[i].text = (retrievedTime/1000).ToString("F3");
// Returns true if the entry belongs to the player
bool isMine = msg[i].IsMine();
if (isMine)
{
names[i].color = mineColor;
rank[i].color = mineColor;
scores[i].color = mineColor;
}
}
}));
}
public void GetPersonalEntry(string publicStringKey)
{
LeaderboardCreator.GetPersonalEntry(publicStringKey, ((msg) =>
{
mineRank.text = msg.RankSuffix();
mineName.text = msg.Username;
float retrievedTime = msg.Score;
mineScore.text = (retrievedTime / 1000).ToString("F3");
}));
}
This is using the leaderboard creator unity addon, whats steps would you take to optimise this to load faster?
Nothing to comment on speed of execution itself, the network and server are probably the bottlenecks here.
Consider renaming msg, its name is not explicit, it does not reflect the contents of that parameter.
You could also offload the entire contents of the lambda to a full method to lighten it up: LeaderboardCreator.GetLeaderboard(publicStringKey, HandleLeaderboardResponse); + private void HandleLeaderboardResponse(? msg) { ... }
You can use the Profiler to see where your app takes the most time to execute.
Presumably the data is coming from the web, so bandwidth considerations are going to make the code speed totally irrelevant
Yes, im so glad you've said this and not "omg what are you doing" lol. Im new to this basic networking and not sure if I am the issue or the server. I thought server as its not dedicated so would be slower but wanted to be sure haha
you know what they say, 'You cannot make a silk purse from a sows ear' and in this case the internet is not just the ear it's the whole sow
Appreciate it and good to know Its not necessarily a me issue haha
Rigidbodies are incredibly heavy, I guess you've never run stress tests on them πMeanwhile you can submit a thousand raycasts in 1 method call thanks to RaycastCommand API and get all the results blazingly fast.
Doesn't raycasting run on the PhysX C++ side just like rigidbodies?
Or were you talking about custom C# raycasting, I didnt read the whole convo
This is fixed with continuous collision detection
Which is most likely way more performance intensive than a raycast
Hi friends! I'm currently trying to get an understanding of hierarchical state machines for a player controller but am having a hard time wrapping my head around how states are split up. In video examples I've watched, they have a whole GroundedState, which I can't really wrap my head around since (at least animator wise) I imagine two separate states for running and idle when grounded. Does anyone have an explanation of how idle and running states work with a grounded state?
Today i've learned about the PlayablesAPI, i'm struggling to find good video/blog tutorials to explain how to use it
does anyone have an example/good tutorial that contains information on how to utilize PlayablesAPI
Nothing prevents you from having a idle/running state inheriting from ground state. Alternatively, you could have a well define function that take care of everything about snapping on the ground. I would highly recommend that to prevent issue with multiple inheritance.
That being said, if your project is more or less simple, having a single state controlling the "idle" and "moving" of the character is more then fine given that not much differ between them (Code wise). Grouping it under the umbrella of GroundState would be red flag in my opinion given that other state might be "grounded". (Play Taunt, Death, etc.)
Obviously, any video you find on internet most be taken with a grain of salt as many content creator never actually worked in the industry, have little experience or their idea have not been challenged by others. It is a start point, and following what they do will usually at least make you able to do exactly what they did, but it might not be the most efficient way or even a good approach in a "real" product or, as in a lot of case, for your specific use case.
I highly recommend simply doing it and acquire experience by yourself. Do not stop yourself to find the "best" way. What I said about multiple inheritance being an issue and why GroundState is a "red" flag would usually be acquired through experience.
+animator-wise you could imagine the two states being SubStates of the Grounded Controls state
Ok, better question. Is it possible to have both a Playable and an AnimatorController run at the same time?
basically currently i'm trying to make a system in a project that allows third party users to basically "Inject" (barebones) animations into an existing controller, thought the playablesAPI would be ideal for that
Is it runtime or editor only the injection ?
ideally at runtime.
i thought i could create a Playable that feeds outputs into the animator both from the RuntimeController and the "injected" clip, but thats only playing the injected clip which i think is because its the last one i call SetSourcePlayable.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Modify the AnimatorController through Playable would be a really bad idea. The best you could do is take the resulting clip and modifying it but it would remove a lot of any customization you would be able to provide your user.
If you limit yourself with Editor Only there is a ton of way to manipulate what the animator is. Obviously, you would not be able to have feature that the animator does not give.
what would the loss of customization entail exactly? stuff like events?
Whatever you want you add as functionnality that does not exists in the Animator ?
fair enough
with editor only i'd need to have access to the runtime controller i'd like to ""inject"", right?
cuz then htats just a matter of modifying the original runtime controller and building its runtime controller
Exactly. But, before doing it you should look into what you already are able to do. If you are not ware of the Animator Override Controllers you should look into it.
OverrideControllers just allows you to override an existing clip with another clip, that isnt what i'm looking for
If you want to explain what you are aiming for we could point you to solution that might already be in place.
Obviously, without knowing I'm shooting up idea that are worth considering before doing anything about modifiying the animator.
||penultimate prohibited content in the guidelines forbids me from giving too many details since it is related to injecting animations in a modding scenario||
||i know you probably dont want to risk getting a warning or outright ban, so i'll take my leave then.||
why is that banned in the first place π
@white pulsar Is it about moding your own game ?
yup
Then there is no issue as far as I know.
The issue is about moding or hacking other games. Obviously if we are talking about making a mod for your own game there is nothing wrong here.
So I posted a topic on the forums but my colleague suggested I might get better traction in discord. Here's the post: https://discussions.unity.com/t/hook-called-before-anything-is-deserialized-after-compilation-domain-reload/1508341
TLDR: I need a hook to invoke code before any asset is serialized/deserialized (via ISerializationCallbackReceiver) by Unity after compilation/domain reloading. A static constructor when using [InitializeOnLoad] is not guaranteed to run prior to serialization events, and AssemblyReloadEvents.afterAssemblyReload runs after all serialization/deserialization has occurred for all assets. Surely I'm overlooking something trivial here right?
I'm simply trying to ensure my MemoryPack formatters are registered in a static context before Unity performs any serialization/deserialization.
Can't you use a static constructor ? https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
It should be executed the first time a class is referenced.
That's what I was doing with [InitializeOnLoad]. Or are you suggesting something else?
you could try a module initializer instead of a static constructor, with no InitializeOnLoad
https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html SubsystemRegistration/AfterAssembliesLoaded
some assets are indeed converted into Objects first though.
I have that setup too, but that's only invoked at runtime, not in the editor.
oh I missed that u also need that in the editor
can you give some info on what you're trying to do? Other than the high-level MemoryPack idea (in case of XY problem)
speaking of which, anyone knows why they removed this checkbox after Unity 2020? I really like manually pressing ctrl+R to refresh
Sure! I have custom serialization code in a bunch of assets that leverage MemoryPack to perform serialization and it's all triggered via ISerializationCallbackReceiver. However, in order for serialization to succeed, I need to have the MemoryPackFormatters registered with the static MemoryPackFormatterProvider. I run into an issue where when hot reloading/domain reloading occurs in the editor, the code that registers the formatters doesn't always run before the ISerializationCallbackReceivers, so serialization fails.
OH DAMN they just moved it to Asset Pipeline in 2021+ π€¦ββοΈ
sorry about the ranting, and bunch of random thanks coz I've been complaining about the lack of this in newer version for weeks
I think the cheapsest way would be to have something you know will be (de)serialized first initialize your MemoryPack thingy
alternatively and most properly, make all MemoryPack-dependent (de)serialization go through a single path of MemorySerialization.Deserialize<T>(..) and have that method do the honors of initializing the system if (!isInitialized)
and when I say most properly I mean it -- this sounds even better to me than hooking an initialization method beforehand
So this is what I ended up doing. It's not pretty and I'm forced to use reflection because the class that registers the formatters lives in a different assembly (I'm modifying a 3rd party asset):
you can load a whole assembly during a deserialization step no problem
oof though π
bashed my head against a wall for a while.
Originally tried to use some nasty hack by using reflection to get the instance of the AnimationLayerMixerPlayable. thought i could increment the input count then add a new input.
However, C++ said no, as trying to connect the new input threw an error because the mixer's canChangeInputs method returned false. which means doing something hacky like this yielded no fruit.
Closest thing i've been able to do is create two animator controller playables and mix them, where one is the base game's animator controller and the second one is the "Injected" animations.
mixing has not been kind to me, the animations just end up mangled
If the idea is to use the playable mixer, you should be able to make it works. It can be a bit tricky working with it, but it definitely worked. I did a prototype in the past of a custom made Animator.
However, it does not seem like mixing two animator would enable you to add "modding" to your game. Not sure what you are attempting to do there.
i got a skill system in my game, the skill system itself is open and can be modded to add new skills to a character.
However, adding new animations to said character so that it plays when the skill executes is not possible by default due to the animator controllers not being editable at runtime.
i thought i could have two animation controllers. the character could have one of the animation controllers playing whatever base states are playing (IE: idle, running, walking, etc). and then utilize a mask for the upper body where that mask has the skill animation (IE: a character swaying it's sword).
In that sense, i thought the "injected" controller could handle the skill state (IE: the sword swaying). while the base game's controller handles stuff like moving animations.
AnimatorController are not made to work this way. Either use Playable (There is asset such as Animancer that have done most of the work) or use AnimatorControllerOverride that are literaly made for that.
You can construct an animator controller override at runtime and feed it to an AnimatorController.
That being said, you initial strategy could potentially work, but it really isnt a good approach as far as I know.
We're using Animancer and we love it. Highly recommend. EDIT: Sorry somehow replied to the wrong message.
I recently made a system that plays and blends animations on top of an existing animator, no problem
With playables
This video inspired me to do it:
https://www.youtube.com/watch?app=desktop&v=fQzKJO-0dS8&t=208s&pp=ygUPVW5pdHkgcGxheWFibGVz
Maybe it helps
@lament salmon @dusty wigeon did you guys like the Playables thingy? I've been avoiding everything related to it like the plague lol
Implementing it was kinda smooth
buuuuuut...? π
Im currently using it to extend the animator
Idk, havent ran into any issues yet π€·ββοΈ
For example now I can do transitions with non linear blending
so all and all you think it adds value / is convenient to have
If you find the animator lacking features then yes
I don't think I ever found it lacking features π¬
I kind of just wanted to test the API but ended up actually using it in my project
I wouldn't use it as a non-animation-related state machine though
that's what I thought π thanks good to know it's viable either way π
Dynamically swapping clips with it is probably also way more performant than swapping the runtime animator controller
I kind of see a charm in not having to set up an exhaustive FSM in the animator and provide the anim pack via the playables though
I like defining my animations from code sometimes, but I dont find it very fun with animator controllers
So I made a sort of mini animancer
same! does this become any better with Playables, then?
I just made a custom animator class that has a few methods like addclip and addtransition etc.
So it is as good as you make it basically
I wanted to abstract it a bit so i dont have to actually worry about Playables API when generating the animator
my use-case for code animations is CustomHandledState with base/empty + coroutine-based animation
hello
i have something which i cant solve on my own
lets suppose there are 2 games i made with unity
And i want to call a method from game 2 in game 1
and both games are loaded separately
any idea on how to achieve such results
i really dont know how to
and also am out of ideas
Loaded separately as in different executables?
yes
loaded separately in different executables
or loading a separate window from the same executable
both solves my problem
I would probably grab a UDP or WebSocket transport depending on platform requirements. Going over the network stack is not the only way to communicate between processes, but it's flexible and potentially relevant in future game dev projects.
can i get some documents to really look into
Documentation of UnityTransport, SimpleWebSockets, LiteNetLib
do they allow like call a method in another game as well as data transfer
Yes
I don't have specific tutorials to provide for these. I would just use their documentation.
do they like
create local networks to communicate
if that is possible then it will be much easier
Yes.
or loading a separate window from the same executable
This could be done without creating an independent process, but it might actually end being more complex depending on how much communication is required between these windows
yea
specially when unity itself doesnt render the other window
ok i will try unitytransport
You can always go beyond Unity APIs and start calling system APIs to do whatever any other program could do.
the problem is the communication
well calling method from same executables would be easier
if i call a separate window from the same executable
is it possible to open a separate window with same executable which unity also renders
Explaining your use case might help
and is not rendered by windows api
i am trying to create a tool like thing
an animation tool at best
but good UI attracts usage so i am trying that at the moment
i dont know openGL or Vulkan or directX so i didnt use any graphics library and used a game engine
i am trying to open a settings window
something that is not limited just within the boundaries of game
but you can actually rescale it and stuff like that if possible
You can of course separate areas of the game window for different purposes. Figuring out some handles and render textures for UIs would be so much simpler than the separate window/process route.
cant understand?
i searched some old support chats
unity replied in it
yes you can create standalone windows like any other standalone application
but unity doesnt render it
you have full control of it
i wonder if we can somehow bypass that limitation as well
the best they also replied was use a local network to establish connection between 2 clients and separate executables
ok lets suppose even if we create a separate windows from same executable
the best UI library i could find was IMGUI
and IMGUI doesnt sound a good idea
What is the exact reason for creating a whole separate OS window instead of just having a window within a window
better control
separate OS window is better as you can resize it, rescale it or minimize it on will
with like imitating a window within a unity game which cannot even go outside the boundaries of the game border
cant minimize and cant rescale
You can hide and rescale elements in Unity. Going beyond the single window would be trickier, but it isn't necessarily very relevant unless you want to support multi monitor layouts.
well unity doesnt support multi moniter as well
Sticking to a single window would just be way simpler and allow you to focus on the animation functionality itself
Out of curiosity, cameras support rendering to up to 8 displays. Are these different displays made available when a game is running in exclusive mode?
ok I heed your advise
but i will still give it a shot in the future
you can switch displays on the same window
but not on different windows
so multi monitors or windows are not supported
That leads me to have more questions that I came with. Is there a published resource on this I can read?
i think it does support multi displays
but i am not sure without testing it myself
In that case, would I be correct in assuming that you can create multiple windows by passing around render contexts etc, but Unity doesn't use these contexts in a platform-agnostic way?
unity allows opening another window
but doesnt render it
you have full control of that window
either render it with IMGUI
or leave it empty
that's what they say
That makes sense. I don't intend to use this, but was just curious.
Wait, is IMGUI so complete that you could use it as a window manager or something?
Like out of the box?
IMGUI is written in C++
you can always use bindings
you can even render IMGUI on your unity game as well
depends if you wanna use it or not
No, it's just a very embeddable UI library. You need to render its output
Should probably specifically call it dear IMGUI, considering that Unity has its own IMGUI solution
yea
Thanls for all the info and links, you guys. I didn't realize that ImGui was somethiung else prior to having used it in Unity.

https://github.com/psydack/uimgui Yeah it's great
UImGui (Unity ImGui) is an UPM package for the immediate mode GUI library using ImGui.NET. This project is based on RG.ImGui project. - psydack/uimgui
Hey folks! Is there any easy way to have a single build that runs two windows as a single application? I was hoping to do something along the lines of a window for streaming/screensharing virtual table top stuff to players and a window that is strictly for the person running the game
Above discussion is highly relevant. Look into Unity multi display support or spawning new windows through platform's API
Thanks!
how do you use the job system with generics so that the burst compiler will actually be used
i restricted my generic to struct but it wont use burst any more unlike when i strongly defined the type
#1062393052863414313 would be the best place for that
thought that was for the ECS setup im still using the regular game object design
just pushing some work in to jobs for perf gains
fair enough
Tertle, Enzi, or Issue are likely to have the best answers is all. And they generally hang out there mostly
what kind of functionality are you trying to genericize? got an example?
a geometry/math class
I mean like an actual code example
the correct way to genericize jobs would be this: https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/compilation-generic-jobs.html
including the constraints and attributes
also there's this restriction:
the link has a typo? π
yeh because that should literally by their definition - burst compile
since its not inside a generic method
oh right, yeah they mean Jobs that **are** Burst compiled..
this is the kind of thing you can't do
yeah time to refactor to use overloads instead of generic functions to fix the issue
lmk how you architect it when you do if it's not too much trouble π
i am using NavMeshSurface for my game, since i have randomly generated dungeons and i need the navmesh to build at runtime, but after a while the navmesh is building too high and weirdly, and it is very hard to recreate the bug, i just use:
surface.RemoveData();
surface.BuildNavMesh();
to build the navmesh, does anyone happen to know what is causing this and how to fix it?
Firstly, how is your surface collecting the data?
Secondly, Why are you completely rebuilding the nav mesh rather than just updating it?
idk this is the first thing i saw when searching up "Navmesh at runtime"
how do i do that?
"UpdateNavMeshData();"?
now i get this error "Assets\SeedGenerator.cs(86,28): error CS1061: 'NavMeshSurface' does not contain a definition for 'UpdateNavMeshData' and no accessible extension method 'UpdateNavMeshData' accepting a first argument of type 'NavMeshSurface' could be found (are you missing a using directive or an assembly reference?)"
Share the code.
I don't think NavMeshSurface has a method like that.
It doesn't, NavMeshBuilder however, does. Why OP tried to apply a method from one class to another confounds me
It also seems like they're using the navigation package, so the surface update method might be more suitable:
https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshSurface.html#methods
That is new, availability will depend on the Unity version
They do show the navmesh surface component in their screenshot. And that didn't exist outside of the package.
yes, but the UpdateNavMesh method is only available in later version of the package even though it appears in the documentation for earlier versions
wait, they've update the packages, literally 2 weeks ago this
surface.UpdateNavMesh(surface.navMeshData);
was throwing a compile error
pretty sure dynamically updating the NavMesh has been a thing since 2021 or so
Yes, using the NavMeshBuilder
Also NavMeshBuilder has an Async method
tbh these is a lot of confusion from the old Nav Mesh Components (on git) and the new A.Navigation package when using older versions of Unity
I'm currently building the physics framework for a fangame I'm developing, and I'm having some trouble with the ground detection. Everything was working fine on flat ground so I started to add the slope physics, but it's pretty flawed so it results in something like this... when he should be smoothly running on the slope. Granted, there are small dents/bumps in the track, but Sonic should be able to just ignore them like he does in his games.
How it's working at the moment is there's a hidden sphere under sonic that is doing all of this phsyics work. The animated sonic model is just a child of the sphere that's following all of it's movement.
the ball isnβt aligning with the slope and is always pointing straight down
i tried increasing the ground distance variable and Sonic does stay on the slope longer, but he still slips off eventually
Here this script on the sphere:
https://pastecode.io/s/2kp144vb
it might be worth investigating if it wouldn't be easier to make a kinematic character controller for a sonic-like game since most of the physics in the game aren't based on realism, so you'd constantly be fighting the limitations of force-simulated physics especially since the game is quite fast-paced and force-physics don't work that well if there is too much distance between position updates relative to the detail of the objects it is colliding with.
alright i'll take a look
I agree with the person above, I don't think there's a chance you'll make a sonic-like controller with a Dynamic rigidbody.
it's technically possible but too much of a pain to make it worth it π
Yeah I used a dynamic one since that would at least solve have the battle in terms of gravity and stuff but I think kinematic might be the move
cuz then I can customise things a lot more
a sonic-like specifically (for ground alignment) should have a gravity of magnitude 100+, and a vector on the opposite of the ground normal
as for why your current movement doesn't work, it's because the velocity doesn't account the ground's normals at all:
ohhhhh ok
I guess I could still apply this for when he's boosting
since he'll be at max speed no matter what in that state
suuuure, but more proper would be something like this:
var arbV = Vector3.right;
if (Vector3.Dot(normal, arbV) == 1) { arbV = Vector3.up; }
var alignedDir = Vector3.Cross(normal, arbV);
var rot = transform.rotation = Quaternion.LookRotation(alignedDir, normal);
rb.velocity = rot * ((Vector3.forward * inputY) + (Vector3.right * inputX));
Physics.gravity = Quaternion.LookRotation(-normal) * (100 * Vector3.down);
I'm not 100% sure regarding the code for the perpendicular direction, but idea is you handle both the gravity and the rotation, then adjust the velocity's vector to stay on the ground.
jump needs special handling (needs to be disabled when on non-horizontal ground, like the in official sonic games)
oh alright so just so I know I'm getting this, arbV is perpendicular to normal and alignedDir is perpendicular both normal and arbV
hmm no the idea would be that alignedDir would be perpendicular to the ground's normal
arbV is an arbitrary vector
oh right sorry, you got the second part right, I'm just getting sleepy
that's fine hahaha
except arbV isn't necessarily perpendicular to normal -- kinda rough guess to get the direction of the surface
icl this is my first time coming across arbitrary vectors i might have to go and do some research lol
there's also the option of: Vector3.ProjectOnPlane(transform.forward, groundNormal); which you could try
this is a method i've actually heard of so I'll give a shot
rewriting everything to work kinemaically instead of dynamically is gonna be a pain in the arse i can just tell π
no, not really.. the main difference is that you'd need to call: rb.MovePosition(rb.position + adjustedVelocityWithGravity * Time.deltaTime); instead of what you're doing
By setting the velocity each frame like you do you're actually misusing the Dynamic Physics system π So you'll be doing yourself a favour by switching to Kinematic
oh alright that don't seem that bad then
I'll get started on the rework in a bit
How would I approach the idea of making drawing/painting tools in Unity? Like to be able to draw and erase colors, in 2D space. I had the idea of a camera, that only renders the "brush" layer, where there is just a regular circular sprite following the mouse. And then rendering that camera view to a texture. But the problem with this is transparency, as far as I know, the default render texture doesn't support transparency, so everything with no color just shows black?
Is there simpler method of achieving this or does anyone have some idea what might work?
Simpler? No, nothing simple about drawing/painting π
You need to use Texture manipulation, Compute shaders, and fragment shaders. It's essentially Graphics Programming territory.
Hello, I'm having some issues with async functions and stuff.
My game has the following asynchronous functions: JoinGame() and LeaveGame(). They already have a semaphore to prevent execution of them at the same time.
When OnDisable or OnDestroy get called, I need to call LeaveGame. But since LeaveGame is asynchronous, there's no way for me to wait for it to finish. Is there a good way to handle this?
First off a semaphore isn't necessary or useful really here since Unity async is generally single threaded
You could get away with just a bool
Actually the semaphore would cause the game to freeze potentially, if you're waiting for it on the main thread
Second, you can wait for it to finish in another asynchronous method. What is it you want to do when it finishes?
Well, I did manage to accidentally run an async function many times at the same time.
Not sure if the return type being a Task or Awaitable or whatever makes any difference.
They will not run "at the same time", but they will run asynchronously at the same time yes. A simple bool and if statements is how to stop that
Not a semaphore
Semaphore is for multi threading
Which this is not
Yeah, maybe, but I'm a bit unsure on how I'd achieve that with bools..
if (alreadyRunning) return;
alreadyRunning = true;
// Rest of the code
alreadyRunning= false;```
I just want to ensure that the function can finish before the game quits, inside the OnDisable or OnDestroy functions
Something like this
Oh there's no guarantee of that
What does the function do
It disconnects from the server, might save some stuff
You would just start the async function and await it
But it's not possible to await for anything in the OnDisable function, even if I mark the OnDisable with the async keyword.
I think the better approach is to handle this long before the scene is being unloaded
So maybe in OnDisable
But why even there
What's triggering all this
MonoBehaviour lifecycle methods don't seem right at all
Is this in response to the player quitting the match or something
The user has multiple ways to leave the game (disconnect, save stuff, maybe return to main menu):
- The user presses the leave button in the pause menu.
- The user closes the game window.
Both should call the LeaveGame function.
Cuz this won't work:
async void OnDisable()
{
await LeaveGame();
}
Since OnDisable itself is not awaited for by Unity.
why is LeaveGame async in the first place, that doesn't make a lot of sense
Because it calls other async methods, like things from SceneManager
And awaits for them
Then why not call LeaveGame as a Task on the main thread and wait on the task completion
Like this?:
void OnDisable()
{
LeaveGame().GetAwaiter().GetResult();
}
not how I would have done it but it may work
Any other way to do it?
Well, like a proper Task structure with Cancellation tokens and error handling
Can you give me an example?
Plenty of examples in the C# Docs but this
https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.wait?view=net-8.0#system-threading-tasks-task-wait(system-int32-system-threading-cancellationtoken)
if you need to run async code from a unity event it's not terrible to make it async void, it's just usually better to try to design your code so you don't have to do that... in this case if you're trying to catch the player while quitting, running async methods probably won't achieve anything since you're not going to have any subsequent frames happening after you quit
maybe look at https://docs.unity3d.com/ScriptReference/Application-wantsToQuit.html ? you can prevent the app quitting, do what you need to do in an async method, then quit when it finishes
The issue with async void is that the function with those keywords will be called, but it might not finish before the game is already exited, since the function is not awaited for by Unity internally.
Thanks! That could work. I'll look into it tomorrow since it's getting a bit late..
yeah exiting the game is definitely a special case haha
i want that lizardman kills pigman but pigman dont want to die can someone help me
Do not cross post! Is that even a serious question?
lizardman moves and wants to kill pigman but pigman dont die
what are you, like 2 years old?
if you would know
Why wait for LeaveGame to finish? Just invoke and forget imo lol
void OnDisable() => LeaveGame();
And do not count on client to clean up their mess. Remember that client can also crash or force exit through the task manager. The server then is responsible for detecting that and cleaning up.
Then start your async function in either of those cases. What does OnDisable have to do with either of these?
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.
oh so i do that then?
didn't get any compiler errors so that's good
thta didn't work, i also made it so it adds a NavMeshData and then updates that navmesh data instead of building the navmesh again and still nothing, the navmesh now doesnt even build https://pastebin.com/980qQPy6
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.
You probably also need to call AddData() or BuildNavMesh() somewhere as well. I'd look for some example code online.
i've made a gizmo2d https://pastebin.com/0nAfNdw4 but it dont works in a game mode, only in scene mode, anyone knows how to fix it? how i can show my custom gizmos in a exported game or game mode
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.
Are your taking this into account?
GL drawing commands execute immediately. That means if you call them in Update(), they will be executed before the camera is rendered (and the camera will most likely clear the screen, making the GL drawing not visible).
I use thé gismos2d in a OnRenderObject and works perfectly fine in thé scène view, not game view, why this situation changes in game?
What render pipeline are you using?
If i draw something thΓ© other draw us erased?
Universal render pipeline
The usual place to call GL drawing is most often in OnPostRender() from a script attached to a camera, or inside an image effect function (OnRenderImage).
Note: The High Definition Render Pipeline (HDRP) and the Universal Render Pipeline (URP) do not support OnPostRender. Instead, use RenderPipelineManager.endCameraRendering or RenderPipelineManager.endFrameRendering.
Either way, OnRenderObject doesn't seem to be correct. As for why it works in the scene view, who knowsπ€·ββοΈ. But there's quite a bit of differences between the scene and game view rendering, so it's not surprising.
This is due to how the rendering system works. The work for the GPU is usually gathered first, then sent to the GPU. But with GL, you send your draw call immediately, so if it happens before unity sends the rendering work, it's gonna be overriten.
Yes
I try starting a corutine drawing all
But dont sΓ©e anything
I'm gonna try this way
How is that related?
Wait
look in scene view
but i dont know why this happens in game view
and it moves with me
Why endcontextrendering??
let me try with endcamerarendering
Try with end frame
What unity version are you using?
unity 6
Well, that makes things more complicated. I'd suggest using the LTS instead. Though, I'm not sure if that's the cause.
I feel like it has something to do with the view matrix, but I don't know enough about GL rendering to say for sure.
i'm going to ask to chatgpt to clarify
i'm mean, i talk with chat gpt , i ask to explain me what am i doing wrong
and learn about that
Oof, bad idea
So is that correct now?
no xd, but its a progress
works fine but its only visible if you see close i dont know why XD
What did you change?
Are you using a pixel perfect camera?
yeah
i've make some tests and this gismos class consume a lot of memory
i'm gonna try another way to make what i want
your game view scale is not 1x, so it's probably just not aligning with the pixel grid
Yeah yeah
I recognize that but
I make some tests, player walking and rendering more chunks
Exists a lot of memory leaks
Not necessarily a bad idea. If one knows what theyβre doing and have obtained some confidence in programming, AI can be useful even if its output is faulty β imo
But when it comes to beginners, theyβll just spoon-eat whatever they learn, so in that case itβs actually dangerous if the specific AI spouts tons of bad practices/code
Gonna just have to disagree
Alright, just gonna say there are some fantastic AIs out there, gpt-4-0613 (API only) being one of the best, yet expensive
-- and gpt-4o-mini/gpt-4o (ChatGPT free/premium) being two of the worst available choices. esp mini is just terrible
Ah yes, LLM the source of knowledge.
hello, how do i benchmark a compute shader performance?
i tried using stopwatch around "ComputeBuffer.GetData()" but its unreliable (it gives random results)
Use a native profiling tool, like PIX
assuming you have a Compute Buffer there, https://docs.unity3d.com/ScriptReference/Rendering.AsyncGPUReadback.Request.html
GPU-level profiling should be the norm though if you're serious about optimizing performance
im just tryna look at the perf first
whats is this supposed to mean?
i calc the diff between the Dispatch and ths ?
no, dispatch is just a GPU.QueueComputeShaderExecution(this) (pseudocode), so it's pretty much instant
This queues the execution of the command. It doesn't mean the shader would be executed immediately.
yes. i meant i queue the difference between the moment after calling dispatch and the callback ?
to get how long it took
this can be called right after the Dispatch, to retrieve the data
Same about GetData. We don't know what unity does with these methods under the hood. That's why the most precise way is to use GPU profiling tools like PIX, render doc, Nvidia nsight, etc...
then the data will be received asynchronously, passed along with the callback
so basically:
cw.Start();
...Dispatch(..);
...Request(.., (f) => { cw.Stop(); Debug.Log(cw.Elapsed); });
f will also contain the data, so you can switch your architecture to that if you want async behaviour
This is not precise, as it includes the time of the data retrieval from the GPU and probably some other overhead.
totally, but it at least doesn't include the whole GFX.WaitForSync π
Well, they asked how they can benchmark the shader execution. Not how to implement data retrieval.
it's execution + data retrieval, which have to do unless you're up for some GPU-level profiling
Hi everyone, we upgraded from 2021 to 2022 LTS and Burst now fails our builds just at the end (after the 20 minutes ...) Atm I'm in rider with the breakpoint on, could someone help me find how I could investigate this. I've managed to retrieve the arg files hinted in the debugging variables (a tmp file), but it links a hundred assembly/plugins. I'd mainly would like to find which one was "in compilation" so I could try remove it.
It's a stackoverflow from the Burst AOT Compiler UnityEditor.Build.BuildFailedException: Burst compiler (1.8.11) failed running Process is terminated due to StackOverflowException. Thanks, and I hope it's not a bad place to ask.
isn't .GetData() Sync call that waits until the shader finishes or am i wrong ?
GetData
sounds a little too complex ngl π
I guess you could upgrade Burst first, then delete systems one by one (or 10 by 10 until you narrow it down)
actually might wanna upgrade all packages together, see if the issue is solved or error changes
are you using unsafe code? you could check for issues in that code or try compiling without unsafe.
yes the CPU calls GFX.WaitForSync(), waits for the whole duration, then requests the data, then waits another mini-cycle then boom, it continues
that's why Request is handy in many cases -- lets the CPU and GPU go independently since none of the processed data is holding down the main thread
- Thanks, all unity packages were auto-upgraded with LTS upgrade (Actually was up to 1.8.17, so tried to revert but was the same). I'll could go for a full revert of all unity packages (it actually upgraded addressables as well) and try.
- I could go into the dichotomy approach but at it is time consuming and might not necessarily be related to the actual package I'd like to pin point this further at first.
Why would unsafe code specifically trigger a stackoverflow on burst ? I'll have to check, I know the unsafe flag was raised some time ago by necessity.
heuristically stack overflows while burst compiling originate from unsafe code and pointer use
well, im not sure why its not returning correct time, when i wrap stopwatch around the getdata call, it returns about 5ms, even on an empty shader.
well, consider this the overhead π
each frame is 16ms (assuming 60fps), so you can be certain it's technically async/not tied to the update loop
There's a possibility that there are other commands queued, so unity will have to execute them as well
There wouldn't be any way to retrieve some burst compilation logs ? I have no idea what part of my code is unsafe atm π (I mean I don't personally wrote unsafe code, so it must be a plugin)
so ur saying, my original shader is under ms perf, just like an empty shader thats why im seeing the same 5ms ?
Good catch. This is meant to be ran standalone on empty scene or something for more correct results
yeah
wdym ? what does this have to do with it ?
i see i see, isnt 5ms overhead a lil bit crazy ?
no -- GPU/CPU sync is expensive :p
also, it's not REAL overhead when it comes to game data -- it pretty much passes before the next frame is due anyway
The GPU executes commands in the order they were queued. Unity could be queueing some other compute commands as part of it's rendering routine during that frame. And when you call execute, it has to execute everything that was queued up to that point.
Though, that's just an assumption as we don't have access to the source code, which is why I suggested using a profiling tool.
so that overhead only really affects async-ish operations
and yeah if I were Unity I wouldn't mind 2-3ms of queued commands per frame, even if some people considered them "overhead"
oh, lol, didnt know this could be bogging it too yea
wym not overhead ? i mean, 5ms every frame is not good
it's 5ms GPU time
and in reality the frame's budget is 16ms for CPU + 16ms for GPU
ah u mean if i dont use GetData() but rather the async callback ?
no if you use GetData you're f*d xD
I don't think an empty shader takes 5 Ms, even including the data retrieval. So you should profile it correctly.
but if you wait for it asynchronously, you can use it before the next frame
how so ?
no idea, to me compile problems in "unsafe code from 3rd party stuff" is only fixable by removing that usafe 3rd party component
doesn't waiting async means u can get it inbetween frames even ?
yeah tbf I've a project where I'm dispatching ~100 REALLY complex compute kernels per frame and still run on >100fps (on 4080/M1 Max)
It's likely gonna be at the end of the frame when unity waits for the GPU to finish it's work.
@wet sail have you locked on 60FPS? or what's your framerate when you click on "Stats" in game view?
no, its not locked
I'm under the impression this specific method could return data in less than a frame or more than a frame
well, lock it and see π Application.targetFrameRate = 60;
i mean, i dont think it matters, since im running the shader only once.
(for testing)
so 1 frame i suppose?
this is running the on scene start() once
the docs certainly confirm it's supposed to not necessarily be for single-frame operations, but no info on whether it gets returned inb4 frames, and I don't wanna test rn π
I'm usually trying to architect the GPU things just so GetData won't ever be needed. Textures and buffers can be passed as-is to other shaders and will have the correct data
yeah.
so what i got is:
- getdata halts cpu, halts frame, dont use.
- if empty shader and original shader both take 5ms using getdata() means ur shader is under ms
- async callback isn't guaranteed to be at end nor start of a frame.
- async callback will always return same time measured as getdata, its just async so u dont halt cpu.
is that correct.
and @hardy sentinel apparently unchecking unsafe code within the player settings and reverting build related packages such addressable didn't change the result. I'll try my luck on the forum as well.
Actually, by looking into winDbg, the whole thing starts with a breakpoint on a GetHashCode within System.ComponentModel.Composition, Version=4.0.0
Good luck! I think it's really complex for someone to jump in and help you with that, not having your project in front of them and all :/
Might even wanna contact Unity Support, lol. There might be a debugging tool that helps with debugging the build.
Yeah ofc I'll prbly have to bug report this ... It might even be a microsoft issue then .... arg.
friggin GetHashCode.. you know it's evil when you write something like this and see it's apparently working
Why?
you just know
I mean that's close to what basicaly every tool generates so please do elaborate
well, when you fall in love, you don't really know why, you just fall in love
it's the same with GetHashCode.. when you see it, you just know it's evil
FowlerβNollβVo (or FNV) is a non-cryptographic hash function created by Glenn Fowler, Landon Curt Noll, and Kiem-Phong Vo.
The basis of the FNV hash algorithm was taken from an idea sent as reviewer comments to the IEEE POSIX P1003.2 committee by Glenn Fowler and Phong Vo in 1991. In a subsequent ballot round, Landon Curt Noll improved on their ...
click the 2nd link only if you're not convinced from the first one, lol
Doesn't seem evil?
ok time to check out the 2nd link then π
Yeah it's fine?
which is __unlikely__ to cause collisions. Evil enough for me. But maybe you do have insights that we don't, so please let me know.
Hashcode has never guaranteed that 2 objects are the same
True, yet it's largelly bug inducing isn't it ? However I think Lyrcaxis pintpointed the fact that he feels it's quite a complex, unpredictive and burdening concept, so the shortword evil.
The only time I've had bugs with hashcodes is when people change them during the lifetime or when people pretend that classes are not reference types
Both of which are not really recommended behaviour
In my experience as any dev can re-implement it, including myself, this it had gone wrong more than one time in list item handling. It is indeed non trivial.
Lists don't use hashcodes?
sorry used list as a generic word, meant more preciselly dictionnaries, sets, anything which does check uniqueness.
Hashes aren't/shouldn't be used to check for uniqueness
Dictionaries use hashes to determine which bucket to put them in
pretty sure GetHashCode is the source of cryptocurrency.. someone just saw all that weirdness and went all like: "Hmm.. I have no idea what this is doing, but let's expand on that!"
You're right, they shouldn't. I remembered though that they could hit issues. What if the hash indicates a wrong bucket? Now this is refreshing some memory but maybe it was because of a bad equals implementation which often goes along. Anyway ! Upgraded the composition dll ... but the stackoverflow remains and this time on something much more obscure. I'm lost in debuging.
@slim bone I'm under the impression that the Library folder doesn't play a role in build, but I think you don't have much to lose to try closing Unity, deleting it, re-opening Unity, and trying to build -- while taking a break or something
Taking a break ... ah ... sure I can ?
it'll likely take >=5' to rebuild the Library folder judging by the 100+ libs you mentioned
try 1h
Library was already deleted for upgrade though. So not sure will do any good. Will try anyway.
clr!JITutil_MonContention rings a bell to anyone ? This is were winDbg breaks
Cool script
How would I go about adding artificial latency to this?
unsafe void ISocketManager.OnMessage(SocketConnection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel)
{
EnsurePayloadCapacity(size);
fixed (byte* payload = payloadCache)
{
UnsafeUtility.MemCpy(payload, (byte*)data, size);
}
InvokeOnTransportEvent(NetworkEvent.Data, connection.Id, new ArraySegment<byte>(payloadCache, 0, size), Time.realtimeSinceStartup);
}```
Throw it in a task and add a sleep
why not async + Task.Delay?
Both are valid. Anything that would create latency, even a coroutine yield WaitForXXX if you feel like it.
It doesn't let me use await in an unsafe context
you can mark specific blocks as unsafe, doesn't have to be the whole method
unsafe {
DoSmth();
}
await Task.Delay(..);
unsafe {
MoreStuff();
}
(right? having second thoughts now that I wrote that lol)
Oh I thought the whole method had to be unsafe, I'll try that thanks
Good to know
See... Whenever I try to wait, or do a cooroutine or delay it in any way, I get an error
[Netcode] Received a packet with an invalid Magic Value. Please report this to the Netcode for GameObjects team at https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues and include the following data: Offset: 0, Size: 192, Full receive array: 00 0c ...
use Span<byte> and pin it if you wanna make sure it's still there after the wait
it's obviously gonna hit performance a little (emphasis on a little), but given the point of the task it doesn't matter
Okay thanks and yeh, it's only for debugging anyway, not going to notice a small delay on a delay
delay on a delay I like the wording
if you put in any kind of await or coroutine you'd end up with different messages writing to the same buffer at the same time, or the source data you're copying from changing if it's not meant to be read on a subsequent frame (hard to guess without knowing everything that's going on there)
are you trying to simulate network latency? you might want to look at copying the messages into a temporary list somewhere with a delay before you call InvokeOnTransportEvent
Yeh I think you're completely right, definitely would explain the weird results I've been seeing in my debugging. I'll make a list and pass those to the transport on a delay
Thanks! And fingers crossed I do it rightπ
i've had to do something very similar in a transport implementation before π
It works! 
thanks for the help everyone, we got there 
I can finally start debugging and fixing some netcode issues with latency... I spent ages working on code, just to throw the game at a friend and learn half of it breaks if there is any latency
When WinDbg hooks on a WinDbg crash you know it's gonna be a hard day.
I could use OnApplicationQuit too, it's to leave the game and stuff when the game exits
Hello, i deleted a texture in my project and i started getting a "Objects are trying to be loaded during a domain backup. This is not allowed as it will lead to undefined behaviour!" with traces about ShaderGraph serialization.
This i assume means that a shadergraph with a reference to the texture is now missing and giving serialization errors.
Thing is, how do i find out which shadergraph has the missing reference? I have quite a large collection
trace is of not much use
Any go to cross platform File Explorer assets?
I need something that gives me a single API and either open the default OS file explorer on each platform or is skinnable / configurable and is statically linked.
ive used this 7 years ago, i bet the principles how it works haven't changed (pragmas and native DLLs) https://github.com/gkngkc/UnityStandaloneFileBrowser
I am greatly struggling with getting my bilateral blur kernel within my compute shader to work. I'm attempting to use a bilateral gaussian blur to blur the depth image and use that to render the surface of a fluid. I have successfully converted the depth image to eye/camera space, and I can even calculate the normals from that image, but despite my best efforts I cannot get the dang depth image to blur. The id of the thread corresponds to (x,y) coordinates of the depth texture, BlurredDepthTexture contains the xyz eyespace coordinates. I've tested pretty much every value and confirmed they're within expected ranges, it's just that the output pixel is the same as the input pixel.
[numthreads(8, 8, 1)]
void BlurDepth(uint3 id : SV_DispatchThreadID)
{
// Get width and height of texture for bounds check
uint textureWidth;
uint textureHeight;
BlurredDepthTexture.GetDimensions(textureWidth, textureHeight);
// Record central pixel's
float4 centralPixelPos = BlurredDepthTexture[id.xy];
float centralPixelDepth = centralPixelPos.z;
// If the central pixel's depth is within a very small number fromt the far place, ignore this pixel
if (abs(farPlane - centralPixelDepth) < epsilon)
{
BlurredDepthTexture[id.xy] = float4(0, 0, (-1 * farPlane), 1);
return;
}
// Kernel size varies based on depth, nearer to camera needs bigger kernel.
// sigma usually sub 10, but can potentially be very large, thus it is clamped at 15.
float sigma = GetSigma(float(textureHeight), worldSpaceFilterSize, centralPixelDepth, fov);
float convolutionDepth = min(15, 3 * sigma);
float convolutionSize = floor(convolutionDepth / 2); // Kernel radius
// Generate starting and ending index of the kernel, clamped to bounds
int xStart = max(0, (float) id.x - convolutionSize);
int xEnd = min(textureWidth, (float) id.x + convolutionSize);
int yStart = max(0, (float) id.y - convolutionSize);
int yEnd = min(textureHeight, (float) id.y + convolutionSize);
// Variable to store summed depth and normalization
float blurredDepth = 0.0;
float normalizationFactor = 0.0;
// Go through each pixel within kernel applying Gaussian blur
for (int i = xStart; i < xEnd; i++)
{
for (int j = yStart; j < yEnd; j++)
{
// Get current pixel depth
float curPixelDepth = BlurredDepthTexture[float2(i, j)].z;
// Get distance of current pixel from central pixel
float curPixelDist = sqrt(pow(float(id.x - i), 2) + pow(float(id.y - j), 2));
// Get difference in depth between current pixel and central pixel
float curPixelEdgeDiff = (curPixelDepth - centralPixelDepth);
// The two weights for calculation
float curWeight = Gaussian(curPixelDist/10); // Div by 10 for mitigating distance dropoff
float curWeight2 = Gaussian(curPixelEdgeDiff);
// Add calculated weight and normalization
blurredDepth += curPixelDepth * curWeight * curWeight2;
normalizationFactor += curWeight * curWeight2;
}
}
// Calculate the new depth
float depth = (blurredDepth / normalizationFactor);
// Calculate new X and Y from the new depth using screenspace coordinates
float newX = (((2 * (float) id.x) / (float) textureWidth) - 1) * _InverseProjectionMatrix._11 * depth * -1;
float newY = (((2 * (float) id.y) / (float) textureHeight) - 1) * _InverseProjectionMatrix._22 * depth * -1;
// Set the new pixel to calculated coordinates for normal recalculation
BlurredDepthTexture[id.xy] = float4(newX, newY, depth, 1);
}```
If anybody could please help me, I would kiss the ground you walk on. Also here is the relevant theorem from wikipedia:
reposting from general.
Oh my god this was one of the stupidest things. Get this - i tested PWA webgl tempalte then switched back to minimal one. That piece of shit left service worker registered. in cache. i spent whole day yesterday trying to figure out why setting headers both in ngnix and in unity to drop cache did fuck all for json caching which that piece of shit continued doing. Only after i cut it out of the cache, by focusing iframe with app and running this from console
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
for (let registration of registrations) {
registration.unregister().then((boolean) => {
if (boolean) console.log('Service worker unregistered successfully');
});
}
});
}``` did it FINALLY stopped caching json requests.
This appears to be a huge bug and an oversight since said service worker doesn't respect request/response header cache rules
I have a problem, I am trying to use the OnMouseOver method but it is never called and I don't understand the reason.
dont repost, if someone knows someone will help you
also, that is a #π»βcode-beginner question. Not a code advanced. perhaps even #π²βui-ux
But again isn't that triggered from some UI or something? Do your stuff there before quitting the application
can I change the weights in ML Agents or Barracuda?
Hi all, I am working on a game that has procedural chunk generation, I would like to generate the chunks on the GPU as textures and then sample these textures to then set the tiles on the map. I'm struggling to find much information on creating textures using the GPU and shaders. The most I have currently found is graphics.Blit which apparently doesn't work in URP (which is the rendering pipeline my project is currently in). The docs suggest using the Blitter API but other then the funciton defernitions their is next to nothing on this, the only over code is using the (as stated in the docs) incorrect approachwith calling by a command Buffer object. But this draws to the camera, cmd does not seem to have a createTexture only function, and also does not seem to work with shade graph shaders too.
Any help in this regards would be really appreciated.
Sorry realising I am over complicating this massively. Looking into compute shaders right now, just ignore this help request for now
If you want to do arbitrary calculations and write to a buffer or render texture, you should probably be using a compute shader.
Blit is more for actual rendering of the scene. Basically a full screen draw call.
Oh, you did mention compute shaders in the next messageπ
Thank you, yeah I think I was confusing the whole thing. Thank you for the assistance though, i'm greatful for the explination on what Blitting actually does!
I would try rewriting it so you're not writing + reading from the same texture, IDK how it works exactly in compute shaders but in normal PostPro that's generally a no-no
Just to let people now that the Burst crash does not in the end prevent the build to create an artifact. It will have issue with our jenkins though. Also, burst related code might not be working in the end and use some fallback (I'm thinking of magica cloth for instance)
Yeah, I originally had it reading/writing from a separate texture, but one of the things I thought might fix it was doing multiple passes so I adjusted things so it could be easily repeated. From my rudimentary testing, it seemed to not affect things, but I'll change it back just in case.
If you're talking about the LeaveGame function, it can be triggered both from a UI button, and when the game quits.
OnApplicationQuit is a Unity message like OnDisable btw.
How else would the game quit
Other than your UI
When the window is closed by the user for example
If the user is essentially "force quitting" your application, can they reasonably expect the game to be saved?
If they try to close the window you can instead show a confirmation UI using this: https://docs.unity3d.com/ScriptReference/Application-wantsToQuit.html
Then you can do the normal quit process.
e.g:
- user presses the window X button
- You show "Are you sure you want to quit? Yes/No"
- If they press Yes, you start your async function that saves the game and closes the application after the save
If they force quit, all bets are off.
That's possible, but the ingame "Quit Game" button should just do the same thing as the close button on the window, in my opinion.
Of course if you have a choice between "Save and Quit" and "Quit Without Saving", a dialog would probably be necessary.
well yeah you can do that too using wantsToQuit. Just start the asnyc process from that listener and return false
and presumably show some UI like "Saving your progress before we quit" in the meantime
It's still possible to have a "Your game quit unexpectedly" thing on startup though
If you actually have a hard crash there's not much that can be done
But that kind of crash is probably something worse than an exception that can be handled.
what kind of exception are you thinking of
throw new Exception("Something went wrong!");
ok but what does this have to do with the question at hand
If you have an exception that cannot be handled then you can't do much about it. "saving the game and then quitting" is a form of "handling it", so by definition that would not be an exception that cannot be handled
I have a Zenject question.
What's the correct way to design and bind an abstract factory?
I have a class that needs to either instantiate ClassA or ClassB that share a base class, so I have factories ClassA.Factory and ClassB.Factory. I have a base class AFactory that both factories derive from.
So I want the client code to depend on the abstract AFactory which returns an abstract class, and then I want to bind in the installer the correct concrete factory for the client.
Is anybody familiar enough with zenject to help me with this? The docs have a section on Abstract factories, but the example isn't very good. Sometimes my factories end up with null providers at runtime, which looks like a bug in Zenject.
can you share what you've got?
Thanks for the response! Unfortunately I'm on my phone and can't type out all the snippets. Maybe I should ask again when I can provide snippets.
By any chance, would you happen to know why Zenject would complain that it couldn't resolve IProvider when building a factory? I'm using the FromFactory binding. This seems like I should get an exception during the binding step if I'm doing something wrong or missing a configuration step.
Hey guys, I have a problem with C++ Compiler configuration.
I have .aar with a library for android arm64 and trying to create shared egl context on different thread.
I have a method in C# that issues command buffer and callback on render thread where i call my native function to C++
Inside the c++ method Im getting eglGetCurrentContext(); and passing it to new thread where Im trying to create eglCreateContext with the previous context as shared context.
The .aar library is compiled with Release and in unity setting the C++ Compiler confugiration to Debug is works and I can draw in the separate thread.
BUT with Release configuration in player settings it failes the context creation on EGL_BAD_MATCH.
I use 2022.3.10f1
Did anybody experienced similar problem ?
After further testing, this was responsible for some of the anomalous artifacting, so you were definitely right! Though unfortunately that hasn't solved my larger problem of not knowing where my gaussian blur is failing.
Hi all, I'm working on writing some compute shaders right now and I seem to be running into some issues with calling functions from different compute files.
Below is the code in which I have the issue, originally I was using the parameters for InRadius as (float2, float2, float) - for position of sample, and the position and radius of a circle. I then converted this to use a NodeData struct instead which contained this information.
float output = output = max(InRadius(offsetPosition, nodeData), 0);
The function is inside a .compute file named "Intersections.compute"
This file I am including using:
#include "Intersections.compute"
And it contains the defonition for the InRadius function like this:
float InRadius(float2 position, NodeData nodeData);
The problem is that since this function originally had the parameters (float2, float2, float) rather then (float2, NodeData) I keep getting an error about the code not being able to convert NodeData to float2 (this is only when using the shader, Riders intellicence seems to work fine with this). I have noticed that this fixes itself if I restart Unity but then any other changes I make are then continued to be ignored in the extra files.
Reimporting the files doesn't seem to fix this issue, is their a way to force a refresh on pressing play for these files without having to close and reopen the editor everytime
This is a question for Unity analytics, but more a programming related question.
If I want to Record a very simple event with just 1 string parameter (example: CharacterSelected = Timothy), is there a shorthand expression I could use instead of first creating a whole new CharacterSelected event class, instantiating it, and then passing that into the record event?
This is the way the documentation suggests -
public class MyEvent : Unity.Services.Analytics.Event
{
public MyEvent() : base("myEvent")
{
}
public string FabulousString { set { SetParameter("fabulousString", value); } }
public int SparklingInt { set { SetParameter("sparklingInt", value); } }
public float SpectacularFloat { set { SetParameter("spectacularFloat", value); } }
public bool PeculiarBool { set { SetParameter("peculiarBool", value); } }
}
MyEvent myEvent = new MyEvent
{
FabulousString = "hello there",
SparklingInt = 1337,
SpectacularFloat = 0.451f,
PeculiarBool = true
};
AnalyticsService.Instance.RecordEvent(myEvent);
But feels like an overkill if I am simply passing a single string or int variable.
This might imply that one of the shaders has a compile error. Thing is, unity wouldn't keep on showing you shader compile errors. When you clear the error, it's gone and I think unity wouldn't try to recompile the shader automatically until you fix the error. You should be able to see the error if you select the shader in the inspector though.
This isn't really a general coding question. This is not a general C# event but an analytics event. I bet they need the data to be in a class so that they can serialize and deserialize it easily when sending over the network.
It seems to be that things arn't importing properly. But even with the most basic form of this function where it is just returning a zero it still cannot import, is their anything I need to include in an external compute shader (external to the kernel compute shader not the project)?
#ifndef _Intersections
#define _Intersections
#include "NodeData.compute"
float InRadius(float2 position, NodeData nodeData)
{
//float2 displacement = nodeData.nodePosition - position;
//const float squaredDistance = (displacement.x * displacement.x + displacement.y * displacement.y);
return 0;
//return (squaredDistance <= nodeData.nodeRadius * nodeData.nodeRadius) ? 1.0 : 0.0;
}
#endif
I've never seen .compute files used in include statements. Only hlsl or cginc. I don't know that it doesn't work, it clearly does to an extent, but maybe that's causing your issues.
Oh! In that case what file type should I be using for this? hlsl?
Yes. And the include file shouldn't contain any compute kernel functions.
For sure, I assume kernel functions should only be written in the .compute files. I'll swap out the file types to hlsl and see if that fixes things
I am trying to figure out what sort of algorithm(s) are used by the Sprite Editor, but can't figure it out. I thought maybe a contour trace, and then some curve fitting. But that doesn't seem right since as you can see, when it is simplified it is a bit bigger.
I guess I don't exactly need/want Unity's, what I want is to be able to get a set of points forming an outline around a image, and be able to increase/decrease how many points/how accurate it is. And do so without cutting off any part of the image.
Seems like having them as hlsl files are working well now! Thanks
This is probably a well documented subject ? Anyway, you could brute force it by "shooting ray" from the 4 side of the picture, the precision could be the interval between your ray or the disance between your contact point and your actual point.
But as I said, this is probably a well documented subject and you should look into it. I am sure there is a lot of clever way of doing it.
I thought so too, but couldn't find anything on this sort of thing. Maybe I wasn't looking up the ring thing?
True, but looking into things a bit I found algorithm that could be use to reduce the amount of points. You could by example do a raycasting past and then applied one of those algorithm to reduce the amount of points.
I think I found it. Seem like it could be "Alpha Shape" you are looking for.
hey, I'm not an advanced coder, but my problem seems kind of advanced since it is Unity's code. Whenever I try to build my game, it gives me two errors (see pictures), and both of them direct me to the code (specifically the underlined line of code). the script is called LinkFileGenerator. I don't know what caused this since I didn't mess with the code, however I did move my project from my C drive to my external D drive. I have asked for help and they told me to use the VS debugger, but I'm a student and don't really have to time/motivation to learn how to use it. I was hoping that I could get help from someone that might've encountered this or at least has some idea on what needs to be done. I was happy that I finally happy that I got a game to the testing phase on google play, then I ran out of space on my C drive and fixed a few problems, and ran into this and I've been stuck for months. Thank you.
Did you try deleting the library folder?
no I have not
Try it
A warning though: that would cause unity to reimport all the assets, so it could take some time
Yes, after unity is done reimporting, see if you can reproduce the issue.