#archived-code-advanced

1 messages Β· Page 109 of 1

misty glade
#

Try the C# discord, this is .. pretty much completely off topic

fresh salmon
#

Non Unity C# questions are out of scope for this server

sterile plover
misty glade
#

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

fresh salmon
#

!cs

thorn flintBOT
sterile plover
#

Thanks

short junco
#

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.

frozen imp
#

!ban save 293392938623565834 Slurs

thorn flintBOT
#

dynoSuccess 1x5x7 was banned.

misty glade
#

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

compact ingot
misty glade
#

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 πŸ™‚

compact ingot
#

If you use the Simple version it’s trivial to use.

misty glade
#

(ie, best is lowest value)

compact ingot
#

You could extract the queue from A* pathfinding project lite

misty glade
#

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

compact ingot
#

It’s the most scalable and real world usable turnkey pathfinding solution

misty glade
#

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

misty glade
#

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

worldly pecan
#

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

umbral parrot
#

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?

ebon flint
flint sage
#

I'm sure it works, just not as you expect it to

untold moth
ebon flint
#

I did

#

the values are correct

#

everything is fine

ebon flint
#

I tried debugging a dev build

#

the values are still correct

#

im so desperate to fix this

ebon flint
#

playmode works

#

build doesnt

untold moth
ebon flint
#

but why is it only in build...

#

im so lost

untold moth
#

The most common cause of such issues is dependency on execution order.

#

And many things are executed in different order in the build.

ebon flint
#

and its random too, some pcs work fine

#

I have tried a shitty laptop, a high end pc, just mine doesnt work

untold moth
ebon flint
#

hmm, what should execute first? I had the level manager with priority didnt work, removed it didnt work

untold moth
#

Anything that is moving or could be moving the character. Just log or breakpoints everywhere that touches the position.

stuck plinth
umbral parrot
umbral parrot
stuck plinth
#

MonoScripts are also assets so you can do AssetDatabase.GetAssetPath on them

ebon flint
# untold moth You should find the cause first.

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 πŸ˜”

untold moth
#

Also, there are conditional and log breakpoints.

#

You can also disable breakpoints and enable them only after that method is called.

ebon flint
#

I disabled them and reenable them but I dont think thats very reliable

untold moth
#

Why not? Also console logs are an option too.

ebon flint
#

does it go to appdata player.log?

untold moth
#

If you have the debugger connected you can see them in the output tab

ebon flint
untold moth
#

Or you can connect the unity console to the build and see the output in there

ebon flint
#

how can I do that?

untold moth
#

Break in your method, and enable the breakpoints durring that time.

ebon flint
#

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

untold moth
#

Also, the player movement is not necessarily limited to just your code.

#

A CharacterController, for example could cause issues with movement.

ebon flint
#

oh and how can I debug that?

untold moth
#

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

ebon flint
#

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

untold moth
#

are the level manager and player DDOL?

ebon flint
#

no, but its in a scene that doesnt get swapped out

#

its all in a scene and the levels get loaded on top

untold moth
#

Okay. If it's a character controller, you can try disabling it before setting the position and reenabling after that.

ebon flint
#

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

untold moth
#

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

hardy sentinel
untold moth
hardy sentinel
#

no, lol

#

I guess with some smarter terms πŸ˜„

untold moth
#

in unity context..

upbeat path
hardy sentinel
#

I didn't even know it was related to something Unity-specific in this context

untold moth
#

And if not, then it's off topic.

hardy sentinel
untold moth
#

You're in advanced-code channel. Of course you'll be roasted over these kind of questions. πŸ˜‰

upbeat path
hardy sentinel
#

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

hoary prism
#

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 notlikethis

#

So any pointers pls, thank you!

upbeat path
hoary prism
hardy sentinel
#

For anything that doesn't use code, you can use Addressables. For code-related stuff, you can setup some DLL loading system.

upbeat path
hardy sentinel
#

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)

hoary prism
#

I see notlikethis

hardy sentinel
hoary prism
#

So all the logic needs to be done beforehand , and can only send out the assets at runtime? ;-;

hardy sentinel
#

yeah, and for security reasons this is the best course of action by Unity

upbeat path
hardy sentinel
# hardy sentinel yeah, and for security reasons this is the best course of action by Unity

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)

hoary prism
#

