#archived-code-advanced

1 messages · Page 120 of 1

edgy moth
#

NavMesh.SamplePosition can only be called on the main thread so I'm guessing there is no alternative to sample a point on the unity navmesh system in a burst job?

lament salmon
#

Man, they abandon all the cool features

#

Looks like NavMeshQuery.CreateLocation is the equivalent of SamplePosition

#

And MapLocation

edgy moth
#

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

lament salmon
#

There's RaycastCommand tho, if you need to do lost of casts

#

It's insanely cheap

edgy moth
#

Ty,

bleak citrus
#

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)

edgy moth
#

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

bleak citrus
#

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

lament salmon
#

It's not surprising that doing something in a batch is faster

honest bear
#

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

bleak citrus
#

I'll have to go profile it more carefully.

lament salmon
edgy moth
#

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

lament salmon
#

While raycastcommand's performance doesn't seem to change depending on hit or not

honest bear
crisp temple
honest bear
crisp temple
honest bear
#

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

nocturne ridge
#

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)

compact ingot
nocturne ridge
#

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

midnight violet
nocturne ridge
#

Ye maybe

midnight violet
#

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

nocturne ridge
#

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

midnight violet
#

Why is Navmesh not an option tho? as you talk about regenerating meshes, but you already have meshes, dont you?

nocturne ridge
#

I have no navmesh at all no

honest bear
# honest bear I ended up finding anyway, don't have the code on hand but I had to import a ren...

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)

midnight violet
#

You can generate it based on the level you have, dont you? Long time ago I played with navmesh tho

nocturne ridge
#

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

lament salmon
nocturne ridge
# nocturne ridge

but this will be very tedious for bigger maps, and any changes will require me to update some parts as well

midnight violet
#

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

nocturne ridge
#

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

lament salmon
nocturne ridge
#

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

lament salmon
#

Between meshes

#

Could also do a validation pass with RaycastCommand to check if connections are valid

nocturne ridge
#

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?

lament salmon
#

I mean how are you going to create connections that go from one mesh to another?

nocturne ridge
#

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)

lament salmon
lament salmon
nocturne ridge
lament salmon
#

You can also just do the merging right when you try to add a vertex

nocturne ridge
lament salmon
#

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

nocturne ridge
#

Hmm ye I see

#

Haha the cleanup seems intricate

#

but thx!

midnight violet
#

maybe you could combine navmesh for walls and floor with a custom generated one for ceilings too. Just throwing my 5 cents in here

nocturne ridge
#

Ye maybe, will look into it if I struggle too much

nocturne ridge
#

ok I think I got the first step down

#

did two different methods, one for box colliders and one for meshcolliders

next lake
#

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

nocturne ridge
#

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

lament salmon
compact ingot
lament salmon
compact ingot
#

recast graphs aim at creating 2D meshes but the idea is basically what you're trying to do

honest bear
#

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?

nocturne ridge
nocturne ridge
honest bear
upbeat path
honest bear
#

fair

nocturne ridge
grave lark
#

any resources for learning how to fuck with transform matrices?

#

(raw manip i mean, no Turn() procs or such)

echo coral
grave lark
nocturne ridge
#

Completed the neighbors attribution!

#

If there is no mistake everything should be very easy now. Thanks again everyone for the help.

grave lark
echo coral
#

you can skew with a matrix but for this you probably need to use a shader or modify the verts

regal lava
#

Those OpenGL tutorials probably as easy as it gets

#

get to it

#
nocturne ridge
midnight violet
sick flame
#

Hi all!
Really quick question: is there any ripper app which could extract the shaders from a shader assets file?

sick flame
upbeat path
#

We do not discuss such things on this server

undone coral
undone coral
#

maye message him and his crew

nocturne ridge
#

Turning it into A* for adding weights wouldn't be too hard anyway

somber swift
#

dijkstra does weights no problem, A* just adds the heuristic to guide the search towards the target faster

undone coral
undone coral
#

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

nocturne ridge
#

For now I won't really need it, I have everything working 👌🏼

undone coral
#

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?

coral citrus
#

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

https://pastebin.com/v6u3VvUG

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

#

the buggy case only has one platform fwiw, but the correct one on the right is multiple in the same area

