#archived-code-advanced

1 messages · Page 81 of 1

limpid prairie
#

The desktop version doesn't let you even reduce the size too much. Like, when you hold-drag the corner of the browser to reduce its width, at some point, it doesn't let you reduce any further.

But I think the UniWebView version doesn't even go this thin. It starts having problems even when bigger.

plush crane
#

Not sure if this is something that anyone here has experience with....

But does Unity 2020.3.48f1 (LTS) support Asynchronous GPU readback? I thought it should - but when using Android and OpenGLES3 I recieve an error stating that it does not support it. But I do not get this error when building with Unity 2021 (LTS)

Specifically I'm trying to make a call to AsyncGPUReadback.Request

For context - I am hoping to not to have to migrate to Unity 2021 and would prefer staying on 2020.

stuck plinth
radiant pasture
#

hey, I found a bug in openXR packet. I managed to fix it by forking the packet and fixing it locally. How can I submit the fix to Unity so they can fix it for the next update?
I really don't want local forks of packets because updating them is annoying.

round jay
#

Hello i have question does someone knows how to access a Hololens2 filebrowther in Unity ?

radiant pasture
#

they could have put all packages on git and we could do prs

marble forge
#

Hi there people, I'm experiencing a crash on startup in my standalone build on some machines. I couldn't grasp the log, so I would like your help to point me on the right direction here. The attached .rar has 3 Player.log files, from 3 different machines, 2 where the crash happened and one where it didn't for comparison. I also posted a thread on Unity forums with additional details:

https://forum.unity.com/threads/standalone-build-error-on-start-some-machines.1494164/

plush crane
plush crane
stuck plinth
#

guess maybe you could put in a different code path using ReadPixels for those builds...

plush crane
# stuck plinth i guess you're stuck targeting GLES3 and can't switch to vulkan? otherwise if it...