Makes sense

hardy sentinel
#

DLL-based patching is fine, imo (assuming carefully designed), but for modding it's extremely dangerous and you shouldn't ever do it

upbeat path
hoary prism
#

Thanks for the advice! I'll drop the idea for now and plan out better next time UnityChanThumbsUp

hardy sentinel
#

pretty sure you can load and execute code from DLLs in IL2CPP (?)

hoary prism
#

Don't really have a need to import new assets yet so yeah

upbeat path
hardy sentinel
hardy sentinel
upbeat path
hardy sentinel
upbeat path
hoary prism
upbeat path
#

patching an apk is really really hard

hardy sentinel
#

yeah if you notice even top-tier apps like Google Chrome force you to download the whole thing all over again

hoary prism
#

True

#

But man Google is an indie company, cut em some slack~

hardy sentinel
#

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

hoary prism
#

I have tonnes of questions regarding what you just said but someday later xD

hardy sentinel
#

alright xD

hoary prism
#

Thanks a lot tho!

#

Helped out much

scenic forge
#

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.

stuck plinth
stuck plinth
#

what do you mean?

upbeat path
#

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

stuck plinth
#

no, they're just assets, it's an alternative to actually updating the game code

stuck plinth
#

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

upbeat path
#

Nah, I cannot see that ever working

stuck plinth
#

why?

upbeat path
#

because a graph is not IL and reflection would have nothing to do with it

scenic forge
#

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.

stuck plinth
hoary prism
umbral parrot
# stuck plinth ah my bad, Rider was showing me internal methods haha! but MonoScript assets do ...

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?

hardy sentinel
#

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

umbral parrot
#

Yeah that's what I meant

#

I'll edit it to be more clear

stuck plinth
#

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

hardy sentinel
#

technically var asm = System.AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.Contains("AssemblyName")); -- then you can get all classes from it etc

upbeat path
#

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

umbral parrot
#

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

hardy sentinel
#

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()); }
umbral parrot
#

Uhh? That wouldn't help at all... I guess I still haven't made myself clear, I'll try again

hardy sentinel
#

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)

umbral parrot
#

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.

hardy sentinel
#

that's some nice ASCII

upbeat path
hardy sentinel
# umbral parrot Say I have the following folder structure: ``` Assets/ β”œβ”€β”€ SomeFolder/ β”‚ β”œβ”€β”€ S...

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)}");
    }
}
umbral parrot
cold breach
cold breach
#

Am I going to get an army of lawyers at my door for removing that single check so I can enable this feature?

cold breach
#

Taking the silence as a no army of angry lawyers.

peak plaza
#

Anyone know how I'd go about making quadtree LOD for meshes?

compact ingot
peak plaza
#

cubespheres

compact ingot
#

so you want to make planets?

peak plaza
#

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

compact ingot
#

but you know the principle how it works?

#

say on a regular terrain?

peak plaza
#

meh

#

sort of

worldly pecan
#

Like a distance based LoD system?

peak plaza
#

yes

compact ingot
# peak plaza and I have no idea how to go abouts this

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

worldly pecan
#

Subdividing boundaries is what's usually very annoying for LoDs, good luck

compact ingot
#

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.

hardy sentinel
#

for 3D games where I DO want custom physics, ON TOP of the existing physics, is Kinematic RB + Reinventing dynamic physics the one way?

dusty wigeon
hardy sentinel
#

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.

upbeat path
#

wait, you moved it, ok

hardy sentinel
upbeat path
#

Explain what you want to do, 99.9% of physics can be customized

hardy sentinel
dusty wigeon
#

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

hardy sentinel
#

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

dusty wigeon
#

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.

hardy sentinel
#

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

dusty wigeon
#

Usually dynamic is more for non important object

#

Even the CharacterController is not using rigidbody.

#

And the moment you have navmesh it breaks everything

hardy sentinel
dusty wigeon
#

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.

hardy sentinel
#

Ahh, I see. Seems that's another point for kinematic RB πŸ˜„

#

thanks

austere haven
#

Does Microsoft.Data.SqlClient work with unity or am I stuck using deprecated system.data.sqlclient

hardy sentinel
#

It's not built-in with Unity's references, but you probably can import the dll add it yourself.

azure meadow
#

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

austere haven
hardy sentinel
#