undone coral
#

what is your big picture goal?

coral citrus
arctic lake
#

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?

midnight violet
undone coral
#

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?

coral citrus
#

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

undone coral
#

it's a little hard to see which one he's trying to use

undone coral
#

which is "more of a toy"

compact spoke
#

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

compact spoke
#

all my research is dead ends, something about rasterization or bounds, but things like modifying uv bounds doesn't seem to help so idk..

agile stream
#

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.

echo coral
#

its been so long since i used asset bundles manually but i dont remember what this manifest even does 🤔

midnight violet
#

Also looks like a temp manifest before exporting the actual bundle?

agile stream
tired stirrup
#

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?

sly grove
#

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

tired stirrup
#

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.
sly grove
#

which version of UNity are you using?

tired stirrup
#

2022.3.51f1 and 6000.0.34

sly grove
#

And why are you modifying manifest directly instead of just using the package manager "Add from git url": option?

tired stirrup
sly grove
sly grove
#

and it all seems fine

#

dumb question but - you have git installed right?

tired stirrup
sly grove
#

CoreTools works

#

I think maybe because: "com.nosirrahh.coretools": "1.0.0", isn't valid in the dependencies for AudioTools?

marsh echo
#

hello

sly grove
marsh echo
#

can anyonepls help me convert a vrm 0.0 to 1.0 file

thorn flintBOT
marsh echo
#

no

#

for desktopmate

sly grove
#

This is a Unity server

marsh echo
#

pls

#

and everyone doing it using unity engine and idk how to use it

sly grove
#

You're not in the right place

marsh echo
#

and could u help me find it?

sly grove
#

No, I don't know anything about DesktopMate

marsh echo
#

and do u know how to use unity engine ?

#

pls

echo coral
#

if its actually a unity question ask but if its "how to use vr char thingy" then go ask them

marsh echo
#

its not for vr chat

#

atleast i dont think theyre the same

sly grove
#

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

marsh echo
#

it was the first one i clicked one

#

ok

sly grove
#

GOod for you

#

this place has rules

tired stirrup
# sly grove Try updating this: https://github.com/nosirrahh/NosirrahhTools/blob/main/Assets/...

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.
echo coral
#

for a version/branch its git@github.com:foo/bar.git#branch_version_here

tired stirrup
echo coral
#

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.

tired stirrup
#

in local do you import the packages using the git url ou "from local file"?

echo coral
#

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)

tired stirrup
#

I will try this, thanks for the support!

short junco
#

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.

echo coral
#

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

short junco
#

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

echo coral
#

So you hope another job already did some work so you can skip it in this job?

short junco
#

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 😄

echo coral
#

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

short junco
#

letme snap my wrong algorithm version xd

short junco
#

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

short junco
#

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 😄

shut surge
#

Hey all, anyone got an estimate of what the per-call overhead for a Burst function would be?

untold moth
shut surge
untold moth
#

There's a chance that burst wouldn't do anything to your function though. You should check the docs for more details.

fresh tangle
#

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

terse inlet
#

I am unsure how it will play with unity's internal code gen for jobs and such though

compact spoke
hushed fable
#

@humble raven !collab and don't crosspost.

thorn flintBOT
#

: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

sly grove
#

Someone please walk me off the ledge of "prefabs are superior in almost every way to ScriptableObjects"

stuck onyx
#

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 🤔

compact ingot
stuck onyx
compact ingot
stuck onyx
#

I thought Rider or Unity project kept a cache.... ow... damn

compact ingot
#

they do, if you keep them open

#

but they can't do each other's caching

stuck onyx
#

Any way to increase the indexing speed?

compact ingot
stuck onyx
#

hahaha ok thanks 🙂

short blade
#

A bigger PC?

compact ingot
#

it should help a lot if you avoid dynamic asset changes

short blade
#

A faster disk would suffice, I'd guess.

stuck onyx
#

I'll try to be carefull on that, thanks Anikki

compact ingot
short blade
#

Very unlikely

compact ingot
#

look at the system monitor

stuck onyx
#

its a MAC from 2021 M1 with SSD , i think it might be indexing too many files

stuck onyx
#

I mean... i saw the progress and there were 17K files in inspection... wth I barely have 20 or 30 scripts