ReadPixels was actually the reason I swapped to using AsyncGPUReadback - it was soooooo slow. :(

Yes that's correct - I can't support Vulkan unfortunately. So might be forced to upgrade. I did manage to find https://github.com/yangrc1234/UnityOpenGLAsyncReadback this, but during my testing I will need to use Cmake to build a native android plugin.

Ty for all the help this has been very insightful!!

misty glade
#

Using unity's new input manager, how should I structure/dispatch events? I'm used to doing it the UGUI way, which is to raycast-capture IPointerX events on the component I care about (buttons, typically).

Should I be making some sort of input dispatch component that routes the input off to the correct code based on game state or something? This seems.. bad? It requires this dispatch component to be tightly coupled to like.. everything in the game.. and also manage state and so on.

What's your approach?

sage radish
plush crane
sage radish
#

But it'll probably depend on the specific device hardware and drivers.

plush crane
flint oxide
#

how do I completely disable frustum/occlusion culling?

#

seems like unticking it on the URP Camera does nothing

sly grove
misty glade
#

Yeah.. I was more wondering about the "send this event to this component" workflow since what I've come across so far doesn't seem to indicate this is a Thing - ie: https://stackoverflow.com/questions/70636241/unity3d-new-input-system-is-it-really-so-hard-to-stop-ui-clickthroughs-or-figu

#

I like making my UI components more or less self sufficient, and it .. didn't seem reasonable to write a UI dispatcher that would need to be aware of UI vs "world" input and send it (or not!) to the right place.. the new input system is probably not what I need.. although it does make "gameplay" input nice - using IPointerX handlers is clunky when you want to do things like double touch, pinch and zoom, gestures, finger/touch tracking etc

misty glade
#

Anyone have any brilliant ideas how to get a list of coordinates that a world space bounding box contains on a GridLayout? (for hex shaped tiles as shown in the video above)

I can get a grid's coordinates given a world position, but I can't think of a way to get all the hexes covered by a "box"

#

At first I was thinking I'd just grab the cell at each of the four corners of the bounding box (and everything in between), but that misses this case:

misty glade
#

Fuck it, I'm too dumb to try to figure out the math for whether or not a line intersects any part of the hex.

I'm just gonna grab lower left and upper right cartesian coordinates and assume everything inside is contained by the box. It works 95% of well.

crimson pumice
#

Is there a way for me to control the values that come out of Random?

For example, if I do InitState, I can set a seed. That is all fine and dandy.

However, the actual values that come out of the static properties (like Range(), or insideUnityCircle) only repeat based on times ran.

This seems completely arbitrary. I have zero control. Say I want to supply my own enumerator value, I simply cannot. It is literally just based on times ran.

Is there a solution to where I can take advantage of Random but mutate the result? So say I have a seed of 5230458 but I want use the value x = 24, I want to be able to get that same exact value if I input x = 24.

Think Minecraft seeds.

I want to use Random without having to come up with my own hashing method.

regal lava
#

Isnt that just hashing

sly grove
crimson pumice
#

Sure, but all of the properties and methods on Random are dependent on how many times they are called

sly grove
#

That's how Minecrafts prng works too

crimson pumice
#

So if I want to recall the values from the 1st time a property is called, I can't

sly grove
#

That's how all prngs work

sly grove
#

I'm not sure what the use case of that would be though

crimson pumice
#

So if I want to recall a value that is 100 times in, I need to recall InitState and then throw away 99 calls of the property?

sly grove
#

You call InitState, then you run your level generator

crimson pumice
#

That's the thing, I want to generate these on-the fly for an infinitely scaling world

#

I don't want to have to store a pre-gened massive array

sly grove
#

Then use that later

crimson pumice
#

Okay, so I have to pre-gen everything

#

I have no option to generate on-the-fly

sly grove
#

I just gave you said option

crimson pumice
#

I am confirming the option

sly grove
#

No

crimson pumice
#

But that doesn't make much sense given how Minecraft works. Minecraft can chunk-gen in one direction

#

Unless you're saying that Minecraft is generating a ton of empty chunks in a radius or something when you go in one direction?

#

The only option I have then, if I want to achieve my specific goal, is to create a custom Hash function

#

which I was trying to avoid because it's a bit complicated

sly grove
#

Minecraft world generation is based on noise functions. The noise function scale and offsets are randomly generated when the world is generated

#

After that it's just perlin or other noise

crimson pumice
#

I see

sly grove
#

And noise functions are NOT random

crimson pumice
#

I don't care too much about it being prefectly random, I care about it seeming random enough

sly grove
#

Yes that's what noise functions are for

crimson pumice
#

but that perlin noise example sounds a bit more like what I need so I might do that, idk. It kind of goes along with what I was trying to originally do which was find a function that gives me enough randomness to distribute objects in the world

#

Thanks for the insight

#

Also for context: It's part of a PS1 gamejam challenge for VRChat where we need to stay within super tight resource limits, and I had already created a grid system to move existing game objects.

So I was trying to cross reference the grid positions with a function to determine what objects to place in that grid tile, and I knew about minecraft seeds.

ancient talon
#

I'm still quite puzzle as to how exactly AndroidJavaClass and AndroidJavaObject works in general... When I created an object after referencing the class in .jar library, it somehow doesn't seem to recognize the code from the object, even though looking in the .jar file show method availability. I would run into NoSuchMethodError errors. (The method in question is not static, and can verify that the class constructor works...)

long ivy
#

naturally, that's going to be hard to help you with without seeing the code you're trying to use. Since you're seeing NoSuchMethod and not ClassNotFound, it sounds like something is wrong with the way you are calling the method

ionic ivy
#

If someone worked with video encoded with chapters, do you know if there are any additional steps you need to take to have faster seeking times between these timestamps in the video in Unity? (using AVPro, but that shouldn't make a difference)

jolly token
#

And sure legacy animation can do it too

rugged radish
#

does unity expose the number of its internal workers anywhere ?

#

at runtime

sly grove
rugged radish
sly grove
#

It's probably based on the current hardware or something

#

(assuming you're on windows)

rugged radish
#

thanks, so they don't expose it through their apis

#

i just need to get the number at runtime to use it in my own code

#

but looks like I need to deduce that number through other means

sly grove
#

what are you wanting to do with it?

rugged radish
#

generating data in chunks in background in my worker instances
workers allocate a bunch of persistent buffers, so there's no point in having more of those worker instances than unity's workers, it will just waste ram

rugged radish
#

yep, I used that before, just not sure how unity treats cpus with low perf cores, it can ignore them and only use high performance cores
so wanted to check if I can just ask the engine how much worker threads it spawns

#

cpus like 12 and 13 gen intel

sly grove
#

not as far as I know

primal knoll
#

rider trial expiring today, need to find my credit card Sadge

misty glade
#

I want to highlight a tile on a TileMap. How can I do this? I have a tilemap, but only see API for setting a single tile at a position with SetTile(). Is there a way to draw two tiles on top of each other? Or should I maybe make two grids, one that's empty most of the time and contains the "highlight" tile?

#

(the tile on the right is mostly transparent, I'd like to use that as a highlight outline thing)

sly grove
#

Lots of options

dusty wigeon
#

Second Tilemap is probably the easiest to implement.

misty glade
#

Yeah, second tilemap was the approach I went, will probably use multiples for various UI needs

#

Now I have another problem... IPointerMove doesn't seem to fire near the edges of the window... I'm 99% sure I don't have anything blocking the raycasts but.. this one's stumping me

#

Oh, I'm dumb. The ui capture GO wasn't stretched to the canvas 🤦‍♂️

#

a zillion things to do, but the UI is "functional" - select a unit, give it commands, interact with the map, etc.. It's always fun to start a new game

spiral fulcrum
#

G night all, its an planet, and de red lines is rays from center of planet to floor of planet... idont know why this rays dont casting to de down side, anyone can help?
The reason to cast on all sides is to spawn trees random on planet floor.

spiral fulcrum
#
    {
        if (treeList.Count > 1)
        {
            DestruirObjetosNaCamada(treeList[0].gameObject.layer);
        }

        for (int x = 0; x < gridSize; x++)
        {
            for (int y = 0; y < gridSize; y++)
            {

                Vector3 samplePoint = GetPointOnSphere(x, y, gridSize);
                Ray ray = new Ray(samplePoint + Vector3.up * (planetRadius - 360f), Vector3.down);
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit, planetRadius * 2))
                {
                    Vector3 rayDirection = ray.direction;
                    Vector3 hitNormal = hit.normal;

                    if (hit.transform.name.ToString() == "Starter")
                    {
                        Vector3 spawnPosition = hit.point;
                        origin = hitNormal;
                        target = hit.point;

                        Vector3Pair pair1 = new Vector3Pair(origin, target);
                        listaDePares.Add(pair1);

                        float elevation = Vector3.Distance(spawnPosition, transform.position) - planetRadius;

                        if (elevation >= minHeight && elevation <= maxHeight)
                        {
                            Quaternion spawnRotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
                            GameObject tree = Instantiate(treePrefab, spawnPosition, spawnRotation);
                            tree.transform.up = hit.normal;
                            //tree.transform.parent = transform;

                            treeList.Add(tree);
                        }
                    }
                }
            }
        }
    }```
spiral fulcrum
#

some of noob and ugly code hehe, but is only things im testing

sly grove
#

also I don't see the code here that ctually draws the red lines

spiral fulcrum
#

i will put all class code minute

sly grove
spiral fulcrum
#

´´´private void OnDrawGizmos()
{
foreach (var coord in listaDePares)
{
Gizmos.color = Color.red;
Gizmos.DrawLine(coord.origin, coord.target);
}
}´´´

#

ops

#

lol

sly grove
#

origin = hitNormal;
You're also treating the normal s if it's a position? Normals are direction vectors, not positions

#

there's a lot of issues with this code.

spiral fulcrum
#

this hitNormal is hit.normal (i think its where from ray start, right ?)

sly grove
#

the normal is not where the ray starts, no

#

that would be ray.origin

#

The normal is the normal vector of the surface where the ray hit

spiral fulcrum
#

its explain why im get errors hehe

#

ive changed to ray.origin

#

and here is the problem hehe

#

really thanks man

sly grove
#

yep that looks like what your code is doing

#

all the rays are going straight down

#

not sure what you are intending to do

spiral fulcrum
#

im trying to send rays from center of planet to a floor of planet... in point ray hit iwill spawn an tree

sly grove
#

wouldn't you need to send rays from outside the planet towards the center?

#

colliders generally don't work from inside. Is this a mesh collider?

regal lava
#

Could just get vertex info of those of a certain radius from the middle

sly grove
#

I'd basically pick random points on a sphere larger than the planet (with the same center) and raycast towards the center of the planet

sly grove
#

yeah you'd have to raycast from outside, not from the center

spiral fulcrum
sly grove
#

I don't know anything about any oceans

#

if you have an ocean height, sure just ignore any that end up at an altitude less than the ocean height

umbral trail
#

is there any way to get the number of materials on a MeshRenderer without allocating an array of materials?

umbral trail
#

I don't want the materials at all

sly grove
#

there is no materialCount property, no

umbral trail
#

I guess using a list would keep the garbage to a minimum, thanks

jolly token
stoic peak
#

How do I convert a normal c# async method to use UniTask? Do I just change the return type from Task<T> to UniTask<T>? My method calls an async method from another library that returns a Task

untold moth
mellow sail
#

does anyone ever use notion API in Unity?

dusk plaza
stuck onyx
#

anybody knows why such a straightforward command like" Screen.SetResolution(x,y, true) is not changing my resolution at all?

compact ingot
stuck onyx
#

and im using:

#

Screen.SetResolution(Screen.width/x ,Screen.height/x ,true);

#

to be sure the ratio is the same

compact ingot
#

you cant set exclusive fullscreen on mobile

#

Exclusive full-screen mode is only supported on Windows standalone player.

stuck onyx
#

ow, so i shall do the same but with false?

compact ingot
#

idk, i would expect mobile to be somewhat particular about what is allowed though

stuck onyx
#

I've read also in forums the fullscreen toggle had to be disabled in playersettings but the alternative is this:

#

and doest make too much sense to set windowed for a mobile device 😅

compact ingot
#

all mobile apps run in an equivalent of "fullscreen window"

#

but ofc thats defined by the OS

stuck onyx
#

gonna try the command without the fullscren flag

#

thanks a lot @compact ingot

sweet cedar
#

so I locked my mind into a particular save system but now I'm having some issues and need help figuring those out

#

I suppose I was too strongly influenced by untyped languages and now it's conflicting with c#

#

the idea is that classes that have persistent data pass a copy of their values to a central savedata object that then gets serialized to disk

#

easy enough to do with untyped, just need to declare each variable once in the main class then assign it to a unique key in the savedata object

#

but when typed, I now realize the problematic of having to declare each save entry twice, while sometimes even having to create doubles of some classes just to make them serializable...

#

is there some way I can do this in c#? to just toss whatever type into an object that gets serialized by json in a neat way?

sly grove
#

as long as you follow those rules, your struct can be serialized neatly

#

usually you can shape your object in a way that it's usable both at runtime and for serialization without too much fuss

#

occasionally you might need a little "glue", especially when it comes to having performant runtime data structures that don't translate well into efficient storage structures

sweet cedar
#

so if I get you right, instead of separating all game logic and persistent data logic, just make all game logic classes serializable directly?

languid spire
#

i wrote a shader a few months ago to occlude object behind it. works great on gameobjects . . . but, ignores terrain. any ideas of what I should google to figure out why.

untold moth
real blaze
# sweet cedar so if I get you right, instead of separating all game logic and persistent data ...

a bit more complicated than that. what you seem to be referring to is commonly known as snapshot of objects, and that's both expensive and pretty unstable. I can tell you why if you needed to.

for your problem, you can just make a serializable data for your object and use that as the saving data. with some initialisation method you can give logic classes a chance to boot themselves up based on these data. There are tons of ways to achieve this. also feel free to ask for more details

languid spire
#

@untold moth i left out an important detail. it invisibly occludes, so with pass through ar, it hides virtual objects behind it, while still showing the real world

#

i put it on walls in ar passthrough, so you see the real walls, and it hides virtual objects behind it

#

i got it working last night 🙂 thanks for the follow up question

#

this may not seem like it, but its the followup question:
I'm working with Meta scene data. I can get a collection of verts that make up the outside edge of a floor. Anyone have a function laying around, that will build the mesh with them, and have correct normals. I've had trouble drawing the tri's when i've tried more complex dynamic mesh generation before. They use a plane by default for the ground, that overextends past the walls, and that breaks what i'm going for

mellow sail
#

Excuse me, does anyone ever use the Notion API with unity?

spiral fulcrum
true coyote
#

I am generating my terrain procedurally but at the moment it just looks like a slice / layer of terrain, and what I am looking for is to have the terrain look more like a cheese slice instead (basically I want it to be volumetric and to have thickness).

Let's tackle this like I am 5, and call this terrain chunk a cubical room, and this cubical room is let's say for the sake of this scenario 4x4. It has air above and ground bellow, represented by 1s and 0s. Where we have 0s, that's where the air is, where we have 1s, that's where the ground it. Somewhere in the middle of these two values (ISO level) is where these values meet and that is where the "surface" of the terrain is created, but ideally bellow this surface I want to have ground. Currently in my case, bellow this surface level there is nothing.

So, back to the explain like I'm 5 scenario, this terrain chunk is a room, and I want this room (the terrain chunk) to have:

  • A Ceiling (the surface), and the level at which this ceiling is mounted is decided by the ISO value and the ground level.
  • Walls, that start from bellow the ceiling/surface and go down all the way to the base of the room (the edges of the chunk).

Currently__ I did manage to have a surface (ceiling) for the "room"__, but I don't know how to make the room have walls and ground bellow the surface. I am using marching cubes.

Marching Cubes Shader Code: https://pastebin.com/VWVLuki5
Noise Compute Shader Code: https://pastebin.com/EHYQj1Vr
Noise Generator Script: https://pastebin.com/ZsZTA1Hu
Chunk Mesh Script: https://pastebin.com/7CG3EwyF

What I'm looking for (but ignore the blocky-look): https://ibb.co/GnhVd2V

I am attaching a photo bellow with how my terrain looks right now (first photo) and how it's supposed to look under the surface (the other 2 photos).

If anyone can have a look at my scripts and tell me what I am doing wrong or what I need to do please let me know.

misty glade
#

I'm getting erratic behaviour when I try to destroy a game object from OnComplete() in DOTween. Docs don't say anything about this. Anyone know anything about this?
Edit: Nevermind, error elsewhere.

dusty wigeon
#

My advice would be to isolate your issue and try to generate exactly that in 3D. If you arent able, take a step at a time an try to generate 1 cube, then 2 cubes. At some point, you are going to be able to generate what you want. From there, implementing it in the actually game will be easier.

true coyote
# dusty wigeon Pretty sure that Cube Marching should already be able to generate cave. If it is...

I've made a diagram with my current situation. So the issue at hand right now isn't that I don't have caves, what I'm trying to figure out is why I don't have solid ground beneath the terrain and been trying to add more noise but it messes up the mesh. I don't get it, it should be as simply as saying anything bellow surface (iso) level is 1, therefore fill it up with ground, everything above the surface is 0, therefore air, therefore don't generate anything there.

So before getting to caves, I'm just trying to understand how I can have it like in the 2nd version where I have terrain and ground and the rest of the chunk is air. Currently I'm in the first version, where there is air above and bellow surface level and I don't understand how to fix that first. I've played with the ISO level, with the noise values and the only thing I managed is to have the terrain spawn lower or upper across the verticality of the chunk, but can't seem to fill it bellow surface level. Basically all I've managed to accomplish was lowering the surface level or setting it higher, which is not what I want. Again, 2nd version in the diagram should explain things more clearly.

#

Or is this only possible if you use cubical voxels like minecraft ? Is there an issue with the Marching Cubes algorithm where when you smooth out the voxels you can't have solid terrain underneath anymore ?

#

For example in minecraft, the chunk is actually solid. Caves are not even generated initially, they are gerated later down in the octane tree. As in, they don't only generate the surface, they generate the ground as well, which is solid, no caves. Caves are carved later.

I can't even generate a solid chunk so I'm not even thinking about caves at the moment until I solve this issue first.

dusty wigeon
dusty wigeon
true coyote
#

Then do you know what do I need to change in my alogrithm to have underground cause at the moment it refuses to do so, it just moves the surface up and down across the y axis ?

#

And because there is no underground, when I dig, the ground ends.

dusty wigeon
true coyote
dusty wigeon
dusty wigeon
true coyote
dusty wigeon
#

Here are 3 solutions

#

1- Add a hard ground under the level. (Not really what I would do)
2- Add dynamic chunk generation for digging. (Definitely more challenging and demanding - Ask yourself how much deep digging is important in your game)
3 - Limit the digging (Definitely the most scalable solution and easiest solution)

#

And, if you want what Minecraft does, then Cube Marching is not the way.

true coyote
dusty wigeon
true coyote
#

As you dig down more chunks generate.

#

Yes but because I don't have my chunks solid I cannot do that, which is what I'm trying to solve here.

#

At the moment if I layer chunks vertically it would make no sense cause they would look like paper slices.

dusty wigeon
true coyote
#

Wait, do you mean that if I add vertical chunks they would automatically connect with the other chunks therefore making the terrain solid ?

austere jewel
#

Below the ground is considered solid by the data, there doesn't need to be any geo to show that.
For example with minecraft there wouldn't be vertical walls if you did a cutaway of a chunk like your above pics. The vertical walls only exist because they're putting them there, presumably because there's empty space next to the chunk

dusty wigeon
true coyote
#

Wouldn't this happen if I tried layering the chunks vertically as I have thme right now ?

#

Ignore the chunk 1, it's supposed to be a slice as well.

dusty wigeon
austere jewel
#

It's far below the y height of the ground, so why would you generate the ground surface there

dusty wigeon
true coyote
true coyote
austere jewel
#

If the ground's y height isn't in the chunk then they're shouldn't be a ground generated there. The same goes for the chunks that exist in the sky, if something is totally air or totally ground then there should be no geo

true coyote
#

But in my case currently it generates air bellow the iso level even though it should generate ground. It only seems to generate terrain data between the 0 and 1 at iso level, but nothing bellow it, therefore air. That's what it doesn't make sense to me.

#

See, nothing bellow the terrain layer.

dusty wigeon
#

If you fill the whole things with white dots, it wouldnt generate anything till you make a dot black.

true coyote
#

Then how comes the black dots are empty as well in the example, (above ground) ?

#

There something I don't understand here, which you guys obviously do.

dusty wigeon
true coyote
# dusty wigeon Cube Marching generate a mesh for the transition between black and white dots.

Good. And what if I want to generate stuff bellow the black dots/white dots. I just like to say black dots are 1 therefore ground, white dots are 0, therefore air. Iso level = 0.5, therefore generate terrain in the middle, but make sure to fill underneath as well, because everything bellow iso level is considered ground/black dots. Like isn't that how it's supposed to work ?

dusty wigeon
true coyote
#

I'll be right back with the results.

dusty wigeon
#

It is hard to be more explicit then this.

true coyote
# dusty wigeon

Unfortunately it looks like I was right, the result is exactly what i thought it will happen, told you guys.

dusty wigeon
dusty wigeon
#

Do it with two

true coyote
#

M1 melting 😆 hold on

true coyote
dusty wigeon
true coyote
#

The first one (left)

dusty wigeon
#

You want the right one

#

It just means that you have to change every points under to a red one

true coyote
dusty wigeon
#

It really encapsulate what Cube Marching is.

#

However, in both case you see the issue. You need red, not blue under

true coyote
#

As in, in which one of the scripts do I have to look for the issue ?

dusty wigeon
#

Just look at the correspondence between the pattern.

true coyote
#

Ah, I think I get it now. The blue dots represent the ground, not the red dots.

true coyote
#

Ah, nope. Actually, red is indeed ground. So basically back to square 1, ground isn't solid where it should be.

true coyote
true coyote
#

💡 I think I just got an insight. I was looking at this from the wrong perspective, because I was missunderstanding what I am seeing. The blue dots do not represent "empty space" and the red dots do not represent "ground space", and the level of blue / red dots (the horizontal line which splits the two across the chunk) is actually the ISO level. If I increase the ISO level for example, I see more red dots than blue, but that doesn't mean now there should be more gound, it just means the weights have different values, either tending more towards negative either towards positive. That is what I think it's actually represented here.

So, in conclusion, this means that there is no issue with the way the terrain is generated, it generates like the code tells it to. The issue is me, I do not understand how the code or the algorithm works exactly, and I am just starting to get a bit of grasp. I guess unless someone takes their time to look a bit into my scripts I will not be able to solve this one until I figure out the rest of the puzzle as well. It's a slow and painful process but at least I'm making progress, even if it's very slow.

zenith osprey
#

Hey! I'm reaching out to the community here after spending hours despairing over Unity Physics. Maybe there is an expert on mesh colliders here.

The following setup: I want to move a cube (box collider) through a dynamically generated voxel game world. I move the rigidbody of the cube physics-based, causing it to rub across the collision surface. In the first version, I had created mesh colliders for my voxel world based on the visual meshes. Accordingly, there were chunks and different mesh colliders in the world. The problem was that the cube got stuck in the edges between different mesh colliders, apprubtly changing the velocity.

To solve the problem, a single mesh collider is now generated around the cube and updated regularly (see video). As you can see in the video, with a small probability it still gets stuck between the triangles of the meshcollider and changes direction. I am walking straight to the left in the video, but bounce of the wall. The video is x0.25 for better understanding. The movement should be as deterministic as possible, which is why such behavior is unacceptable. Does anyone have an idea how I could solve this problem?

#

Here is also another video looking more from the top.

The Cube RigidBody is already set to: Interpolate, Continous Dynamic.
Physics Settings: Bounce Threshold 2, Sleep Threshold 0.005, Default Contact Offset 0.05, Solver Iterations 8
MeshCollider: No Rigidbody, but the generated mesh has Mesh Cleaning and Weld Colocated Vertices enabled

clever urchin
#

@zenith osprey Tried changing your physics precision?

#

In project settings somewhere

zenith osprey
#

Probably yes, I played around and increased all physics settings based on the docs

clever urchin
#

Default contact offset

#

Set to like 0.0001

zenith osprey
#

I don't understand why I didn't stay on these settings earlier. At first it seems to do the trick. I think for now this solves my problem until other issues occure.
One more aspect I can think of in the future is, that I want performance sparing values for a later mobile port.

I just got another idea as a last resort in case of problems. Do I understand it correctly that I can also filter the occurring velocity changes caused by overlapping? Since I have access to the voxel data, it's relatively easy to see where I'm bouncing off a smooth surface where that shouldn't be happening.
https://docs.unity3d.com/Packages/com.unity.physics@0.3/manual/collision_queries.html

#

Damn, I remember why this is not an option 😄
A low value improves the collision with the walls, but breaks the collisions of several cubes with each other. As the docs also say, the collision becomes jittery. I can probably find a sweet spot by minimizing both problems. But a really reliable working solution would be better. (Video at 0.5x)

mellow sail
#

does anybody know how to request API post with unity?

zenith osprey
mellow sail
#

its driving me crazy with this Notion API, the syntax is correct but it keeps resulting bad request 400

sly grove
#

400 just means the request is invalid it doesn't necessarily mean a syntax error

mellow sail
#

Yeah, i already fixed it. The learning postman web is a live saver. I just found out there's a loop mistake in my code when requesting

#

But it's still c#, i think im going to migrate it to use unitywebrequest

random shell
#

Hello,
I'm facing a problem and I'm hoping someone can help me out. Here's the situation:

  • Blue Arrow: Represents the transform's local forward vector.
  • Red Arrow: Represents the camera's look direction with y = 0.
  • Red dot: Represents the point towards which the transform should rotate.

I want the transform to rotate towards the red dot based on the movement input. For example, if the transform wants to move forward, I want the blue arrow to rotate towards the red arrow.To achieve this, I'm looking for guidance on how to calculate the rotation angle between the blue and red arrows. Additionally, if the transform wants to move downwards, I would like to know how to rotate the blue arrow in the opposite direction of the red arrow.Any help or suggestions would be greatly appreciated. Thank you!Please note that I'm seeking advice on the implementation details, so if you have any specific code examples or resources, that would be fantastic.Thank you in advance for your assistance!

devout coyote
#

Set the world rotation of the blue to the rotation value from your camera, if you need to inverse it, you can multiply it by a quaternion created from a rotation of 180 on the by you specified axis, although there is probably a utility method for this

sly grove
oblique lake
#

While my old way worked, it was giving me wacky values when I zeroed out the stick which I didn't want.

tiny pewter
#

to who delete his question
i think this is nearly impossible to solve unless you raycast from all points to all points in another Mesh (btw float is discrete so you can do this unlike real world) since every point has its own "sphere space" (idk how to explain it but you can imagine Celestial sphere), and it means no any universal mapping (to 2D space) can apply to the target mesh
i simply the 3d case a lot to 2d case (here is 2d to 2d point mapping)

#

i maybe wrong there maybe some transformations

rapid osprey
# tiny pewter to who delete his question i think this is nearly impossible to solve unless you...

Sorry I thought my question was just too low quality (didn't have enough info). As you said, the number of raycast needed is crazy and I can't really reduce the amount because of edge case like these where partial part of the model is obfuscate.

Someone proposed checking the pixel inside a stencil buffer instead of ray casting. I would check on ~5 points in different angles and it should work on most case. Since the game is turn based even if it is expensive I can spread the work on multiple frames and recalculate once in a while.

hazy bear
#

I need to create exact copy of UnityEvent instance and tbh idk what to put in that method, propably some reflections which is always tricky to me

            var newEvent = new UnityEvent();
            for(int i = 0; i<Event.GetPersistentEventCount(); i++)
            {
                var target = Event.GetPersistentTarget(i);
                var method = Event.GetPersistentMethodName(i);
                var mode = Event.GetPersistentListenerState(i);
                newEvent.AddListener(); //It takes UnityAction which is some sort of delegate
                newEvent.SetPersistentListenerState(i, mode);
            }

Any help?

dusty wigeon
hollow plinth
#

Compute Shader Multithreading Question.
I tried to do my own research for this, but I can't seem to find the right keywords to use.
I'm still not very knowledgeable with both Compute shader and Multithreading, my current concerns is stuck in my head and preventing me from progressing.
I want to create a simulation of battles millions of times, where every 9 consecutive normal battle wins, the next battle is a boss battle. Is this possible to do in Multithreading?

untold moth
# hollow plinth Compute Shader Multithreading Question. I tried to do my own research for this, ...

It's possible to do without multithreading too.

Multithreading implies running several threads that execute code in parallel, so you can increase the speed of something being processed if it needs to do a lot of the same logic.
That being said, most unity API can only be used on the main thread, so your simulation would need to be implemented without relying on unity.
Also note, that there are many pitfalls with multithreading, like race conditions.

#

As for compute shaders, they are similar to multithreading in the sense that there is a simple program that runs in parallel on many many small processing units. The difference is that it runs on a different device - GPU, so there are many restrictions imposed.

tired basin
#

i'm facing an issue with UnityWebRequest, i was using Unity 2021.3.15 before and content downloading for me was working fine, but after i upgraded to 2021.3.30, the same batches of WebRequests are getting time out errors. i can reduce the batch size but that makes the initial loading slow. but the catch is why this is causing issue on upgraded Unity, can anyone help me here

dusky kettle
#

hey guys im putting this here cos the math here is messing with my brain a little and i'm a little lost. I'm trying to create a system to roll a ball along a flat plane, but with a controlled outcome.
the part that I'm stuck on is i'm trying to create a function that will take in a starting position, ending position, ending rotation, and a radius, and return a quaternion representing the starting rotation that the ball would need to be at to roll without slipping or skipping and end at the ending rotation.
I was actually using chatgpt to help me with this because i'm pretty hopeless with this kind of math, and I got a pretty usable answer. this is what i've got at the moment:

public static Quaternion CalculateStartingRotation(Vector3 startPosition, Vector3 endPosition, Quaternion endRotation, float ballRadius)
{
    // Step 1: Determine how many revolutions the ball needs to make
    float distance = Vector3.Distance(startPosition, endPosition);
    float circumference = 2 * Mathf.PI * ballRadius;
    float revolutions = distance / circumference;

    Debug.Log(revolutions); //I added this to debug, this wasn't chatgpt's doing

    // Step 2: Determine the direction that the ball will rotate
    Vector3 direction = endPosition - startPosition;
    Vector3 axisOfRotation = Vector3.Cross(Vector3.up, direction).normalized;
    if (Vector3.Dot(Vector3.up, direction) < 0)
    {
        axisOfRotation *= -1; // Reverse the axis if needed
    }

    // Step 3: Determine the starting rotation
    Quaternion startingRotation = Quaternion.AngleAxis(revolutions * 360f, axisOfRotation) * endRotation;

    return startingRotation;
}```
This code will give me a rotation that rotates in the correct direction, but the amount of revolutions seems to be messed up. I tried it with some parameters where the debug.log outputted 0.8 and it somewhat looked okay, but then i tried it with around 2.2 revolutions and it rotated in opposite direction, less than 1 time.
does anybody know how I can fix this? do quaternions store revolution counts at all, or would I need to use eulerangles or something? i'm kinda at a loss
dusky kettle
#

interesting, i fed it parameters with a distance equal to the circumference so that the revolution was equal to 1 and the ball didnt rotate at all

#

yeah i cant figure out how to get it to return a rotation that doesn't wrap

#

which sucks cos im using dotween and id imagine that means theres no way to get dotween to rotate more than one full revolution

upbeat path
#

logically you should be tweening on revolutions

#

or on start and end positions

dusky kettle
#

what

dusky kettle
#

lmfao

#

i found something on google taht says its possible to do DORotate that takes eulerangles beyond 360

#

im wrangling with chatgpt to see if i can get it to understand what I now need but its frustratingly bad at doing things i'm bad at

upbeat path
#

tweening goes from 0 (start) to 1(complete). if you want revolutions to go from 0 to 2,2 for example then that is what you should be tweening on
likewise goes from start to end positions

dusky kettle
#

are you talking like literally with dotween

#

or just the concept of tweening

#

for something so seemingly simple im shocked that literally 0 solutions exist for this online from what ive found

upbeat path
#

why would there be a solution online for something simple?

#

and yes I'm talking about tweening in general

#

@dusky kettle How are you actually moving your ball?

dusky kettle
#

do you know of dotween

#

cos im using that

#

the use case is im trying to create a sorta scripted thing with a ball that has a face on it

#

i need the face to end facing a certain way

#

the way the ball moves is by rolling

upbeat path
#

?
If you're tweening the Quaternion how is that converted into movement?

dusky kettle
#

dont worry about that part

#

im just doing a second tween at the same time

#

thats not part of it anyways

#

right now the part i cant figure out is how to figure out that starting rotation and how to get it to rotate accurately

#

im just trying to script a ball rolling in a way that allows me to control the final position, rotation, and initial position

#

without accounting for anything that would complicate it like ramps or drops or whatever

upbeat path
#

Look it should be simple.

  1. Set the start rotation from your start, end and end rotation
  2. Tween between start and end positions
  3. for each tween calculate current rotation based on distance traveled
dusky kettle
#

lmfao dude i know

#

thats the easy part

#

my problem was never the tween

#

ignore the tween part

#

the calculate part is what isnt working

#

thats the part that isnt simple

upbeat path
#

your problem is you are tweening the quatenion when you dont need to

dusky kettle
#

you're misunderstanding the situation

#

i need the ball to end at a rotation I need it to be at

#

the end rotation needs to be predetermined

upbeat path
#

yes

#

yes

dusky kettle
#

the start rotation needs to be backwards-engineered from that

upbeat path
#

yes

dusky kettle
upbeat path
#

so what have I misunderstood?

dusky kettle
#

and is not the problem

#

because atm my issue is that i dont have a functional way of determining what the starting rotation is

upbeat path
#

yes you do, the math given by Gpt looks ok to me

dusky kettle
#

its not

#

ive been testing it lmao

#

the axis is correct

#

but its not giving me a rotation that works

#

unless im mistaken, quaternions dont store rotations above 360 degrees in magnitude

#

they just wrap around

upbeat path
#

Ah, so quaternons dont work the way you want them to, my solution negates that problem

dusky kettle
#

you're going to need to give me an example mate cos im really not following what your solution is

upbeat path
#

OK,
Say we have a distance of 1 circumference
So the ball needs to rotate 360 degrees
If you tween between 0 and 1 for each step you calculate the rotation over that distance, then you apply that to your ball

dusky kettle
#

yeah nah but thats not solving the problem

#

the problem is I don't know if the ball needs to rotate 360 degrees

#

because the thing isn't calculating that properly

#

like sure i can get the revolutions

upbeat path
#

that was just an example, it will work for any distance

dusky kettle
#

but it's not returning it in terms of the axis it needs to rotate around

#

okay this is just going in circles rn

dusky kettle
#

does anybody know how I might be able to get a change in rotation based on a starting position, ending position, ending rotation, and ball circumference, given that the ball is rolling without slipping on a flat plane

upbeat path
#

Ah, I see your point, what you need is to a return an array of Rotations where each entry is 1 full turn of the ball

dusky kettle
#

thats an extremely janky solution dude

#

it would be a lot better to just return one vector3 with numbers that exceed 360 in magnitude

upbeat path
#

no, it's a game dev solution

dusky kettle
#

brother what are you on about

upbeat path
#

it's one that
A) Works
b) is easy to implement