yeah πŸ˜„

austere haven
hardy sentinel
azure meadow
hardy sentinel
#

Dependency Injection is the standard -- and the cheaper version is System.Action (/delegate) composition

austere haven
#

use reflection or addressables or asset bundles

#

you can build the scriptable objects out to asset bundles then load them from Application.streamingData path

azure meadow
#

and during development, you skip your bootstrap scene a lot πŸ˜…

hardy sentinel
#

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

austere haven
#

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

azure meadow
#

the only static part is the "save system" which is a strategy manager πŸ€”

hardy sentinel
azure meadow
#

I never thought of having two DI points πŸ˜…

#

that would probably work

austere haven
#

i dont see why it wouldn't

azure meadow
#

and yes, I am using Resource.load which is eeeviiiiiil πŸ‘€
but I am doing it on UNITY_EDITOR so I don't really care πŸ˜…

austere haven
hardy sentinel
#

Resources.Load is fine afaik πŸ˜›

azure meadow
austere haven
#

nah not addressables

#

asset bundles

hardy sentinel
#

hmm... neither web builds

austere haven
#

addressables have been buggy for years

#

bundles been around since unity 3? and have always just worked

azure meadow
#

I couldn't get bundles to lazy load on web builds

austere haven
#

lazy load?

azure meadow
#

I managed to punch addressables into shape

azure meadow
austere haven
#

oh

azure meadow
#

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

#

πŸ˜…

austere haven
#

that wont stall the web build from loading

#

also

azure meadow
austere haven
#

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

azure meadow
#

mybad

#

I meant that the addressable loadscene thingy autoloads all dependencies

austere haven
#

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

azure meadow
#

what problems are you finding about addresables in prod? πŸ€”

#

(oh, also, I am not doing the hotpatching of the addressables, not yet anyways)

austere haven
#

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

hardy sentinel
#

a super-barebones motor would be just this

dusty wigeon
#

For projectile, I would use rb kinematic or no rb at all.

hardy sentinel
#

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.

dusty wigeon
#

With Overlaps or other manual collision detection

hardy sentinel
#

Physics.OverlapX OP

dusty wigeon
#

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.

hardy sentinel
#

I was under the impression this makes it emulate the inb4 frames?

austere haven
dusty wigeon
#

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.

hardy sentinel
#

tbh the first go I was so frustrated at built-in physics I went up with completely custom physics system lol (including collisions)

dusty wigeon
#

I suspect it might not work as intended because of that.

azure meadow
# austere haven and bandwidth isn't cheap

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 πŸ˜›

hardy sentinel
austere haven
#

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

azure meadow
#

I will look into spinning my own "per scene loading" system then πŸ€” πŸ‘€

austere haven
#

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

austere haven
hardy sentinel
#

for now I'm contemplating on how I'll go about the physics.

austere haven
#

well i mean you should be able to make a projectile bounce off a wall pretty easily with the default physics

austere haven
hardy sentinel
#

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 πŸ€”

austere haven
#

high speed projectiles can sometimes not detect collison

hardy sentinel
#

fiiiiiine I'll write custom transform-based physics again...

austere haven
#

just use raycasts?

hardy sentinel
#

yeah.. issue is I'll need to do it for any and all physics entities

austere haven
#

you're worried about performance?

hardy sentinel
#

what? no, not at all xD I'm worried about the scope

austere haven
#

can you elaborate?

hardy sentinel
#

well making a custom physics engine will be time-consuming no? And bugs will be constantly be detected along the way

austere haven
#

yes

#

so why not use unities raycasts?

#

im confused haha

hardy sentinel
#

well that's a custom physics engine πŸ˜›

austere haven
#

you say custom physics engine

#

and I think you're talking about writing something like bepu

austere haven
hardy sentinel
#

it's kinda like that except I'd be using UnityEngine.Collider and UnityEngine.Physics(/collision-detection methods) as bases

azure meadow
#

the real question is: are you 3000% sure you want a bullet object and not just instant hitscan damage?

hardy sentinel
#

don't be stuck on the projectiles xD

azure meadow
#

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 πŸ˜›

hardy sentinel
azure meadow
austere haven
#

well oct tree in your case since its 3d

sage radish
#

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.

austere haven
hardy sentinel
#

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

azure meadow
hardy sentinel
#