short blade
#

Assets perhaps?

stuck onyx
#

I guess is taking packages and plugins and everything

compact ingot
#

ofc it is

#

still, look at your system monitor, you will find its very CPU heavy

stuck onyx
#

next run ill try to cancel the auto-analysis and run it myself just in the folders i want

flint sage
#

Idk about you but the analysis I get is usually pretty short

novel plinth
regal lava
#

Unreal's a little special

novel plinth
#

UE is left-handed, it's just follow a different convention for z axis. z is up in ue

regal lava
#

Left-Handed, Y-up is by far superior

raven ruin
#

I've never understood why blender uses Z-up

#

it makes a lot of sense with all the other tools in the category

echo coral
#

I think for games its often so in 2d you can use x+y but i guess cinema 4d and unreal swapped

undone coral
#

z is forward index finger, y is up thumb, middle finger is x

novel plinth
#

3d artists love to lock their viewport based on certain XY axes when modeling

raven ruin
#

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

red jewel
#

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

undone coral
red jewel
undone coral
#

Such profiling would also track side effects of editor stuff, which might not even be interactive

#

Does that make sense

red jewel
#

yes, but i see this in the hierachy:

#

so it is in the playerloop

undone coral
#

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

undone coral
#

Yes unfortunately this stuff is hard to track down

undone coral
undone coral
#

There’s nothing special about Unity Jobs for solving problems. It’s just cooperative multitasking

red jewel
undone coral
regal olive
#

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
}
austere jewel
#

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

regal olive
midnight violet
#

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.

echo coral
#

Nah I'm on the events team for this

midnight violet
#

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

midnight violet
echo coral
#

With good design and by utilizing interfaces, inheritance and events you shouldn't need to do this weird reflection to call some function

midnight violet
echo coral
#

whatever spawns the UI can provide dependencies to it on creation

midnight violet
#

And how do I get the method in i want to call?

echo coral
#

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.

midnight violet
#

so write a single script for every button I want a specific behaviour?

echo coral
#

how much reflection does your UI need???

midnight violet
#

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.

echo coral
#

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

midnight violet
echo coral
# midnight violet I am still asking, how would you exactly do it. If you got the time, that would ...

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

midnight violet
echo coral
#

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

midnight violet
#

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 😄

old swallow
#

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)

echo coral
upper cape
#

guys can someone make a short tutorial about how to make a skilltree in unity

random dust
regal olive
midnight violet
regal olive
#

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

echo coral
#

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

midnight violet
#

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"

regal olive
#

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)

echo coral
#

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

regal olive
#

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

echo coral
#

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)

midnight violet
#

you can get a property "Instance" and return as an object

regal olive
# echo coral The Info objects you get when using reflection describe the method/field/propert...

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

echo coral
#

Use Awake if it should be earlier

regal olive
#

nah, spawned is 100% getting set to true, checking via the inspector

#

and the call to Toggle in this case happens after that

echo coral
#

Are you doing this on the new instance or accidentally on the prefab asset?

regal olive
#

probably on the prefab asset

echo coral
#

Because this won't suddenly break start() soo

regal olive
#

#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

echo coral
#

Drag flashlight in the UI down into it (drag the actual title bar in the inspector)

midnight violet
#

arent you invoking on a new instance with that code?

echo coral
#

That's what they want right?

regal olive
#

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

echo coral
#

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?

regal olive
#

I originally had it as mono behaviour but I attempted with UnityEngine.Object as well

echo coral
#

Do component or behaviour or mono

midnight violet
#

wait, _script is a monobehaviour file, right?

regal olive
#

yeah

midnight violet
#

so you call the method of a script dragged from a project folder?

echo coral
#

😐 plz dont tell me it was referencing the ASSET and not the mono instance on the prefab

regal olive
#

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

echo coral
#

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

midnight violet
#

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 ?

regal olive
#

yeah I saw someone suggest that earlier, haven't looked into it yet

midnight violet
#

just tostring the method name and pass in your stuff if its the same gameobject anyways

echo coral
#

I have never used send message but it will just do similar stuff but be slower

regal olive
#

in my case I also need to handle returning values

midnight violet
#