dusky kettle
#

look if you wanna try solve it yourself taht way, be my guest, but I am not doing it your way, and taht also still has absolutely nothing to do with the problem here

#

ijust need help calculating those numbers in the first place

#

not figuring out a data type to return the result

upbeat path
#

best of luck with that, considering you had to use GPT in the first place, bye

dusky kettle
#

😐

dusky kettle
untold moth
dusky kettle
#

reverse engineer it from the start position, end position, end rotation, and ball circumference, assuming the plane is completely flat

#

im essentially trying to animate a ball that rolls lmao

untold moth
dusky kettle
#

the thing is im not using rigidbody at all

untold moth
#

Who said anything about rb?

dusky kettle
#

i can if necessary

#

oh so you just mean like

#

hmm okay

#

i am using tweening libraries tho

#

so the trajectory isnt constant

#

the point is that im not trying to calculate it based on something that happened, rather trying to make it happen so that it ends exactly as I need it to

untold moth
#

If it isn't, then you'll have to keep track of all the velocity changes.

dusky kettle
#

do I?

#

if it takes the shortest available path from a to b

#

the rotation of the ball should never change

#

rather

#

the rotation over the path should never vary

#

assuming the ball never ceased contact with the plane it was rolling on

untold moth
#

Yes, if you don't, you don't have enough info on what happened to the object, at which point you can't calculate it's initial position without guessing.