yeah πŸ™‚ must-have in a physics engine imo

austere haven
#

so what you're trying to do this?

azure meadow
azure meadow
#

look for the "collide-and-slide" algorithm

#

it's a whole paper and all πŸ˜›

#

or maybe unity has one and I reinvented the wheel

hardy sentinel
# austere haven

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

sage radish
#

Physics2D.Distance for 2D.

upbeat path
austere haven
upbeat path
#

put a rigidbody on anything that moves

austere haven
#

slow moving projectiles are fine

#

but bullets? they will not work correctly

upbeat path
austere haven
#

no you just use raycasts instead

upbeat path
#

no, you use BOTH

austere haven
#

why?

upbeat path
#

because a raycast can be used as predictive technology

austere haven
#

and what exactly is the point in using a rigidbody at all when you can just raycast it?

upbeat path
austere haven
#

you can do batched raycasts and jobified raycasts now so I really dont see how youll run into any perf issues with raycast

upbeat path
austere haven
#

so is raycasts

#

you're just calling a method in c#

upbeat path
austere haven
#

calling c# methods is a sin?

#

dang I better switch to unreal im not trying to burn in hell for my actions

untold moth
#

no, it's cosines

austere haven
#

ik im jokin xd

upbeat path
austere haven
#

the benchmarks prove otherwise

warm tusk
#

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?

austere haven
warm tusk
austere haven
#

i learned how to code like 15 years ago modding grand theft auto lol

austere haven
# warm tusk 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"

warm tusk
warm tusk
half swan
thorn flintBOT
#

:teacher: Unity Learn β†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

half swan
warm tusk
half swan
warm tusk
#

Can i ask how you started?

half swan
warm tusk
knotty hornet
#

!code

half swan
#

No worries! Best of luck with everything

thorn flintBOT
warm tusk
warm tusk
knotty hornet
#
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?

fresh salmon
# knotty hornet ```cs public void GetLeaderboard(string publicStringKey) { Leaderboa...

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.

upbeat path
knotty hornet
#

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

upbeat path
knotty hornet
#

Appreciate it and good to know Its not necessarily a me issue haha

sweet niche
lament salmon
lament salmon
white echo
#

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?

white pulsar
#

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

dusty wigeon
# white echo Hi friends! I'm currently trying to get an understanding of hierarchical state m...

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.

hardy sentinel
#

+animator-wise you could imagine the two states being SubStates of the Grounded Controls state

white pulsar
#

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

dusty wigeon
white pulsar
#

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.

dusty wigeon
# white pulsar ideally at runtime. i thought i could create a Playable that feeds outputs into...

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.

white pulsar
#

what would the loss of customization entail exactly? stuff like events?

dusty wigeon
#

Whatever you want you add as functionnality that does not exists in the Animator ?

white pulsar
#

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

dusty wigeon
#

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.

white pulsar
#

OverrideControllers just allows you to override an existing clip with another clip, that isnt what i'm looking for

dusty wigeon
#

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.

white pulsar
#

||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 😭

dusty wigeon
#

@white pulsar Is it about moding your own game ?

white pulsar
#

yup

dusty wigeon
#

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.

pliant dome
#

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.

pliant dome
#

That's what I was doing with [InitializeOnLoad]. Or are you suggesting something else?

long ivy
#

you could try a module initializer instead of a static constructor, with no InitializeOnLoad

hardy sentinel
#

some assets are indeed converted into Objects first though.

pliant dome
#

I have that setup too, but that's only invoked at runtime, not in the editor.

hardy sentinel
#

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

pliant dome
#

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.

hardy sentinel
#

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

hardy sentinel
#

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

pliant dome
#

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

hardy sentinel
#

you can load a whole assembly during a deserialization step no problem

dusty wigeon
hardy sentinel
#

oof though πŸ˜…

white pulsar
# dusty wigeon The issue is about moding or hacking other games. Obviously if we are talking ab...

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

dusty wigeon
#

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.

white pulsar
#

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.

dusty wigeon
#

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.

pliant dome
lament salmon
#

With playables

hardy sentinel
#

@lament salmon @dusty wigeon did you guys like the Playables thingy? I've been avoiding everything related to it like the plague lol

lament salmon
#

Implementing it was kinda smooth

hardy sentinel
#

