#archived-code-advanced
1 messages · Page 120 of 1
All I know is that this exists...
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Experimental.AI.NavMeshQuery.html
It seems to be marked obsolete on newer versions tho
Man, they abandon all the cool features
Looks like NavMeshQuery.CreateLocation is the equivalent of SamplePosition
And MapLocation
Yeah I figured it wouldn't be that useful if marked obsolete but could give it a try
Reality is I could just do a top down raycast on my terrain and check for colliders and it would probably be cheaper so I might just do that
I don't think a Physics.Raycast is thread safe either
There's RaycastCommand tho, if you need to do lost of casts
It's insanely cheap
Ty,
I wouldn't say it's "insanely cheap" -- the actual raycasts are about as fast as normal
You just have the option to punt it to another thread (but this can wind up blocking the game until it completes if the physics scene needs to be changed)
Its for spawning enemies essentially, I mean its a gamejam game my main concern is just that I'm spawning probably in the 1000nds. I can batch the actual spawns and offload the point generation to another thread.
As long as the rate isn't too low it should saturate
SamplePosition's cost goes up dramatically with a large radius, btw
One approximation is to just pick random triangles from the nav mesh
But this will be biased towards dense areas of the mesh, of course
It is cheaper though even if you force it to complete immediately, according to my tests
For example, 10k raycasts takes ~25ms
10k with Raycastcommand takes ~4ms
In a medium sized forest scene
It's not surprising that doing something in a batch is faster
possibly dumb question :
I'm trying to write a custom render pipeline that uses render graph
without render graph I could just directly draw to screen using the command buffer's render target
however with render graph afaik I'm not supposed to touch the command buffer, so how do I get the final screen render target? I can draw to RTs I created but I can't figure out how to actually get anything on screen
Interesting. I haven't observed that much of an improvement on large numbers of queries
I'll have to go profile it more carefully.
Let me know when/if you get some results
Depending on what its doing it makes sense it would be obscenely faster. Traversing the acceleration structure in memory to do a generic raycast vs batching a bunch of raycasts together and gathering the tris for a continuous chunk of memory to do all your ray tri intersect calculations
Dunno what its actually doing though
I must add to this, it does depend on the scene geometry and apparently the raycast in this scenario takes ~25ms only if it doesn't hit anything
When it does, it's around ~15ms
While raycastcommand's performance doesn't seem to change depending on hit or not
am I missing something or this page says you need to get the backbuffer from the camera but doesn't show how, and nowhere else in the core RP library doc is it shown how to do that https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.0/manual/render-graph-writing-a-render-pipeline.html
CPU side you just use resourceData.activeColorTexture, GPU side you have to use FRAMEBUFFER_INPUT_X_HALF(0) / LOAD_FRAMEBUFFER_X_INPUT. And yeah, the docs on it are not great.
resourceData.ActiveColorTexture works for the URP but not a custom RP
Ah - never done custom RP stuff myself. Not sure there.
I ended up finding anyway, don't have the code on hand but I had to import a rendertagrgetidentifier made from some enum as the backbuffer
Hey guys!
I am about to use Djikstra (or maybe A*) for adding pathfinding to a creature that can crawl on any surface, in a 3D world
I was about to represent the world as a 3D grid, using maybe octrees if I need precision
My question is simply: is there already a built-in, or quality free plugin for a flying, or surface-crawling pathfinding?
(I know about Navmesh but it really does not fit my case, building the whole mesh via rotating parts of it for each wall and ceiling would take forever)
I would think it’s likely that you have to DIY it. But components of the solution can be found. Recast navmesh generator should be adaptable to your use case, all the datastructures aren’t limited to the 2D case and the algorithm itself isn’t concerned about 2D either. Whether a grid, point cloud or navmesh is the ideal topology would depend on the scene geometry.
Just by curiosity, could you expand just a bit on what scene geometry archetypes would be better for one way or the other?
For grid vs point cloud especially
Currently, I feel like the best way for me would simply be a point cloud that I generate on each surface that is inside the navigation bounds
Sounds like you could use the vertices and random or average poinst between to generate "touchable" points for your point cloud.
Ye maybe
Or do raycasts as soon as your "foot" needs a new position because the leg has gone "straight" or something, depends on your character I guess
I already have something like this, but it does not help for pathfinding
I need a full path 🤔 I'm thinking about the way to have points on every surface that I need, but it seems quite hard hahaha
I see lots of ways it could go south
Why is Navmesh not an option tho? as you talk about regenerating meshes, but you already have meshes, dont you?
I have no navmesh at all no
For whoever ends up looking for this next : how to get the current camera backbuffer into RenderGraph
RenderTargetIdentifier cameraRT = camera.targetTexture != null ? new RenderTargetIdentifier(camera.targetTexture) : BuiltinRenderTextureType.CameraTarget;
resourceData.BackBufferColor = renderGraph.ImportBackbuffer(cameraRT);
(replace resourceData.BackBufferColor with whichever variable you want to store the backbuffer in for the duration of graph recording)
You can generate it based on the level you have, dont you? Long time ago I played with navmesh tho
Ah and it is not an option because the surface can be walls & ceilings
for example here if the agent is on ground and the target is the light bulb, the base navmesh system will require me to generate 3 different navmeshes and rotate them for each surface
and with navmeshlinks I'll be able to have a sort of "pathway" from one navmesh to the other
Make a graph structure where the points are connected to their neighbors (vertices that share a triangle or are close enough in world space?).
Use octree/spatial hash or similiar for the lookups with world positions.
Perform A* or other pathfinging algorithm on the graph.
How does that sound?
but this will be very tedious for bigger maps, and any changes will require me to update some parts as well
At least on walls there is also a tutorial with navmesh, but I get what you mean. And I guess, Osmals suggestion is the right way to go if youw anna go custom written
For octree & algo (will use Djikstra) I'm ok, but the graph structure is the pain point
I have trouble seeing how I could create this graph structure (each node must be on a surface, and the extremity nodes of the ceiling, for example, should be neighbors to extremity nodes of adjacent walls)
Also, just to be sure of understanding everything, octrees are only used for optimization, correct?
Or is there some shenanigan that I missed
You could first add nodes and connections for each mesh in world space and then in a second pass you can "stitch them together" by adding connections between meshes if their vertices are close enough.
This is where the octree comes in handy also
I understand 🙏🏼 thank you, this helps
But I do not see what is the purpose of the octree in all of this
for now I only see them as ways to quickly check if a point is in the bounds of something
When generating you'd use it in the second pass to find neighboring nodes to connect (or probably merge)
Between meshes
Could also do a validation pass with RaycastCommand to check if connections are valid
Hmm but won't I already know which nodes are on which meshes? The octree will serve as a way to limit the number of meshes to check for each one?
I mean how are you going to create connections that go from one mesh to another?
Hmm in my head I wouldn't directly link connections to their meshes, and in the second pass I would merge the connections that are close enough
But modular walls might create issues then
Would creating a temporary mesh from the whole scene be a good idea? This would allow me to maybe more easily create points on its surface
without the hastle of reconnecting them between meshes
(of course this would only work if the objects used in the graph are static, but in my project this is the case)
Exactly
that are close enough
Don't you see how the octree is useful in that part?
That feels like an extra step to me tbh
I think I do yes, as it will prioritize the near points
You can also just do the merging right when you try to add a vertex
Hmm I'm not sure of understanding
Just saying you could maybe do it in one pass. When adding a node, merge it into another if one already exists close enough.
But I don't really think it's a good idea. You need to somehow validate that the vertices are walkable anyway.
Because you could have overlapping/intersecting shapes, not every vertrex in the mesh is walkable
So it's probably best to collect all vertices together and then do the cleanup
maybe you could combine navmesh for walls and floor with a custom generated one for ceilings too. Just throwing my 5 cents in here
Ye maybe, will look into it if I struggle too much
ok I think I got the first step down
did two different methods, one for box colliders and one for meshcolliders
Hi
I'm setting up autobuild via gitlab for my ios project and encountered a build error in xcode via fastlane
“error: Driver threw unknown argument: '-enable-experimental-feature' without emitting errors. (in target 'VGSLFundamentals' from project 'Pods')”
Has anyone encountered any of these?
Link to fastfile - https://pastebin.com/dLZJQiny
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
#📱┃mobile might be more feasable for this
I'd like to have you guys' input on what I think about doing for validating neighbors (making sure they are walkable)
I think about checking the average position between the two points
And then, with an octree, check if this average is inside the bound of one of the game's collider
I feel like this would be easier, and potentially safer, than using raycasts
But of course I still have a problem: edges
even if the points are near, their average will still be inside the collider (even tho this is completely walkable...)
If you guys have an idea I'm all ears. Thanks for the previous help! Really helped me go quick
How are you currently creating the nodes? If you would include the mesh vertices, that corner would have its own node, right?
you may want to research "recast graphs", here is an outline: https://arongranberg.com/astar/documentation/4_2_1_d6eff531/recastgraph.html and implementation https://github.com/recastnavigation/recastnavigation
This would only work if all your colliders are boxes. How would you handle something like a one-sided plane mesh? I would def just use raycasts here (or perhaps spherecasts)
recast graphs aim at creating 2D meshes but the idea is basically what you're trying to do
Not really expecting an answer since this is super niche, but out of curiosity : Is it possible to extend shader graph to be compatible with a custom RP without forking the shader graph package?
I'll definitely check this tomorrow, thanks
True yes
I'll try but this is kinda more about making/extending the tooling for shaders than making shaders themselves
yes, but it is not a code-advanced question
fair
I'll try with a raycast then
any resources for learning how to fuck with transform matrices?
(raw manip i mean, no Turn() procs or such)
This is good for explaining translation, rotation and scaling with matricies and it also covers the model, view and projection sequence:
http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/
Free tutorials for modern Opengl (3.3 and later) in C/C++
yeah uhhh nvm im too dumb for that
actual question, what transform matrix do i shove onto an object to skew a square into a triangle (so pinch the bottom edge into nothing)
Completed the neighbors attribution!
If there is no mistake everything should be very easy now. Thanks again everyone for the help.
nvm
not-wolframalpha says its impossible
you can skew with a matrix but for this you probably need to use a shader or modify the verts
Those OpenGL tutorials probably as easy as it gets
get to it
https://learnopengl.com/Getting-started/Transformations
https://learnopengl.com/Getting-started/Coordinate-Systems
That's a fun one too
Learn OpenGL . com provides good and clear modern 3.3+ OpenGL tutorials with clear examples. A great resource to learn modern OpenGL aimed at beginners.
Learn OpenGL . com provides good and clear modern 3.3+ OpenGL tutorials with clear examples. A great resource to learn modern OpenGL aimed at beginners.
(pathfinding working perfectly! Thanks again!)
Good work bud! Nice
Hi all!
Really quick question: is there any ripper app which could extract the shaders from a shader assets file?
Utinyripper is one app, but that is a bit old
We do not discuss such things on this server
do you mean skew a 2d square into a 2d triangle, or a skew of a camera to make an object that appears to be a square to appear to be a triangle?
did you look at the granenberg a* package?
maye message him and his crew
Using djikstra was enough 👌
Turning it into A* for adding weights wouldn't be too hard anyway
dijkstra does weights no problem, A* just adds the heuristic to guide the search towards the target faster
hmm. it's the name of the package. it has little to do with a star
it's worth messaging that community
and they will tell you how to have critters climbing on walls
since this stuff is kind of arbitrary
For now I won't really need it, I have everything working 👌🏼
you are reinventing UniTask, and also, you should just write the method instead of trying to design it in the inspector.
is this a kerbal space program esque game you are trying to make, where the user can sequence a launch?
former
heya, I was hoping someone would be able to lend me a hand with this marching squares implementation- I've been looking online but it seems to be a pretty rare usecase. the tl;dr is that I'm trying to replicate something like this: https://fxtwitter.com/t3ssel8r/status/1364480023982342145 and I'm struggling specifically with the issue of having multiple platform/plateau heights.
as shown I can replicate the desired effect pretty well if all plateaus are assumed to have a static/similar height. I just calculate marching squares for the plateau's "dense" area, then raise it up and calculate marching squares for the void/undense area. then connect with walls and done
but trying to have different heights has been troubling. as you can see, neighbor squares interpolate between heights just by virtue of how marching squares works, defeating the aesthetic of what i'm looking for. ideally each platform is its own separate slice that I can connect together with wall polys after generation
you can see the code here ^, generation for the map itself is very simple- just a 2d array of vector2s, where X describes density ("1" or "0") and Y describes height in world space
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the buggy case only has one platform fwiw, but the correct one on the right is multiple in the same area
your goal is to create terrain or what exactly?
what is your big picture goal?
yep, this is something like what I’m trying to achieve
Playing around with a new tile-like custom terrain system #unity3d
Let's say:
I have a public variable in my code --> my code works
I change that public variable into private, and suddenly my code doesn't work and I get an error thrown about some object not being referenced
What's weird to me is that I'm only changing it to private so I don't have to look at it in the editor, I don't reference that public variable in any other script. Is there a reason why changing a variable from public to private would do this?
The way you describe this is 100% not advanced code related #💻┃code-beginner
okay and just to clarify. why?
is it for terrain or something else? i agree that you can make a very attractive effect with marching cubes
is terrain editing part of the gameplay?
yeah it’s for terrain, for creating maps the player will play on
the method in question is the method t3ssel8r confirmed he’s using in that tweet, i’m just figuring out the specifics
there's marching cubes for meshing, but there's also marching cubes for tiling
it's a little hard to see which one he's trying to use
there's a good marching cubes implementation for meshing here - https://assetstore.unity.com/packages/tools/particles-effects/mudbun-volumetric-vfx-modeling-177891?srsltid=AfmBOoon3Lc_sKg5yuyxITsoAnO2kouGl7YQxfgGoLQ_9qdezP9WoSid#releases
and to totally clarify, you want marching cubes as used in like Townscaper?
which is "more of a toy"
if I use .Blit to process my shader/textures when my texture is 5x1 it only runs frag call for the first 2 pixels and the rest are left zero filled, it also doesn't work if I trigger the pass with draw procedural with a 4 vertex quad topology, but it works if I do drawprocedural/now with 2 triangles .. I'd like to understand exactly why Blit fails this way and how to avoid it, if someone knows more
all my research is dead ends, something about rasterization or bounds, but things like modifying uv bounds doesn't seem to help so idk..
hi, not sure if this is a place to ask about AssetBundles, but I have a bit of a problem. I'm testing AssetBundles dependency system. It seems to work, but for some reason the manifest for each bundle refers to its dependencies by its absolute path. Is there a way to make this relative instead of absolute? Thank you in advance.
using addressables will make this a lot easier and solve this issue
its been so long since i used asset bundles manually but i dont remember what this manifest even does 🤔
Also looks like a temp manifest before exporting the actual bundle?
I'm not even sure if its important, the docs says it is (unless i misread)
Can you elaborate?
Hey guys, im developing some packages for Unity and im having trouble making them available via github
When writing the dependencies of my package like this, i get the error that it's not possible to find the package "com.nosirrahh.coretools"
"dependencies": {
"com.unity.addressables": "1.0.0",
"com.nosirrahh.coretools": "1.0.0"
}
I tried writing it like this, but the error still occurs
"dependencies": {
"com.unity.addressables": "1.0.0",
"com.nosirrahh.coretools": "git+https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/CoreTools/"
}
Repo: https://github.com/nosirrahh/NosirrahhTools
Do you know what might be happening?
wrong URL
You want this one: github.com/nosirrahh/NosirrahhTools.git
wait nvm sorry
misread what you had
This worked for me though:
"com.nosirrahh.coretools": "https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/CoreTools/",
the git+ thing is not right afaik
When i put like this, i receive this error:
com.nosirrahh.coretools (dependency): Version 'https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/CoreTools/' is invalid. Expected a 'SemVer' compatible value.
which version of UNity are you using?
2022.3.51f1 and 6000.0.34
And why are you modifying manifest directly instead of just using the package manager "Add from git url": option?
Im using the package manager, but trying to add the "AudioTools", that depends on CoreTools:
ref: https://github.com/nosirrahh/NosirrahhTools/tree/main/Assets/NosirrahhTools/AudioTools
Pasting "https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/CoreTools/" into that "Install package from git URL" option gives me:
And then my manifest looks like:
"com.jschiff.unity-extensions": "git@github.com:jschiff/unity-extensions.git",
"com.nosirrahh.coretools": "https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/CoreTools/",
"com.unity.addressables": "2.2.2",```
and it all seems fine
dumb question but - you have git installed right?
yes, the git in installed, if you try with this: https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/AudioTools/, it works?
no, that one gave an error
CoreTools works
I think maybe because: "com.nosirrahh.coretools": "1.0.0", isn't valid in the dependencies for AudioTools?
hello
Try updating this:
https://github.com/nosirrahh/NosirrahhTools/blob/main/Assets/NosirrahhTools/AudioTools/package.json
to use:
"com.nosirrahh.coretools": "https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/CoreTools/",
perhaps? @tired stirrup ?
can anyonepls help me convert a vrm 0.0 to 1.0 file
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
This is a Unity server
You're not in the right place
and could u help me find it?
No, I don't know anything about DesktopMate
if its actually a unity question ask but if its "how to use vr char thingy" then go ask them
In any case even if this is a unity question this is absolutely not the right channel
this is a channel for advanced programming questions
You might want #🔀┃art-asset-workflow or #💻┃unity-talk
I update the AudioTools package: https://github.com/nosirrahh/NosirrahhTools/blob/main/Assets/NosirrahhTools/AudioTools/package.json
But doesnt seens to work:
Unable to add package [https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/AudioTools/]:
Package com.nosirrahh.audiotools@https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/AudioTools/ has invalid dependencies or related test packages:
com.nosirrahh.addressablestools (dependency): Version 'https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/AddressablesTools/' is invalid. Expected a 'SemVer' compatible value.
com.nosirrahh.coretools (dependency): Version 'https://github.com/nosirrahh/NosirrahhTools.git?path=Assets/NosirrahhTools/CoreTools/' is invalid. Expected a 'SemVer' compatible value.
Maybe this is relevant for you
for a version/branch its git@github.com:foo/bar.git#branch_version_here
i think i will have to split up the projects in different repos
For git repo packages i just have the package raw in the repo instead of embedded in a project (meaning package.json is at root)
you can automate having the package as local/custom so you can edit it.
in local do you import the packages using the git url ou "from local file"?
I mean putting the package repo in packages/
I have a script that will clone it into there so i can edit it easily (you will see in unity you can modify the package contents when its like this). after pushing changes I can remove that folder and it will swap back to using the git url. (it has checks also to prevent me deleting it with un commited changes or unpushed commits)
I will try this, thanks for the support!
Hey all , I'm having trouble with something to give preliminary information:
I have a parallel job.
Index means that it starts from its own combination index.
I find all combinations before entering the job and the parallel job runs for each combination.
Combination tiles is a list of tiles with all combinations next to each other.
Combination offsets the offsets of the combinations.
Combination Lenght length of combinations
In this way, we can access the combination we want from inside in parallel processing with the index.
What I want to do is :
With this starting index I want to try all other combinations so that their order is important.
Actually I know this is a permutation but how can I do this in a parallel process.
I can't figure out how to do this without using any managed type and I can't use any extra recursive function.
private struct SolveCombinationJob : IJobParallelFor
{
[ReadOnly] public int TileCount;
[ReadOnly] public NativeList<NetworkTileBurstData> CombinationTiles;
[ReadOnly] public NativeList<int> CombinationOffsets;
[ReadOnly] public NativeList<int> CombinationLengths;
[ReadOnly] public NativeList<int> CombinationPoints;
[WriteOnly] public NativeParallelMultiHashMap<int, NetworkTileBurstData>.ParallelWriter CombinationResultWriter;
[WriteOnly] public NativeParallelMultiHashMap<int, int>.ParallelWriter CombinationOffsetResultWriter;
[WriteOnly] public NativeArray<int> PointResult;
private int _maxScore;
private int _minRemainingTile;
public void Execute(int index)
{
}
}
I tried to look at it sequentially, I wrote it.
But this time let's say the index is 2
We added 2 indexed combination
Then, if we start looking from 0, for example, starting with the 2nd index and continuing with the 3rd index, or
I'm missing the trial that starts with 2 and continues with the 5th indexed combination etc.
This leads to not getting exactly the result I want.
I think i understand how the data is stored and read using just the job index but i dont really get the bottom example and therefore the issue
For example lets say the job received index 3
Job collect combination data indexed 3 initialty
Then starts iterate over all offsets and look if the current collected combination contains a tile data from iterated combination look .
If exisist then it will continue , we are collecting data and skipping other combinations if we collected same tile data before from another combination.
This leads a problem of order if u your look order is 2 -> 3 for example the next look will 4 and that have to not contain any data belongs to 2 and 3 indexed combination
So i have to look all orders like 2 - 3 - 4 , 2 - 4 -3 to find best possiable outcome
I hope I made it clear :/
So you hope another job already did some work so you can skip it in this job?
No, only the initial combination is different in other jobs.
What I want to do is to set up a recursive logic in each job and try to try all combinations with the initial combination, but I cannot create it 😄
err why can you not create the initial data?
i think i need to see code to actually understand im a bit lost 😆 I dont know what this work the job will do even is
I absolutely lost too 😄
Maybe this will make it easier for you to understand what I'm trying to do. ones will be zero i created quickly with smart gpt xd
I want to try combinations in this order in each job
i found the solution i guess xd
there is no need to permutate in each job because its already there xd 😄 when look index 0 there is no order like 0 - 2- 3- 1 but in paralel in 2 indexed job will already look for that result
anyway thanks @echo coral 😄
Hey all, anyone got an estimate of what the per-call overhead for a Burst function would be?
There should be no overhead. At least in an Il2cpp build. It's just a normal function with simd and other instructions that make use of the processor optimization techniques.
Amazing, thank you. That's a lot better than I'd expected the answer to be, actually.
There's a chance that burst wouldn't do anything to your function though. You should check the docs for more details.
@shut surge Burst is an amazing tool, but use it with care. You can get some insane performance boosts, but if you mess it up, you will seg-fault your game. For my company's product, I built a full burst compiled physics and location system, and it runs stupidly fast. We can easily get 10k+ objects positioning themselves with semi complex logic with zero performance cost. The key thing is to keep in mind that burst jobs run off the main thread, so if you time the run and complete correctly, all the math is done while the main thread is doing other things
If there's anyone here with experience with Code-Gen in unity, and you have some free time, I would love to sit and chat about building a system to take care of a lot of the boiler plate for writing burst compiled jobs. I have a burst utility package I'm working on, but its a bit akward to use because you need to write the same set of operation repeatedly. Its a prime candiate for code gen!
How complicated of code gen are you looking for. you can take a look at roslynn compiler code gen steps.
I am unsure how it will play with unity's internal code gen for jobs and such though
I've been meaning to look into it tbh, https://docs.unity3d.com/6000.0/Documentation/Manual/create-source-generator.html
@humble raven !collab and don't crosspost.
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Someone please walk me off the ledge of "prefabs are superior in almost every way to ScriptableObjects"
Anybody using Rider could tell me why my Unity project has to be analyzed EVERY time I open it? This didn't happen to me before 🤔
cause rider can't observe changes while it is closed and to provide valid analysis/hints/refactoring it needs to validate its caches, this has always been the case
So this happened because Im doing changes meanwhile being closed and the chached indexes become obsolete?
more or less, unity also probably does automatic changes that invalidate some caches
I thought Rider or Unity project kept a cache.... ow... damn
Any way to increase the indexing speed?
buy a bigger PC
hahaha ok thanks 🙂
A bigger PC?
it should help a lot if you avoid dynamic asset changes
A faster disk would suffice, I'd guess.
I'll try to be carefull on that, thanks Anikki
most of it is CPU bound
Very unlikely
look at the system monitor
its a MAC from 2021 M1 with SSD , i think it might be indexing too many files
That could also be it
I mean... i saw the progress and there were 17K files in inspection... wth I barely have 20 or 30 scripts
Assets perhaps?
I guess is taking packages and plugins and everything
next run ill try to cancel the auto-analysis and run it myself just in the folders i want
Idk about you but the analysis I get is usually pretty short
OGL uses right-handed system while Unity uses left-handed.. they're not really the same
true, but that's just part of the learning experience since you may not always be working with Unity
Unreal's a little special
UE is left-handed, it's just follow a different convention for z axis. z is up in ue
Left-Handed, Y-up is by far superior
I've never understood why blender uses Z-up
it makes a lot of sense with all the other tools in the category
I think for games its often so in 2d you can use x+y but i guess cinema 4d and unreal swapped
what kind of maniac points their index finger up for Y? the handedness is always a pistol hand 🙂
z is forward index finger, y is up thumb, middle finger is x
it makes sense for topdowns and 1 sided 2d views
3d artists love to lock their viewport based on certain XY axes when modeling
yeah like in CAD youre almost always looking from the top down, laser cutting or CNC work has no real need to know theres a third axis going up into the air
Source probably chose it as its primarily going to be used for level design at a top down view
but Blender being a general purpose 3D tool, if youd model a character youre far more likely to be locking the view to face the front more often than you would the top
I guess its something they chose long ago and its too late to really change it without causing a lot of chaos
during gameplay unity is loading at some point some files. does anybody know how i can figure out what unity is loading. it cretes some heavy FPS spikes. thank you very much
Profile standalone instead of editor
thank you very much. I will do but still this loading itself is the thing: I would assume that the loading will also happen during standalone.
It’s hard to tell if this is from the editor or not
Such profiling would also track side effects of editor stuff, which might not even be interactive
Does that make sense
Could be the camera loading something for a shader like the hdri which it is dynamically building the cube map for
Try in standalone first
Thank!! will try out
Yes unfortunately this stuff is hard to track down
What are you trying to write?
What problem are you trying to solve?
There’s nothing special about Unity Jobs for solving problems. It’s just cooperative multitasking
before build standalone i just had another sample this time giving more insights: It loads in this case a material. I am just a little bit surprised by this. I pool all my enemies in the very beginning. Maybe unity loads lazily the assets. anyway thank you very much
That night just be in editor…
I wrote this attempting to reference a function on a mono behaviour that is dragged in via the inspector
https://paste.mod.gg/gdqmccblhnhh/0
The issue is that I'm referencing the mono behaviour that exists on the prefab, not the instance (I believe). Any ideas on how to get around this? For example, if I were to serialize a reference to InspectorFunction, it ends up printing false when called.
public bool spawned = false;
public void Start()
{
spawned = true;
}
public void InspectorFunction()
{
Log.Info(spawned) // prints false
}
Is there a reason to not just use a UnityEvent?
It would be a similar problem though, you'll have to subscribe to the instance's method (i.e. create the delegate) after it's spawned
Yeah I want to be able to return values
You can use reflection to get all methods and then use teh SendMessage to that specific runtime object holding that class
Ah, just looked into your code. yeh, you are reflecting already. So where do you access that instance?
For my solution, I always access classes, that have an "Instance" static representation I will access onEnable with reflection. Then I can just pass in the method with or without properties (UnityEngine.Object) in my case for now.
Nah I'm on the events team for this
I had to do it that way, so I can call methods from my UI which is dynamically loaded and instantiated. So I never have access to the scene object rightaway, if that makes sense
any reason why? Is there another way to access those methods then with unityevent?
With good design and by utilizing interfaces, inheritance and events you shouldn't need to do this weird reflection to call some function
So as an example. I have a setup UI, it gets created on runtime because it needs to. That setup UI can call a function on the lets say a gamemanager called SaveMe() and on an AudioManager called VolumeUp(). How would you access those methods dynamically for that specific runtime Instance?
whatever spawns the UI can provide dependencies to it on creation
And how do I get the method in i want to call?
you write it
you subscribe to events in code and set up everything in code because you already know what you want it to do.
so write a single script for every button I want a specific behaviour?
how much reflection does your UI need???
actually, a lot 😄 Because its a package being used in different projects and the people can use that button whereever they need.
My custom editor will just take a cs script and then later onenable look for its static instance. If its there, you can call that method on it.
over use of static references for core dependencies is bad. Ive made hundreds of UI bits over many games and not once did i need reflection to make it work
I am still asking, how would you exactly do it. If you got the time, that would be very helpful to get that insight. Imagine, someone can use your button anywhere and wants to trigger a system manager specific method and on another button another specific method from that manager. Lets say, save and load for the simplest example.
I will have a script for a "popup" or "dialog" and its all manually set in there. each button or checkbox event is subscribed to call or do its task.
The ui dialog/popup is initialized manually and provided the dependencies it needs to do these tasks (given a service instance, configuration, player data, localisation system...)
If you wanted to make it fully doable in the inspector then you may want to have small components that can execute these small tasks but they are all provided a way to get core services or data in a common way (UI opens -> provides dependencies to all of these). Then you could add the component and setup the button event and know it will "increase volume" or whatever. There are more ways to go about it without reflection (it should be a last resort and not the first solution for production code).
But that "subscribed to call or do its task", that would be more or less hardcoded, right?
it is but its reliable and If say my settings popup needs to change then i just change the code
not everything has to be magical UI drag and drop
Thats correct 😄 Just to be clear, I only use this reflection for the editor and onenable of the button to get the dependency once. The rest of the project has never seen reflection, but in that case, it was unavoidable, because you can import the package, use its core features but also just easily add your own static instances as methods and so on. But I get your point. If it would be possible to pass in the correct dependencies because of a more or less fixed structural behaviour, I would not go into the reflection rabbit hole myself 😄
Hey, do anyone know any resources for Roughness only (no metalic) PBR that is cheap on mobile (quest). I use deferred so cant afford so many calculations.
only diffuse, specular and energy conservation needed (no fresnel unless cheap)
wrong channel but urp simple lit is just diffuse + specular + normal which should be cheaper
guys can someone make a short tutorial about how to make a skilltree in unity
Done, if you Google "unity skill tree" you can find it
Access the instance? I assumed that if I create the delegate using _script that'd it call the method on the actual instance
If you get the fields from your reflection, you just get like the "blueprint" of the class. You are not getting any values from any instance active until you use GetValue() at some point, because GetValue is using a reference to an actual instance to get that runtime object
Not sure if this answers your question, using _script I want to be able to call the method on the specific instance mono behaviour
So I create the delegate using the type, mono behaviour, etc. with the goal down the line to be able to invoke that method and actually call the method on said mono behaviour instance
what is _script, the actual instance?
if you want to magically call a method on any newly made instances of a type then you need to do a lot more to make that work
It is quite simple if its a singleton of course. But if you want to have duplicate versions of one class and access a specific one, you gotta lead to the correct "version"
Is it a singleton?
So, here is an image of a prefab component tree, in this case the prefab of an item in my game
the flash light monobehaviour being dragged onto the _script
the idea being that once this prefab is spawned, the interaction can call the method on Flashlight (well it does, but not the actual instance)
So you want to call "Toggle" on _script ?
At runtime get the method info from the script type, and Invoke it by giving _script as the instance
as ofc when this is instantiated you have a new instance of Interactable + Flashlight
getting the method info from script type I understand, can you throw me some pseudo code in terms of invoking it via _script as the instance
The Info objects you get when using reflection describe the method/field/property. They still need an instance to actually invoke it on (except for static things)
you can get a property "Instance" and return as an object
hmm.. I'm wondering if I'm missing something or misunderstanding,
// invoke code
var methodInfo = _script.GetType().GetMethod( _method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
if ( methodInfo == null )
return default;
methodInfo.Invoke( _script, new[] { first, second } );
// flashlight code
public bool spawned = false;
public void Start()
{
spawned = true;
}
private void Toggle( Player player, Interactable __ )
{
Log.Info( spawned );
}
It's calling the method, but I would expect spawned to be set to true, right?
and I'm fetching the method info and invoking the method all at run time
Did you call it before start happened? Use a debugger to check when both are called
Use Awake if it should be earlier
nah, spawned is 100% getting set to true, checking via the inspector
and the call to Toggle in this case happens after that
Are you doing this on the new instance or accidentally on the prefab asset?
probably on the prefab asset
Because this won't suddenly break start() soo
#archived-code-advanced message
so I'm left clicking my prefab in the unity inspector, seeing the component list pop up, dragging the flashlight mono behaviour into my script field
Drag flashlight in the UI down into it (drag the actual title bar in the inspector)
arent you invoking on a new instance with that code?
That's what they want right?
yeah, I want it to invoke on said new instance
hmm, and yeah i'm dragging down the mono behaviour into the field exactly as you described... hmm...
wonder what i'm missing here
Do a sanity check, check if the game object the interaction script and flashlight script are on are the same.
Also is that field of type MonoBehaviour?
I originally had it as mono behaviour but I attempted with UnityEngine.Object as well
Do component or behaviour or mono
wait, _script is a monobehaviour file, right?
yeah
so you call the method of a script dragged from a project folder?
😐 plz dont tell me it was referencing the ASSET and not the mono instance on the prefab
no, I'm dragging the mono behaviour on the same prefab down below to the inspector field
in this image right here, my mouse is dragging the Flashlight title bar, into the Script field
then i see no reason for this not to work. add a check to compare .gameObject and see what the result is and use a debugger in your ide
Ahhh okay, thats what I was not aware of if you dragged the script or the actualcomponent
So why dont you just sendmessage the method ?
yeah I saw someone suggest that earlier, haven't looked into it yet
just tostring the method name and pass in your stuff if its the same gameobject anyways
I have never used send message but it will just do similar stuff but be slower
in my case I also need to handle returning values
ah, okay
ye will check this in a second, thanks all the help
So you want your method to be called and what happen on return?
I have another radical idea... no reflection and use an interface 🤯
Tbh I would just build my own custom class for that using unityevents with a 2nd unityevent as callback
its the same gameobject. He could just drag drop everything with events 😄
as rob said, no need for reflection at all
okay yeah, different game object ids
interface might actually be fine, I forgot why I didn't end up doing that
if my Flashlight class implements x interface, does it allow you to nicely drag it into the inspector?
if you use an interface, validate it in OnValidate(), make the field of type Component and validate it implements said interface
e.g
[SerializeField]
Component comp;
void OnValidate()
{
if(comp != null && comp is not IInterface) comp = null
}
For my interaction systems, I usually have the specific implementation scripts (such as your Flashlight.cs) listen to events from the generic Interactable script.
It does mean that the Flashlight script will be coupled with Interactable, which may be something you don't want.
I have this piece of code to use a culling group for a bunch of npcs ``` BoundingSphere[] spheres = new BoundingSphere[_skinnedMeshRenderes.Count];
for (int i = 0; i < _skinnedMeshRenderes.Count; i++)
{
spheres[i] = new BoundingSphere(_skinnedMeshRenderes[i].gameObject.transform.parent.transform.position + Vector3.up, _skinnedMeshRenderes[i].bounds.extents.x*2);
}
using (Draw.WithColor(Color.green))
{
for (int i = 0; i < spheres.Length; i++)
{
Draw.WireSphere(spheres[i].position, spheres[i].radius);
}
}
_npcCullingGroup.SetBoundingSpheres(spheres);
_npcCullingGroup.SetBoundingSphereCount(spheres.Length);```
This works for npc's that get spawned in from a spawner, but the same npc that just exists in the level do not get the event fired for them
{
if (evt.hasBecomeVisible)
{
Debug.Log($"Enabling renderer for:{ _skinnedMeshRenderes[evt.index].gameObject.name}");
_skinnedMeshRenderes[evt.index].enabled = true;
}
if (evt.hasBecomeInvisible)
{
Debug.Log($"Disabling renderer for:{ _skinnedMeshRenderes[evt.index].gameObject.name}");
_skinnedMeshRenderes[evt.index].enabled = false;
}
}```
I can confirm that all npc's are in the list and their bounding spheres are also correct and move with them
so any idea wtf is going on ?
Are you using this just to disable the renderers? Because Unity can already do that sort of culling for you. The CullingGroup API is mainly designed for when you're rendering things manually, without using Renderer.
Yes, but my profilling showed that skinning still happens without manually disabling the renderer
Even with "Update When Offscreen" disabled?
In a test scene with a camera and a skinned mesh renderer, I can see PostLateUpdate.UpdateAllSkinnedMeshes in the GPU profiler go down to 0 when I turn the camera away from the renderer.
anything related to culling: only have the game window open and close scene as it can mess this up.
I usually have a scene and game view side by side, I made sure to have only the game view for this test.
Thats for the frustum I also need occlusion taken into account
I can see the npcs that spawn in later not render in the scene view
Hmm, I added a wall, baked occlusion culling and I see it working as expected, no skinning while it is occluded behind the wall, starts skinning when I move the camera around the wall so it's visible.
I wonder if something else is causing the renderers to update.
Maybe its just a bug in that specific version
Some forums talk about targetCamera being not set can cause this?
Im setting it manually in code
Just out of curiosity, what happens when you disable and enable them entirely in runtime? Just tick off and on the gameobject. do they get taken into account by then?
Nope
I should mention that the project is using HDRP, gpu driven rendering and gpu occlussion is on as well
Oh, I could imagine HDRP's GPU occlusion culling doesn't go deep enough to prevent skinning, unless HDRP is also handling skinning.
So the entire flow is like this. Scene gets additively loaded and enabled, level geometry sfx enemies etc get batch enabled after that to prevent frame spikes.
It does not, hence the use of a culling group
Baked occlusion still works with the gpu occlusion
And npcs from previous scenes are not taken into account then?
But still the order does not matter, I tested with the batch enabling turned off
Yes? But thats not the problem here. Npc’s from the additive scene are not taken into account
Wait that might be. The npc’s that get spawned are spawned in the active scene….
And that is different from the level scene
Thats why I was asking. If there is some kind of cullinggroup to scene or whatever relation
CullingGroup will use the baked occlusion culling from the active scene only, I assume.
Hmm but then again I have other culling groups in that level that work
Like for all the environment vfx
If you want multi scene occlusion culling, you have to bake all the scene combinations beforehand
https://docs.unity3d.com/Manual/occlusion-culling-scene-loading.html
Phew, what a not very fluid workflow 😄
But guess thats whats happening here. There is no occlusion data yet. nice to know for the future 🙂
i swear unity has been soo shit with additive loading of stuff
Hmmmmm, this would explain if none of my occlusion groups worked but they all do. The npc one just does not work for a subset of it’s items
The env vfx that get culled are also part of the level and work like a charm
Still that is the only difference between npc that get culled and the ones that do not
@sage radish wait so what happens if the active scene does not have occlusion data ? We only load in one additive scene per time with occlusion data
"If Unity finds that the the occlusion data of an additively loaded Scene is the same as that of the active Scene, occlusion culling works as intended." So I guess you have to bake it for all scenes at once even if one scene does not need it
But if I load in another level they overlap wont that cause issues ?
Well, best case it has one map but each level its own sub map (so to say) and then they might merge if overlapping. But I dont know so I guess, you should test it.
Ok so putting all my mangers and player and so on in the level, baking occlusion just for it makes it work
so there is definetly something fucky going on with the scene loading etc
did you try bake both scenes at once and run your current setup?
Thats what I have been doing
Okay, let me rephrase. So you before putting everything in one level, had your scene and the additive scene in editor mode and baked it for both scenes at once, and there you had the issue with the npcs, right? And now you have changed, that everything is in the main scene to test?
In a way. So we have a gameplay scene that is the active scene. Levels are scenes that get additively loaded in
Placing the player directly in a level and baking occlusion just with that level open works
the whole is kinda complicated
So if you throw all levels into the hierarchy view and built the occlusion map, it still breaks?
Main menu scene -> Gameplay scene -> Tutorial Scene + Transition Scene -> Level 1 ( Transition scene gets moved to the entrace/exit of a level)
Tutorial and transition scenes have no occlusion by default since they are small
Ok putting Gameplay scene first in hierarchy(making sure it’s active) then opening level 1 and baking did not fix it
So main menu, gameplay and level 1 maybe? that is so try and error weird 😄
Fuck it Ill bake with all the scenes
Yeh, just test ALL at once and see what happens 😄 Thanks for researching , hehe
Since spawned npc’s work I will just write a small script to spawn the static ones in the level the same way if worst comes to worst
Thats so weird, that this does work tho 😄
Well baking with all scenes at ones completely borked the occlusion culling but still not fix the issue
But can confirm that overlapping geometry causes issues with multiple scenes
Im so fucking done with Unity I bet this works in Unreal
Hm, unreal has it querks too. I am just wondering, your npcs instantiated, are they part of the main scene?
The instantiated npc are part of the gameplay scene since that is the active scene yes
Technically the only scene with occlusion data is the level
And there is only one of those at a time
But somehow the occlusion map is bound to the active scene, as those npcs work. Thats weird
Yes
But also
Env vfx that have their own culling groups and are also part of the same level
Do work
Ah
But the culling group for the npc, is defined in a manager in the gameplay scene while the vfx groups are monos from the level
Could that be it ????
That doesn’t make sense the spheres are what is important
have you experimented with saving it in the scene with the skinnedmeshrenderer component disabled, then, on Start, enable it?
i think you've already determined that there's a bug with occlusion and skinnedmeshrenderers that are active and saved into the scene versus instantiated at runtime
No no the problem is for sure with the multi scene set up
i'm sure some part of the occlusion grouping process in the editor is marking your skinnedmeshrenderers as occlusion excluded as opposed to no opinion
If everything is in one scene, occlusion gets baked for that then it works
It has nothing to do with the initial enabled state
to clarify, you are only trying to sort out the occlusion of skinned mesh renderers in a scene
gotchya
as opposed to instantiated at runtime which does work
The problem is complicated
So the instantiated npc’s get instantiated into the gameplay scene where the npc managers that also controlls the npc culling group is. Culling for those npc’s works. Npc that are in another scene but also register in npc manager do not even get the culling group event fired
are you by any chance registering to the wrong culling group in the level scene?
So your level npcs register to the game scene group and therefore not interacting with it?
because not being part of it technically
At the same time an environment vfx manager with it’s own culling group that is part of the level works as expected
that sounds like a bug
i mean, with unity's culling group implementation
As I lack the experience, how do you set the group. By script?
The game scene group is the only npc group. All npc register to the same one
Code is somewhere above
And does your level scene have that group attached?
it's possible that event is busted. can you work around that?
i don't even know if you can "move" objects between scenes. you can experiment with a placeholder transform in the other scenes, and then instantiate the npc into it once the other scene is loaded
sounds like a huge hassle though
So following this thing her from previous link https://docs.unity3d.com/Manual/occlusion-culling-scene-loading.html
Does your folder structure hold those files as the docs tell in step 3 of multi scene ?
Also they describe that you need to load your first scene of that occlusion group with single mode so it loads correctly (weird again)
Yes to all of that
The docs are wrong however the folder with the scene name gets created in the same folder where the scene asset is not in Assets but that is what ever
I guess they had to give some example there 😂
the could have done {path_to_scene}/"ActiveSceneName"/ or something
ok so maybe I found a bug in the culling groups. When setting the bounding spheres each frame the state change event does not fire
doing the check like this for (int i = 0; i < spheres.Length; i++) { _skinnedMeshRenderes[i].enabled = _npcCullingGroup.IsVisible(i); } works
fml
do I need to dispose of the group everytime before I set the event ?
but why would the event fire for the spawned npc's ???
anyways this was fun ride thank you all
nope disposing the group just kills it as expected
Distribute code as mods to android
Question related to Burst in Mono build/ Editor Player
When using [BurstCompile] on static methods and their enclosing types (classes/structs),
as well as on structs implementing IJob.Execute, these methods appear to be compiled into native code inside lib_burst_generated.dll.
For static methods, are the corresponding native functions directly referenced in IL? I see a P/Invoke call, which suggests this is the case:
.custom instance void [UnityEngine.CoreModule]AOT.MonoPInvokeCallbackAttribute::.ctor(class [netstandard]System.Type)
= (
01 00 37 4d 79 42 75 72 73 74 46 75 6e 63 74 69 // ..7MyBurstFuncti
6f 6e 73 2b 4d 75 6c 74 69 70 6c 79 5f 30 30 30 // ons+Multiply_000
30 30 30 30 33 24 50 6f 73 74 66 69 78 42 75 72 // 00003$PostfixBur
73 74 44 65 6c 65 67 61 74 65 00 00 // stDelegate..
)
And for IJob implementations, they seems to be wrapped in JobStruct<T> where T is IJob, with a pointer to the Burst-compiled native function, Can anyone confirm?
Sounds like you already confirmed it?
Since nobody deny what i provided as a question then it seems my reasoning is correct, anyway counted for some details.
The 2nd is just quick guess, didnt digged deeper with disassebler, just saw pulling native pointer in IL to JobStruct.Data so wanted confirmation, instead i will just dig deeper.
Are you wanting to know so you can perhaps call the burst code yourself? May be fun to investigate the burst code in ghidra
what is your goal?
Could someone critique my approach to a simple addressable model loader? (local, no remote data)
where is it? 😄
I didnt mean to post that question already 😅 , currently working on it
you know you can edit messages, right? 😄
no goal, just learning, static methods seems to just have pointer to native function in IL, and Jobs have C# source code generated which invoke wrapping and binding to native function, so its good to know what its different for jobs and static methods, thats all.
id guess this code gen is to aid in calling the exten c function (i also presume it uses the c abi), but a static function doesn't require this
no clue, both calls native functions, the difference is that static methods have it already include in IL code, but Jobs getting the pointer when [InitializeOnLoad] invokes, after wrapping them in a struct that have the field to store pointer. So there no changes in IL code for [BurstCompile] marked Jobs, just c# code gets generated (ofc its new IL code for managed .dll, but it doesnt changes already existed IL)
Okay here it is
My goal here is to create a simple script i can call SetModel(AssetReference newAsset) whenever I want to update the model.
I want it to be fairly secure so that it wont break if called multiple times repeatedly or before it finishes loading.
Next step I think is to make it guaranteed load the last specified model even if it was busy while you requested
I will probably re-fit this to apply to whatever player model is synced on the server of a multiplayer game
using System.Collections;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class TestModelLoader : MonoBehaviour
{
[SerializeField] private AssetReference newModelReference;
AsyncOperationHandle<GameObject> opHandle;
[Header("[ Required Components ]")]
[SerializeField] private Transform modelRoot; // Parent transform for spawned model
private bool isLoadingModel = false; // Set true while loading to ensure single operation
void Update() {
// Hold button down to spam/test
if(Input.GetKey(KeyCode.Alpha1)) {
SetModel(newModelReference);
}
}
public void SetModel(AssetReference newAsset) {
if(!modelRoot || isLoadingModel) return;
// Lock Operation
isLoadingModel = true;
// Begin replacing old model
StartCoroutine(LoadNewModel(newAsset));
}
private IEnumerator LoadNewModel(AssetReference newAsset) {
// Destroy current instances or misc gameobjects
if(opHandle.IsValid()) { Addressables.ReleaseInstance(opHandle); }
else if(modelRoot.childCount > 0) {
while(modelRoot.childCount > 0) { Destroy(modelRoot.GetChild(0).gameObject); }
}
// Spawn new instance
opHandle = Addressables.InstantiateAsync(newAsset, modelRoot);
yield return opHandle;
// Unlock operation
isLoadingModel = false;
}
}
Heres a video of it working, when it flickers i am holding the button down
To improve this i would make the load method async.
You should also then use cancellation tokens to correctly cancel an active load when you want to instead begin a new one.
I can make an example if it helps using UniTask.
also to avoid flickering you probably want to pre load the prefab assets for all of the things you plan to show here instead...
An example would be sweet, my friend metioned looking into UniTask for cases like this
The flickering doesnt feel like much of a defect since this isnt meant to be rapidly instantiated anyway
Im just experimenting with addressables before applying it to project
give me a few mins to write something
np, I am trying to make it guaranteed load the last model you gave it
mine ignores new requests while its busy
quick note, you can't actually cancel Addressables.LoadAssetsAsync after you have invoked it. The operation will compleat anyways. You can call realease on the handle before it finishes, effectively discarding the result of the opearation and unloading it once it finished, but in terms of real cancellation, that's not really going to work
check the notes under this doc section : https://docs.unity3d.com/Packages/com.unity.addressables@2.3/manual/AddressableAssetsAsyncOperationHandle.html#coroutine-and-ienumerator-operation-handling
dw im well aware of this fact!
The type or namespace name 'CanvasScaler' could not be found (are you missing a using directive or an assembly reference?)
i get this error even though i imported using UnityEngine.UI
anyone know the fix?
i can send the whole code but its 70 lines
@sweet summit
CancellationTokenSource loadTokenSource;
GameObject currentInstance;
public void CancelLoad()
{
if(loadTokenSource != null)
{
loadTokenSource.Cancel();
loadTokenSource.Dispose();
loadTokenSource = null
}
}
public void DestroyCurrent()
{
if(currentInstance != null)
{
Addressables.ReleaseInstance(currentInstance);
currentInstance = null;
}
}
public async UniTask LoadModel(string address)
{
CancelLoad();
DestroyCurrent();
//Create new cancellation token source but link it to the destroy state of this mono. Requires 2022+
loadTokenSource = CancellationTokenSource.CreateLinkedTokenSource(destroyCancellationToken);
var token = loadTokenSource.Token;
//UniTask lets us await and get the result.
GameObject loadedObject = await Addressables.InstantiateAsync(address, transform);
if(!token.IsCancellationRequested)
{
currentInstance = loadedObject;
}
else if(loadedObject != null)
{
Addressables.ReleaseInstance(loadedObject);
}
}
private void OnDestroy()
{
DestroyCurrent();
}
I am not 100% sure how this example will behave when trying to "release instance" when this monobehaviour is destroyed but hopefully this example helps you understand how a cancellation token source can be used.
oh i see
That is the correct namespace though. Are you seeing the error in the IDE and/or in Unity?
unity
Ideally the instantiate async function would accept a cancellation token argument so we could cancel it properly
e.g. await UniTask.Delay(100, cancellationToken: myToken);
its usually the norm that async functions accept a token arg so you can cancel them easily from elsewhere but unity dumb
Try to recompile again (and make sure you save ofc)
now that got rid of that error but im getting another error saying that simulationmode doesnt exist in the current context and that its not a part of physics on lines like this:
Physics.simulationMode = SimulationMode.Script;
That's not available on versions below 2022.2.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SimulationMode.html
This is not an advanced topic btw
ohh
im on 2021.3
That's... not how it is gauged
update to 2022 at a min but if you dont have any reason to stay on an old ver go to unity 6
is there an alternative to simulation mode in 2021
i dont feel like updating rn lowk
if you want newer features then you update. You wont get new features or updates (unless on a paid subscription)
i really like 2021 unity tho
but ill consider it
You'd only need to update if you needed SimulationMode.Update
The other two are already available with the bool
lol now i replaced it with autosimulation
but im getting an error that simulation mode doesnt exist on a line thats empty
Hellou, im trying to build an occlusion culling algorithm and I would like to make use of the depth texture before any instanced draw call is done. Basically, the idea is for the depth texture to only contain the terrain data. How could I do that? One option is having a copy camera that only draws the depth buffer of the terrain layer, but im not sure if there's another way to extract the depth texture at a certain point?
what are you trying to do
pause the game but i fixed it
Hi !
I don't know how to handle rotations here.
I would like to make a 2D game with a character made of a cube that I wish could be able to be deformed.
Right now, I made a custom mesh that can change the shape of the cube and, I made a collider that can change it's shape. It seems to work, but the collider keep rotating. I decided to fix the rotation, but now the cube doesn't rotate much.
For your information, there is no main object in this. All the corners are separate entities and I just draw a mesh in the middle.
Here is the code for the colliders can can be deformed :
[SerializeField] Transform[] CornersOfCollider; // These are the transforms of the 2 corners next to the main one
[SerializeField] PolygonCollider2D colliderToUpdate;
void Update()
{
Vector2 point1 = new Vector2(CornersOfCollider[0].position.x - transform.position.x, CornersOfCollider[0].position.y- transform.position.y);
Vector2 point2 = new Vector2(CornersOfCollider[1].position.x- transform.position.x, CornersOfCollider[1].position.y - transform.position.y);
Vector2 point3 = new Vector2(0, 0);// This is the local position of the object which would be (0,0)
colliderToUpdate.SetPath(0, new[] { point1, point2, point3 });
}
You can see better what happens when I remove the rotation restriction in the last video vs what happens when I put it on.
I feel like I did so much more complicated things to get there, but that colider thing is bugging me out.
are you saying you want a soft body cube?
Yeah
you can't implement it this way
you're not any closer to your goal, even if it feels that way
I made a collider that can change it's shape. It seems to work, but the collider keep rotating. I decided to fix the rotation, but now the cube doesn't rotate much.
using springs?
Yeah
i think it's worth looking at how the asset store assets work
they never modify the shape of a collider
Right now, I am starting to consider the possibility to change how I calculate the colliders and not longer freeze the rotation on the Z angle.
Because It works other wise
If the shape of the object changes in a soft body, I feel like I should change the collider
Keep in mind that the sides of my cube will always be straight.
The cube will not be that soft.
I think I will need to rotate the collider myself or handle the calculation of the corners of my other angles differently
you will be reinventing springs
it's very arbitrary. maybe ask one of the asset developers how to achieve what you want
Who do I reach out to talk to and how can I do it ?
I never wrote to any people who worked on assets on the Unity store.
sometimes they are active on the unity forums or host their own discord
imo use the forum thread for a particular asset
is it important in your game that something could slide on one of the edges of the box?
hey guys, i have a problem with the controllercolliderhit method. I'm using it to allow my player to push a box around and it works flawlessly in editor, but in build nothing happens.
I tried debugging and the method does get called, but it doesn't progress further than if (hit.gameObject.CompareTag("pushable")), again, it happens only in the build version.
What could be causing this?
Look at your standalone logs
you mean the build logs? that's where i saw that it doesn't get called
Build with debugging support and try debugging it
Hello, I do not know if this really advanced but definitely for me it is. I am trying to make a melee combat system in Unity3D. So far, my combat system is only about punching. However, I can not figure out the best way to create an efficient and fluent way of attacking. I just figured out how to "attack" the enemy, which is basically calling and overlapsphere at the end of the animation where the hand is and if there is an enemy, then they get hit. But it is not fluent, efficient or nice to play. I would like to know how to make that "multidirectional" combat system that games have, where you are looking at an enemy and if it is close enough to the player and you attack, the player is redirected to the enemy, at the perfect distance for the hit to look god and looking towards the enemy. For example, in spiderman games that is very well done and the player gets redirected all the attacks to the enemies, as of course if they have to be next to the enemies to attack and do something that would make not fun at all the combat. So, the main question is basically how do I get a smooth melee combat system where the player gets redirected towards the enemy and if the best way to detect the hitbox is with the overlapsphere. I found a video that might help (or might not) to see what I want to do, even though this video is with two swords, it redirects towards the enemy: https://www.youtube.com/watch?v=YXxahl07IJc I do not expect the exact solution, of course. I just want to know how to approach it so I can start learning because I have no clue where to start now. Thanks!
Small update, I've been using the 3D Game Kit Lite to help flesh out the "action" in the action rpg. Rather than continuing with my previous setup which was in a soulslike direction, I honestly just wasn't having much fun with it, so I'm going back in the direction of hack and slash, although I do want to cherry pick some soulslike pieces to kee...
I'd look into how to do general lock on systems. The redirection is simply finding the closest enemy to you then slerping your character into that direction
Thank you! I will try and start from there to see what I can find
What you are looking for is "Freeflow Combat". Here is a tutorial on how to achieve something similar.
https://www.youtube.com/watch?v=GFOpKcpKGKQ
This project is a take on the Freeflow Combat system from the Batman Arkham series of games! Let’s explore game dev techniques and try to achieve a similar system!
PROJECT REPOSITORY
https://github.com/mixandjam/Batman-Arkham-Combat
REFERENCES
Jammo
http://u3d.as/1G8A
------...
That being said, it really is a niche combat system. I believe you would be able to achieve better result with what you have if you simply remove the wind up and added a really simple lock on system for controller.
I also think if you were to add a combo, where you can chain up different attack depending on the button press, that would look and play awesomely. I also believe you might want to either do like lost ark where the enemies are frozen or genshin impact where they are slightly stagger.
Is it important to recreate a specific game?
I found this video to be quite good https://youtu.be/GFOpKcpKGKQ?si=6L1TDVEIgGgXwPis
Oh it was already posted lol
Nevermind
anyone familiar with the shader warmup feature in unity 6 ? https://discussions.unity.com/t/graphicsstatecollection-tracing-and-warmup-in-unity-6/951031/28. I traced a valid looking collections. Then I do the following ```public class PreCoockGraphicStateCollection : MonoBehaviour
{
public GraphicsStateCollection collection;
public JobHandle preCoockHandle;
void Awake()
{
if (collection!=null && !collection.isWarmedUp)
{
preCoockHandle = collection.WarmUp();
}
}
}``` and
{
while (!shaderCoocker.preCoockHandle.IsCompleted)
await Task.Delay(100);
shaderCoocker.preCoockHandle.Complete();
}
``` this is awaited during the game loading phase
but the result is that the game still stutters when a new shader is first viewed
such as a explosion from a bomb
- I'm implementing a procedural large-scale world gen right now. So far the biggest bottleneck is instantiating mesh renderer game objects. Is there any way that doesn't tank the performance to draw many unique meshes without the need for tons of objects to back it all up?
Upd. Unity 2022 URP, if this is of any significance
What sort of objects are these that you are referring to? Not the chunk meshes themselves I assume?
- Game objects with mesh renderer + filter components
But what are they? Buildings? Rocks? Trees? Grass?
- The meshes? It's a voxel world, so pretty much all of the above combined in one mesh
- Think of minecraft as a reference with its chunks
if there's lots of identical objects, it sounds like they should be using batching or instancing, maybe your materials aren't allowing that?
Oh right. Did you profile the code to make sure it's the instancing part (and what of it exactly) that's slow and not the mesh generation, rendering, etc.?
- It's not about the rendering proccess of the meshes, but rather a way to start it. Right now my approach is as naive as creating individual blank mesh renderer objects to assign them a mesh later, which creates noticeable lag spikes. I'm thinking of any way to store and draw my meshes without the need to instantiate one object per one chunk consistently
draw them directly you do not need a mesh renderer
You can always use Graphics.Render... functions
- Yep, i'm 100% sure. Both voxel data and mesh generation are jobified, and the profiler shows me that ~40% of the sampled time is prefab instancing
- Huh. I never imagined that to be this much straightforward. What about all the batching stuff? Is it automated enough that i don't need to take extra considerations, and just throwing a bunch of my meshes in there would be fine?
- I wish i could pool renderers before the game starts. They are, but it doesn't help during the initial load
I don't think you could get any benefits from most of the batching methods when all the meshes are unique other than SRP batcher which doesn't really care of meshes (batched per shader, kind of)
- I see. Thanks!
Then do not render with gameObjects at all https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Graphics.RenderMesh.html
since you have a unique mesh per chunk you do not have much to instance anyways
so just go with the simple Render Mesh call
At least I cannot find any information on calling the Graphics api breaking SRP batching so I assume it should work just fine
Sure, but SRP batching is bit different. It is not really a batching method that even aims to reduce draw calls at all but rather makes them much cheaper
I know what the srp batcher does
i just dont think that Graphics.DrawMesh goes trought the SRP batcher code path
I wouldn't expect anything to work properly when you directly ask for a mesh to be rendered
This seems to suggest otherwise https://discussions.unity.com/t/how-to-get-srp-batching-performance-while-using-command-buffer-drawmesh/859398/5
then again a forum post from a unity dev says it should so
Oh, I was mixing that up with DrawMeshNow, etc.
heh beat me to it
Yeah, DrawMeshNow pretty much disregards the render pipeline but DrawMesh should be a draw call among others in the render pipeline pretty similar to how every other mesh is rendered. Haven't really tried myself, but I always thought that wouldn't break SRP batching, it's not really clarified on their documentations
I’m too deep in my own shit to give it a try right now
Just gonna rebump my question in case someone smarts knows what going on
I haven't used it. Have you confirmed the prewarm job finishes?
Yes I get a log after it’s completed
And are you causing the same explosion to happen when you are tracing as the one you see the stutter in?
Maybe it’s worth bumping to lates u6 but I was hoping to send a build out today
Yep I even looked at the graphicsstate file and the shader is in there
And you're seeing this stutter in a build and confirmed in the profiler that the stutter is from CreateGraphicsPipelineImpl?
Could also be other first time related stutters, like Mono JIT, class static field initialization
It happens on a variety of objects. Some of which are just a mesh with a vfx shader
It's probably shader compile, but good to confirm it before you spend a bunch of time on debugging this
But now I have not seen that specific marker, but I have not looked for it
this is something i'm a bit unclear on
so unity compiles from HLSL to some intermediate language during the build, and then that gets translated into something the user's GPU understands at runtime?
I was talking to Mao about this just yesterday, in fact.
#archived-code-general message
Makes sense.
you can take a look at the articulations system, which supports real robotic arm / leg simulation
I am pretty sure you are supposed to drag and drop the shader variant collection into the slot for shader collections that's in the Player Settings somewhere or the Graphics settings
that has always worked for me
i don't recall how the shader variant collection is made, i think it is platform specific no?
like the editor has to be run on the device you want to create the precompiled shaders for?
at least that's how appmana does it
I’m pretty sure the variant collection is just for what to include in the build it has no effect on the runtime compilation
Interestingly enough I’m not seeing that marker. Im getting a DXGI.WaitOnSwapChain but the gpu frame time is about 8ms
I'm gonna version bump to 6.35 see if that helps
hmm perhaps it just gets everything to compile on start before the scene loads
is that sufficient?
are you trying to avoid runtime compilation altogether? or only runtime compilation while rendering frames?
that would be sufficient but I do not think the shader variant collection will help
you see I am in the dx 12 case
before it was easy there was a static call from Shaders.somethingbla
ah you must be talking of this ShaderVariantCollection.WarmUp
Add the shader variant collection to the Preloaded shaders section of the Graphics Settings window. Unity then uses the ShaderVariantCollection.WarmUp to warm up the shader variants when your built application starts. , yep so what yu are sayinh will work
just not for dx12
okay i do see that i call prewarm
standby
I observe freezes in my stream, or the game is stuttering in a way I cannot reproduce in editor or player builds.
Your machine has cached shader compilation. Shader compilation can take a long time. To resolve this:
- Open the editor on Windows.
- Make sure your Unity editor title bar says DX11 (the default). If it doesn't, change the order of your player graphics backends. DX11 should be first.
- Vist the Graphics tab in Project Settings. Observe at the bottom, you should see "Currently tracked: X shaders, Y variants" or similar.
- Hit play.
- Play through all the content in your game, ensuring that all the shaders have been compiled and loaded. Be thorough.
- Click off play.
- In the Graphics tab, observe now a greater number of shaders and variants are tracked.
- Click the Save to assets button at the bottom of the Graphics tab.
- Drag and drop the saved shader variants asset into the preloaded shaders list in this tab.
- Save your project, save your scene, then commit.
can you try this?
i mean you can use dx12
maybe when i tested and wrote this it was only supported for dx11?
i'm sure there is a good reason my own docs say that lol
appmana also runs rendering for 4s to really force the game to load everything. in other words you would have a scene that has all the things you want to precompile shaders for, show a loading canvas overlay, disable occlusion, and then just run the screen for 4s.
@livid kraken anyway dont' waste your time writing with any of the documented API because hte instructions i provided do the same thing but better
That wont work for dx 12. I'm not super deep into the material but as far as I can tell the traditional shader warmup will not work for dx12
do you need an approach that works 100% of the time?
well yes
in my experience the shader compilation scene was the most robust approach because it works regardless of the device that is used to run the graphicsstatecollection stuff
that's really what appmana does
I'm aware of that approach but I'm rather pressed for time so messing with the flow of the game now is sorta off the table
do you use any dx12 features like raytraced whatevers
We benefit greatly from the split graphics jobs
it's a overall perf win
so again going back to 11 is a no
i'm building with 6.35 now hoping the damn api works
gotchya. and you don't want to try the little thing i wrote up anyway? i know there's what their docs say
it would take you a total of 5 minutes to try
i think it will probably not help lol
i mean the docs say so
but in my experience it was also the vfx graph object that needed the most optimization
If that doesnt work im gonna make then shader bootstrap scene
yeah ultimately that's what the game did that used vfx graph objects
@undone coral the shader variable collection did not work as well on dx12 fyi
So I made the bootstrap scene but now I need to hunt down all vfx and things that cause hitches 😭 really wish Unity’s shit would at least work sometimes
i want to make something similar, for mobile and keyboard controls, it should also be easier (my target is younger audience)
should i fake it by titlting the model and apply effects?
is that a good way to approach? (i am not a very advanced coder, especially in physics related things)
Pretty sure youtube has a bunch of tutorials on drift mechs
yo in which channel should i ask question about build problems?
never doubt my own docs
there's a prolific vehicle simulation asset developer whose stuff you should look at. his most balanced package is edy's vehicle physics
you'll learn a lot more about this stuff from the package
especially if you don't know anything about cars
If you run a RaycastCommand batch, the order of returned hits in the buffer is essentially random, right?
Doesn't seem that way.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RaycastCommand.html
The results for a command at index N in the command buffer are stored at index N * maxHits in the results buffer.
In other words - seems like it respects the order of the command buffer
Ahhh, silly mistake, I was removing my mesh instances from the buffer which changed the index and made it appear random
Thanks for the sanity check
What do you mean. Im saying it does not work for dx12
yes tat's what i mean. the docs said that only dx11 is supported
i mean both sets of docs
the loading scene grind is real
i wonder why they don't provide a built in way to do the graphics state recording
do you ever feel like unity implements something like that because somebody at some giant company asked for it, but they have no idea if it works, and the guy doing that thing doesn't care, it' sjust a checkbox, so it's one big circle jerk?
like because electronic arts f'artsengine has it
Actually I found that I was being a moron. The script responsible for warming up the graphics state collection had two instances in the scene and the wrong one was getting warmed up as part of the loading process
and there's a meeting with 9 people
i don't know i think you did everything right. they should just set up the settings panel where the shader variant collection is assigned to work with graphics state
it doesn't make any sense that you manage this manually
I honestly prefer less handholding from Unity. Then again that does let me be a moron
I mean the api was pre-warming a graphics state, just not the correct one
Does anyone know how I might access the currently selected keyframes like in this asset?
It has to be reflection, right?
not clear what asset you're talking about or what it does
It's a keyframe easing tool
From the screenshot, it seems like you can select keyframes
and then open up a seperate window to select an ease type
I can understand the extra window and ease type
but I cannot figure out how they can get the current keyframes
I'm going to assume reflection, since I don't believe unity exposes the inner workings of the animator window
thanks a lot
i didn't either and i learned a lot from the package!
I thought about that, but I doubt it
I'll try it out though
thanks for your help
So after warming up the right collection there are still stutters. In the end I went with a whole shader bootstrap scene
With it the stutters are gone
me too bro me too
i think the vfx graph might be compiled with something that is dependent on runtime in a way that doesn't reproduce well
can someone help me with this script its supposed to generate the faces of a cube using a flags enum for instruction but no matter what it generates the same face
Having one of your flags values be 0 is not right
0 should only be a None flag
Question related mostly on C# stuff.
I'm currently struggling to know the differences between Boxing/Unboxing and Casting.
Is for example, Casting an AssetReferenceT<Material> into an AssetReference the same as just boxing it? is it just as computational expensive as boxing it into an object via (object)assetReferenceT? ((In this case i'm casting from a child class to it's parent class, AssetReferenceT inherits from AssetReference for the people who dont know addressables.) )
Boxing is when a value type object is wrapped and put in the heap for some reason
Everything you posted was type coercion and casting
The concept of boxing is also used in rust by Box<> to have a heap allocated object owner on the stack.
Right. Value types are stored directly -- so if you need to be able to handle one like a reference type, you have to box it
You can use ref in out to avoid boxing for function args but these aren't async compatible
AssetReferenceT<Material> x;
var y = (AssetReference)x;
upcasting has no computational cost
what is your goal?
yes, that's a very important remark -- upcasting always works
downcasting does not
You generally don't need to upcast, of course
right now to be able to generate a cube mesh but only genenerating the faces selected with a flags enum
to make a game based on voxels? like what kind of game? based on the snippet you shared you are at the start of a long journey. have you looked at any asset store assets that do this stuff?
im just messing around trying to recreate something like minecraft
but do you know why its not working?
https://github.com/Zarbuz/VoxToVFX have you seen this?
im trying to make a generated world like minecraft i wasnt looking for a tool to make models out of voxels
well the two problems are related
the tool doesnt help with my problem of getting the mesh faces to generate
You should provide more details on the issue and the debugging you've done so far. Also share !code correctly:
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
i think i fixed it for now
right now i imlpemented a small version using tilt
because it was feasible for me now (dont want to slow the entire production)
I can show you a trick for cross type casting that dont inherits but are still compatible and won't box...
yes I made that terms simply bcos I don't know what it's called 😄
Vector4 vec = new Vector3(1,2,3,4);
var nowVec3 = Unsafe.As<Vector4, Vector3>(ref vec)
the downsides are it can't be inlined, and may lead to memory corruption if not used properly 😄
Hi there
does anyone have experience with the PlayStation savedata library?
I'm trying to write our save files but having trouble with how things work there
upon request to write the data into a file I have the following code
try {
int userId = PS5Input.RefreshUsersDetails ( 0 ).userId;
DirName savesDir = new () {
Data = "saves"
};
Mounting.MountRequest mountRequest = new () {
UserId = userId,
Async = true,
DirName = savesDir,
MountMode = Mounting.MountModeFlags.Create2 | Mounting.MountModeFlags.ReadWrite,
Blocks = SavesBlockSize,
IgnoreCallback = true
};
Mounting.MountResponse mountResponse = new ();
int requestId = Mounting.Mount ( mountRequest, mountResponse );
if ( requestId < 0 ) {
Debug.LogError ( $"[{nameof ( PS5StorageProvider )}]: Failed to mount." );
return;
}
while ( mountResponse.Locked ) {
await UniTask.Yield ();
}
Mounting.MountPoint mp = mountResponse.MountPoint;
string outputPath = mp.PathName.Data + "/" + Path.GetFileName ( path );
await File.WriteAllBytesAsync ( outputPath, asBytes );
Mounting.UnmountRequest unmountRequest = new () {
UserId = userId,
MountPointName = mp.PathName,
UnmountMode = Mounting.UnmountMode.Commit
};
EmptyResponse unmountResponse = new ();
Mounting.Unmount ( unmountRequest, unmountResponse );
while ( unmountRequest.Locked ) {
await UniTask.Yield ();
}
}
catch ( Exception e ) {
Debug.LogException ( e );
}
Saving for the first time works, but after that I'm getting the error
SaveDataException: The mount point name provided is already unmounted. /savedata0
Does anyone have an idea what I'm getting wrong?
I thought I'd have to unmount the mounting point after I was done with my transaction
that's just reinterpret_cast 😛
yeah, that's the terms 👍
use unmountResponse.Locked not unmountRequest.Locked
ohhh good catch
you should also get in the habit of searching github for snippets too, to see how other people use APIs. that's what i did.
!warn 247793168056057857 don't post ChatGPT links here. If you can't bother to write down the answer then don't bother at all.
doctorpangloss has been warned.
thank you for your feedback. my goal was to show people how they can use tools to do the kind of syntax checking they are seeking. to me, posting the link is the same as showing screenshots warnings and code analysis in your IDE, it shows the succinct prompt i used, how i copied and pasted the code, and how the reply was useful.
There's no promotion on the server. Especially underbaked tech that can hamper learning process. You can do that somewhere else.
okay
Not a feedback either. Next time warning will be escalated.
@raven knot is this true? is it intended that posting a link to a chatgpt conversation should be a warnable or bannable offense?
you have met me in person. i think my goals are sincere.
seems like an important community question. unity itself has code assistance and generative AI tools.
@undone coral Don't spam the channel. And don't ping admins. There's #1161868835423526933 for this.
there appears to be a few threads on this in server-feedback but i think it's sort of up to the company
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
when i paste into here it bevomes txt file how to i made it fix?
If only someone posted a message that called up a bot that says how to post large code blocks
its to large i dont have nitro
If only someone posted a message that called up a bot that says how to post large code blocks
i dont understand whaty to do when i paste the code in it
You send the link
https://scriptbin.xyz/obavovavid.cs
its kinda buggy and it uses a weird stabbing mechanic (vr) and the pullout dosent work (USED AI) when i stab the blood effect does not show it dosent show any errors but i have another script that makes it react to the knife and touvhing so when i stab it generated inf speed but i dont think its this script
Use Scriptbin to share your code with others quickly and easily.
ty
Hi, is there a way to capture the Game View window whilst not being in play mode, as a Texture?
ScreenCapture.CaptureScreenshot works for this. GameView has to be focused. You can force it to be focused with EditorWindow.FocusWindowIfItsOpen and passing Type.GetType("UnityEditor.GameView,UnityEditor")
I gave that a go an I'm sure it only works in Play Mode. I want it for Non-Play mode
Ah. Thanks. I also require altering the texture pixels. I've found a quicker way. I have this so far:
string folderPath = Application.dataPath + "/Screenshots/";
string shotName = $"Screenshot {System.DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss")}.png";
RenderTexture renderTex = new RenderTexture(Screen.width, Screen.height, 16);
Camera.current.targetTexture = renderTex;
RenderTexture.active = renderTex;
Camera.current.Render();
Texture2D copyTex = new Texture2D(Screen.width, Screen.height);
copyTex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
// Adjust pixel colours here
copyTex.Apply();
RenderTexture.active = null;
byte[] bytes = copyTex.EncodeToPNG();
System.IO.File.WriteAllBytes(System.IO.Path.Combine(folderPath, shotName), bytes);
Does anyone know how to smoothly move from one animation to another in the blend tree
This is the code I'm using for input:
private void GetInput()
{
Input = Vector2.zero;
if (InputManager.ReadInput(Controls.MOVEMENT, out Vector2 _rawInput))
{
if (PlayerFeatures.NormalizeMovement)
{
_rawInput.y = _rawInput.y > 0.1f ? 1 : _rawInput.y < -0.1f ? -1 : 0;
_rawInput.x = _rawInput.x > 0.1f ? 1 : _rawInput.x < -0.1f ? -1 : 0;
}
Input = _rawInput;
}
}
And this is how the blend tree looks right now
It's too sharp
do you mean you want to add smoothing in the code? if so just use SmoothDamp or something. that's also not exactly advanced. its a pretty basic thing for unity devs to know about.
if you're asking about the animator, consider asking in #🏃┃animation
Smooth damp wouldn’t work because it requires initial position which would instantly be too high, that’s my issue
It doesn’t start from 0 to 1 as the blend tree would require to smoothly blend between animations. The second I press the key on the keyboard is just 1 that’s why the animations are so sharp, and I have no idea how to combat this
can you not just smooth the input after running GetInput?
maybe you could also use one of the other smoothing methods available. like lerp or moveTowards
Maybe I’d interpolate raw output with normalised output?
private Vector2 inputSmooth = Vector2.zero;
private void ReadInput()
{
Vector2 targetInput = Vector2.zero;
if (InputManager.ReadInput(Controls.MOVEMENT, out Vector2 _rawInput))
{
if (PlayerFeatures.NormalizeMovement)
{
_rawInput.y = _rawInput.y > 0.1f ? 1 : _rawInput.y < -0.1f ? -1 : 0;
_rawInput.x = _rawInput.x > 0.1f ? 1 : _rawInput.x < -0.1f ? -1 : 0;
}
targetInput = _rawInput;
}
inputSmooth = Vector2.Lerp(inputSmooth, targetInput, Time.deltaTime * 10f);
input = inputSmooth;
}
Is this the kind of thinking you had in mind?
hi getting some errors which im a bit confused about im trying to parse data from a file and make scriptable objects out of the information but im getting this error ```Asset import failed, "Assets/AMD_ECS_Simple_E.TomBen" > InvalidOperationException: Failed to add object of type Type. Check that the definition is in a file of the same name and that it compiles properly.
UnityEditor.AssetImporters.AssetImportContext.AddObjectToAsset (System.String identifier, UnityEngine.Object obj, UnityEngine.Texture2D thumbnail) (at <2f9d421960d84dffaa88793de0f4b5f3>:0)
UnityEditor.AssetImporters.AssetImportContext.AddObjectToAsset (System.String identifier, UnityEngine.Object obj) (at <2f9d421960d84dffaa88793de0f4b5f3>:0)
TomBenImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) (at Assets/TomBenImporter.cs:42)
UnityEditor.AssetImporters.ScriptedImporter.GenerateAssetData (UnityEditor.AssetImporters.AssetImportContext ctx) (at <2f9d421960d84dffaa88793de0f4b5f3>:0)
UnityEditorInternal.InternalEditorUtility:ProjectWindowDrag(HierarchyProperty, Boolean)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)```
using UnityEngine;
public class TomBenSO : ScriptableObject
{
}
[CreateAssetMenu(menuName = "ScriptableObjects/Type")]
public class Type : ScriptableObject
{
public string displayName;
public int id;
public int health;
public int damage;
public int speed;
}
[CreateAssetMenu(menuName = "ScriptableObjects/Cluster")]
public class Cluster : ScriptableObject
{
public string displayName;
public int id;
public int typeID;
public int spawnAmount;
}``` ive got just some basic scriptable object templates
https://paste.ofcode.org/Du5Kk8Y29heeYZPD7bsrUW thats the importer
if it works, yup. exactly what i meant
if not, no. i would never conceive such a thing
Hello. Im asking a beginner question here but im unable to edit my script even after double clicking on it in my project files. I've set my external script editor to VS code and restarted Unity a few times, but it can't seem to open up.. Does anyone know what should i do? My script is basically uneditable
anyway. class name and file name dont match
Ive renamed it. Still unable to edit the contents of the script
sounds like you haven't configured your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
What the. Don’t have type named Type
But i do
Change the name
To what
Oh shi
Also you should have any SO or MB in separate file
And that class name suppose to match with file name
Hey is anyone here familliar enough with Monos internals to explain something to me? working on orbital mechanics in unity and the single precision transforms were becoming a problem. So i rerolled my physics system to keep state with double3 instead of using Vector3. then cast the double3 to the postion.transform each frame. I expected this to add overhead and performance penalties but it actually made it notably faster?
Also haven't enabled burst compilation for this yet. So that shouldnt be a factor
Yeah they are in a seperate one to the importer
It should be the same
You posted code that putting three SO in one file
This isn’t advanced topic anyways
Hey there, i am having an issue where the raycast wheel the object is fall through the map while the car still drives and functions see screenshots:
The demo i scene i got the script from works fine the wheels are not going through the ground, its doing that in my project
I'm having troubles with collision at high speeds.
I tried going with hitboxes closely matching my weapon models but fast animations make them go undetected most of the time.
I tried messing with the physics step but it didnt help much and impacted performance. also tried looking for some custom physics solution in the asset store but nothing seemed to handle that.
what's the usual approach for this? do big games just pay for havok?
Raycasting is one option. For weapons with a large surface area, like a sword, you can use multiple raycasts along the weapon and trace the swing.
yeah I tried it pointing forward to anticipate the collision like people do with projectiles but it didnt work all the time
havent tried pointing backwards like the video
It's casting a ray from a previous position to the current position, to see if that part of the sword passed through a collider in the last frame.
i made a custom playable script, but I don't know how to get the placed object/behavior (type of NPCTownBehaviour) from the playableasset, any clue?
Here's my custom PlayableAsset script
public class CharacterTransformClip : PlayableAsset
{
public Vector3 position;
public Vector3 rotation;
public Vector3 scale = Vector3.one;
public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
{
var playable = ScriptPlayable<CharacterPlayableBehaviour>.Create(graph);
CharacterPlayableBehaviour characterPlayableBehaviour = playable.GetBehaviour();
characterPlayableBehaviour.position = position;
characterPlayableBehaviour.rotation = rotation;
characterPlayableBehaviour.scale = scale;
return playable;
}
}
I did something with this ages ago and i think you need to get the binding from the playable director: director.GetGenericBinding(track);
cast to NPCTownBehaviour and hopefully it works
is Application.logMessageRecieved supposed to fire for native logs as well? I have an error from Native Unity that's not picked up for my custom logger. I am experimenting with Unity.Logging package
I wanted to try and repo it on a blank project but I'm not sure if there's a way to trigger a native log/errorlog?
by native do you mean like stderr or stdout? that event is probably only for engine specific logging
Is there a way I can expand the options available here with my own code? I have this method I would like to use:
public static class Utils
{
public static void Toggle(this GameObject gameObject)
{
gameObject.SetActive(!gameObject.activeSelf);
}
}
has to be a member function taking 0 to 1 arguments. a static extension method will never work
Ok Thanks
you can always sub in code and do this there
or yea have a sub class of button or some method in some mono somewhere to help
not sure honestly. I get an error from BatchRenderGroup that (in editor) shows up in the unity console window. But I can't seem to catch that error to log it in my own logger
the stacktrace seems to point to internal unity engine
there appears to be a variant for non main thread logs so perhaps this will include this?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Application-logMessageReceivedThreaded.html
oo hang on a minute I might have misunderstood the note on that page
I assume then that I won't get a callback on logMessageReceived if the log is on a thread.
When I read it the first time I assumed they meant threaded logs will be forwarded to main
yea i think that is the case, and this alt gets them all
you can then use something like editor coroutines/editor update/unitask to get back to the main thread from the event
hmm no even with the threaded version it's still not receiving those logs
A BatchDrawCommand was submitted with an invalid Batch, Mesh, or Material ID. Shader pass: SHADOWCASTER, BatchDrawCommand index: 15, (index in range: 0), BatchDrawRange index: 2
This is not supported when rendering with a BatchRendererGroup (or Entities Graphics). MaterialID: 0 ("<null>"), MeshID: 34 ("Cube"), BatchID: 6.
0x00007ff9ae87616d (Unity) StackWalker::ShowCallstack
0x00007ff9ae886129 (Unity) PlatformStacktrace::GetStacktrace
0x00007ff9afaef76e (Unity) Stacktrace::GetStacktrace
0x00007ff9b0097faf (Unity) DebugStringToFile
0x00007ff9ae5d4dc9 (Unity) LogRepeatingStringWithFlags
0x00007ff9ae0df7f2 (Unity) BatchRendererGroup::LogBRGErrorInvalidID
0x00007ff9ae3539f0 (Unity) InjectShadowDrawCommands
0x00007ff9ae351fb8 (Unity) ExtractActiveCasterInfo
0x00007ff9ae35224f (Unity) ExtractActiveCasterInfoJob
0x00007ff9ae35215e (Unity) ExtractActiveCasterInfoGuardianJob
0x00007ff9ae398339 (Unity) ujob_execute_job
0x00007ff9ae39772f (Unity) lane_guts
0x00007ff9ae39a374 (Unity) worker_thread_routine
0x00007ff9ae590a0d (Unity) Thread::RunThreadWrapper
0x00007ffab0d27374 (KERNEL32) BaseThreadInitThunk
0x00007ffab1c1cc91 (ntdll) RtlUserThreadStart```
This is the error in question
I'm recording everything to a ConcurrentQueue and dequeuing in Update()
all logs show up except this particular one
I wonder if you need to instead read the std out yourself to get this:
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput?view=net-9.0
or standard error
yeah this seems to be editor specific behaviour btw. In builds it appears to work fine
yea id expect that to get most things excluding native crashes
What would be a decent way to implement user-defined expressions, preferably with tools built into the language, no dependencies?
I want to have a text field where you can type an expression such as (1 + 2) * @x where @x would be a variable lookup from a Dictionary<string, float>
Should I look into Linq.Expressions?
Also, should I implement my own parser or is there something handy built in that I can use?
Later I might want to support some predefined functions too, such as Sin, Max, etc. but that's not the main focus now.
This would be used for some exposed parameters in a proc gen system. When the expression is evaluated, a "Scope" object is present and it has the variables in dictionaries.
For some reason I had missed that, thanks, I'll look into it
Doesn't seem to support named variables/placeholders but I could just replace them with literals first and then pass the string into that
Would regex match what you want? Because you can prob convert all the keys into a string and use regex on it
Regex just for replacing the placeholders with literals, right?
(turning @x into 1 after looking it up from the dict, for example)
In a nutshell yeah
but it's the standard pattern matching language
I might use that for replacing the placeholders, yeah. The expressions wouldn't generally be too complex or have too many named variables though, so this is not the main concern
regex is not meant for parsing on its own but may be useful to use if you create custom parsing
This looks pretty good, though my only concern is extensibility. It doesn't seem to have min and max, for example
I could always yoink the source code and make my own class, but I doubt unity is OK with that
Hello, hope you all are doing well. I'm doing some optimizations for my code, and I thought to update how my game saves objects by checking if a certain object in a list, because currently it does that for every single type of object
Thankfully, I thought it would be easy because they all use the same base class, I'll call it BaseObject (It contains position, rotational, scale data) in the code
Here's an example:
{
public int health = 100;
public bool kinematic = false;
}```
Here's the wrapper function that I'm going to use for each and every ``BaseObject`` derivative:
```public bool CheckPersistence(ref List<BaseObject> list, string objName){ //* code here *//}```
``Gameobject obj`` is a gameobject that is trying to save to the persistence class
``List<PhysicsObject> objects`` is a list that contains all the objects currently in persistence
``CheckPersistence(ref objects, obj.name)``
However, it is throwing me an error, that it cannot convert ``List<PhysicsObject>`` to ``List<BaseObject>``, but I wouldn't think it would be a problem because ``PhysicsObject`` derives from ``BaseObject``. Can someone please explain to me what is going on and how I could fix this?
Its possible on some types but not Lists without casting all elements and making a new instance
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/
I see
I did manage to do it but it was somewhat hacky, I created a new list that simply converts it to it's base class
thats going to copy the whole list so thats gonna be pretty shit
It seems that because IEnumerable defines its generic arg as out T it can therefore support covariance and allows this implicit cast.
It also doesn't seem to work past two objects
I'm a bit stumped on what I have to change to make this world
I guess I could go back to how it was before but
You can do a for each to check each element yourself. Casting to IEnumerable should work
Oh no, I guess I should actually show my code now that we're talking about the function itself; Sorry-
{
if (list.Count.Equals(0))
{
return -1;
}
List<AstroEngine_ObjBaseInfo> listConverted = list as List<AstroEngine_ObjBaseInfo>;
for (int i = 0; i < list.Count; i++)
{
Debug.Log(listConverted[i]);
if (listConverted[i] != null && listConverted[i].obj_name.Equals(objName))
{
return i;
}
}
return -1;
}```
(I changed it to return an int because I also needed to get an ID from it)
Let me try to convert each element
The as cast won't work so yea you need to cast or check each element yourself.
{
if (list.Count.Equals(0))
{
return -1;
}
for (int i = 0; i < list.Count; i++)
{
if ((list[i] as AstroEngine_ObjBaseInfo).obj_name.Equals(objName))
{
return i;
}
}
return -1;
}```
Here's what I have right now
Do (Type)var instead of an as cast as it will throw an exception if it fails
Or handle a null result from it
I've actually never done a handle expection beofre
By handle I mean account for it:
(Foo as Bar)?.Thing()
Thank you @echo coral
That's not going to make a difference
If a cast fails, it fails. as would be the safer option in general as instead of failing you'd have null returned over an exception, so you can gracefully handle it as specified above
Once Unity updates its base again (or probably when switching to CoreCLR), this pattern match can be done
for (int i = 0; i < list.Count; i++)
{
if (list[i] is AstroEngine_ObjBaseInfo info
&& info.obj_name.Equals(objName))
{
return i;
}
}
For now the same pattern match can be done, but the added assignment to info is not supported and hence kind of ruins the benefit of it since you'd still have to explicitly cast it
Would foreach (AstroEngine_ObjBaseInfo info in list)) work also?
I forget exactly how foreach behaves if you use a specific type on a collection that can have other types
With how it works, I need the ID of it, although I could also just... use an int index for it
Are you use it does not work ? Because I'm using pattern matching with the extra fields at multiple place.
Pretty sure it's not part of .NET Standard but I could be wrong
That looks like it should work tbh
Definitely worth a test
The syntax would be foreach(list.OfType<AstroEngine_ObjBaseInfo>()) {}
There's also foreach(list.Cast<AstroEngine_ObjBaseInfo>()) {} but this again does a hard cast rather than a pattern match so it's prone to the same issue
So yes OfType would be an even better idea since the whole type is filtered already, good catch
For reference, they are both very simple implementations: https://github.com/microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs#L1020
it works with unity 2021+ since it was part of c# 9
Yeah I'm often unsure if things are natively supported in .NET Standard
Then again it's really just anything at this point, and the rest can be with that library I forgot the name of
This one: https://github.com/Sergio0694/PolySharp
afaik it's easier to update the compiler than the whole framework so things that are purely language features not .NET versions are a lot easier to bring in from modern C#
I see many people use as to cast but not handle the potential null state. It would result in a null ref exception instead which is not actually describing the issue (an invalid cast)
If null is preferred for a failed cast then as should be used.
That's an issue with Unity not explicitly enabling nullabillity warnings. It would have helped a ton of these were enabled by default
Otherwise sure, but this is a preventable issue and you should make sure the type is correct beforehand anyway
throws are important to know if your game logic working properly or not, you don't want to hide them for all cases
I can't comment on the logic
For all I see it's a list of various types that are filtered then acted upon
Even then, there's [.Cast()](#archived-code-advanced message) if you have to worry of this. The logic should be adjusted to account for this way before it gets to this point if it should only contain 1 type. Not that it makes much sense unless they explicitly list a bunch of object types for some reason.
Looking back at this, one big glaring issue is that it's obvious the list is expected to contain AstroEngine_ObjBaseInfo instances, and otherwise the code can't act on it.
T should just have a generic constraint on AstroEngine_ObjBaseInfo here
No need for the whole casting then
Only issue is compile time errors in the event you pass a list of a different type, in which case you have to fix it, or use the aforementioned OfType/Cast here
Hi guys. I've created a wrapper for a native library. It works fine and compiles quickly using the Mono backend, but it takes around 40 minutes to compile with IL2CPP. My project basically contains only the wrapper code and an example usage. Does anyone have any general guidance on avoiding long compilation times when using IL2CPP?
The first il2cpp build would always take some time. The exact time would vary depending on the unity version, packages, project, hardware, etc...
Can you check if the consecutive builds take less time?