I'd assume that's why Steve mentioned storing stuff in array.

dusky kettle
#

in fact

#

even without taking the shortest path

#

no nevermind

#

that wouldnt be the case

dusky kettle
#

you give the initial position

untold moth
dusky kettle
#

you only are calculating the initial rotation

#

the intial position, final position, and final rotation are all given

#

it returns the initial rotation

untold moth
dusky kettle
#

velocity isnt really relevent here

#

time wouldnt affect it

#

unless the ball is slipping

#

which is isnt

untold moth
#

I don't understand why you have initial position, but not rotation. Is the ball rolling backwards?

dusky kettle
#

i want to chose where the ball ends

#

as i said

#

i am trying to "animate" a ball that rolls realistically

#

so i need it to end in a certain spot with a certain rotation and position

#

and I need it to start in a certain spot

#

it doesnt matter what the initial rotation is

#

just the ending rotation

#

and i need to do this frequently enough to justify writing code that will do it for me

untold moth
#

Why can't you just rotate it realistically every frame?

dusky kettle
#

what

#

wdym

untold moth
#

Just rotate it every frame a little bit.

dusky kettle
#

thats not the problem

#

time is completely irrelevant to the problem

#

nor the implementation

untold moth
#

What does it have to do with time?

dusky kettle
#

just ignore all the tweening part

#

my problem is I need to figure out how to get its initial rotation

#

or the change in rotation from the intial rotation

#

that one actually

#

i think i need that one more

#

in a formwhere the magnitude is still 360 degrees times the amount of revolutions the ball did while rolling

untold moth
#

Why are you so stuck with the "initial rotation"? If you have a position and rotation in one point and you want to get the rotation and position in point b, you can just tray point a as the initial state, and point b as the final state.

#

At which point it's the same calculation as if the ball is moving from a to b.

dusky kettle
#

okay sure

#

you can flip the points around

#

the problem stands

#

i need to figure out the rotation delta of a ball from a point to another point only knowing the rotation at one of those points

untold moth
#

Then it's what I mentioned before.

#

The ball moves the distance of it's circumference in one 360 degree rotation. There's that relation between distance moved and rotation of the ball. For a more detailed formula, you'll need to google.

dusky kettle
#

oh i see what you're saying

#

i wonder if thats any easier for me though

#

id still like the number as a representation of a rotation that has the ability to be greater than 360 degrees

#

idk if quaternion is capable of that

#

and idk how to do that math with euler angles

devout hare
#

Quaternion doesn't store the amount of rotations. But I don't see why you'd need that.

dusky kettle
#

for this i do need that

#

cos i need to figure out how much a ball rotates when it rolls from point a to b

#

but now that i can word it a lot simpler like that

#

google may have a solution to it already

devout hare
#

You'll have to store that information to something else other than a quaternion

#

but if you start with the correct rotation and rotate the ball as it moves, there shouldn't be any need to know beforehand how many times it will rotate

dusky kettle
#

i was thinking just as a euler angle that exceeds 360 in magnitude

dusky kettle
#

because i'm going to flip it around

#

and make the final rotation the initial rotation

#

since what I actually need is to control the end rotation and not the start rotation

upbeat path
wraith storm
fast falcon
#

Hello, I'm not sure if this question would be better asked here or in #archived-urp, but I'll ask here first:

I am trying to copy the rendered texture of a camera while still letting the camera render to the screen. Rn I'm using a script on the camera object to call Graphics.CopyTexture in OnPostRender() to copy RenderTexture.active to a different render texture.

But for some reason, this has inconsistent results. It works great in play mode in the editor window, but when I build the project, the render texture is blank.

Does anyone know why this might be happening, how I could fix it, or a different way to copy a camera's output to a render texture?

bleak citrus
#

I think this is a more general problem. I remember seeing this exact thing happen before

#

Something wasn't being done automatically in the build

#

I do not remember what it was. Maybe you didn't create the render texture properly?

#

maybe it was related to not calling Create?

#

I'm looking at the project where I had this issue. it was a game jam that had a total of 5 commits

#

so, can't exactly pull the answer out of that...

misty glade
#

Documentation is a little light on Tilemap.cellBounds and I can't seem to figure it out (https://docs.unity3d.com/2023.2/Documentation/ScriptReference/Tilemaps.Tilemap-cellBounds.html). I've made what appears to be a sparse (contains a couple empty places) 13x12 grid but bounds is returning 16x15 with an origin of -4, -4. It's making it a bit hard for me to recreate it, but maybe I'm doing it wrong. Screenshots of the tilemap and the same map inside a Grid looking how I want it to. The lower left grass tile should be (0,0) and in the grid, appears to be so..

#

I was thinking I'd make a prefab of the "map" (the Tilemap) and then recreate it at runtime by doing a Tilemap.GetTilesBlock() and then iterating it and setting tiles of the runtime map based on what's in the prefab map

#