buuuuuut...? πŸ˜›

lament salmon
#

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

hardy sentinel
#

so all and all you think it adds value / is convenient to have

lament salmon
#

If you find the animator lacking features then yes

hardy sentinel
#

I don't think I ever found it lacking features 😬

lament salmon
#

I kind of just wanted to test the API but ended up actually using it in my project

hardy sentinel
#

I wouldn't use it as a non-animation-related state machine though

hardy sentinel
lament salmon
#

Dynamically swapping clips with it is probably also way more performant than swapping the runtime animator controller

hardy sentinel
#

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

lament salmon
#

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

hardy sentinel
#

same! does this become any better with Playables, then?

lament salmon
#

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

hardy sentinel
#

my use-case for code animations is CustomHandledState with base/empty + coroutine-based animation

lament salmon
#

Is that like a script based Playable?

#

Oh I see, not a playable

hardy sentinel
#

πŸ‘

#

just manually controlling bones, position, or whatever else needed

magic parrot
#

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

hushed fable
magic parrot
#

loaded separately in different executables

or loading a separate window from the same executable

#

both solves my problem

hushed fable
#

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.

magic parrot
hushed fable
#

Documentation of UnityTransport, SimpleWebSockets, LiteNetLib

magic parrot
hushed fable
#

Yes

magic parrot
#

sorry to ask much

but can i get a link?

#

to get started

hushed fable
#

I don't have specific tutorials to provide for these. I would just use their documentation.

magic parrot
#

do they like
create local networks to communicate
if that is possible then it will be much easier

hushed fable
magic parrot
#

ok i will try unitytransport

hushed fable
#

You can always go beyond Unity APIs and start calling system APIs to do whatever any other program could do.

magic parrot
#

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

hushed fable
#

Explaining your use case might help

magic parrot
#

and is not rendered by windows api

magic parrot
#

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

hushed fable
magic parrot
#

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

hushed fable
#

What is the exact reason for creating a whole separate OS window instead of just having a window within a window

magic parrot
hushed fable
#

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.

magic parrot
hushed fable
#

Sticking to a single window would just be way simpler and allow you to focus on the animation functionality itself

violet valve
#

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?

magic parrot
magic parrot
violet valve
magic parrot
#

i think it does support multi displays

#

but i am not sure without testing it myself

violet valve
#

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?

magic parrot
#

that's what they say

violet valve
#

That makes sense. I don't intend to use this, but was just curious.

violet valve
#

Wait, is IMGUI so complete that you could use it as a window manager or something?

#

Like out of the box?

magic parrot
#

you can even render IMGUI on your unity game as well

#

depends if you wanna use it or not

hushed fable
magic parrot
#

i think
i can take my approach with a local network

#

that makes more sense to me

hushed fable
#

Should probably specifically call it dear IMGUI, considering that Unity has its own IMGUI solution

violet valve
#

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.

small latch
small torrent
#

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

hushed fable
small torrent
#

Thanks!

steel snow
#

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

half swan
steel snow
#

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

half swan
#

Jobs and burst are part of DOTS

#

It is not just ECS

steel snow
#

fair enough

half swan
#

Tertle, Enzi, or Issue are likely to have the best answers is all. And they generally hang out there mostly

hardy sentinel
steel snow
#

a geometry/math class

hardy sentinel
#

I mean like an actual code example

#

including the constraints and attributes

#

also there's this restriction:

steel snow
#

that link has a typo too

hardy sentinel
#

the link has a typo? πŸ˜›

steel snow
#

yeh because that should literally by their definition - burst compile

#

since its not inside a generic method

hardy sentinel
#

oh right, yeah they mean Jobs that **are** Burst compiled..

#

this is the kind of thing you can't do

steel snow
#

yeah time to refactor to use overloads instead of generic functions to fix the issue

hardy sentinel
tawny glen
#

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?

upbeat path
tawny glen
#

idk this is the first thing i saw when searching up "Navmesh at runtime"

#

how do i do that?

tawny glen
#

"UpdateNavMeshData();"?

tawny glen
#

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

tawny glen
untold moth
#

I don't think NavMeshSurface has a method like that.

upbeat path
untold moth
upbeat path
#

That is new, availability will depend on the Unity version

untold moth
#

They do show the navmesh surface component in their screenshot. And that didn't exist outside of the package.

