#archived-code-advanced
1 messages · Page 81 of 1
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.
it definitely supports it in general, are you getting false from SystemInfo.supportsAsyncGPUReadback or SystemInfo.IsFormatSupported(format, FormatUsage.ReadPixels)?
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.
Hello i have question does someone knows how to access a Hololens2 filebrowther in Unity ?
thanks
they could have put all packages on git and we could do prs
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/
Thanks for your reply! I'll double check, but yes I believe I am getting false from these. I'm not sure but I think that OpenGL is not supported in versions older than 2021. However Vulkan and Metal appear to be supported.
@frosty mountain I actually think I saw your thread post about this question a few years ago. Did you have any input on this? Am I correct in saying that OpenGL in Unity 2020 does not support Asyncronous GPU Readback?
i guess you're stuck targeting GLES3 and can't switch to vulkan? otherwise if it wasn't implemented in 2020 you might have no choice but to upgrade 😔
guess maybe you could put in a different code path using ReadPixels for those builds...
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!!
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?
It was added recently, 2021 sounds about right. But I've seen it count towards a significant portion of GPU time, even with a pretty small texture readback.
Thanks! Yeah it looks like it was added in 2021 and someone on the forms confirmed that for me.
Interesting that you've seen that it's slower. I had a render texture process taking 15ms on my thread and after updating to Async GPU it was only taking about 2ms.
It wasn't slower than ReadPixels, I never used that. It was just much slower than what I was seeing on desktop, so it wasn't really worth using in my case.
But it'll probably depend on the specific device hardware and drivers.
Interesting! Thanks for sharing! I'll definitely keep that in mind. We're running on VIVE Focus 3's - so really trying to get as much performance as we can get. I'll have to play around with it a bit more and see what works and what doesn't.
how do I completely disable frustum/occlusion culling?
seems like unticking it on the URP Camera does nothing
The input system and the UI syustem are orthogonal. You can and still should use IPointerX events, etc. That stuff is part of the UI system, not the input system
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
Re: the bit about ambiguities under "UI and game input" - my games tend to have world and UI interaction at the same time.. ie, something like this (this is just a proof of concept but the idea should be clear): there's world interaction (click and drag to pan the camera) and UI interaction (click a button to deploy a unit)
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:
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.
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.
Isnt that just hashing
Random state works exactly the same way as Minecraft seeds
Sure, but all of the properties and methods on Random are dependent on how many times they are called
That's how Minecrafts prng works too
So if I want to recall the values from the 1st time a property is called, I can't
That's how all prngs work
Of course you can. you call InitState
I'm not sure what the use case of that would be though
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?
You call InitState, then you run your level generator
What's the use case for this
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
You can save the current state of the prng after 99 calls
Then use that later
I just gave you said option
I am confirming the option
No
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
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
I see
And noise functions are NOT random
I don't care too much about it being prefectly random, I care about it seeming random enough
Yes that's what noise functions are for
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.
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...)
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
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)
Not possible to add state directly. But look into https://docs.unity3d.com/ScriptReference/AnimatorOverrideController.html
And sure legacy animation can do it too
oh the worker threads? I thought you meant employees lol
yeah, thread workers
You can inspect them with this: https://superuser.com/questions/462969/how-can-i-view-the-active-threads-of-a-running-program
It's probably based on the current hardware or something
(assuming you're on windows)
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
as far as I know, no.
what are you wanting to do with it?
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
Typically for this kind of thing I just use https://docs.unity3d.com/ScriptReference/SystemInfo-processorCount.html
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
not as far as I know
rider trial expiring today, need to find my credit card 
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)
You could tint it with https://docs.unity3d.com/2023.3/Documentation/ScriptReference/Tilemaps.Tilemap.SetColor.html or use a second tilemap for an overlay or just a SpriteRenderer or Graphics.DrawTexture
Lots of options
Second Tilemap is probably the easiest to implement.
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
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.
You would have to show the code
{
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);
}
}
}
}
}
}```
there is
some of noob and ugly code hehe, but is only things im testing
absolutely ll of your rays seem to be directed directly down: Ray ray = new Ray(samplePoint + Vector3.up * (planetRadius - 360f), Vector3.down);
also I don't see the code here that ctually draws the red lines
i will put all class code minute
BTW if you're a beginner you should be sking in #💻┃code-beginner generally
´´´private void OnDrawGizmos()
{
foreach (var coord in listaDePares)
{
Gizmos.color = Color.red;
Gizmos.DrawLine(coord.origin, coord.target);
}
}´´´
ops
lol
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.
this hitNormal is hit.normal (i think its where from ray start, right ?)
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
its explain why im get errors hehe
ive changed to ray.origin
and here is the problem hehe
really thanks man
yep that looks like what your code is doing
all the rays are going straight down
not sure what you are intending to do
im trying to send rays from center of planet to a floor of planet... in point ray hit iwill spawn an tree
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?
Could just get vertex info of those of a certain radius from the middle
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
yes
yeah you'd have to raycast from outside, not from the center
hummmmm... lemme try
and calculate the ocean height to dont spawn inside ocean, right?
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
is there any way to get the number of materials on a MeshRenderer without allocating an array of materials?
You can use https://docs.unity3d.com/ScriptReference/Renderer.GetMaterials.html to avoid allocations
I don't want the materials at all
there is no materialCount property, no
I guess using a list would keep the garbage to a minimum, thanks
Your mesh’s submesh count is material count
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
Unitask just provides some convenient wrappers around the regular task afaik, so you'd use it just like any other task.
does anyone ever use notion API in Unity?
Do anyone knows if this works for Built in Render Pipeline?
https://docs.unity3d.com/Packages/com.unity.rendering.hybrid@0.51/manual/material-overrides-code.html
anybody knows why such a straightforward command like" Screen.SetResolution(x,y, true) is not changing my resolution at all?
your monitor might not support the given resolution
its an android device
and im using:
Screen.SetResolution(Screen.width/x ,Screen.height/x ,true);
to be sure the ratio is the same
you cant set exclusive fullscreen on mobile
Exclusive full-screen mode is only supported on Windows standalone player.
ow, so i shall do the same but with false?
idk, i would expect mobile to be somewhat particular about what is allowed though
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 😅
all mobile apps run in an equivalent of "fullscreen window"
but ofc thats defined by the OS
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?
basically whatever serialization framework you use will have some rules about how it decides which things to serialize or not
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
so if I get you right, instead of separating all game logic and persistent data logic, just make all game logic classes serializable directly?
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.
Occlude? Why do you need a special shader to occlude things. The default shader does that very well. Unless I'm misunderstanding the meaning of "occlude" here.
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
@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
Excuse me, does anyone ever use the Notion API with unity?
all works !! thanks for ur idea !
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.
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.
Pretty sure that Cube Marching should already be able to generate cave. If it is what you want. If we ignore 3rd dimension, the following should work.
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.
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.
Minecraft is not made with voxel, all individual cubes are cube. They arent using Marching Cubes.
Marching Cubes does not prohibit having underground.
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.
Your issue is probably because you are using a 2D noise generator for the Height and not incorporating other type of generation such as Perlin Worm.
This is what happens when I try to dig.
Cube Marching does not have the notion of Up and Down.
Either have a hard limit or have a way to dynamically generate new "chunk" as you dig lower and lower.
I did watch the video you linked, it looks like that's for cave generation but I'm trying to give volume to the terrain.
This is what you have at the moment
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.
What I have in mind is this.
That would be solution 2.
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.
What do you mean ? You have a hole because you do not have any data below it.
Wait, do you mean that if I add vertical chunks they would automatically connect with the other chunks therefore making the terrain solid ?
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
I mean, you might need to do some seeming between the chunk, but you would be basically doing the same as increasing the height of your chunk.
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.
Why ? Just fill your chunk with filled data and not empty
It's far below the y height of the ground, so why would you generate the ground surface there
Well yes, that's what I want as well. Of course I do not want internal walls as long as there's solid stuff connecting to the chunk (like other chunks) but when isolating a chunk or slicing it, it should appear as if it's a solid piece of ground (but only then, otherwise the engine would have to render stuff the player wouldn't even be able to see anyway, so there's no point).
I was just trying to show the fact that my terrain only generates the ground level and there is nothing solid underneath, so I thought that if I generate chunks vertically, it would just do the same for the other chunks, therefore creating a bunch of ground slices on top of each other, separated by air.
Then it shouldnt.
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
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.
It does exactly this @austere jewel
See, nothing bellow the terrain layer.
There is someting, it just not generating it because it isnt needed.
If you fill the whole things with white dots, it wouldnt generate anything till you make a dot black.
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.
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 ?
If there is no transition between black and white, there is no mesh. If you want something below, then generate a new chunk filled with white dot (In your case).
Let me actually do that and see what happens.
I'll be right back with the results.
It is hard to be more explicit then this.
Unfortunately it looks like I was right, the result is exactly what i thought it will happen, told you guys.
Visualize the points. Make a snapshot where you show the points as reference
Give me a moment.
M1 melting 😆 hold on
So, from what you see, which version you have from the picture I sent ?#archived-code-advanced message
The first one (left)
Exactly, then it is expected to have what you have.
You want the right one
It just means that you have to change every points under to a red one
I apologise, updated the visualisation to be a bit more readable.
The other one is better
It really encapsulate what Cube Marching is.
However, in both case you see the issue. You need red, not blue under
Do you have any idea why is it like that ?
As in, in which one of the scripts do I have to look for the issue ?
I mean, you are definitely able to answer that.
Just look at the correspondence between the pattern.
Well it's not the ground percent. The issue is somewhere else, cause even when the dots are red, there is no ground bellow.
Ah, I think I get it now. The blue dots represent the ground, not the red dots.
Ah, nope. Actually, red is indeed ground. So basically back to square 1, ground isn't solid where it should be.
If anyone knows what exactly causes this to happen please let me know. You can have a look at the scripts I am using here.
💡 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.
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
@zenith osprey Tried changing your physics precision?
In project settings somewhere
Probably yes, I played around and increased all physics settings based on the docs
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)
does anybody know how to request API post with unity?
I previously did use the programm postman to test my requests. It can also generate you C# Code for the requests that also works in Unity.
https://learning.postman.com/docs/sending-requests/generate-code-snippets/
Otherwise eg. this post looks promising
https://stackoverflow.com/questions/51926762/how-to-write-http-post-request-in-unity-by-using-unitywebrequest
okay thank you
its driving me crazy with this Notion API, the syntax is correct but it keeps resulting bad request 400
Usually it will also give a message explaining what's wrong with your request
400 just means the request is invalid it doesn't necessarily mean a syntax error
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
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!
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
Here's one way.
Vector2 input = HoweverYouGetInput();
Vector3 input3D = new Vector3(input.x, 0, input.y);
Vector3 camForward = cam.transform.forward;
camForward.y = 0;
Quaternion camRotation = Quaternion.LookRotation(camForward);
input3D = camRotation * input3D;
// Now you move/rotate your character in the direction of input3D
Cheers, worked perfectly.
While my old way worked, it was giving me wacky values when I zeroed out the stick which I didn't want.
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
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.
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?
UnityAction stringFunctionToUnityAction(object target, string functionName)
{
UnityAction action = (UnityAction)Delegate.CreateDelegate(typeof(UnityAction), target, functionName);
return action;
}
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?
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.
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
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
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
what
could you elaborate on that please
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
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
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
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?
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
?
If you're tweening the Quaternion how is that converted into movement?
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
Look it should be simple.
- Set the start rotation from your start, end and end rotation
- Tween between start and end positions
- for each tween calculate current rotation based on distance traveled
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
your problem is you are tweening the quatenion when you dont need to
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
the start rotation needs to be backwards-engineered from that
yes
this is not relavent then
so what have I misunderstood?
and is not the problem
because atm my issue is that i dont have a functional way of determining what the starting rotation is
yes you do, the math given by Gpt looks ok to me
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
Ah, so quaternons dont work the way you want them to, my solution negates that problem
you're going to need to give me an example mate cos im really not following what your solution is
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
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
that was just an example, it will work for any distance
but it's not returning it in terms of the axis it needs to rotate around
okay this is just going in circles rn
the problem still stands here
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
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
thats an extremely janky solution dude
it would be a lot better to just return one vector3 with numbers that exceed 360 in magnitude
no, it's a game dev solution
brother what are you on about
it's one that
A) Works
b) is easy to implement
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
best of luck with that, considering you had to use GPT in the first place, bye
😐
bump for anybody else who might be able to help out please
Not sure I understand what you're asking.
You can get the difference in rotation in angles by subtracting the initial rotation from the final one.
yeah im just ttrying to calculate that initial rotaiton
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
Oh, if you have the final state and the angular velocity, you can calculate it. Assuming the angular velocity is constant. You can also calculate the angular velocity from regular velocity and circumference, but you'll need to google the exact formula.
the thing is im not using rigidbody at all
Who said anything about rb?
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
If it isn't, then you'll have to keep track of all the velocity changes.
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
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.
in fact
even without taking the shortest path
no nevermind
that wouldnt be the case
no you're not calculating the initial posiution
you give the initial position
In this case the angular velocity is constant, and you should be able to calculate the initial state.
you only are calculating the initial rotation
the intial position, final position, and final rotation are all given
it returns the initial rotation
So you have initial position and velocity?
velocity isnt really relevent here
time wouldnt affect it
unless the ball is slipping
which is isnt
I don't understand why you have initial position, but not rotation. Is the ball rolling backwards?
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
Why can't you just rotate it realistically every frame?
Just rotate it every frame a little bit.
thats not the problem
time is completely irrelevant to the problem
nor the implementation
What does it have to do with time?
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
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.
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
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.
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
Quaternion doesn't store the amount of rotations. But I don't see why you'd need that.
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
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
i was thinking just as a euler angle that exceeds 360 in magnitude
for my case I need to know the final rotation though
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
@dusky kettle Just in case you're interested, I implemented my solution, it's not perfect but it works
https://pastebin.com/LzNanN8m
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Will this work?
Vector3 positionStart;
Vector3 positionEnd;
float ballRadius;
float rotationAmount = ( positionEnd - positionStart).magnitude / ( 2f * Mathf.PI * ballRadius ) * 360f;
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?
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...
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..
it’ll calculate the the amount of degrees the ball needs to rotate yeah, but the part i’m stuck on is then getting that as a rotation around the correct axis
i’ll give this a shot when i get home, thanks for sending
You can get an axis perpendicular to it's movement direction with cross product.
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
Axis is a direction vector, not a rotation angle.
so then how would i turn that into a vector3 representing the same rotation delta
You don't, but you can use it to rotate an object around that axis .
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
You don't need to rely on dotween. In fact I'm not sure that you can use it for your use case.
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
Yeah, I think you're overcomplicating the solution...
Perhaps it would've been simpler without dotween at all.
dotween gives me free ease types tho
You can have ease without dotween.🤷♂️
regardless i don’t see how dotween is complicating it more
yeah but you don’t have those giant selection of choices tho
there’s like a billion ease types
Then I guess this would be the most appropriate solution.
yeah
idk i’ll have to actually try it
dot and cross product and all that are hella confusing
like
for this is it just
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
cross product of vector3.up and the endPoint relative to the startPoint?
You can probably issue a draw call manually, but I don't think it's gonna be much different from just enabling/disabling a renderer.
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
It takes 2 direction vectors, so endpoint - start point, up.
Yes, but you don't need a separate GameObject for it. You can issue these commands from your game manager or something.
Still isn't worth it imho.
Well, depends on the context I guess.
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
Why not use some kind of pooling system?
well - more code to write for meshes that only there temporarily
only once i finally click i solidify them in place
I mean, issuing a draw call is not a one line thing either...
Hmm
since i have a List<Mesh> alongside List<Material> i was thinking of using it
I guess there's this then. Still need to calculate the world matrix and stuff.
Yes. This and many other things.
Seems like you can create that matrix with utility methods though.
i dont even know when these functions became a thing
unity just sneaks them in and tells no one 😄
I think they've been here for a while. Just never had a need in using them.
ah i see one downside it wont cull as it has no bounds
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 ?
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.
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?
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..?
Calling create? Rn the project uses a render texture I made in the assets folder. Do I need to create one at runtime?
ah, I don't think that's needed..
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.
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.
eventInfo is actually my custom type so I know whats inside XD
Im actually trying to, lets say, expose UI events in inspector in form of UnityEvent
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
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
There is already a ton of solution on github. You could just snatch one or copy one.
https://github.com/Baste-RainGames/SerializableAction_Unity
https://github.com/Siccity/SerializableCallback
https://github.com/wlgys8/SerializableEvent
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
I am pretty sure I sent you the solution #archived-code-advanced message. What was not working ?
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
copy created in such manner isnt serialized, and there is more data needed to be copied that isnt straight forward accessable, either more reflections or fooling around serializedObject
but one of these may be easier to copy, but this is definitely not a worry for now for me
If you want serialized you want to use https://docs.unity3d.com/ScriptReference/Events.UnityEventTools.AddObjectPersistentListener.html
I love and hate how many such helpful methods are hidden somewhere in a little classes no one knows about...
Most of them are hidden behind a google search though. But yeah, they are really spread between a lot of class. Keep an eye on those "Utility"/"Tool" class, Unity likes to have a lot of them for the editor.
Hi, is there a way to get gameobject before their awake call for each new scene?
"get" it for what purpose
theoretically script A can reference an object in its own Awake before some other script B runs, if that's what you mean
for injecting dependencies
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
it works for first scene , what about others which will be loaded later
it will only work if the dependency injector is in each scene, not DDOL. If it IS a DDOL, you could have a stub object in each scene which just invokes the dependency injector in its awake using script execution order settings
e.g.
public class DIStub : MonoBehaviour {
void Awake() {
DependencyInjector.Instance.InjectFieldsForScene(this.gameObject.scene);
}
}```
thanks
Callback invoked when the first scene's objects are loaded into memory but before Awake has been called.
https://docs.unity3d.com/ScriptReference/RuntimeInitializeLoadType.BeforeSceneLoad.html
https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
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.
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?
An image for my previous comment
Does it not follow it now?
*rotate towards it.
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.
Why not just use 3d physics if you need depth?🤔
Because tilemaps don't support 3D colliders, and 3D physics can't interact with 2D.
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.
My game is procedurally generated, so generating collider meshes on the fly is kinda expensive.
Otherwise you're just reimplementing 3d physics in an awkward way.
While it's not cheap, it's totally possible.
Minecraft managed that somehow. And it was written in java.
You can use jobs or compute shaders for the heavy processing if needed.
I was going that way, but it smelled like overengineering, so I'm checking if there's any easier solutions. I don't need a full custom rigidbody implementation. Non-overlapping collisions would be enough to me actually.
Well, you don't have a way to do that without relying on layers(only 32) or butchering the collisions and stuff.
Perhaps I could do a simple custom CharacterController2D using raycasts and tile checks.
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.
This is a test with 3D tilemap colliders I made.
Will try to optimize it with Jobs, just need to understand it better firstly.
Thanks for your help!
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];
...```
Here's the whole trace log:
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.
Do you need to read the data from that array or are you just using it as a reusable temporary buffer for your method?
Yes
That's being read/written too extremely often
But do you read the data that was previously in it, or are you overwriting it immediately?
Oh damn wait I see what you mean
It didn't occur to me I was writing to the array I was spanning 
Thank you-- I can't test now but I'll let you know
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.
Ahhhh
Well damn
Long-lifespan native array it is?
Wait can I span a native array?
Yeah. You could still wrap a span around that though.
But I would still create the span outside the method and pass it in
Hmm, you might be right
Hello I'm working with asperite importer, how can I enable a layer midway through my animation,
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
That's not possible because there isn't an array for each key. It's stored as a linked list, so it has to be enumerated.
Ahh, I see. Thanks
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 ?
what type is _services?
private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
you cannot remove an item from the object of a foreach anyway
ok i will fix that but the issue is why it is not null when it's destroyed
it's because you have the value type as object
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>
or just UnityEngine.Object
foreach (Type key in _services.Keys.ToArray()) {
if (((UnityEngine.Object)_services[key]) == null) // do something
@upbeat path @sly grove thanks
basically
You have to
I have to what?
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.
No. I have not seen, nor can I think of a workaround that doesn't involve a wrapper type
Unfortunate. Thanks!
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 ?
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, /
At this point you better of implement your own terrain system that generates the blocky mesh.
yeah i was afraid of that answer :/
Maybe the issue is with how you get the results or interpret them?
It's really hard to help with that without seeing the code.
True that.. I'll try a bit harder tomorrow, and if stuff doesn't work I'll create a simplified script to show-off the problem
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!
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?
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 🙂
You can find all components using :
https://docs.unity3d.com/ScriptReference/Resources.FindObjectsOfTypeAll.html
But I think this will also return prefabs in your assets folder, or something like this, you might need to filter the results somehow to make sure you are only looking at Renderers in your scene maybe.
Thanks, thats what I do, but it has some pretty crazy overhead
Would Tagging be a solution in your project?
If you made a tag and then made sure all your Renderer gameobjects had that Tag, then you can find them super fast using GameObject.FindGameObjectsWithTag()
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
I'm not sure of any other method, other than have a root object in your hierarchy, and then transform.GetComponentsInChildren<Renderer>()
Maybe you could maintain a list of all root gameObjects, and then use the GetComponentsInChildren on each of those?
yeah thanks, I thought it might be the case.
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
What's the use case for you needing a faster way to find the Renderers? Maybe there is another solution that would work for your project.
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
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.
Usually, Unity does not needs to "find the repository". It does not even knows that it has one. You just send the link of your repository and make sure that other members have the appropriate permission.
when I try this I keep getting the error that the git repo can't be found, even though I've double checked the path and everything. Is there something I'm missing in the setup here?
That standard Git issue I would assume. Simply Google it and you gonna find a gazillion possible issue. (Remove Unity from your research)
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?
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
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?
If the texture you need to sample is dynamic, that is you have to calculate the index in shader, then Texture2DArray is very convenient. The alternative is... what? A big switch statement?
What do you mean with dynamic? Like, something regenerated at runtime?
In a shader no less 😰
More like if your character has several states and you need to know which state to sample based on what's going on currently
Maybe you want the position of the pixel to determine which texture to use, or the vertex color, or something else that you can't know ahead of time.
hmmmm, I see
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.
They're useful for when you have an unknown number of textures, which can change at runtime, like shadowmaps for example. But the limitations of all textures in the array having to be the same size leads a lot of people to just make a texture atlas (which has it's own problems, especially with filtering, but whatever)
Wait, isnt triplanar mostly for sampling the same texture, but across different uv inputs?
An unknown number of textures which can change? Do you have a game example where this is done? Or is this in a similar line to what Praetor explained?
You can sample the same texture three times, but you can also sample two or three different textures, which is not uncommon, such as for drawing a grass texture on top and a cliff texture on the sides of a terrain.
Ohhh, I see
It should become obvious to you if you would benefit from using Texture2DArray, because the alternatives will be very inconvenient.
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
If you're talking about serialized arrays, then no. There's no lazy loading in Unity's serialization.
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.
Resources folder is also not lazily loaded. It's not recommended because everything in it will always be loaded at startup and remain loaded throughout the game.
ok
Unity has the Addressables package which can solve this problem.
ok I know nothing of this, can you pls explain?
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.
Does anybody know what changes are in Burst 1.8.9? The changelog is blank; https://docs.unity3d.com/Packages/com.unity.burst@1.8/changelog/CHANGELOG.html
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
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?
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.
you could always pass it in as a shader parameter from C#
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]]```
there's no stack trace there unfortunately
Does you project have a custom android manifest file?
Perhaps it's being mentioned there
It would be called AndroidManifest.xml
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)
Yep, it seems like I was mistaken. MaterialPropertyBlock it is
i'll take a look in the files.
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 😢
if you can't find it in any manifest, look for any scripts you might have missed that might be inserting it during a build processing step (ex: https://docs.unity3d.com/ScriptReference/Android.IPostGenerateGradleAndroidProject.html)
I'm fairly certain that is the issue - since I can't find anything in my project. I can't find anything obvious while searching my code base but will try to look more.
Dumb question but have you tried searching for "facebook" in your entire project?
Yes I did lol - that was the first thing I tried.
you searched where/how though? In your IDE? In Unity?
Or with some other tool
If possible I'd use something like this:
https://stackoverflow.com/questions/16956810/how-to-find-all-files-containing-specific-text-string-on-linux
should work in e.g. git bash or mingw32 if on windows
i've searched with my IDE & in my Unity project. The only thing that comes up is a link from Appsflyer for deeplinking but that is not currently used for anything.
interesting - i'll take a look.
Hello, does methods in math run faster even without BurstCompiler?
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.
I don't think so. Even if they do, the difference is probably negligible.
But math has SIMD optimization. Will that affects computation outside BurstCompiler?
No. Single instruction multiple data is one of the optimizations that burst enables. Without it, it's not in effect.
What if I'm doing matrix multiplication?
If you need to assign them via the inspector, use https://docs.unity3d.com/ScriptReference/ColorUsageAttribute.html
I'm not sure. Test it. I bet that there isn't much difference.
Ok, thanks
i want to do it via code
everything is in a file. its being set through an editor window button.
From what I understand, an HDR color is just a normal Color in memory. The inspector just makes the calculation for you.
It takes the base color and increases its brightness along all the 3 components.
For the exact formula you'll need to google
I've tried multiplying the color amounts by the intensity amount, and it made the color intensity nearly max.
It went from 1.4 to 8.7 by multiplying the color values
Yeah, I'm not sure that's as simple as just multiplying the values by intensity.
I could use min and max exposure, although deprecated I think that affects it
I'll have to test
It's even slower hahahaha🤣
Probably some overhead necessary for burst.
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`
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.
You'd probably need to look up a plugin that provides that functionality or write your own(it would probably involve writing a native plugin and C# bindings)
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
once you allocate a native/unsafe something then immediately put its dispose() in OnDestroy or somewhere else
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 ?
what do you mean "gave them different submesh indices"? Set second parameter of CombineMeshes to false, rest of code stays the same
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
in the input? If s has 1 submesh and you specified subMeshIndex 1, it's naturally not going to appear
huh
am i not specifying that i want mesh s to be submesh [1] of final ?
i presume thats what it means
no
yes
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!
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
what are the texture settings on your texture? Maybe it's being clamped
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
yeh its inefficient it was a quick job to figure out why the uvs wont work
let me try what you suggested
worked for the default plane 😭
what does that mean though for my generated mesh
surely its not the vertex values
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?
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
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
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
wtf
it just suddenly decided to work
🤔
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.
the radius is set to 0.05 not 0.5 in that image
Sorry, I wrote it wrong. Actually it will be 0.05f.
Any smaller and the navmesh agent steering will bug out
Are you sure about this? In previous "Unity AI" versions, Agent Radius could be reduced to 0.01f.
I'm not aware of that
Maybe the inspector is stopping you but in code you can still use a smaller value
I tried this, but even when I change the radius value through the code, the radius value updates itself to the minimum value of 0.05f while creating the NavMesh Surface.
The problem is probably not on the inspector.
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.
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
Usually, you do not want to get that small. My advice would be to change everything so that your unit is not meter but centimeter. (Multiply the size of everything by a factor) In other words, your 0.05 would be 5. Remember, Unity Unit is whatever you want it to be.
It seems I have no other choice. Thanks!
My question was not resolved yesterday night, so I'm asking for this again, to see if today morning people can answer 😦
i want an object to follow exact player movement with some offset but i have no idea how to do that, help pls
Could you make the object a child of the player object, then it will always maintain the same offset.
no, like multidimensional baby in The binding of isaac
Player moves and after for example 2 seconds the object follow players path
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();
}
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
!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.
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
I am aware, which is why it's so strange
(would recommend using string interpolation to make that cleaner though)
it is part of a larger algo, the algo breaks and creates a different outcome when I remove the debug
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
how am I misinterpreting, when I remove the debug, the outcome is different
and adding the log slows it down enough to change the behavior
nothing is multithreaded
you'd have to give more details
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
I thought the same as well, but I'm sure it's not the case
another possibility is that doorNumber < some of these things are properties and the getter for the property has side effects
I removed door number and several other parts of the debug and it worked fine
are any of those things properties?
only upon removing " doorEnd: " did it break
how are you so sure?
and again, what is the nature of the breaking
it causes the function to return false in a case where it is true
nothing is moving, none of the properties are changing
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
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
show the two functions?
are any of these properties?
currentPointX nextInterruptionX door?
no
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
that was my thought as well
but how does calling debug change it that?
or affect the results
not sure...
spooky
especially since the debug.log is after the bools are already computed
What happens if you just call the same function twie
the one with the debug or without?
Debug.Log("First");
Debug.Log(DoorLiesWithinIntervalX(...));
Debug.Log("Second");
Debug.Log(DoorLiesWithinIntervalX(...));```
I guess either one
but let's say without
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
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?
I'm not sure either
definitely weirdest bug I've ever had
thanks for helping out!
it doesn't work
but it doesn't give any errors
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*
}```
coroutines do not work interchangeably with async
unless they introduced that recently
you can't yield return AsyncFunction()
that will just wait one frame
like yield return null;
Oh, it will only wait one frame? I thought it waited like with
yield return new WaitForSeconds(2);
you would need to do something like:
Task t = AsyncFunction();
yield return new WaitUntil(() => t.IsCompleted);```
WaitForSeconds is special
it only knows how to deal with special things like WaitForSeconds
It has no idea what a Task is
Wooooow, thank you for your help Praetor!
I will try out your code snippet! Sounds like I need to convert the whole function to async rather than snippets.
Yaaaay it works!
You are amazing Praeor!
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.
Ok, thanks.
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
OH
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
Use an assembly reference so you can add your own class to the assembly and do whatever you want
🤔 how I do that
do you have some resource online you might be able to point me in the direction of
Unity assembly reference
lmfao aight
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
i suppose i can just try doing a janky override here
idk if itll work
why are you making it public? The class must be the same or less accessibility than what it inherits from
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
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
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
you would use abs on an element. Not the vector itself. It works on ints/floats/doubles
Also, try transform.forward instead of Vector3.forward?
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;
It toggles the enabled state.
.enabled is a bool. So if it returns true (it is enabled), it SETS it to the opposite (disabled)
so it is swapping cameras
! Is just the negation operator for bools. Turns false true and vice versa
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
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
yes! but it seems to only work on properties