(also the array returned by GetTilesBlock() has nulls in it, but the docs seem to indicate it shouldn't? compared to GetTilesBlockNonAlloc()

#

hm.. nevermind.. google to the rescue..

dusky kettle
dusky kettle
untold moth
dusky kettle
#

will that go over 360 degrees tho

#

actually ig it doesn’t matter

#

cos i can just add an extra 360 degrees worth of rotation based on the amount of revolutions right

untold moth
#

Axis is a direction vector, not a rotation angle.

dusky kettle
#

so then how would i turn that into a vector3 representing the same rotation delta

untold moth
#

You don't, but you can use it to rotate an object around that axis .

dusky kettle
#

for the sake of dotween i think it wants me to do it

#

in theory it’s as simple as multiplying the normalised axis direction vector though

untold moth
#

You don't need to rely on dotween. In fact I'm not sure that you can use it for your use case.

dusky kettle
#

i don’t have to but i’d like to be able to easily chose the ease type

#

since it’s meant to happen synchronously with the actual movement

#

actually i suppose i can like

#

use dotween to get a value from 0 to 1

#

and then just map the movement along that

#

that might’ve been what steve was trying to say earlier

untold moth
#

Yeah, I think you're overcomplicating the solution...

#

Perhaps it would've been simpler without dotween at all.

dusky kettle
#

dotween gives me free ease types tho

untold moth
#

You can have ease without dotween.🤷‍♂️

dusky kettle
#

regardless i don’t see how dotween is complicating it more

dusky kettle
#

there’s like a billion ease types

untold moth
dusky kettle
#

yeah

#

idk i’ll have to actually try it

#

dot and cross product and all that are hella confusing

steel snow
#

is it possible to display meshes without making game objects ?

#

since im constantly adding/removing them wondering if i can just skip all that extra overhead

dusky kettle
#

cross product of vector3.up and the endPoint relative to the startPoint?

untold moth
steel snow
#

i presume i would have to call it every frame in update for it to remain seen meaning i would still need a gameobject?

#

i guess at least i would only need one mesh manager

untold moth
dusky kettle
#

yup

#

i can try that

untold moth
#

Still isn't worth it imho.

#

Well, depends on the context I guess.

steel snow
#

it would simplify my code in my case because i have to instantiate child objects and delete them all the next frame

#

or at least every time i mouse the mouse

untold moth
#

Why not use some kind of pooling system?

steel snow
#

well - more code to write for meshes that only there temporarily

#

only once i finally click i solidify them in place

untold moth
#

I mean, issuing a draw call is not a one line thing either...

steel snow
#

i thought that was what this does

untold moth
#

Hmm

steel snow
#

since i have a List<Mesh> alongside List<Material> i was thinking of using it

untold moth
#

I guess there's this then. Still need to calculate the world matrix and stuff.

steel snow
#

oh true

#

i presume unity's mesh renderer does this under the hood

untold moth
#

Yes. This and many other things.

#

Seems like you can create that matrix with utility methods though.

steel snow
#

i dont even know when these functions became a thing

#

unity just sneaks them in and tells no one 😄

untold moth
#

I think they've been here for a while. Just never had a need in using them.

steel snow
#

ah i see one downside it wont cull as it has no bounds

round jay
#

Hello i have a question, i'm building an app for Hololens2 in order to use UWP library in my code i need to switch my Scpriting Bakcend from IL2CPP to ".NET" i'm getting in to Project Settings > Player Other Setting> Scrpting Backend but it's grayed and i can't switch. Is there a way to change this ?

dusty wigeon
# round jay Hello i have a question, i'm building an app for Hololens2 in order to use UWP l...

The platform you have selected does not support Mono. (Scripting Backend is between Mono and IL2CPP)

Unity has two scripting backends: Mono and IL2CPP
(Intermediate Language To C++), each of which uses a different compilation technique:

Mono uses just-in-time (JIT) compilation and compiles code on demand at runtime.
IL2CPP uses ahead-of-time (AOT) compilation and compiles your entire application before it is run.

https://docs.unity3d.com/Manual/scripting-backends.html

round jay
#

So yeah it's busted

#

I'll go by sharepoint

hazy bear
#

I need a little bit of help from some Reflection magician if possible :/
I have Type type variable and Action callback variable. I need to create a delegate of type EventCallback<> of generic type type, that will invoke callback. Im experimenting a bit and getting somwhere but tripping all the time...
I came up with this idea, but I got exception: methods arguments are incompatible :/

            Action callback = () => {
                Debug.Log("lol");
            };
            Type eventType = Type.GetType(eventInfo.EventType); //eventInfo.EventType is a string with AssemblyQualifiedName
            Type eventCallbackType = typeof(EventCallback<>).MakeGenericType(eventType);
            Type genericExecuterType = typeof(GenericEventExecuter<>).MakeGenericType(eventType);
            object executer = Activator.CreateInstance(genericExecuterType, new object[] {callback});
            var callbackDelegate = genericExecuterType.GetMethod("HandleExecution", BindingFlags.NonPublic | BindingFlags.Instance)
                .CreateDelegate(eventCallbackType, executer);

and my dummy class

    internal class GenericEventExecuter<T> where T : EventBase
    {
        private Action callback;

        public GenericEventExecuter(Action callback)
        {
            this.callback = callback;
        }

        private void HandleExecution<T>(T type)
        {
            callback.Invoke();
        }
    }
#

nahh... sry my bad apparently it works, i have a problem somewhere else

#

I think some ui event types holds additional info on which depends the execution or something, and with this generic approach they dont work

#

like ClickEvent (which is left mouse button) work, but ContextualClickEvent (which is right mouse button) doesnt

#

because what I do is

            Action callback = () => {
                Debug.Log("lol");
                if (enabled) eventInfo.Event?.Invoke();
            };
            Type eventType = Type.GetType(eventInfo.EventType);
            Type eventCallbackType = typeof(EventCallback<>).MakeGenericType(eventType);
            Type genericExecuterType = typeof(GenericEventExecuter<>).MakeGenericType(eventType);
            object executer = Activator.CreateInstance(genericExecuterType, new object[] {callback});
            var callbackDelegate = genericExecuterType.GetMethod("HandleExecution", BindingFlags.Public | BindingFlags.Instance)
                .CreateDelegate(eventCallbackType, executer);


            MethodInfo registerCallbackMethod = typeof(VisualElement).GetMethods()
                .Where(x => x.Name == "RegisterCallback")
                .FirstOrDefault(x => x.IsGenericMethod)
                .MakeGenericMethod(eventType);
            registerCallbackMethod.Invoke(target, new object[] { callbackDelegate, TrickleDown.TrickleDown }); //where target is some visual element
#

or maybe someone has better idea why it doesnt work for some events and how to resolve it?

misty glade
#

Event.EventType isn't a string, it's an enum, although I'm not sure if that's your problem, but I imagine it might be worth verifying that Type.GetType works like you expect it to on an enum

#

although what you're doing seems ... weird. What are you trying to actually do..?

fast falcon
bleak citrus
#

ah, I don't think that's needed..

fast falcon
#

I just tried calling RenderTexture.Create() in the awake method, but that doesn't seem to fix the issue

#

It works if the camera renders directly to the render texture, but then it won't render to the screen.

fast falcon
#

Okay, I've done some more testing and copying a different render texture in the OnPostRender method works, and calling RenderTexture.active.IsCreated() returns true. But for some reason I can't copy that specific texture when the game is actually built.

hazy bear
misty glade
#

gotcha

#

Thought you were maybe just hooking into IPointerDown etc events and maybe there was some enum to string implicitly happening that was messing up your reflection

hazy bear
#

dont get me wrong, I actually managed to do it and it works sweet, but only some specific events dont seem to work, but ill try make custom wrappers that register them in a way they supposed to be registered (I mean with no reflections) and then expose them or smth (idk yet)

#

even inspector itself looks clean for which im proud of

hazy bear
#

yeah that could be cool extension to what I already have, but I dont mind using native UnityEvent, and it isnt a big problem to replace it in the future if I need to, the whole problem revolves around registering callbacks to UI elements with reflections

dusty wigeon
hazy bear
#

oh this, sorry i forgot that I ever asked this question XD Thanks for the solution but later I understood that if I want to have "duplicate" funcionality for UnityEvent in inspector this would be much more work, but now Im thinking that this is a very good excuse to use one of these alternatives you have sent

hazy bear
hazy bear
hazy bear
#

I love and hate how many such helpful methods are hidden somewhere in a little classes no one knows about...

dusty wigeon
tawdry plinth
#

Hi, is there a way to get gameobject before their awake call for each new scene?

sly grove
#

theoretically script A can reference an object in its own Awake before some other script B runs, if that's what you mean

tawdry plinth
sly grove
#

One way would be to use the Script Execution Order settings and make sure your dependency injector runs before everything else

#

Another way is to explicitly call MyDependencyInjector.InjectFields(this); in Awake for each script that needs things injected

tawdry plinth
sly grove
#

e.g.

public class DIStub : MonoBehaviour {
  void Awake() {
    DependencyInjector.Instance.InjectFieldsForScene(this.gameObject.scene);
  }
}```
sly grove
#

That's only for the first scene though

#

Sadly

dusty wigeon
#

Yeah, didnt see that it needed to be done for each scene. I'm using it for Singleton Init, though it could have been the same use case here.

shrewd hemlock
#

https://hastebin.skyra.pw/jizutuqaqi.java Hi I wanted to ask again maybe here this time. I currently have this code from a tutorial, and I tried to apply it to a 3D model's torso and I was wondering how I would change this such that the torso properly follows the mouse?

shrewd hemlock
#

An image for my previous comment

untold moth
#

*rotate towards it.

visual hollow
#

Hello! I'm trying to add depth support to Rigidbody2D, so it can ignore collisions with colliders on different Z levels. What I have is a script that controls a kinematic Rigidbody2D by checking collisions with a contact filter and moving the body via MovePosition. In the screenshot is my test with two BoxCollider2D using my script. Following is my code.

#
using System.Collections.Generic;
using UnityEngine;

namespace Game
{
    [RequireComponent(typeof(Rigidbody2D))]
    public class CustomRigidbody2D : MonoBehaviour
    {
        private Rigidbody2D rigidbody { get; set; }

        private Collider2D[] overlapColliders = new Collider2D[8];

        private void Awake()
        {
            rigidbody = GetComponent<Rigidbody2D>();
            rigidbody.bodyType = RigidbodyType2D.Kinematic;
            rigidbody.gravityScale = 0;
            rigidbody.interpolation = RigidbodyInterpolation2D.Interpolate;
            rigidbody.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
        }

        private void FixedUpdate()
        {
            ContactFilter2D contactFilter = new ContactFilter2D
            {
                useDepth = true,
                minDepth = transform.position.z,
                maxDepth = transform.position.z,
            };

            int overlapColliderCount;

            if ((overlapColliderCount = rigidbody.OverlapCollider(contactFilter, overlapColliders)) > 0)
            {
                for (int i = 0; i < overlapColliderCount; i++)
                {
                    Collider2D otherCollider = overlapColliders[i];
                    Rigidbody2D otherRigidbody = otherCollider.attachedRigidbody;
                    ColliderDistance2D colliderDistance = rigidbody.Distance(otherCollider);

                    if (colliderDistance.distance <= -0.01f)
                    {
                        Vector2 force = 0.25f * colliderDistance.distance * colliderDistance.normal;
                        otherRigidbody.position -= force;
                        rigidbody.position += force;
                    }
                }
            }
        }
    }
}
#

The question is: how can I improve this to make the collision mimic the behaviour of a regular Rigidbody2D (no overshooting, velocity transfer, drag, etc)?

#

And is there another way to make a Rigidbody2D care about depth?

#

My end goal would be to have a single tilemap with multiple levels (z position) and enemies across all levels that can only collide with enemies in the same level.

untold moth
#

Why not just use 3d physics if you need depth?🤔

visual hollow
untold moth
#

Then just use a different collider for the tilemaps. And if you use 3d physics, then you wouldn't need it to interact with 2d physics.

visual hollow
untold moth
#

Otherwise you're just reimplementing 3d physics in an awkward way.

untold moth
#

You can use jobs or compute shaders for the heavy processing if needed.

visual hollow
untold moth
#

Well, you don't have a way to do that without relying on layers(only 32) or butchering the collisions and stuff.

visual hollow
untold moth
#

If you want to handle collisions manually, you can just use triggers.
There are many ways to approach it, depending on how much of the physics functionality you want to be working.

visual hollow
#

Will try to optimize it with Jobs, just need to understand it better firstly.

#

Thanks for your help!

next marsh
#

I'm getting an error with the Burst compiler:
G:\Unity\Space-Gaem-Aw-Yeah\Assets\Scripts\RTS\Physics\Manager.cs(110,13): Burst error BC0102: Unexpected internal compiler error while processing function `IL_0008: call System.Void System.ReadOnlySpan`1<UnityEngine.Vector2>::.ctor(!0[]) args(IL_0001(ldloca.s), IL_0003(ldsfld))`: System.NullReferenceException: Object reference not set to an instance of an object

#

Manager.cs (110, 13) being:

[BurstCompile]
private static void _step(float timeIncrement, int count)
{
    var velocitySpan = new ReadOnlySpan<Vector2>(Velocities);
#

Velocities being:

public static class Manager
{
  private const int BodyCap = 150;
  private static readonly Vector2[] Velocities = new Vector2[BodyCap];
...```
#

Using a couple day old install of Unity 2023 (2023.1.14f1)

#

Seems to compile fine when I comment out the [BurstCompile] tag on the function call.

sage radish
next marsh
#

Just reading from them

#

Oh you mean the array Velocities?

sage radish
#

Yes

next marsh
#

That's being read/written too extremely often

sage radish
#

But do you read the data that was previously in it, or are you overwriting it immediately?

next marsh
#

Oh damn wait I see what you mean

#

It didn't occur to me I was writing to the array I was spanning facepalm

#

Thank you-- I can't test now but I'll let you know

sage radish
#

Burst doesn't support managed arrays, unless they are static readonly, in which case it will interpret it as a constant array, which is evaluated at compile time.

next marsh
#

Ahhhh

#

Well damn

#

Long-lifespan native array it is?

#

Wait can I span a native array?

sage radish
next marsh
#

Oh wow

#

Thank you

sage radish
#

But I would still create the span outside the method and pass it in

next marsh
#

As far as I can tell Burst doesn't like Spans being passed in

#

Lemme retest

sage radish
#

Hmm, you might be right

golden lodge
#

Hello I'm working with asperite importer, how can I enable a layer midway through my animation,

shell horizon
#

does anyone know if there's a way to directly get the array of values for a given key in a native multi hash map?

#

without enumerating

sage radish
tawdry plinth
#

foreach (var (key ,service) in _services)
{
if (service != null)
continue;
_services.Remove(key);
Debug.Log($"Removing service of type {key}.");
}
context : key is of class Type and service is c# object
I'm removing null services but it's not working, i'm sure that the service of Type Key where is a monobehaviour is destoryed.
After this code when i access this service this gives me Missing Ref exeption any idea about this ?

upbeat path
#

what type is _services?

tawdry plinth
#

private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();

upbeat path
#

you cannot remove an item from the object of a foreach anyway

tawdry plinth
sly grove
#

it will NOT do unity's special check for destroyed objects

#

If they're all MonoBehaviours you can make it Dictionary<Type, MonoBehaviour>

#

worst case: Dictionary<Type, UnityEngine.Object>

upbeat path
#

or just UnityEngine.Object

#
foreach (Type key in _services.Keys.ToArray()) {
if (((UnityEngine.Object)_services[key]) == null) // do something
tawdry plinth
#

@upbeat path @sly grove thanks

upbeat path
#

I have to what?

coarse compass
#

So I was working on a property drawer for an interface that gives me a dropdown of all implementing types. It's as simple as making a field like this:

public class MyMono : MonoBehaviour
{
    [SerializeReference]
    public IMyInterface Obj;
}```

The problem is that I would like to be able to reference components and scriptable objects as well, but unity doesn't like it when you use any UnityEngine.Object with SerializeReference. 

Is there any way around this? I would really like to get this to work with ANY implementation of the interface without restriction, and without making a wrapper type.
austere jewel
coarse compass
#

Unfortunate. Thanks!

dull epoch
#

Hey everyone.
I am trying to write a shader for the Terrain to make it appear Blocky like it is made out of Voxels. But i will face problems with the Terrain Collider if i do that.
Is there a clever way to overwrite the Terrain Collider ? Since i know the maths where which block should be, it should be easy to bring that into a terrain collider ... right ?

crisp parcel
#

Heya! Question on compute shaders
To bugfix my code, I ported the shader code over to cs, by merely replacing the math calls (add .math), and keeping the rest (practically) intact

Any idea why the cs output and compute shaders output may differ, by LARGE amounts? I've triple-checked my code, diff-checked it twice, but can't find any misinputs or changes in code between both

(Note: I can't show the code, but can list which functions I am using: anything quaternion related (using hlsl quaternion code / manually ported version to cs), normalize, clamp, dot, length, abs, a bunch of acos/sin/... , lerp, /

untold moth
dull epoch
untold moth
#

It's really hard to help with that without seeing the code.

crisp parcel
hoary merlin
#

Hey there, working on a mod for a game (Yes the game supports mods and Harmony)
I'm looking to add a file browser to my mod allowing the user to import files.

I've tried using OpenFileDialog and SaveFileDialog, whilst these work, they only seem to work when the game is running in windowed, and not when the game is running fullscreen (Otherwise these open behind the game window) so I need to have something that will run directly in the game.
I found this Runtime File Browser which works absolutely brilliantly when using the editor, although I'm unsure / unable to port this to a mod as scripts can't be added to AssetBundles.
When seperating the scripts and AssetBundles I get the following error The referenced script on this Behaviour (Game Object 'FileOperationConfirmationPanel') is missing! (This is one of many)
Obviously I could manually hardcode it to fix all these script errors, but there are hundreds of them.

I'm looking to see if anyone here has a solution to this problem, or if I'm going to need to build a file explorer from scratch. Thanks!

Use the Runtime File Browser from yasirkula on your next project. Find this GUI tool & more on the Unity Asset Store.

junior stone
#

Hi! Is there a good way to keep track of all the Renderers in a scene, even though gameplay code I dont control might add or remove them randomly?

#

At the very least is there like an event I can listen to, to flag something in the scene has changed and I should do another search for all renderers?

wraith storm
# hoary merlin Hey there, working on a mod for a game (Yes the game supports mods and Harmony) ...

Hi, I've been using this asset for, hmm, maybe 4 years now :
https://assetstore.unity.com/packages/tools/utilities/file-browser-pro-98713

I can't really give you an opinion on how it compares to the competition, I've not really thought much about it since I started using it. It just works I guess 🙂

Use the File Browser PRO from crosstales on your next project. Find this utility tool & more on the Unity Asset Store.

wraith storm
junior stone
#

Thanks, thats what I do, but it has some pretty crazy overhead

wraith storm
junior stone
#

so I was wondering if there was another strategy. Normally I'd be like 'Hey I can just add/remove them from a list as they get created', but I dont see a way to do that

#

I guess the real problem is that Im writing a SRP thats meant to plug into other games, so Im limited on my ability to demand they do anything

wraith storm
#

Maybe you could maintain a list of all root gameObjects, and then use the GetComponentsInChildren on each of those?

junior stone
#

yeah thanks, I thought it might be the case.

wraith storm
#

Hmm, another option might be to make a sub class of MonoBehaviour, called something like MonoBehaviourRendererTracked

And then in the Awake() method, you just check to see if there is a Renderer and if so add it to a static List.

But that would only work if the Renderer is there already when Awake() is called

wraith storm
junior stone
#

I have a SRP, and it needs to feed data to materials for a forward renderers materials like the number of lights

#

so essentially I have to maintain those relationships every frame

regal olive
#

for people that host packages on private github repositories (say something like com.mycompany.core), what solution did you go with to be able to have unity successfully find the repository? Since I'm going to be working with multiple people off and on I'm not crazy about either managing SSH keys or including some credentials file, but I'm wondering if there a better solution to get around this.

dusty wigeon
regal olive
dusty wigeon
regal olive
# dusty wigeon That standard Git issue I would assume. Simply Google it and you gonna find a ga...

ok yeah looks like that was it, now that the repository is being found, any idea how to resolve this error? An error occurred while resolving packages:
Project has invalid dependencies:
com.systemsheavy.core: Version 'https://github.com/systemsheavy/sh-unitypackages?path=/Assets/com.systemsheavy.core' is invalid. Expected one of: a 'SemVer' compatible value; a value starting with 'file:'; a Git URL starting with 'git:' or 'git+', or ending with '.git'.

is the path messing things up here?

stuck plinth
#

yeah i don't think you can reference a subpath like that in the manifest? fwiw i've always found it easier to add dependencies as git submodules, you can add them straight into the Packages folder - if the manifest is at the root it just finds them automatically, otherwise you can add them to the manifest as "embedded" and set the path that way

solar condor
#

Heya - techartist here:
What is a good use case for Texture2DArrays instead of multiple Texture2D's? I kind of see how TexArrays are powerful, but I'm having a hard time thinking about how to harness the flexibility of the index-based sampling on top of uv's in a way which isn't just just "read from multiple textures that are actually in the same file now!"

Or is that particular feature that much of a performance gain?

sage radish
solar condor
#

What do you mean with dynamic? Like, something regenerated at runtime?

sly grove
#

In a shader no less 😰

sly grove
sage radish
sage radish
#

If the number of textures aren't too crazy, then you can get away with just sampling all the textures and lerping between them. That's usually how triplanar mapping works. But that doesn't scale very well.

plucky trellis
solar condor
solar condor
sage radish
solar condor
#

Ohhh, I see

sage radish
#

It should become obvious to you if you would benefit from using Texture2DArray, because the alternatives will be very inconvenient.

languid isle
#

HI everyone!

Are objects in an array "lazy loaded"?

#

I need help because I need to make certain I'm not creating a resource train wreck in the future

sage radish
languid isle
# sage radish If you're talking about serialized arrays, then no. There's no lazy loading in U...

Ok then I have a problem.

I'm making a board game where people can change the cells and pieces of the board in mid game. I was told that it might suck up resources if I put all of the graphic sets on a piece. I then said : "Ok, can I put the sprite renderer with different graphics on each object, and then fill the array with objects." They said they were unsure if all the graphics would be loaded or lazy loaded. I came here because they had to leave (it's like 3am their time), and now you answered the question.

So it sounds like they are all fully loaded and not lazy loaded.

So what would be the best way to have those graphic packs available for a player to swap in mid play without loading up 300 graphic packs and models into memory?

#

I was also warned off using a resources folder.

sage radish
languid isle
#

ok

sage radish
languid isle
#

ok I know nothing of this, can you pls explain?

sage radish
#

The idea is that you build your assets into separate bundles, which you can then load lazily at runtime. Addressables makes it a bit simpler to load these bundles and find the asset you want from them.

#

I don't have much experience with it, so I'm not the best person to ask.

languid isle
#

oooo

#

I will send this info to my tutor

tender helm
finite pond
#

Is there a way to access a SpriteRenderer's size inside Shader code?

#

I feel like I remember using it sometime in the past, but I can't find any info about it nor do I remember how I did it

hoary merlin
#

Hey there, currently working on an IMGUI menu, and I'm having some issues with usingGUILayout.BeginArea inside GUILayout.BeginScrollView

contentScrollPosition = GUILayout.BeginScrollView(contentScrollPosition, false, false, GUIStyle.none, GUI.skin.verticalScrollbar);
int count = 0;
foreach (var directory in currentDirectoryInfo.GetDirectories())
{
    GUILayout.BeginArea(new Rect(0, count * (height / 15), width, height / 15), Mod.Bundle.LoadAsset<Texture2D>("folder-icon"));
    if (GUILayout.Button(directory.Name, _contentButtonStyle, GUILayout.Width(width), GUILayout.Height(height / 15)))
    {
        ChangeDirectory(directory.FullName);
    }
    GUILayout.EndArea();
    count++;
}
GUILayout.EndScrollView();

At the moment this is the setup I've got - my goal is to have an icon alongside the button (but also allow the icon to be clickable) similar to the attached screenshot. Although the issue is, when using BeginArea inside BeginScrollView, the scroll view doesn't get populated, therefore there's nothing to scroll.

Is there a way to keep the visual of the icon and the text, whilst keeping them inside BeginScrollView?

lament ruin
#

Hey guys - I am currently unable to build & run any version of my game on the phone, as it always crashes due to gradle trying to run facebook java code from the FB SDK which I removed a few weeks ago. I always get this error:

Fatal Exception: java.lang.RuntimeException
Unable to get provider com.facebook.FacebookContentProvider: java.lang.ClassNotFoundException: Didn't find class "com.facebook.FacebookContentProvider" on path

Anyone encountered this before? I have removed the SDK from the project but it's still trying to run it in some way. So clearly I didn't catch all of it.

sly grove
sly grove
lament ruin
# sly grove is there any more to this stack trace?

yeah - this is the full one:

Unable to get provider com.facebook.FacebookContentProvider: java.lang.ClassNotFoundException: Didn't find class "com.facebook.FacebookContentProvider" on path: DexPathList[[zip file "/data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/base.apk", zip file "/data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/split_config.arm64_v8a.apk"],nativeLibraryDirectories=[/data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/lib/arm64, /data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/base.apk!/lib/arm64-v8a, /data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/split_config.arm64_v8a.apk!/lib/arm64-v8a, /system/lib64, /system_ext/lib64]]```
sly grove
#

there's no stack trace there unfortunately

lament ruin
#

this is all i have from firebase crashlytics

sly grove
#

Does you project have a custom android manifest file?

#

Perhaps it's being mentioned there

#

It would be called AndroidManifest.xml

lament ruin
#
Fatal Exception: java.lang.RuntimeException: Unable to get provider com.facebook.FacebookContentProvider: java.lang.ClassNotFoundException: Didn't find class "com.facebook.FacebookContentProvider" on path: DexPathList[[zip file "/data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/base.apk", zip file "/data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/split_config.arm64_v8a.apk"],nativeLibraryDirectories=[/data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/lib/arm64, /data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/base.apk!/lib/arm64-v8a, /data/app/~~uN2HgfnUxpXc6E7PfrBDLg==/com.ggs.dungeoncreeprs-yLGKbyfWrpzwEq7FRlvNIA==/split_config.arm64_v8a.apk!/lib/arm64-v8a, /system/lib64, /system_ext/lib64]]
       at android.app.ActivityThread.installProvider(ActivityThread.java:7513)
       at android.app.ActivityThread.installContentProviders(ActivityThread.java:7019)
       at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6790)
       at android.app.ActivityThread.-$$Nest$mhandleBindApplication()
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2132)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:201)
       at android.os.Looper.loop(Looper.java:288)
       at android.app.ActivityThread.main(ActivityThread.java:7918)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