upbeat path
#

wait, they've update the packages, literally 2 weeks ago this

        surface.UpdateNavMesh(surface.navMeshData);

was throwing a compile error

hardy sentinel
#

pretty sure dynamically updating the NavMesh has been a thing since 2021 or so

upbeat path
#

Yes, using the NavMeshBuilder

hardy sentinel
#

what's all this talk about the early version package then?

upbeat path
#

Also NavMeshBuilder has an Async method

hardy sentinel
#

oh I see now you already mentioned it.. I misread the convo, my bad

upbeat path
#

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

graceful pumice
#

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

compact ingot
# graceful pumice I'm currently building the physics framework for a fangame I'm developing, and I...

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.

graceful pumice
#

alright i'll take a look

hardy sentinel
#

it's technically possible but too much of a pain to make it worth it πŸ˜›

graceful pumice
#

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

hardy sentinel
#

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:

graceful pumice
#

ohhhhh ok

graceful pumice
#

since he'll be at max speed no matter what in that state

hardy sentinel
# graceful pumice I guess I could still apply this for when he's boosting

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)

graceful pumice
hardy sentinel
#

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

graceful pumice
#

that's fine hahaha

hardy sentinel
#

except arbV isn't necessarily perpendicular to normal -- kinda rough guess to get the direction of the surface

graceful pumice
#

icl this is my first time coming across arbitrary vectors i might have to go and do some research lol

hardy sentinel
#

there's also the option of: Vector3.ProjectOnPlane(transform.forward, groundNormal); which you could try

graceful pumice
#

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 😭

hardy sentinel
graceful pumice
#

oh alright that don't seem that bad then

#

I'll get started on the rework in a bit

next quiver
#

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?

hardy sentinel
#

Simpler? No, nothing simple about drawing/painting πŸ˜†
You need to use Texture manipulation, Compute shaders, and fragment shaders. It's essentially Graphics Programming territory.

hushed vortex
#

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?

sly grove
#

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?

hushed vortex
sly grove
#

Not a semaphore

#

Semaphore is for multi threading

#

Which this is not