ah, okay

regal olive
midnight violet
#

So you want your method to be called and what happen on return?

echo coral
#

I have another radical idea... no reflection and use an interface 🤯

midnight violet
#

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

regal olive
#

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?

echo coral
#

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
}
sage radish
#

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.

livid kraken
#

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 ?

sage radish
livid kraken
#

Yes, but my profilling showed that skinning still happens without manually disabling the renderer

sage radish
livid kraken
#

Yep

#

Turns out that is for the bounding box 🤣

sage radish
echo coral
#

anything related to culling: only have the game window open and close scene as it can mess this up.

sage radish
#

I usually have a scene and game view side by side, I made sure to have only the game view for this test.

livid kraken
livid kraken
sage radish
#

I wonder if something else is causing the renderers to update.

midnight violet
#

Maybe its just a bug in that specific version

midnight violet
livid kraken
#

Im setting it manually in code

midnight violet
#

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?

livid kraken
#

Nope

livid kraken
sage radish
livid kraken
#

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.

livid kraken
#

Baked occlusion still works with the gpu occlusion

midnight violet
#

And npcs from previous scenes are not taken into account then?

livid kraken
livid kraken
#

Wait that might be. The npc’s that get spawned are spawned in the active scene….

#

And that is different from the level scene

midnight violet
sage radish
#

CullingGroup will use the baked occlusion culling from the active scene only, I assume.

livid kraken
#

Hmm but then again I have other culling groups in that level that work

#

Like for all the environment vfx

sage radish
midnight violet
#

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 🙂

echo coral
#

i swear unity has been soo shit with additive loading of stuff

livid kraken
#

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

midnight violet
#

"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

livid kraken
#

But if I load in another level they overlap wont that cause issues ?

midnight violet
#

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.

livid kraken
#

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

midnight violet
#

did you try bake both scenes at once and run your current setup?

livid kraken
#

Thats what I have been doing

midnight violet
#

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?

livid kraken
#

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

midnight violet
#

So if you throw all levels into the hierarchy view and built the occlusion map, it still breaks?

livid kraken
#

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

midnight violet
#

So main menu, gameplay and level 1 maybe? that is so try and error weird 😄

livid kraken
#

Fuck it Ill bake with all the scenes

midnight violet
#

Yeh, just test ALL at once and see what happens 😄 Thanks for researching , hehe

livid kraken
#

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

midnight violet
#

Thats so weird, that this does work tho 😄

livid kraken
#

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

midnight violet
#

Hm, unreal has it querks too. I am just wondering, your npcs instantiated, are they part of the main scene?

livid kraken
#

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

midnight violet
#

But somehow the occlusion map is bound to the active scene, as those npcs work. Thats weird

livid kraken
#

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

undone coral
# livid kraken Yes

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

livid kraken
#

No no the problem is for sure with the multi scene set up

undone coral
#

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

livid kraken
#

If everything is in one scene, occlusion gets baked for that then it works

#

It has nothing to do with the initial enabled state

undone coral
#

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

livid kraken
#

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

midnight violet
#

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

livid kraken
#

At the same time an environment vfx manager with it’s own culling group that is part of the level works as expected

undone coral
#

i mean, with unity's culling group implementation

midnight violet
#

As I lack the experience, how do you set the group. By script?

livid kraken
livid kraken
midnight violet
undone coral
#

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

midnight violet
#

Also they describe that you need to load your first scene of that occlusion group with single mode so it loads correctly (weird again)

livid kraken
#

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

midnight violet
#

I guess they had to give some example there 😂

livid kraken
#

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

sterile thunder
#

Distribute code as mods to android

pastel whale
#

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?

echo coral
#

Sounds like you already confirmed it?

pastel whale
# echo coral 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.

echo coral
sweet summit
#

Could someone critique my approach to a simple addressable model loader? (local, no remote data)

sweet summit
#

I didnt mean to post that question already 😅 , currently working on it

midnight violet
#

you know you can edit messages, right? 😄

pastel whale
# undone coral what is your goal?

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.

echo coral
pastel whale
# echo coral id guess this code gen is to aid in calling the exten c function (i also presume...

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)

sweet summit
# midnight violet where is it? 😄

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;
    }
}
echo coral
#

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