finite pond
lament ruin
lament ruin
# sly grove Does you project have a custom android manifest file?

I do have a bunch of them and checked the packages, but all I can find are firebase related packages / unity appsflyer (i only installed the base SDK so far and didn't do anything with it yet) / and some android sdk packages. Thanks for the hint tho - i'm going to scour further for possible solution 😢

long ivy
lament ruin
sly grove
lament ruin
#

Yes I did lol - that was the first thing I tried.

sly grove
#

you searched where/how though? In your IDE? In Unity?

#

Or with some other tool

#

should work in e.g. git bash or mingw32 if on windows

lament ruin
lament ruin
loud wadi
#

Hello, does methods in math run faster even without BurstCompiler?

crystal panther
#

anyone know how to access an hdr color's intensity value accurately in-code? I'm writing an editor piece to help with doing one thing over and over, and one of those things is setting a list of colors on an added script. The colors are static.

untold moth
loud wadi
untold moth
#

No. Single instruction multiple data is one of the optimizations that burst enables. Without it, it's not in effect.

loud wadi
untold moth
crystal panther
#

everything is in a file. its being set through an editor window button.

untold moth
#

It takes the base color and increases its brightness along all the 3 components.

#

For the exact formula you'll need to google

crystal panther
#

It went from 1.4 to 8.7 by multiplying the color values

untold moth
crystal panther
#

I could use min and max exposure, although deprecated I think that affects it

#

I'll have to test

loud wadi
untold moth
#

Probably some overhead necessary for burst.

knotty obsidian
#

Henlo, Cloud code C# modules, cloud save data. I want to access 2 players' data via my game server, how would I do this? This is my current code

     var apiResponse = await gameApiClient.CloudSaveData.GetItemsAsync(
            context,
            context.AccessToken,
            context.ProjectId,
            playerId,
            new List<string> { PlayerInventory.Keys.MatchDeck }
        );```
 on my C# module. `gameApiClient` is `IGameApiClient` sourced by `GameApiClient.Create()`. `playerId` is a string, the other player's Id 
As it stands, the requesting user (currently anon login) does not have perms to check the other player's (also anon) data. I don't know if it is possible to make the request as an admin of some sort.
The C# module is called via Unity's `CloudCodeService.Instance`
subtle nexus
#

Odd question, does anyone know if there is a good way to allow for Bluetooth file sharing from and android build to windows and windows to android? I'm looking to send fairly small txt or csv files.

untold moth
gusty tusk
#

I enabled stack trace and notice I am getting leaks at a simple NativeArray<float3> allocation on TempJob.

#
TempJob leak at address 0000023A3DAAC0B0:
0x0000023c203cadeb (Mono JIT Code) Unity.Collections.NativeArray`1<Unity.Mathematics.float3>:Allocate (int,Unity.Collections.Allocator,Unity.Collections.NativeArray`1<Unity.Mathematics.float3>&)
0x0000023c203cacd3 (Mono JIT Code) Unity.Collections.NativeArray`1<Unity.Mathematics.float3>:.ctor (int,Unity.Collections.Allocator,Unity.Collections.NativeArrayOptions)
0x0000023c203c9abb (Mono JIT Code) ProjectBrave.Runtime.Combat.WalkMoveSystemManager:OnSystemUpdate (System.Collections.Generic.List`1<ProjectBrave.Runtime.Combat.WalkMove>,int) (at C:/Users/Frava Office/Documents/Unity Projects/Project Brave/Assets/_ProjectBrave/Scripts/Runtime/Combat/Core/CombatObject/AI/Movement/WalkMoveSystemManager.cs:38)
#

This is the simple code

#
    public class WalkMoveSystemManager : BaseSystemManager<WalkMove>
    {
        private NativeArray<WalkData> _moveData;
        private NativeArray<float3> _outputData;

        public const int BATCH_SIZE = 128;

        protected override void OnSystemUpdate(List<WalkMove> dataList, int dataCount)
        {
            _moveData = new NativeArray<WalkData>(dataCount, Allocator.TempJob);
            _outputData = new NativeArray<float3>(dataCount, Allocator.TempJob); // Leak here at line 38

            for (int i = 0; i < dataCount; i++)
            {
                _moveData[i] = dataList[i].GetMoveData();
            }

            ManageWalkMoveParallelJob moveJob = new()
            {
                DeltaTime = Time.deltaTime,
                MoveData = _moveData,
                OutputData = _outputData
            };

            moveJob.Schedule(dataCount, BATCH_SIZE).Complete();

            for (int i = 0; i < dataCount; i++)
            {
                dataList[i].MoveAgent(_outputData[i]);
            }
        }

        protected override void DisposeAllNativeArray()
        {
            if (_moveData.IsCreated) _moveData.Dispose();
        }
    }
#

Not sure why this leaks, its a very simple system

#

Oh wait I forgot to dispose of it

#

Sorry my bad

tiny pewter
#

once you allocate a native/unsafe something then immediately put its dispose() in OnDestroy or somewhere else

steel snow
#

So i have a weird behaviour i dont understand

Im combining two meshes like this:

CombineInstance[] combines = new CombineInstance[2]
{
    new CombineInstance(){mesh = m, subMeshIndex = 0, transform = Matrix4x4.identity},
    new CombineInstance(){mesh = s, subMeshIndex = 0, transform = Matrix4x4.Translate(Vector3.up) }
};

Mesh final = new();
final.CombineMeshes(combines, true, true, true);
_filter.mesh = final;

but i want each mesh to be a submesh, so i initially gave them different submesh indices and set combine submeshes flag to false, only the second combine instance didnt even end up in the final mesh.

The only way i can get both meshes to become one is same submesh index and setting combine submshes to true but then i dont have the submeshes anymore only 1 submesh ... any one know why that might be ?

long ivy
#

what do you mean "gave them different submesh indices"? Set second parameter of CombineMeshes to false, rest of code stays the same

steel snow
#

i had submeshIndex 0 and 1 respectively

#

and flag was false

#

but only the first combine instance in the mesh appeared

#

the only way both appear is as the code shows above

long ivy
#

in the input? If s has 1 submesh and you specified subMeshIndex 1, it's naturally not going to appear

steel snow
#

huh

#

am i not specifying that i want mesh s to be submesh [1] of final ?

#

i presume thats what it means

long ivy
#

no

steel snow
#

oh

#

so i need both = 0 and then flag to false?

long ivy
#

yes

steel snow
#

ok let me try it

#

oh

#

i thought i had tried this before but then i realised i hadnt added a second material

#

kinda wish it would give pink shader error color if missing a material rather than simply not display 😄

#

@long ivythanks for clearing up the confusion on submesh indices though!

#

all working nicely now!

steel snow
#

got a weird issue with mesh uvs.. i have a 2d polygon that i generated procedurally... im setting the uvs to the world space of the vertices on the x,z plane yet when i apply my texture its as if its scaled so much that it's just one colour

#

i dunno where to begin to debug this problem

#

this is how i do it:


_polygonMesh = triangulation.Triangulate2D(p);
var uvs = new Vector2[_polygonMesh.vertexCount];
for (int i = 0; i < uvs.Length; i++)
{
    var v = _polygonMesh.vertices[i];
    uvs[i] = new Vector2(v.x, v.z);
}
_polygonMesh.uv = uvs;
#

this is how it turned out

#

offsets seem to offset the texture but incorrectly and tiling doesnt even do anything - this is using the default urp lit material

long ivy
#

what are the texture settings on your texture? Maybe it's being clamped

steel snow
long ivy
#

create a Plane GO, put it at origin, apply this material, and run your uv code excluding the triangulation

#

also you might want to copy the vertices array, your loop is extremely inefficient currently

steel snow
#

yeh its inefficient it was a quick job to figure out why the uvs wont work

#

let me try what you suggested

steel snow
#

worked for the default plane 😭

#

what does that mean though for my generated mesh

#

surely its not the vertex values

long ivy
#

well it definitely looks like something is wrong with your uvs, so now I'd use that plane as a reference for what the uvs should look like and generate your triangulated mesh in the same place. Does your mesh have any scaling?

steel snow
#

no scaling

#

but the uvs in my generated mesh is using the same code as that plane mesh

#

using x;z of the vertex values

#

what other uv setup is there to do

long ivy
#

debug the actual values. Make a simplified triangulated mesh and see what the uvs end up as

#

btw you are not using world space for the uvs coords, they're in object space which is why I asked about scale

steel snow
#

oh my bad as for scale the transform is 1,1,1 and the material tiling is 1,1

#

not sure what other scaling there is

#

ive not applied a multiplier to the uv values

#

it just suddenly decided to work

#

🤔

mortal ocean
#

Hi everyone,

Due to the structure of my game, I need to use a radius value smaller than 0.05f, which is the minimum agent radius value. But as you know, Unity currently limits this value to a minimum of 0.05f. Therefore, I cannot set a smaller value in any way.

Is it possible to remove this limitation? I don't want to increase the size scale of the entire game just because of this problem.

Thanks.

steel snow
#

the radius is set to 0.05 not 0.5 in that image

mortal ocean
steel snow
#

Any smaller and the navmesh agent steering will bug out

mortal ocean
steel snow
#

I'm not aware of that

#

Maybe the inspector is stopping you but in code you can still use a smaller value

mortal ocean
#

The problem is probably not on the inspector.

sterile meteor
#

Do you know of any articles, blogs, courses on advanced code architecture for large Unity projects? I understand that every project is different and may require a different architecture, but there are general concepts, such as for eg. Clean Architecture.

dusty wigeon
# sterile meteor Do you know of any articles, blogs, courses on advanced code architecture for la...

You can read on architecture, it does not need to be related to Unity. Whenever you deal with advance architecture, it might help to have a basic understanding of the technology you work with, but the most important is to understand key concept that transcend the technology in use.

By example,

  • SOLID + T(Tell don't Ask) Principle
  • Cohesion/Coupling
  • Design Pattern (Statemachine, Pub/Sub, etc.)
  • Inheritance vs Composition
  • Screaming Architecture
dusty wigeon
mortal ocean
knotty obsidian
astral kernel
#

i want an object to follow exact player movement with some offset but i have no idea how to do that, help pls

wraith storm
astral kernel
#

no, like multidimensional baby in The binding of isaac

#

Player moves and after for example 2 seconds the object follow players path

wraith storm
# astral kernel no, like multidimensional baby in The binding of isaac

In FixedUpdate() you could store the Players position in a Queue()

So somethign like...

Queue<Vector3> historyOfPositions = new Queue<Vector3>();
int historySize = 60 * 10; // 10 seconds if FixedUpdate is 60fps

void FixedUpdate() {
historyOfPositions.Dequeue();
historyOfPositions.Enqueue( thePlayer.transform.position );
}

public Vector3 GetDelayedPlayerPosition() {
return historyOfPositions.Peek();
}

#

Oh, sorry in FixedUpdate() it should be...

if( historyOfPositions.Count > historySize ) {
historyOfPositions.Dequeue();
}

livid goblet
#

Hey I'm getting this really weird behaviour where removing this debug line from my code causes the code to run differently

#

bool DoorLiesWithinIntervalX(float start, float end, TestDoor door)
{
float doorPosition = door.transform.position.x;
float doorWidth = door.transform.localScale.x;
float doorStart = doorPosition - doorWidth / 2;
float doorEnd = doorPosition + doorWidth / 2;

    bool entirelyLeft = doorEnd <= start;
    bool entirelyRight = doorStart >= end;

    Debug.Log("door number " + doorNumber + " doorStart: " + doorStart + " doorEnd: " + doorEnd + " start: " + start + " end: " + end + " entirelyLeft: " + entirelyLeft + " entirelyRight: " + entirelyRight);


    return !(entirelyLeft || entirelyRight);
}
#

Here is the code

sly grove
#

!code

thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

livid goblet
#
bool DoorLiesWithinIntervalX(float start, float end, TestDoor door)
    {
        float doorPosition = door.transform.position.x;
        float doorWidth = door.transform.localScale.x;
        float doorStart = doorPosition - doorWidth / 2;
        float doorEnd = doorPosition + doorWidth / 2;

        bool entirelyLeft = doorEnd <= start;
        bool entirelyRight = doorStart >= end;

        Debug.Log("door number " + doorNumber + " doorStart: " + doorStart + " doorEnd: " + doorEnd + " start: " + start + " end: " + end + " entirelyLeft: " + entirelyLeft + " entirelyRight: " + entirelyRight);


        return !(entirelyLeft || entirelyRight);
    }
#

Hey I'm getting this really weird behaviour where removing this debug line from my code causes the code to run differently

sly grove
#

Differently how?

#

Nothing in that statement would change anything as written

livid goblet
#

I am aware, which is why it's so strange

sly grove
#

(would recommend using string interpolation to make that cleaner though)

livid goblet
#

it is part of a larger algo, the algo breaks and creates a different outcome when I remove the debug

sly grove
#

that's very vague

#

I assume you're misinterpreting the situation somehow

#

or perhaps you are doing something multithreaded and you have a race condition

livid goblet
#

how am I misinterpreting, when I remove the debug, the outcome is different

sly grove
#

and adding the log slows it down enough to change the behavior

livid goblet
#

nothing is multithreaded

sly grove
#

you're giving very little to work with

#

the only thing that could conceivably change is how long this code takes to run

#

so maybe you have something very time or framerate sensitive going on

livid goblet
#

I thought the same as well, but I'm sure it's not the case

sly grove
#

another possibility is that doorNumber < some of these things are properties and the getter for the property has side effects

livid goblet
#

I removed door number and several other parts of the debug and it worked fine

sly grove
#

are any of those things properties?

livid goblet
#

only upon removing " doorEnd: " did it break

sly grove
#

and again, what is the nature of the breaking

livid goblet
#

it causes the function to return false in a case where it is true

#

nothing is moving, none of the properties are changing

sly grove
#

I think it's more likely you are misinterpreting something about this situation than it is that the log statement is actually changing anything.

Perhaps this function is running multiple times for example and you are mixing up multiple iterations somehow

#

or maybe something about how you're checking the result is off

#

you can write a simple test case here where you write another version of the function with and without the log statement

#

pass the same data to both

#

and see if they return the same thing

livid goblet
#

I'll give that a try

#

even running on the same data, they are returning different results

#

I'm just gonna restart my pc

#

there are demons in the machine

sly grove
livid goblet
sly grove
# livid goblet

are any of these properties?
currentPointX nextInterruptionX door?

livid goblet
#

no

sly grove
#

I am noticing doorEnd and start are... either the same or very close to one another?

#

so this could be some kind of floating point precision issue

livid goblet
#

that was my thought as well

#

but how does calling debug change it that?

#

or affect the results

sly grove
#

not sure...

livid goblet
#

spooky

sly grove
#

especially since the debug.log is after the bools are already computed

sly grove
livid goblet
#

the one with the debug or without?

sly grove
#
Debug.Log("First");
Debug.Log(DoorLiesWithinIntervalX(...));
Debug.Log("Second");
Debug.Log(DoorLiesWithinIntervalX(...));```
#

I guess either one

#

but let's say without

livid goblet
#

both versions call the same with and without

#

meaning, it doesn't change anything

#

bool DoorLiesWithinIntervalX(float start, float end, TestDoor door)
    {
        float epsilon = 1e-6f;

        float _doorPosition = door.transform.position.x;
        float _doorWidth = door.transform.localScale.x;
        float _doorStart = _doorPosition - _doorWidth / 2;
        float _doorEnd = _doorPosition + _doorWidth / 2;

        bool entirelyLeft = _doorEnd <= start + epsilon;
        bool entirelyRight = _doorStart >= end - epsilon;

        return !(entirelyLeft || entirelyRight);
    }
#

this fixes it smh

sly grove
#

still weird though

#

i'm kinda stumped tbh

#

the only thing I can think of is that somehow the Transform position or scale getter has side effects?

livid goblet
#

I'm not sure either

#

definitely weirdest bug I've ever had

#

thanks for helping out!

astral kernel
#

but it doesn't give any errors

ancient sequoia
#

Alright, Im getting some weird behavior in Unity 2023.1. My coroutine is not waiting for my async to finish. The code roughly looks like this:

StartCoroutine(function)

public IEnumerator function {
yield return AsyncFunction();

*do stuff that requires AsyncFunction to finish first (I need value2)*
}

async Task AsyncFunction() {
value = await AnotherAsync();
value2 = await AnotherAsync2(value);
*store value2 to memory*
}```
sly grove
#

unless they introduced that recently

#

you can't yield return AsyncFunction()

#

that will just wait one frame

#

like yield return null;

ancient sequoia
#

Oh, it will only wait one frame? I thought it waited like with
yield return new WaitForSeconds(2);

sly grove
#

you would need to do something like:

Task t = AsyncFunction();
yield return new WaitUntil(() => t.IsCompleted);```
sly grove
#

it only knows how to deal with special things like WaitForSeconds

#

It has no idea what a Task is

ancient sequoia
#

Wooooow, thank you for your help Praetor! Citric_Love I will try out your code snippet! Sounds like I need to convert the whole function to async rather than snippets.

#

Yaaaay it works! PogG You are amazing Praeor!

fossil girder
#

I need some help with rendering issue.
When I drag the game to enlarge or reduce the windows size. The graphics does not get resize properly.
This only happens with xiaoxiao921’s DearImGuiInjection.
I assume the issue is with DX11, but I am not sure how I can fix it.

dusky kettle
#

Hey guys, I'm trying to get the water in HDRP to simulate in game time instead of unscaled time, and I think I've found the part of the code that I would need to modify to do that, but the problem is that this class is an internal class. Since HDRP is a package I don't see a way to modify it without outright copying the entire thing and changing the names, does anybody know if there would be a more elegant way to override this update function without ruining all future updates and compatibility?

#

this update function is in the internal class WaterSimulationResources and I found it in at Library\PackageCache\com.unity.render-pipelines.high-definition@14.0.8\Runtime\Water\HDRenderPipeline.WaterSystem.Simulation.cs

#

im on 2022.3.10f1

#

im struggling to find where this update function is called at the moment, and WaterSimulationResources doesn't derive from monobehaviour or anything for that matter

#

a WaterSimulationResources object is created when the WaterSurface method CheckResources is called

#

dont see any direct calls to Update though and i didnt see any calls to Update within WaterSimulationResources either

#

man so close yet so far, i cant really see a way to get around this

#

itd be a lot easier if there was a solution that i could use to search through

#

I FOUND WHAT CALLS IT

#

unfortunately this doesnt look like the kinda thing i should be overriding

#

its the UpdateWaterSurface function in Library\PackageCache\com.unity.render-pipelines.high-definition@14.0.8\Runtime\Water\HDRenderPipeline.WaterSystem.cs

austere jewel
dusky kettle
#

🤔 how I do that

#

do you have some resource online you might be able to point me in the direction of

austere jewel
#

google Unity assembly reference

dusky kettle
#

lmfao aight

dusky kettle
#

oooh okay

#

right hmm

#

let me try that

#

im trying to figure out which assembly the water stuff is in

#

if it even is just one

#

cos theres both runtime and editor stuff here but it looked like the code was accounting for both editor and runtime mode

#

oh theres like 5 more editor scripts but im assuming and hoping that theyre not relevant

#

well that's one problem solved

#

but another created

dusky kettle
#

idk if itll work

austere jewel
dusky kettle
#

good point

#

i guess my problem is more i dont know if this override is gonna be very useful cos the override class would need to then be used

#

maybe i can override the object creation part in WaterSurface and take advantage of polymorphism stuff

#

its accessibility does make that an attractive prospect

#

id need to copy all my parameters over but thats fine

#

thats also a problem

#

okay maybe this is just the wrong approach

#

i dont know any other approach i could take tho

#

oh the new keyword

#

oh okay that sounds like what I need

#

seems like i didnt manage to fix much

#

i think its just not using the new fuinctions i made

#

since its not an abstract class

#

when it gets upcasted it just uses the base function instead of the new ones in the children classes

#

alright well theres the new problem

#

i need to figure out how to make a non-abstract class abstract

#

kinda

#

oh i can just use the exact same name???

#

but then it loses access to everything the base one does for some reason

dusky kettle
#

im looking real hard for anything i can hijack and am coming up empty

#

i realised that simulation.simulationTime and simulation.deltaTime were fully exposed and could be written to from literally anything

#

so i thought it might be possible to just to calculate the values in my own scripts instead

#

but unfortunately the simulation Update function is called right before it renders the water surface every time so im not gonna be able to get inbetween that without some more drastic changes to the entire system

#

this would be such an easy change if I just had access to the system itself

#

im not in a rush here it might just be better to make a feature request and hope they can make that change

#

that being said i think the shortest amount of time I could need would be a week, or i could be drastically miscalculating and could need months

#

idk where to even make feature requests of tiny scale like this

full zealot
#

i need some help

#

my car is driving backwards and i want to use Math.Abs (Vector3.forward * speed * Time.deltaTime); But the Vector3 keeps throwing errors with doing that

half swan
full zealot
#

thank you it worked

#

if (Input.GetKeyDown(KeyCode.C)) {
cam1.enabled = !cam1.enabled;
cam2.enabled = !cam2.enabled;

#

what does this code do

#

mainly the !cam1.enabled;

half swan
#

so it is swapping cameras

full zealot
#

ohhh ok thank you so much

#

you helped me alot

sly grove
vestal condor
#

anyone know why the text is getting a bit warped? using textmeshpro

#

you can see how the T curves slightly upwards or the top of the H isnt exactly straight

light falcon
#

how to fix references to a class if the class and file have been renamed? I recall there being an attribute that could do this

light falcon
#

yes! but it seems to only work on properties