hushed vortex
sly grove
#
if (alreadyRunning) return;
alreadyRunning = true;
// Rest of the code
alreadyRunning= false;```
hushed vortex
sly grove
#

Something like this

sly grove
#

What does the function do

hushed vortex
#

It disconnects from the server, might save some stuff

sly grove
#

You would just start the async function and await it

hushed vortex
#

But it's not possible to await for anything in the OnDisable function, even if I mark the OnDisable with the async keyword.

sly grove
#

I think the better approach is to handle this long before the scene is being unloaded

hushed vortex
#

So maybe in OnDisable

sly grove
#

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

hushed vortex
#

The user has multiple ways to leave the game (disconnect, save stuff, maybe return to main menu):

  1. The user presses the leave button in the pause menu.
  2. 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.

upbeat path
#

why is LeaveGame async in the first place, that doesn't make a lot of sense

hushed vortex
#

Because it calls other async methods, like things from SceneManager

#

And awaits for them

upbeat path
#

Then why not call LeaveGame as a Task on the main thread and wait on the task completion

hushed vortex
upbeat path
#

not how I would have done it but it may work

hushed vortex
#

Any other way to do it?

upbeat path
#

Well, like a proper Task structure with Cancellation tokens and error handling

hushed vortex
#

Can you give me an example?

stuck plinth
# hushed vortex Can you give me an example?

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

hushed vortex
hushed vortex
stuck plinth
regal olive
#

i want that lizardman kills pigman but pigman dont want to die can someone help me

upbeat path
regal olive
upbeat path
regal olive
hardy sentinel
#

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.

sly grove
tawny glen
tawny glen
#

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

untold moth
gleaming onyx
untold moth
gleaming onyx
gleaming onyx
#

If i draw something thΓ© other draw us erased?

gleaming onyx
untold moth
# gleaming onyx 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.

gleaming onyx
#

So i have to use Γ©vents?

#

Endcamerarendering?

untold moth
untold moth
gleaming onyx
#

But dont sΓ©e anything

#

I'm gonna try this way

untold moth
gleaming onyx
#

Wait

gleaming onyx
#

look in scene view

#

but i dont know why this happens in game view

#

and it moves with me

untold moth
#

Why endcontextrendering??

gleaming onyx
#

let me try with endcamerarendering

untold moth
#

Try with end frame

gleaming onyx
#

i want to this

untold moth
gleaming onyx
#

unity 6

untold moth
#

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.

gleaming onyx
#

i'm going to ask to chatgpt to clarify

untold moth
#

Bad idea

#

You probably need to set up the matrix somewhere before your draw call

gleaming onyx
#

i'm mean, i talk with chat gpt , i ask to explain me what am i doing wrong

#

and learn about that

half swan
#

Oof, bad idea

untold moth
gleaming onyx
#

works fine but its only visible if you see close i dont know why XD

untold moth
gleaming onyx
#

use a matrix based on the camera proyection

untold moth
gleaming onyx
#

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

austere jewel
gleaming onyx
#

Yeah yeah

#

I recognize that but

#

I make some tests, player walking and rendering more chunks

#

Exists a lot of memory leaks

hardy sentinel
# half swan Oof, bad idea

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

half swan
#

Gonna just have to disagree

hardy sentinel
#

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

scenic forge
#

Ah yes, LLM the source of knowledge.

wet sail
#

hello, how do i benchmark a compute shader performance?
i tried using stopwatch around "ComputeBuffer.GetData()" but its unreliable (it gives random results)

untold moth
hardy sentinel
#

GPU-level profiling should be the norm though if you're serious about optimizing performance

wet sail
#

im just tryna look at the perf first

wet sail
#

i calc the diff between the Dispatch and ths ?

hardy sentinel
#

no, dispatch is just a GPU.QueueComputeShaderExecution(this) (pseudocode), so it's pretty much instant

untold moth
#

This queues the execution of the command. It doesn't mean the shader would be executed immediately.

wet sail
#

to get how long it took

hardy sentinel
untold moth
#

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

hardy sentinel
#

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

untold moth
#

This is not precise, as it includes the time of the data retrieval from the GPU and probably some other overhead.

hardy sentinel
#

totally, but it at least doesn't include the whole GFX.WaitForSync πŸ˜„

untold moth
#

Well, they asked how they can benchmark the shader execution. Not how to implement data retrieval.

hardy sentinel
#

it's execution + data retrieval, which have to do unless you're up for some GPU-level profiling

slim bone
#

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.

wet sail
#

isn't .GetData() Sync call that waits until the shader finishes or am i wrong ?

#

GetData

hardy sentinel
#

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

compact ingot
hardy sentinel
#

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

slim bone
# hardy sentinel actually might wanna upgrade all packages together, see if the issue is solved o...
  • 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.
slim bone
compact ingot
wet sail
hardy sentinel
#

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

untold moth
#

There's a possibility that there are other commands queued, so unity will have to execute them as well

slim bone
wet sail
hardy sentinel
wet sail
wet sail
hardy sentinel
#

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

untold moth
# wet sail wdym ? what does this have to do with it ?

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.

hardy sentinel
#

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"

wet sail
#

wym not overhead ? i mean, 5ms every frame is not good

hardy sentinel
#

it's 5ms GPU time

#

and in reality the frame's budget is 16ms for CPU + 16ms for GPU

wet sail
#

ah u mean if i dont use GetData() but rather the async callback ?

hardy sentinel
#

no if you use GetData you're f*d xD

wet sail
#

yea exactly

#

i mean even 5ms on gpu is expensive

untold moth
#

I don't think an empty shader takes 5 Ms, even including the data retrieval. So you should profile it correctly.

hardy sentinel
#

but if you wait for it asynchronously, you can use it before the next frame

wet sail
#

how so ?

compact ingot
wet sail
#

doesn't waiting async means u can get it inbetween frames even ?

hardy sentinel
#

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)

untold moth
hardy sentinel
#

@wet sail have you locked on 60FPS? or what's your framerate when you click on "Stats" in game view?

wet sail
#

no, its not locked

hardy sentinel
hardy sentinel
wet sail
#

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

hardy sentinel
#

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

wet sail
#

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.

slim bone
hardy sentinel
slim bone
hardy sentinel
#

friggin GetHashCode.. you know it's evil when you write something like this and see it's apparently working

flint sage
#

Why?

hardy sentinel
#

you just know

flint sage
#

I mean that's close to what basicaly every tool generates so please do elaborate

hardy sentinel
#

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

hardy sentinel
#

click the 2nd link only if you're not convinced from the first one, lol

flint sage
#

Doesn't seem evil?

hardy sentinel
#

ok time to check out the 2nd link then πŸ˜‚

flint sage
#

Yeah it's fine?

slim bone
# flint sage 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.

flint sage
#

Hashcode has never guaranteed that 2 objects are the same

slim bone
#

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.

flint sage
#

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

slim bone
#

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.

flint sage
#

Lists don't use hashcodes?

slim bone
#

sorry used list as a generic word, meant more preciselly dictionnaries, sets, anything which does check uniqueness.

devout hare
#

Hashes aren't/shouldn't be used to check for uniqueness

#

Dictionaries use hashes to determine which bucket to put them in

hardy sentinel
#

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

slim bone
# devout hare Hashes aren't/shouldn't be used to check for uniqueness

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.

hardy sentinel
#

@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

slim bone
#

Taking a break ... ah ... sure I can ?

hardy sentinel
#

it'll likely take >=5' to rebuild the Library folder judging by the 100+ libs you mentioned

slim bone
#

try 1h

hardy sentinel
#

ssssssss

#

alright, new plan.. make a QA tester do it πŸ˜†

slim bone
#

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

flint sage
#

Cool script

molten pawn
#

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);
        }```