sweet summit
#

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

echo coral
#

give me a few mins to write something

sweet summit
#

np, I am trying to make it guaranteed load the last model you gave it

#

mine ignores new requests while its busy

rich olive
# echo coral To improve this i would make the load method async. You should also then use can...

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

echo coral
oak swan
#

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

echo coral
#

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

sweet summit
#

oh i see

lament salmon
echo coral
# sweet summit oh i see

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

lament salmon
oak swan
oak swan
#

i mean the script that the error is in has 4000 lines

#

so id say its advanced

lament salmon
echo coral
#

update to 2022 at a min but if you dont have any reason to stay on an old ver go to unity 6

oak swan
#

i dont feel like updating rn lowk

lament salmon
oak swan
#

alright ill try autosim

#

its for pausing the gaem

echo coral
oak swan
#

but ill consider it

lament salmon
#

You'd only need to update if you needed SimulationMode.Update

#

The other two are already available with the bool

echo coral
#

i liked win 7 too

oak swan
#

lol now i replaced it with autosimulation

#

but im getting an error that simulation mode doesnt exist on a line thats empty

tired fog
#

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?

oak swan
empty shell
#

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.

undone coral
empty shell
undone coral
#

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?

undone coral
#

i think it's worth looking at how the asset store assets work

#

they never modify the shape of a collider

empty shell
#

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.

empty shell
empty shell
#

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

undone coral
#

it's very arbitrary. maybe ask one of the asset developers how to achieve what you want

empty shell
#

I never wrote to any people who worked on assets on the Unity store.

undone coral
#

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?

halcyon flower
#

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?

whole stone
#

Look at your standalone logs

halcyon flower
#

you mean the build logs? that's where i saw that it doesn't get called

echo coral
mental hazel
#

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

▶ Play video
regal lava
#

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

mental hazel
#

Thank you! I will try and start from there to see what I can find

dusty wigeon
# mental hazel Hello, I do not know if this really advanced but definitely for me it is. I am t...

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

▶ Play video
#

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.

undone coral
livid kraken
#

Oh it was already posted lol

#

Nevermind

livid kraken
#
   {
       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

rare gale
#

- 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

somber swift
rare gale
#

- Game objects with mesh renderer + filter components

somber swift
#

But what are they? Buildings? Rocks? Trees? Grass?

rare gale
#

- 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

stuck plinth
#

if there's lots of identical objects, it sounds like they should be using batching or instancing, maybe your materials aren't allowing that?

somber swift
rare gale
livid kraken
#

draw them directly you do not need a mesh renderer

somber swift
rare gale
livid kraken
#

or yhou know pool your mesh renderers

rare gale
#

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

rare gale
somber swift
rare gale
#

- I see. Thanks!

livid kraken
#

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

somber swift
#

At least I cannot find any information on calling the Graphics api breaking SRP batching so I assume it should work just fine

livid kraken
#

there wont be any batching calling Render mesh

#

one call = 1 draw call

somber swift
livid kraken
#

I know what the srp batcher does

#

i just dont think that Graphics.DrawMesh goes trought the SRP batcher code path

bleak citrus
#

I wouldn't expect anything to work properly when you directly ask for a mesh to be rendered

livid kraken
#

then again a forum post from a unity dev says it should so

bleak citrus
#

Oh, I was mixing that up with DrawMeshNow, etc.

livid kraken
#

heh beat me to it

somber swift
#

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

livid kraken
#

I’m too deep in my own shit to give it a try right now

livid kraken
sage radish
livid kraken
#

Yes I get a log after it’s completed

sage radish
#

And are you causing the same explosion to happen when you are tracing as the one you see the stutter in?

livid kraken
#

Maybe it’s worth bumping to lates u6 but I was hoping to send a build out today

livid kraken
sage radish
#

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

livid kraken
#

It happens on a variety of objects. Some of which are just a mesh with a vfx shader

sage radish
#

It's probably shader compile, but good to confirm it before you spend a bunch of time on debugging this

livid kraken
#

But now I have not seen that specific marker, but I have not looked for it

bleak citrus
#

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?

sage radish
bleak citrus
#

Makes sense.

floral summit
undone coral
# floral summit

you can take a look at the articulations system, which supports real robotic arm / leg simulation

undone coral
#

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

livid kraken
#

I’m pretty sure the variant collection is just for what to include in the build it has no effect on the runtime compilation

livid kraken
#

I'm gonna version bump to 6.35 see if that helps

undone coral
#

is that sufficient?

#

are you trying to avoid runtime compilation altogether? or only runtime compilation while rendering frames?

livid kraken
#

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

undone coral
#

standby

undone coral
# livid kraken that would be sufficient but I do not think the shader variant collection will h...

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:

  1. Open the editor on Windows.
  2. 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.
  3. Vist the Graphics tab in Project Settings. Observe at the bottom, you should see "Currently tracked: X shaders, Y variants" or similar.
  4. Hit play.
  5. Play through all the content in your game, ensuring that all the shaders have been compiled and loaded. Be thorough.
  6. Click off play.
  7. In the Graphics tab, observe now a greater number of shaders and variants are tracked.
  8. Click the Save to assets button at the bottom of the Graphics tab.
  9. Drag and drop the saved shader variants asset into the preloaded shaders list in this tab.
  10. 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

livid kraken
undone coral
livid kraken
#

well yes

undone coral
#

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

livid kraken
#

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

undone coral
#

do you use any dx12 features like raytraced whatevers

livid kraken
#

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

undone coral
#

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

livid kraken
#

Well Im gonna give the collection a try after this build

#

Might as well

undone coral
#

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

livid kraken
#

If that doesnt work im gonna make then shader bootstrap scene

undone coral
#

yeah ultimately that's what the game did that used vfx graph objects

livid kraken
#

@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

untold sandal
#

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)