flint sage
#

Throw it in a task and add a sleep

hardy sentinel
#

why not async + Task.Delay?

slim bone
#

Both are valid. Anything that would create latency, even a coroutine yield WaitForXXX if you feel like it.

molten pawn
#

It doesn't let me use await in an unsafe context

hardy sentinel
#

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)

molten pawn
molten pawn
#

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

hardy sentinel
#

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

molten pawn
#

Okay thanks and yeh, it's only for debugging anyway, not going to notice a small delay on a delay

hardy sentinel
#

delay on a delay I like the wording

stuck plinth
#

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

molten pawn
#

Thanks! And fingers crossed I do it rightπŸ˜…

stuck plinth
#

i've had to do something very similar in a transport implementation before πŸ˜„

molten pawn
#

It works! 1foxyay

#

thanks for the help everyone, we got there Moon_JJ_UwU

#

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

slim bone
#

When WinDbg hooks on a WinDbg crash you know it's gonna be a hard day.

hushed vortex
scenic sapphire
#

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

wide elbow
#

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.

compact ingot
solid grove
#

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:
left sundial
#

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

gleaming onyx
#

I have a problem, I am trying to use the OnMouseOver method but it is never called and I don't understand the reason.

spare sleet
left burrow
sly grove
spiral swift
#

can I change the weights in ML Agents or Barracuda?

abstract hill
#

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

untold moth
#

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

abstract hill
#

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!

crisp temple
slim bone
solid grove
hushed vortex
sly grove
#

Other than your UI

hushed vortex
#

When the window is closed by the user for example

sly grove
#

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.

hushed vortex
sly grove
#

and presumably show some UI like "Saving your progress before we quit" in the meantime

hushed vortex
sly grove
#

If you actually have a hard crash there's not much that can be done

hushed vortex
sly grove
#

what kind of exception are you thinking of

hushed vortex
#

throw new Exception("Something went wrong!");

sly grove
#

ok but what does this have to do with the question at hand

hushed vortex
#

that's the type of exception I meant

#

by "an exception that can be handled"

sly grove
#

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

grizzled lake
#

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.

stuck plinth
grizzled lake
grizzled lake
# stuck plinth can you share what you've got?

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.

oblique imp
#

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 ?

solid grove
abstract hill
#

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

night hare
#

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.

untold moth
untold moth
abstract hill
#

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
sage radish
abstract hill
#

Oh! In that case what file type should I be using for this? hlsl?

sage radish
abstract hill
#

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

urban warren
#

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.

abstract hill
dusty wigeon
#

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.

urban warren
dusty wigeon
dusty wigeon
elder heath
#

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.

untold moth
elder heath
#

no I have not

untold moth
#

Try it

#

A warning though: that would cause unity to reimport all the assets, so it could take some time

elder heath
#

okay

#

then should I try building it?

untold moth
elder heath
#

does it reimport when I start up the project again?

#

I'm sorry for asking so many questions this is my first unity build