regal olive
#

Pretty sure youtube has a bunch of tutorials on drift mechs

jovial bough
#

yo in which channel should i ask question about build problems?

undone coral
#

you'll learn a lot more about this stuff from the package

#

especially if you don't know anything about cars

whole stone
#

If you run a RaycastCommand batch, the order of returned hits in the buffer is essentially random, right?

sly grove
#

In other words - seems like it respects the order of the command buffer

whole stone
#

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

livid kraken
undone coral
#

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

livid kraken
#

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

undone coral
#

and there's a meeting with 9 people

undone coral
#

it doesn't make any sense that you manage this manually

livid kraken
#

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

rough sky
#

Does anyone know how I might access the currently selected keyframes like in this asset?

#

It has to be reflection, right?

sly grove
rough sky
#

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

sly grove
#

I guess so

#

But also maybe it's part of the general Selection class?

untold sandal
undone coral
rough sky
#

I'll try it out though

#

thanks for your help

livid kraken
#

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

undone coral
#

i think the vfx graph might be compiled with something that is dependent on runtime in a way that doesn't reproduce well

obsidian frigate
#

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

sly grove
#

0 should only be a None flag

obsidian frigate
#

oh ok

#

will that fix the problem?

sly grove
#

idk

#

it might help

#

as of now it is always going to generate the up face

obsidian frigate
#

ill try it

#

it didnt fix the problem

white pulsar
#

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

sly grove
#

Everything you posted was type coercion and casting

white pulsar
#

ohh, so boxing is only related to value types

#

got it

echo coral
#

The concept of boxing is also used in rust by Box<> to have a heap allocated object owner on the stack.

bleak citrus
#

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

echo coral
#

You can use ref in out to avoid boxing for function args but these aren't async compatible

undone coral
bleak citrus
#

yes, that's a very important remark -- upcasting always works

#

downcasting does not

#

You generally don't need to upcast, of course

obsidian frigate
undone coral
obsidian frigate
#

but do you know why its not working?

undone coral
obsidian frigate
#

im trying to make a generated world like minecraft i wasnt looking for a tool to make models out of voxels

undone coral
obsidian frigate
#

the tool doesnt help with my problem of getting the mesh faces to generate

untold moth
thorn flintBOT
obsidian frigate
#

i think i fixed it for now

untold sandal
novel plinth
#
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 😄

onyx violet
#

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

stuck plinth
novel plinth
#

yeah, that's the terms 👍

undone coral
onyx violet
undone coral
#

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.

frozen imp
#

!warn 247793168056057857 don't post ChatGPT links here. If you can't bother to write down the answer then don't bother at all.

thorn flintBOT
#

dynoSuccess doctorpangloss has been warned.

undone coral
#

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.

frozen imp
undone coral
#

okay

frozen imp
undone coral
#

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

frozen imp
undone coral
#

there appears to be a few threads on this in server-feedback but i think it's sort of up to the company

plain abyss
#

!code

thorn flintBOT
visual dust
plain abyss
#

If only someone posted a message that called up a bot that says how to post large code blocks

visual dust
plain abyss
visual dust
plain abyss
#

You send the link

visual dust
#

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.

visual dust
hybrid belfry
#

Hi, is there a way to capture the Game View window whilst not being in play mode, as a Texture?

long ivy
hybrid belfry
long ivy
#

it works in non-play mode

#

is the game view focused and visible?

hybrid belfry
#

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);
grizzled cedar
#

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;
            }
        }
#

It's too sharp

compact vault
grizzled cedar
#

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

compact vault
#

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

grizzled cedar
#

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?

wicked coral
#

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
compact vault
frozen lintel
#

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

compact vault
#

"im asking a beginner question"

compact vault
frozen lintel
compact vault
#

sounds like you haven't configured your !ide

thorn flintBOT
jolly token
wicked coral
#

But i do

jolly token
wicked coral
#

To what

jolly token
#

Something that is not Type

#

Your code is using System.Type not your Type

wicked coral
#

Oh shi

jolly token
#

Also you should have any SO or MB in separate file

#

And that class name suppose to match with file name

thick shoal
#

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

wicked coral
wicked coral
jolly token
#

This isn’t advanced topic anyways

wanton siren
#

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:

wanton siren
#

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

slate nova
#

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?

sage radish
slate nova
#

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

sage radish
#

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.

barren scroll
#

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;
    }
}
echo coral
#

cast to NPCTownBehaviour and hopefully it works

novel wing
#

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?

echo coral
hybrid belfry
#

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);
    }
}
echo coral
echo coral
#

you can always sub in code and do this there

hybrid belfry
#

So a derived class is a way around it I guess

#

Yeah

echo coral
#

or yea have a sub class of button or some method in some mono somewhere to help

novel wing
#

the stacktrace seems to point to internal unity engine

novel wing
#

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

echo coral
#

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

novel wing
#

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

echo coral
#

or standard error

novel wing
#

yeah this seems to be editor specific behaviour btw. In builds it appears to work fine

echo coral
#

yea id expect that to get most things excluding native crashes

lament salmon
#

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.

cursive horizon
#

you'd have to sub in your variable values first probly

lament salmon
#

Doesn't seem to support named variables/placeholders but I could just replace them with literals first and then pass the string into that

worldly pecan
lament salmon
#

(turning @x into 1 after looking it up from the dict, for example)

worldly pecan
#

but it's the standard pattern matching language

lament salmon
#

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

echo coral
#

regex is not meant for parsing on its own but may be useful to use if you create custom parsing

lament salmon
#

I could always yoink the source code and make my own class, but I doubt unity is OK with that

charred drum
#

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?
charred drum
#

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

echo coral
#

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.

charred drum
#

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

echo coral
charred drum
#

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

echo coral
#

The as cast won't work so yea you need to cast or check each element yourself.

charred drum
#
{
    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

echo coral
#

Do (Type)var instead of an as cast as it will throw an exception if it fails

#

Or handle a null result from it

charred drum
#

I've actually never done a handle expection beofre

echo coral
#

By handle I mean account for it:
(Foo as Bar)?.Thing()

charred drum
#

Thank you @echo coral

random dust
#

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

lament salmon
#

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

charred drum
#

With how it works, I need the ID of it, although I could also just... use an int index for it

dusty wigeon
random dust
lament salmon
#

That looks like it should work tbh

random dust
#

Definitely worth a test

random dust
#

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

thin mesa
random dust
#

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

stuck plinth
#

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#

echo coral
random dust
#

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

novel plinth
#

throws are important to know if your game logic working properly or not, you don't want to hide them for all cases

random dust
#

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.

random dust
#

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

icy smelt
#

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?

untold moth