#archived-code-advanced
1 messages · Page 102 of 1
Can we make a draw like stuff during runtime. Is that really possible in unity. Just like paint.
Yes
How?.
About utility AI, I have seen it is generally implemented and the score is calculated using AND operation (multiplication) between consideration scores. Is it correct?
Is there any more complex approach to combine them?
For example: C means consideration score
R1 = (C11 * C21 * ...* Cn1)^1/n
R2 = (C12 * C22 * ...* Cn2)^1/n
Rn = (C1n * C2n * ...* Cnn)^1/n
R = Max(R1,...,Rn)
i will check it out. thankz.
Is there any way to debug events that the editor is calling to know which ones are being called when certain actions happen?
You have interfaces like ISerializationCallbackReceiver for serialization purposes
there's a few others around but I usually use that when I notice references not bind / working or need to do extra work
You can get the stack trace with new StackTrace(). But why do you need this? If it's for debugging, just use a breakpoint.
The thing is that I wouldn't know where to place a break point. It's probably something related to unity so I don't even know if It would jump to the code related. Plus, is it safe to apply breakpoints through the unity editor?
I use them for editor scripts, sure
Yes, why wouldn't it?
I don't know, I thougt it might make editor non responsive and crash
It's going to crash if you have an infinite loop
It doesn't crash from the break points
Just put the breakpoint where the "certain actions" are and then you can see the call stack to see what led up to it.
alright, this one didn't work
Okay! Im gonna try that
It seems that AssetDatabase.Refresh is what breaks it
After 2 days trying to make InputFields work on mobile, I've started to wonder, how do you guys implement input fields?
It's so bad I cannot believe mobile devs use this.
Any advice would be awesome: asset store/github links etc.
If everything is perfect for you, would love to know what Unity version, TMP version, Input System you use.
Better question for #📲┃ui-ux but usually I just make my own in-game keyboard and make my own input fields using stuff like IPointerHandler for input field selection
oh, thanks, but hope I can avoid this 😄
Hi can some one have a look at my saveManger please. It seems to work, but the more i save the more random destroyed items seem to come back https://gdl.space/xeliwumoji.cs
Wdym by "random destroyed items come back"? And how do you know that?
why is there no evidence that you have even tried to debug this?
There is evidence. I just removed my debugs.
i think i worked it out. think my unique id was a clash
so i created a Editor script to regen a new unique id
2 secs i will test
yh dont worry i see my id now
why would you remove debugs and then come here for help?
leaving in the debugs and showing us the console output helps us to help you
I just added the script that i had at the time
but see your point
maybe you can tell me if this is wrong
So because im using prefabs the Uniue id that im generating will be the same for each prefab. hence why i brought in this editor script that contains a button to generate a new id. But i can clearly see that the prefab is waiting for overide(update) what ever its called. Wound you say this is safe at runtime
Not on the basis of that, no
ok so not over riding prefabs is ok?
I've no idea, you are not providing anywhere near enough information of what you are doing, what you expect to happen and what is actually happening
here is my prefab
with a unique id
every time i make a copy of the prefab the id will be the same
So i make a generate new id
But im not overriding it
to make each one unique, is that safe?
when it come to builds
what do you mean you're not overriding it?
What are you using these IDs for? Are you sure you need them to be GUIDs?
meaning i have not updated the prefab with an override
So the id is for when i enter a scene i load my saved data and it will destroy all gameobjects i have already collected
i mean i could unpack it
but that makes no sense, one thing you can guarantee is the the id's in your save file willl not be in the currently running instance if you generate a new one upon instantiation
Can you not just use an int for the ids?
well it is working. my issue is can prefabs work with out override on builds
does not matter what he uses, as I understand this the whole technique is flawed logic
yes i could use an int, but i went with this and feels like extra work if i can get this to work ok
can you explain why this is flawed logic
Well, if it works, you do you. Just know that you're probably using exponentially more memory/disk space than you could.
yh so this again is what i need to know. is it just becuase the id has more digits and takes up more space?
or somthing else
well, from what I see is you are trying to match data from a save file to data generated in game. But how can an instance id generated in game ever match an instance id from a save file?
It takes more bits to store, yes. Though it's probably unrelated to your issue.
public List<string> destroyedObjectIDs = new List<string>();```
{
if (uniqueID != null && !string.IsNullOrEmpty(uniqueID.uniqueID))
{
GameManager.instance.destroyedObjectIDs.Add(uniqueID.uniqueID);
}
yield return new WaitForSeconds(1);
Destroy(gameObject);
}```
so my game manager holds a list of destroyed objects
then when i pick up an item it adds it to the list ready for when i save
then when i save i clear the list
So it only ever saves when i want it to. but will always store the collection no mater what scene im in
And then when you restart/reload. You try to re-instantiate the objects with a completely new id and try to match it to an id from the save file?
no the id are what i said they are just generated with a button on my scene. they are never generated at run time, Im talking about the the prefabs that i say have 3 of them in at one scene
is this what you mean?
this is a terminology problem. You do not have prefab in a scene you have gameobjects in a scene
which may just happen to be made from a prefab
yes so these are the prefabs
no they are not
so are you saying they are just game objects unless they are instaciated ?
they are gameobjects made from prefabs
yes correct
so they aint prefabs, they have their own life
so back to my original question, is there any harm using a game object that are made from prefabs but hold infomation that i have not over riding
or would it make scene to just unpack them
sence
no, the only problem with your system is if you are instantiating from prefabs at runtime
awesome thanks steve. out of interest can you tell me why you would not do it this way? am i making this over complicated?
tbh, I would just use the instance id given by Unity. Once your prefab is turned into a gameobject in the scene it is given an instance id and that does not change
It depends on the information. Is it information that is unique to each instance? Or shared among all the prefab isntances?
Assuming it's the id that you use to identify a specific object in the scene, it obviously needs to be unique to each instance and not shared among them.
Ok so unity can give unique ids?
yes each needs to be unique
object.GetInstanceID(). But use wisely. Not to be relied upon for runtime instantiated objects
and does that id have its own id so if i had 2 gameobjects that where prefabs they each would be uniqie?
absolutely, when you copy a prefab into a scene and turn it into a GameObject it gets a unique id
I really appreciate all your help, thanks so much for your time
and you dlich i appreciate your help tp
to
Not sure we understood that question correctly. Might want to rephrase it.
thats ok i think i know the direction i want to go now
There is something which I want to know did anyone ever tried making a game like paper.io
I was thinking about it but the only option to make that is terrain painting through script during runtime.
I want to know is there any other option of making such game other than terrain painting. Because terrain painting is heavy.
Seems easy to handle with splines and mesh generation
Quite performant as well and simple tbh
You'd generate a spline (https://docs.unity3d.com/Packages/com.unity.splines@2.0/manual/index.html) behind the user and at the moment of connection generate a mesh based on the vertecies provided by spline. Slap a texture on top of it if you want to as well
This might provide more info as well https://catlikecoding.com/unity/tutorials/curves-and-splines/
It's all editor-only links, but the idea is the same during runtime
Catlike coding also has a good tutorial on mesh generation (https://catlikecoding.com/unity/tutorials/procedural-meshes/) of which you probably need only a few of the first ones
They look interesting will check tomorrow. Thanks for the links.
Hey! Anyone have any idea in custom timelines, when and how FrameData.seekOccurred returns true? For a custom track with its own mixer and underlying clips, I'm receiving FrameData.seekOccured = true after I add more than 3 tracks. I can't track this down at all.
I have awake function on an abstract class with some code and I want the children to define their own awake function and maybe run the function on the abstract class as well. How do you achieve it.
I thought about making a virtual function with some code on the abstract class then maybe override that function and call something like base() to run the abstract class version of the code.
Is there anything like that in c#?
yes of course. C# is an object oriented language that supports virtual and abstract methods
public override void Awake()
{
base();
target = playerMovement.GetCurrentIndex();
FindPath(currentIndex, playerMovement.GetCurrentIndex());
}
public virtual void Awake()
{
audioPlayer = GetComponent<AudioSource>();
}
The second one is on the abstract class
I want the references to be set
but If I override then the code in the virtual function wont run
base.Awake() not just base()
Your IDE should auto fill this when you autocomplete the override
one sec
ah damn
base is the class reference
I was thinking of it as the base function
thanks
so no one knows how to correctly update backfillTickets?
use unity multiplayer networking discord.
okay thx, let me delete it from here and post there then
hello has anyone ever used mlagents and run into this: TypeError: list indices must be integers or slices, not str when using mlagents-learn and then running the project
here is my crash report: https://hst.sh/johofuriyu.sql
Hi, I'm trying to apply a perlin noise across all x terrains in my scene, but they seem to be getting wrong values entirely at the edges, could anyone take a look at this iteration and let me know if I seem to be doing anything wrong here? I'm looping through all 9 terrains here at t, afaik I should be reading from the same noise map each time, but it's like I'm not. I'm assuming there's something wrong with my position calculations? The terrains are 1000 wide (hence the magic number)
Vector3 terrainPosition = t.transform.position; Vector2 terrainHeightmapPosition = new Vector2( // convert from world position to corresponding heightmap position (terrainPosition.x / 1000f) * t.terrainData.heightmapResolution, (terrainPosition.z / 1000f) * t.terrainData.heightmapResolution ); for (int x = 0; x < res; x++) { for (int y = 0; y < res; y++) { Vector2 position = new Vector2(terrainHeightmapPosition.x + x, terrainHeightmapPosition.y + y); mesh[x, y] = Mathf.PerlinNoise(position.x * 0.01f, position.y * 0.01f) * m_Multiplier; } } t.terrainData.SetHeights(0, 0, mesh);
it looks like this
Unless res is 1000 this won't line up
Let's say res is 100 then you would have:
0.099 next to 0
For example at the edge
But they're 1000 wide each in actual world units, I divide and then multiply by the res to convert it to heightmap units. If I just use the terrain position directly, it's still way wrong. What would you suggest?
What is res
Terrain world size doesn't matter
res is 513 currently, it was just the default maybe will change
You need to also divide the terrain coordinate by the same 1000 if you want it to line up
I need to factor in the terrain world positions so that the perlin waves flow nicely across
sorry I'm confused, am I not already doing that?
you probably just need to rotate your terrains. index 0 is not going to match index 999
Yes. I love you.
the other option is to switch iteration depending on terrain number
odd number for 0 to 999
even numbers for 999 to 0
I just had to set mesh[y,x] and it's generated much better thanks a lot
I do still get these small seams though
that could be floating point error in the positioning, try to close them up by 0.01f
what do you mean by closing them up, sorry?
when you position your terrains dont try to position exactly next to each other, make a very small overlap
I've positioend them all at 999.99 increments, still have that small line looked exactly the same whe nI loaded
that would tend to suggest that your terrain is larger than the number of iterations
how can i make a gameobject look at an orthographic camera? If i use the default LookAt it looks off in some angles when the player moves.
my terrain is 1000 units wide, heightmap is 513
I'm iterating through the heightmap as that's what I'm assigning to
show me your code again
private void UpdateTerrainHeights(Terrain t) { var res = t.terrainData.heightmapResolution; var mesh = new float[res, res]; Vector3 terrainPosition = t.transform.position; Vector2 terrainHeightmapPosition = new Vector2( // convert from world position to corresponding heightmap position (terrainPosition.x / 1000f) * t.terrainData.heightmapResolution, (terrainPosition.z / 1000f) * t.terrainData.heightmapResolution ); for (int x = 0; x < res; x++) { for (int y = 0; y < res; y++) { Vector2 position = new Vector2(terrainHeightmapPosition.x + x, terrainHeightmapPosition.y + y); mesh[y, x] = Mathf.PerlinNoise(position.x * 0.01f, position.y * 0.01f) * m_Multiplier; } } t.terrainData.SetHeights(0, 0, mesh); }
A simple foreach loop to get the Terrains
this tutorials didnt worked out but i understood how to fill a spline curve.
Yeah, as I said, they're editor only and meant to give you an idea
Glad you know how to proceed
How can i make a window popup after the asset is imported?
Right 🙂.
AssetPostProcessor
I never used such assetpostprocessor Steve is there really such thing.
you think I make this shit up?
https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html
Got to check it out.👍🙂.
Assetpostprocessor got plenty of options. And you are genius person Steve. You can make it if you want to. I believe in you.👍.
wtf are you talking about?
You know alot in unity got to learn alot from you Steve.
I would have thought you were experienced enough to teach yourself, just read the docs
Hey,
is there maybe someone who knows OneSignal and used it before?
I'm making a portal system using the stencil buffer and I've now run into this issue that I can't for the life of me get to the bottom of.
Essentially, when I use the function someCamera.CalculateObliqueMatrix(Vector4 nearPlane), the projection matrix produced by it has the correct near-clip plane, but the far-clip plane is all over the place when I approach the portal surface. I've been able to read up on the depth buffer and clip-space and it appears to be because the near-clip distance approaches zero as the camera approaches the portal surface, and so the clipspace/depth becomes very funky and the far-clip plane appears as if it comes closer to the camera (and tilts oddly if the camera's line of sight isn't perpendicular to the portal plane).
However, I've been basing the general portal camera system off of existing guides and tutorials, such as Sebastian Lague's "Coding Adventure: Portals", or Daniel Ilett's "Fully Functional Portals in Unity URP" (both videos on YouTube).
What I note in these two videos in particular, is that they don't appear to have any issue with this "oblique near-clip plane approaching the camera's origin" deal, in fact, I haven't found any online articles or posts about this type of issue when it comes to portal rendering (specifically with the ability to pass through the portal seamlessly).
The way I compute the plane for the portal (which itself is the default unity quad mesh) is like so:
plane = new Plane(-transform.forward, transform.position);
```Following this, is where I define the Vector4 representation of the plane relative to the portal camera. In this instance, as the player's camera views Portal A, a portal camera is placed equally relative to the backside of Portal B, so we can render the view through Portal A via Portal B.
The code for getting the relative portal plane (in Vector4 form) is:
```c#
Vector4 portalPlane = Matrix4x4.Transpose(cam.cameraToWorldMatrix) * Util.GetVector4(-outPortal.plane.normal, -outPortal.plane.distance); // Util.GetVector4() produces a Vector4 from a Vector3 for XYZ and a single float for the W component.
cam.projectionMatrix = playerCamera.CalculateObliqueMatrix(portalPlane);
This is mostly the same as in the articles/guides I've found online, except they tended to manually invert "worldToCameraMatrix" instead of just using the built-in "cameraToWorldMatrix". I've tried either one, and the result has always been the same.
I suppose I'm mostly wondering why this is affecting me, but not others seemingly? It is super confusing. I'll try to attach a video showing the issue clearly.
I forgot to mention, this far-clip plane business is entirely gone when I replace the oblique projection matrix with the default, in fact at that point the portal rendering is flawless (except for the obvious case where the portal camera ends up rendering something that is behind the out-portal plane, which ruins the effect. This is also showcased in Sebastian Lague's video.)
This is virtually the same code I have, and your code also has that flaw I mentioned where the "worldToCameraMatrix" is manually inverted before being transposed, when using the already inverted "cameraToWorldMatrix" would've done the trick...
True yeah, that's what I'm figuring. I just have no clue what could be causing this, even if it is a setting or not. My near-far clip distances are 0.1 and 100 so it's not an extreme clipping-space we're dealing with. And I've tried adjusting these as well. As far as I can tell, lowering the near-clip distance and upping the far-clip distance seems to lower the "limit" for how close you can be to a portal before the effect becomes severe. But we're talking 0.01 to 10,000, it's not really good when the game's fog is at like 64 units away.
Downgrade proto fixed it you have to install the older version instead of changing your path
why do i get the error that i cannot use a managed type for my unity job if i use an interface and restrict it to struct?
public struct TestJob<T> where T : struct, ITopology, IJobParallelFor
gives error:
(0,0): Burst error BC1051: Invalid managed type found for the field `spline` of the struct `TestJob` the type `ITopology` is a managed type and is not supported```
the field in the job is private T spline;
from my understanding this should be fine
ah i fixed it \o/
SQLite ... searching for an up-to-date tutorial on this, all I found were a large number of incorrect and/or broken approaches for Unity. So far as I can tell, the correct 2024 approach in Unity is:
- Get sqlite3.dll (from SQLite.org) and put in Assets/Plugins
- Get the "precompiled for .Net Framework 4.5.1", but the one that contains SQLite.Interop.dll, not the one that doesn't
- .. and put "System.Data.SQLite.dll" and "SQLite.Interop.dll" into Assets/Plugins
- Done: any platform that ships with SQLite (most of them) will now work; any platform that ships without (consoles? some mobile?) will additionally need native-binary DLLs for that specific platform - but in theory: should then Just Work (thanks to the Interop dll)
... can anyone who's shipped SQLite3 to multiple platforms recently confirm/deny this? I don't have access to consoles etc to test on, but would like to know if the above is the right approach (NB: in the past, different / more complex options were necessary, but current SQLite this appears to be simpler).
NB2: If I understand correctly, the setup will change again sometime this/next year when Unity changes their .Net integration and/or MSBuild integration ... instead of nf-451 by default the expectation would be net-core3 by default, or possibly a different binary altogether
Advertisement doesn't belong in this channel @upbeat path
just offering an alternative
@upbeat path They did not ask for alternatives. This is not a place to plug ads
really? 'but would like to know if the above is the right approach'
If you don't have and answer to the question don't respond with ads, that is the right approach. And no need to continue unrelated spam.
I'm interested in the answer as well. Last time I looked into using SQLite I had the same experience, lots of outdated information and broken approaches. My game targeting mobile also doesn't help, there are information specifically about iOS and Android that don't agree with other approaches that claim to "work for every platform."
local sqlite for cross platform? 😵
SQLite implementation are fraught with danger, especially when shipping to console platforms. It is one of the reasons I developed my own RDBMS which, apparently, I am not allowed to mention here
I don't think there's any open source binaries that properly work for all .net platforms
A pure .NET implementation of it would work everywhere. I've never used this, but I found this:
https://github.com/praeclarum/sqlite-net
Came here to ask because SQLite.org specifically has a broard range of .net-only binaries that I'm pretty sure didn't exist / didn't work years ago.
There are many many many random trash github projects - I strongly recommend avoiding all of them. Almost all of them are badly designed, incompete, undocumented, buggy, unmaintained and/or written by people who apparently didn't fully know what they were doing
3.9k stars and release from 2 months ago doesn't sound so bad.
(and started over 8 years ago)
e.g. I've seen 3 different versions of that sqlite-net which are all variations on a theme, recommended by different Unity projects 😄
Yeah, maybe this is the 'root' one that the others have been badly mangling?
IIRC, when I was doing (i.e 2 years ago) it was something similar so it makes sense. I did never end up trying out the pure .net ones though
I think I did always provide the native sqlite assembly though
(wasn't aware that some platforms allow you to use theirs)
But note: that's an ORM ... and all of the variants of it I've seen so far you cannot separate the ORM from the SQL client ... in edge cases you are forced to write bad/broken/non-SQL code because you can only use it in ORM mode (I'm checking now to see if this project is different, but the docs don't appear to allow non-ORM access)
ORMs are great, but .. .being forced to use one perosn's ORM just to get access to SQL is definitely not going to be 'the right way' to do anything 🙂
It's fine that you have an asset, and some people will want that for their own reasons and/or convenience. But SQLite is an incredibly popular and old standard, I cannot believe that commercial wrppers are in any way "necessary".
For me, here, I'm looking for the 'correct, won't need to change, will work in all projects going forwards, will fully be compaiibl with any support requests made to sqlite.org, any patches sqlite.org demands will work directly because nothing has been customized, etc.
The last thing I want is to write dozens of projects that are dependent on a 3rd party asset that is not part of the SQLite project - it makes my apps harder to maintain overall. I'm very happy writing low-level SQL.
Also: Unity's handling of asmdefs, DLLs, etc, is fraught with so many problems that I have always regretted having anything more than the absolute minimum of 3rd party wrappers around 4th (?) party code. Debugging these things is hard enough, but when you get to large chains of dependent assemblies in Unity its horrible. I even wrote a custom "visual debugger for Unity assemblies" to solve some of these problems in the past
(tl;dr: I'm sure your asset is great, but for now I just want to find/document/use the 'most correct/standardized' approach)
what makes you think my asset is a wrapper of SQLite? fyi. SQLite has some fundamental design flaws if you want to live with those, go ahead
Yep, SQLite has plenty of flaws. But almost everyone I work with knows it well (e.g. I've used it extensively on native mobile - non Unity - projects for many years), so there's lots of cases where it's better to work with "the devil you know" 🙂
from my understanding of your question, you were looking for a solution which 'just worked' seamlessly across Unity supported platforms, I can tell you SQLite is not it
ah, right, I see the misunderstanding. This is code-"advanced", so I was looking for: the correct approach that, once configured (which could require non trivial effort), would work across Unity platforms.
In the past that's been a juggle of large numbers of dlls in many subfolders. Today it seems to have become significantly less tricky. But I wondered if I was doing that wrong - e.g. maybe the use of .net binaries has major performance penalties that are undocumented by the sqlite project?
You've probably already seen this if you read the README, but there are options to run SQL queries manually.
https://github.com/praeclarum/sqlite-net?tab=readme-ov-file#manual-sql
I haven't used SQL much. Are the ORM implementations usually opinionated? Isn't it just a direct mapping of the SQL clauses with some different naming and then a bunch of extra features on top of that which you don't need?
Their own example isn't SQL, it requires a type. Attemptig it with e.g. "object" causes their library to crash internally with an exception.
It's a non-direct mapping, with extra (non-optional) parameters, classes you have to write by hand beore you can execute queries, etc.
fyi, my asset does that automatically for you but, hey, I'm not allowed to mention that asset here
what's the best approach for rendering trees(and their LOD's) with physics
should there be GameObject + MeshRenderer + LOD Group
or GameObject + some kind of algorithm to render mesh data based on distance
You need to take resolution into account to a certain degree, it's mainly subpixel triangles that tank performance.
No it's like, when your triangles get small enough to the point there's multiple per pixel, rendering time increases exponentially.
https://medium.com/@jasonbooth_86226/when-to-make-lods-c3109c35b802
There's also this article here.
well, if i use billboarding for far-away trees, it won't be a problem, right? thing should be like just 2 triangles pointing to player
and also if i won't render trees which are too far
its not loading for me
might be just my country blocking
is it loading alr for you?
Medium is so/so
Really good quality articles but I use Firefox to dodge the paywalls
VPN time
How would i create a drag and drop system within unity to influence objects. something like scratch. is it a complex process?
It's just the command pattern.
Good morning. I had a curiosity about grass/foliage generation and was trying to figure out if it's possible or not. Maybe it's been done already but, is it possible to dynamically generate a height map of a mesh in Unity, without already having one? The reason I ask is because I've been trying to find a way to do so to make grass happen for my game. I've come across two separate tools and/or projects that both do pieces of what I want but can't seem to mentally construct a bridge between the two:
Note: I should also mention that the Unity Terrain tool is not an option, because it can't accomplish what I need it to, regarding the non-plane meshes in my game & Polybrush doesn't seem to do at-scale GPU instanced foliage correctly, either.
- MinionsArt's Grass Painter tool is fantastic and let's me paint grass on all the Non-UnityTerrain meshes I need to. The issue here is that it saves the grass data in a serialized array in the scene, which causes the scene file size to balloon ( 426KBs without grass, to 248MBs with grass for 1.2M grass blades in my scene ).
- The methodology behind Acerola's GPU Instancing method is another fantastic option but it only takes height/displacement maps of the meshes to render the grass.
My question is if it's theoretically possible to use an editor tool to draw where the grass should be placed on any surface of meshes (again, not Unity's Terrain), make a height map out of that drawing, and then use that to generate grass at runtime via GPU instancing? Any thoughts/input/feedback would be helpful.
So a splatmap?
Maybe? I haven't looked into those?
That's how unity paints it's terrain textures.
When you say 'heightmap', do you mean a texture that encodes the height of a mesh/terrain, or are you talking about a texture that encodes where grass should be rendered?
So, that's where I'm at a disconnect. XD The methodology behind Acerola's GPU Instancing uses a 'heightmap' and draws grass via that but I'm wanting to use Unity to make that, instead of already having one.
And again, maybe the solution already exists and I've been looking in the wrong place for a solution but I'm stumped. 
A grass renderer might use a heightmap to draw grass at the correct height, so it follows the terrain instead of being rendered as a flat plane. But what you're describing sounds more like a mask texture for where grass should appear.
You will probably need both a heightmap and a mask texture.
Could also store each grass angle in one of the color channels of the heightmap. Unless you go with grayscale
VFXGraph is pretty decent at rendering lots of grass btw
yo
come to vc
if you are still on grass problem
I'm about to come back from my lunch break at work. Could we postpone until this afternoon?
yeah sure
that's what i currently got
might suit you
grass here has a height limit, so it can't grow on hills
increased it for demo
this is the close grass
and this is far grass
So, I'm trying to avoid using the bilboarding method
Yes. As an example, I would need the grass to be generated on the inner face of this, and not the exterior
like 32+ poligons
well, you can probably use the raycast hit.normal rotated 180 degrees
I dont think a heightmap is suitable for this kinda geometry
More like 8-16 vertecies per grass blade
so grass will grow from top of smth and look down/sideways insetead of up
what i currently do is perform RaycastJob in the beginning
To get the set of positions to spawn grass on
And I agree. That's why I was trying to combine these two methods:
- Editor Tool: https://www.youtube.com/watch?v=2OA9sicjj7E
- GPU Instanced Rendering at Runtime: https://www.youtube.com/watch?v=jw00MbIJcrk
Grass system Post: https://www.patreon.com/posts/grass-system-urp-83683483
(URP and Built-in shader only)
My Github site with all tutorials
https://minionsart.github.io/tutorials/
Discord: https://discord.com/invite/astrokat
Twitch: https://www.twitch.tv/minionsart (Gamedev streams)
Twitter: https://www.twitter.com/minionsart
Patreon: https://...
While billboard grass is a performant, easy option for visualizing grass, modern games like Breath Of The Wild are able to utilize real geometry to get more interesting and appealing foliage. How can games nowadays afford to do so?
Support me on Patreon!
https://www.patreon.com/acerola_t
Twitter: https://twitter.com/Acerola_t
Twitch: https://w...
as i'm thinking, you need to pass the grass direction inside the grass shader
There is no vc in this server. You'd have to do it in dms
yeah just found out
Anybody knows a way to capture object into a texture
I want to "bake" LOD for trees by capturing it from 2 different sides and creating a mesh/material/texture to act as a far lod
like that's the tree itself, and i need to get how it looks from forward and right directions
Those are called impostors or billboards
Or both
yeah, but i need a way to create those impostors
From 3d mesh to 2 separate textures
I didnt find anything free to generate those so I made my own tool. Its still WIP though
The idea is to have a script that renders the object from a few different angles
#6 on this list addresses the Imposters rendering technique:
https://danielilett.com/2022-12-05-tut6-2-six-grass-techniques/
Manually with Camera.Render for example
and that's the thing i want to apply the resulting textures to
Get the object's bounds and make an orthographic camera fit to those bounds
Render to a rendertexture and combine the results into one atlas
Generate the mesh on the go also
Btw this mesh shape will look kinda bad unless your object is fairly symmetrical, like a spruce tree
Billboard looks better on most objects
i can probably capture a thing from 1 side only and just rotate towards the player
it's only gonna be for distant trees
which are like barely visible
Yeah, just gotta figure out the shader for that billboarding effect. Probably not too complex to make
yeah, just some shadergraph logic ig
Rotating the trees via script might be a bit heavy, but worth a try too
I did this last year with some docs I found online
I can try to find the logic for baking and the shader when I am home
Thanks
can anyone help me with an issue i'm facing when i'm trying to run a thread inside of a coroutine?
That whole concept sounds like a disaster, go on.
Well, depending on what you mean I guess
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
right, give me sec
anyway, it seems to work fine, when i run it on a single instance of an enemy inside of my game
And when you do something else...?
but when i have more of those running the same script simultaneously, it seems like somehow the threads are getting access to values from instances of those threads on other enemies?
like, its weird coz as far as i know, each gameObject runs its own instance of the script and all values inside of it should be isolated from other instaces of gameObjects running those same scripts
Well what does GameController.pathfinding.FindPath(x, y, Px, Py); do?
Well this is very problematic:
PathNode startNode = grid.GetGridObject(startX, startY);
PathNode endNode = grid.GetGridObject(endX, endY);
if (!endNode.isWalkable) { return null; }
openList = new List<PathNode>() { startNode };
closedList = new List<PathNode>();
for (int x = 0; x < grid.GetWidth(); x++)
{
for (int y = 0; y < grid.GetHeight(); y++)
{
PathNode pathNode = grid.GetGridObject(x, y);
pathNode.gCost = int.MaxValue;
pathNode.CalculateFCost();
pathNode.cameFromNode = null;
}
}```
you're modifying these path nodes 😱
presumably all the threads will modify them as they please
and clobber each other
indeed ^^
e.g. pathNode.gCost = int.MaxValue;
huh, i see
Shared resources are quite hairy for multithreading.
You could lock the whole grid for each pathfinding thread but that would essentially make you single threaded
So you'll want to rewrite this to have each one use its own exclusive copy of the mutable data
you need data isolation so that FindPath is never called with overlapping parameters
i thought doing stuff like:
PathNode pathnode = grid.grid.GetGridObject(x, y);
creates local copy of that node inside of this function
If PathNode is a class, it's a reference, not a copy
Only if it's a struct do you get a copy.
And if it WAS a copy, then:
pathNode.gCost = int.MaxValue;
pathNode.CalculateFCost();
pathNode.cameFromNode = null;```
none of these would do anything^
unless you explicitly wrote them back into the grid
Nobody ever said multithreading was easy 😉
thanks for the help anyway, at least now i know what seems to be the issue at all, instead of staring into my monitor
it's my first time doing stuff like that. And i wanted to play around with the optimization.
I guess i will have to accept having a slight lag every time enemy is trying to find a really long route for the time being.
and just somehow reduce the situations where the path is going to be very long
Have you positively identified it's a performance bottleneck? Have you profiled to see how long it takes to find a really long route?
Not really, i'm pretty much still a beginner when it comes to unity and i don't really know well how the profiler works yet.
It's just that this whole pathfinding algorithm has a pretty big time complexity as far as i know, and it's more just me deducing that it's its fault by trial and error
Yeah for any optimization, the first step is always, always profile it and get concrete numbers. Often time what people assume to be the performance bottleneck isn't actually the one, or something the technique they are optimizing is the wrong approach.
(If you are sure game can keep up with single threading, and your entire purpose of multithreading is just to prevent sudden hiccups in individual frames because of large amount of calculation concentrated in one frame, then you can simply have a queue of calculations and run them single threadedly on a background thread to not block the main thread's game loop, essentially side stepping all the complexities with race conditions and concurrent access)
yeah, i guess i'll look into that at some point. First i think i should focus more on getting the basics of all of this
Yes, profile first. If you don't have any concrete number to back up your claims, then it's not the time to optimize yet.
thanks again for help and the suggestions
When I generate a MonoBehaviour in a Roslyn Code Generator, Unity doesnt seem to pick up on it. I can't add it to a GameObject, even though I verified the code exists. Does anybody have a clue what might be the issue here?
I've never tried it, but I would assume in order to add a script file to a component, Unity does a check by looking at the file content in isolation and see if the class is there or not, which if your entire MB class is generated then it wouldn't be found to pass the check.
What's your code generation logic? One immediate idea I can think of is to just declare the class yourself but with partial, and the SG can fill in the rest.
Yeah that actually works, but it would sort of defeat the purpose of what I am trying to do. I am sort of trying to recreate GenerateAuthoringComponent from old ECS Versions, if you know what that is.
Which also means that it should be possible to do
Was hoping maybe someone who worked on that might be around here and could give me a hint 😄
Interesting, now I wonder how that worked.
What was the generated component data name and the corresponding generated class name like? I wouldn't be surprised if the component data struct passes the check then the class is used because of some naming convention.
May wanna ask in #1062393052863414313 about that. Tertle or Issue may know
The Behaviour is basically called {ComponetName}Authoring
I already posted on the ECS Forums, maybe I just need to be patient. Thought I give this discord a try, didnt even know Unity had one 😄
Ah, I am linking to a channel in this server, not the forums.
The general discussion thread gets some real quick responses
let me try
Hello, is it possible for anyone here who is a senior developer to review my code , i can add him/her to the git repo, I want to see where I can improve my code/architecture.
Just share the link here and people would have a look when they have time. You're pushing too much responsibility on one person, so people are unlikely to respond at all.
@untold moth Actually its a game I am working on it's a private repo , you are probably right , but I am looking for someone who can just have a look at it any time they feel like it, not as a responsibility. I cannot make it public for now
You could share samples via a paste site
@half swan https://easyupload.io/r8pxfl Here is the project
Hmm. That is one way to do it I guess.
I was thinking using a paste site listed here: !code
To share scripts.
I'm on my phone, so I cannot check out your project. At least not now.
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
@half swan I think it would be better to look at the project to get a better understanding of how everything is done, If i just paste the code I think what I want to achieve will lose it's essence, because I cannot paste all the code
Fair enough. Someone might be willing to do that. I am not
yeah 😄
So you can't make it public on GitHub but you can share it via a link on discord? Doesn't make sense to me, but I can have a look at it when I get back from work. Gonna be in 9-10 hours from now though.
This is like the boiled down version which gives you the overall picture of the code style and the architecture , Not the complete game , looking forward to it ,
Maybe you can create a separate repository for it then. Then me and other people would be able to have a look without needing to download it on their machine.
@untold moth I will do that , did not think about it like that
I would consider using a poco instead of an SO for your mutable data. Generally you want SOs to be immutable.
But that is a debated subject, not a hard rule
@half swan poco ??
Plain old c# object
Just a class
public class MyData { }
got it , but the reason I used SO , is because lower cost of entry, good for prototyping and not scene dependent . That is what I had in mind .
Dunno if I agree with the first, I kinda feel the opposite. I totally get the second. The third can easily be true for a poco as well with additive scene loading or ddol
Makes sense ,
Are there any particular places you're worried about?
Just about the overall code and the structure of it . Its tendancy to break if i extend it
Overall looks fine to me. It's pretty simple, so there's not much to say.
Aside from maybe what Aethenosity said. I'd have plain classes instead of these SOs as well.
But to be honest, it's not great of a deal at this scale.
alright thanks for the feedback 😄
from some of the scripts, i assume this is a flappy bird game. i presume you probably arent looking for the strictest review because of that. Overall if everything works, then not much to really say. If you can get away with simple scripts while achieving your goal this is good.
One thing is you should reconsider how you organize your folders. One general Scripts folder does not suffice when you start to have a large number of scripts. I find it nice to just group similar content. For example like all the movement stuff could go under one folder.
Another thing is some of the scripts are definitely.. questionable. Like ParticleSystemParent, im not truly sure what the point of this is. It looks like a way of trying to mass delete particle systems when every single PS are all stopped. The code itself though uses weird practices, like at line 21 its just completely remaking the array yet you're still iterating on the "old version" of it.
Another script, Ground isnt too clear on what it does. At first i was actually surprised to see the logic being done inside this script, given the name. It also seems like there could be bugs associated with it, since you never check what its colliding with. Id also just wary of using DoTween everywhere, because iirc it does allocate a lot relatively.
I do notice DoTween being used in the Movement script, lines 85 to 103. This seems to be an area thatll be called a lot, so id quickly profile it just to see. A very questionable thing: the movement script is calling _playerDataSo.InvokeOnPlayerMove(); , to invoke an event on the playerDataSO, which movement is subscribed to so it can call OnPlayerMove(). You can just directly call OnPlayerMove. Also stuff like OnFingerSwipe() you dont need to write ShootRayInDirection(); in every if statement, just write it at the end.
@tall ferry Thanks for the detailed break down, I am using layers for collision detection so the ground only detects collision with the player.
What would be a good alternative to dotween because I use dotween alot.
Yes I will be removing the Scriptable obejcts completely and use plain c# classes.
The game is not similar to flappy bird but yeah it is quite simple in terms of mechanics 😄
It can be replaced with coroutines or using update. Though I didn't really look too in detail what the tweens were actually doing
@tall ferry tween is used for movement of the player between two points and they are used for text animations simple appear scale rotate
and the ParticleSystemParent is attached to each parent of the particle system , as each particle is of different length and when they finish they destroy themselves, so if all of them are destroyed I just want to destroy the parent as well , that is why I used the script so if I attach it to any particle it will delete the parent after all the particle systems have been destroyed
does unity's burst only work with unity's mathematics api or will it also work with System.Numerics?
i presume it wont be optimised for regular Vector3 such as for SIMD
their meshes still use Vector3 so have to convert arrays all the time kind've annoying
Isn't there a burst compatible mesh api
they have this:
using (var dataArray = Mesh.AcquireReadOnlyMeshData(input.Mesh))
{
var data = dataArray[0];
var vertices = new NativeArray<Vector3>(input.Mesh.vertexCount, Allocator.TempJob);
data.GetVertices(vertices);
foreach (var v in vertices)
Debug.Log(v);
}
but i would still have to then copy to a float3 native array
I don't really know about the API just mentioning that it exists
well even the code you linked uses V3 native arrays in the example
you can do this in both c# and cpp and c
float3 *arr=(float3*)vec3_ptr;
just cast the pointer, then you dont need copy it to float3 array
sizeof float3 same as sizeof vector3, so it is "safe" and the memory location of x y z are the same
https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1.Reinterpret.html is this the same idea?
yes
can you explain this part a bit
Hey! I am looking for some good resources on connecting code to UI elements. My inventory and Ammo system are completely separate and I woud love to learn how I can comfortably connect those to systems onto a UI element to show ammo and currently equipped weapon.
Not sure this is advanced, but I tend to write either a custom reflection script, where I can just select functions I want from different scripts or, if you want to receive data, I use a generic metadata class on those elements and then handle the incoming type and the component found on that UI to show the received updated value. they just register to a global metadata update event for example.
This sounds like a nice solution. Any writeups or videos I can go read up on?
Not really, just came up with this myself. Just have an enum in your dataviewer class and then hook into your global delegate. If you make it dynamic, you can just use overrides to hook into that delegate for floats, strings, ints and what not.
Alright. Let me give it a whirl Thanks a bunch !
I for example have two delegates, one for float and one for strings and I just use two overrides for ReceiveMetaData to handle the incoming data on my viewer class. They then call the shared functino to update the component found on the gameobject. Thats all. I cant really send you my script because its part of a framework we are workign on and replacing all values to non project specific would take too much time 😄 But you will be able to do it, im sure
Ya, I got some idea now! Thank you
does anyone know if theres a way to render a gpu instanced mesh to a specific layer using RenderMeshIndirect()? i know you can with RenderMeshInstanced() but i dont really want to redo my whole instancing setup for this
RenderParams includes a layer field: https://docs.unity3d.com/ScriptReference/RenderParams.html
renderingLayerMask is different from GameObject layers, in case you weren't already aware.
RenderParams.layer matches GameObject layers.
welldone.
I put this is networking but I guess it also applies here since it's code
Does anyone know a fix to my problem
I know the real answer is going to be profiling it depending on use-case but whenever I see anything related to reflection I see people mention to avoid doing it due to performance concerns, But is there anything I can read up on that goes a little deeper into that?
curious to know which aspects of actually using reflection sit between the pain scale of a hammer to a atomic bomb
To put it simply, a reflection is basically rendering your scene one more time from another angle. So roughly speaking it's doubling your rendering time.
Ugh, okay.
Reflection is not that bad. To be fair I'm not sure how much impact it has. I know that it is limited in a il2cpp builds.
What are you looking for exactly? Performance impact? Limitation? Implementation details?
Mostly performance wise, Just was curious about any sort of additional context other than "you shouldn't use this"
all i ever hear is reflection scary performance bad typa thing yknow
Performance wise, it’s actually not too much of pain. You just want to avoid it in your Update loop tho. You can cache many things, just like how Unity does for its event methods.
It can be mitigated by caching the data aggressively
e.g. caching MethodInfo or PropertyInfo instances
This typically comes from people that try to squeeze every bit of performance in their project.
They do have a point though: games are performance critical programs. If you can do something with less overhead, why not do it? Now, there are other considerations, like ease of development and maintenance and such. Gamedev is always a tradeoff between these things. If you decided that the overhead worth the use of reflection, who's to stop you..?🤷♂️
Forsure, and their hearts in the right place but I think after modding Lethal Company for 5 months I learned a lot more about how you can get away with doing a lot of unideal things pretty fine as long as your aware of the stuff you have going on, has helped me iterate a lot better now that I've stopped myself from always over engineering everything aha
ooo interesting ty
Reflection has popped up a couple times for random stuff i've been messing with but one thing in particular I was curious about was doing full copied instances of scriptableobjects at runtime
Why not just use Instantiate for that
unless i'm mistaken it doesn't copy over values too does it?
If your value is unity-serialized that is
dunno i kept getting warnings in unity telling me to use .CreateInstance so I just assumed it was the most ideal option
Would be very excited to know that i'm wrong
When you used Instantiate?
You would get that warning when using a Constructor
I was thinking of messing with a custom UI system for fun and learning. First thing is rendering. And I was wondering what the most efficient way of doing rendering for procedural styled elements (like background color, gradients, borders, corner radius, circle shapes, etc.).
I though of the following, but not sure the performance difference and couldn't find much online on the subject. (Unity or otherwise)
- Bake a texture for each element(that has styling) that gets updated when the styling changes.
- I assume this one isn't a good idea due to the potential memory usage.
- Use quads, and a use a shader for all of the styling.
- Procedural meshes with tessellated corners and stuff.
Any suggestions or recommendations of resources?
2 is the closest one to how most engines do it afaik.
Huh really? After writing this, I was thinking it might perform pretty badly at scale due to the increase in shader complexity and potential overdraw.
I mean, the shader is pretty simple usually. What exactly do you want to put into it?
Each ui element is basically a quad with a texture rendered on it.
There might be some masks or something, but that's not very heavy for a shader.
You can inspect the canvas ui in a frame debugger and you'll see that it's mostly quad draw calls.
Hmm, I guess it would be
- background - color/sprite/gradient
- corner radius per corner
- border thickness per side
Would be cool to do shape as well, like circle/pie/ring, and a path/spline
I don't think canvas ui does anything special for borders, as for corner radius is a pretty simple thing. You just modify the mesh once when that property changes.
There's nothing about background either. It just renders the image.
I think ui toolkit is a bit more sophisticated in what it does. So might want to look at the frame debugger at it as well.
I don't think UGUI supports anything sort of procedural textures/styling.
Yeah, I think UITK does mesh generation mostly
any ideas as to what is causing this terrain to be so bumpy?
It's supposed to be smooth, I converted from generating my own mesh to using terrain but when I use my algorithm on the terrain it comes out with these ridges and none of the fixes on the internet seem to be doing anything - using HDRP
It just looks like the mesh is bumpy, so it must be an issue with your algorithm
Hey, I am using the unity terrain-tools package, there are some interesting features in the package as the noise generator or the terrain generator toolbox.
I would like to use these tools at runtime as for generating noise and then creating a little terrain that uses this noise. I can't find a way to use these utilities at runtime, can anyone help me or give me some advice? I can't find the source code either. Thanks!
They're not available at runtime
im unsure if this is even a coding question, but look at the #854851968446365696 on how to properly ask. Theres literally nothing that can be said for what you wrote. Also there are free recording softwares like obs, or really anything else you find. No one wants to watch a phone video, especially one thats sideways
are trees usually a single mesh
or one mesh for tree and several different for leaves
Depends
Close range, probably multiple
LODs are probably a singular
But also depends on how many lods, how far away, detail level, vert/texture/shader limits
Okay I have this problem is anybody knows a solution:
Image a coroutine A
Also imagine a void method B, that has a LOT of code going on, meaning it freezes for 15-20 seconds when called, it doesnt crash though, as it is not running async.
method B is called once in Coroutine A. How could I make it so that it forces the method B to be called and ran asynchronously. Important to note: I cannot change method B's code. Is there a way?
Run it in a different thread
E.g. using Task.Run
Coroutines still block the main thread
Okay, so outside the coroutine then?
Can I call it the moment the coroutine is called? And then have some kind of check within the coroutine to check when the task is finished?
Depends on your implementation?
Asking since I tried Thread (not Task) and it wouldnt let me outside of Awake and STart
The coroutine in question basically waiting for multiple "tasks" (not literal Tasks) in a row already*
Any options? Similar addons? Do you know if the source code is available? I searched in unity's github and it doesn't seem to be there 🥲
It's a package so the source is on your machine
C:\Users{USER}\AppData\Local\Unity\cache
around there somewhere
Or <project_path>/Library/PackageCache
oh, that makes sense, thank you!!
Anyways, no idea if it's possible to replicate the behaviour
you can use tasks and check .IsCompleted I would say https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.iscompleted?view=net-8.0#system-threading-tasks-task-iscompleted
But there's plenty of terrian tools out there, no idea how they work
yea, but it is a starting point
Hey guys, I'm running some Burst jobs in OnAudioFilterRead(data, channels) but experiencing long stutters on the Quest 2 headset that satisfies CanBeDelayed. This suggests that the main thread (or whatever manages draw calls) is getting starved on that device.
This code should introduce an n second delay in audio playback and convert float samples to short samples handed over to another thread over a Channel (not shown).
I am utterly vague on this, but it may be due to the sharing of _delayControlBufferNative. I am unsure since the write and read jobs access different parts of that buffer.
Relevant Code Snippets: https://gitlab.com/-/snippets/3714468
Hi everyone !
I'm facing a "little" problem 🙂
In the editor, I'm trying to get the current resolution preset selected for the Game View.
I've found this script to get some data :
https://gist.github.com/Biodam/b0616918ea5c50c2c9e4b16e5bb1034b
But nothing to get which resolution preset is currently selected in the menu.
I've also found this, which could be where I could get the information I need, but I can't find how to access to the selectedSizeIndex property
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/GameView/GameView.cs
Any help would be appreciated 😉 thanks !
Hi everyone !
Anybody knows how to make trees?
Like good trees with leaves and wind effect + collisions.
And are there some hacks like GPU instancing i can use to make these 10k trees not eat 999 fps
GameObject approach feels bad
not reallty a code question
That's what I thought, I'll look into it more, however, it works fine when I generate my own "terrain"
Most of this is solved by Unity's terrain so I'd try to dig those answers from that
Leaves and particles can be gpu instances via vfx graph
i can't use unity terrain sadly
wind shader, object instantiation, collision, gpu instancing(maybe)
and well, not a 3d modelling question
static colliders should be enough
Only thing you probably need to look into is wind zones controlling a tree's vertex shader based on proximity
So ideally you figure out a way to manage this controller without having to constantly update the vertex shader.
could also consider a global windzone, but I think Unity's terrain does go above that and allows you to add multiples
I'd expect is just sampling multiple different vector fields
what are static colliders
Colliders which don't need to move
you mean static gameobject with collider component
Yeah, basically.
You can still change the rendering, but the collider should stay the same
I'm trying to create a gravity switcher mechanic and I'm failing to use quaternions/rotations to reorient and remap player input to handle movement.
Would someone hop in 5min call so I can show current state and ask questions?
Define "gravity switcher"
@jaunty swallow
Context:
Prototyping Gravity Mechanic Switch in Game Engine (Unity3D)
We have a few planes with different orientations, cubes green to purple to visualize plane forward.
Problem
Which sequence of math operations and functions (assume quaternions calls) to
1. Determine TargetPosition when EventTrigger happens - Low Priority
Player press Key, If within collider range, project GamObject.position to plane
Current State - Hardcoded Center point of the plane
2. "Preserve" gameobject last lookForward from playerInput direction on Inclined planes - High Priority: 1
Current State - Planes have 2 cubes as child objects. When we rotate the plane, the cubes suffer the same rotation to help visualize but is hardcoded and wrong logic.
3. "Process" playerInput into CurrentPlane coordinates before sending to HandleMovement, so player won't feel disoriented - High Priority: 2
Though the WASD movement in some planes are "correct", they feel wrong and disorienting as a player. Like the last plane, I'd rather have Vertical movement WS and left to right AD even though the plane normal makes WS be left to right and AD be down to up.
I didn't understood what are you trying to do anyways.
Hi! I am instantiating a model inside an object with an animator. The animations have keyframes and I name the instantiated object accordingly. The instantiated object stays in a T-pose and refuses to be animated. I've tried using Animator.Rebind and Animator.Update(0) but these do not seem to fix it. I can disable and enable the animator in the editor and it works after that, but if I enable and disable it in code it doesn't. Any ideas on how to fix this? edit: Figured it out. The original object with the same name cannot be there. No idea why it works like this 🤷♂️
as in, you had a hierarchy like this?
- Animator
- Foo <--- was always there
- Foo <--- newly created
the animator works entirely off of names
so it was probably finding the wrong object
Ok, so I have a very specific request. I need some help thinking of how to go about a system for AI inspired by Five Nights at Candy's remastered. I am recreating it in VR and cant wrap my head around how to do a specific mechanic.
In the original, Animatronics cannot be in the same room, and will check if anyone is in their target room. I want to be able to do this without hardcoding everything for each specific character. Basically whenever the entity runs TryToMove(), I want to check the target room to see if there is another entity occupying the space, but I have no idea how to go about assigning animatronic's current rooms during runtime. If anyone could help that'd be awesome
you could just have a boolean / animatronic class array which dictates whether a room is occupied
seems like the simplest way
and when you TryToMove(), pass in a parameter which says which room you want to go to
then check against the array[room you want to go to] and see if it is false / null
Do you think it would be a good idea to hold the room array in the GameManager script or another manager for all Animatronic instances to be able to access it
storing it in the game manager is a good idea, all animatronics would still be able to access it
you usually do this by making the manager a singleton
in unity anyway
Awesome, I'll probably make an Enum for each room to have its own ID that lines up with the array
Thanks for the help, i have lind of overthought it haha
I mean you can do it however you want really, in the end, the only real difference is your readability
if you do every single thing inside of one manager, it might eventually get to a point where you will struggle to improve / rework things
np
I'll probably separate the GameManager and NightManager so the GameManager can just control the game flow
And keep all Night functions in its own script
I barely remember candy's so idrk what you mean. Just make sure to keep your code in line with your goal for the game
if you intend this to be a big project for example, put bigger emphasis on keeping code manageable and clear
Forgive me if this isn't the right place to ask but bear with me.
This is gonna lead to a bit of an odd question but I'm modding a game and want to introduce a new audio effect plugin, so I create a new audio mixer, add the effect to it, bundle it in an asset bundle which I load in my mod, and put the plugin dll and its dependencies in a directory they can be accessed. Then I run the game and...
[Error : Unity Log] Audio effect FluidSynth could not be found. Check that the project contains the correct native audio plugin libraries and that the importer settings are set up correctly.
So it turns out, Unity might be able to find this dll but the audio effect isn't loaded, presumably because the import settings never get applied to this plugin, so it isn't loaded on startup like you would typically use an audio plugin. In the editor I could just tick the box in the attached image but now I need to look for a runtime solution.
I understand this is not something unity is designed to do at runtime, but I reckon there's a chance that I could hook onto a method in a UnityEngine dll with a tool like MonoMod.RuntimeDetour.HookGen and force Unity to load the plugin on startup.
So my question is: does anyone know anything about the specific systems that unity uses to load plugins at or around runtime, so that I may forcibly load one not handled by the editor-defined import settings? I'm looking for a class or method in a Unity assembly that handles this.
Thanks for your time.
oh and the image I forgot to attach
got this working
I'm trying create a preview for custom playables in editor
Currently it's almost working with AnimationMode.SamplePlayableGraph which I guess the way to trigger preview in editor and not lost the "rest" state. basically if you start previewing and stop it object reverts to original state (same with AnimationMode.SampleAnimationClip)
but to make it work properly I have to create a "preview playable graph" and create a default state myself (I can't use IAnimationWindowPreview as rigging system because it's not always post processing the stream, it could by fully procedural animation, ie there is no AnimationClip and basically nothing to preview in Animation/Timeline)
the thing is that unity itself can create default state playable, it's called AnimationPosePlayable and it even creates dynamically DefaultPose animation clip containing all the animated properties by graph
is it exposed anywhere? the docs for playables are just non existent
ok, just to answer to my own question
it's not exposed, as usual as soon you dig into low level unity apis you bump into some random design choices
basically there is internal method:
EditorCurveBinding[] AnimationUtility.GetAnimationStreamBindings(GameObject root)
this one returns all properties bound to animation stream, whether they coming from animation controller graph or your own custom jobs
anyways with that you can create a DefaultPose clip to retain state before animation. this method used by AnimationWindow internally
Hey everyone. I am trying to figure out how to do Unity testing for unit tests but I cant figure out how as all the videos I have watched have been in a older version of unity. I dont seem to have the same interface as Unity has updated that interface since then for testing so I cant follow along.
Does anyone have resources that teaches how to do Unity tests for Unity editor 2022?
This should still be relevant. I do unit testing in my 2022 project using these same concepts
https://www.kodeco.com/9454-introduction-to-unity-unit-testing
Thanks @sly grove , I appreciate it! I will give it a watch.
does anyone know how dotween made it so you can call any dotween method through a gameobject's transform? like transform.DOScale() etc
well done.
Just bog-standard extension methods
interesting, i've never heard about those! is this also how he made it so you can chain any kind of methods together? or does that use something different? by that i mean how dotween allows you to do stuff like .append(stuff).append(stuff).appendelay(1).append(stuff) etc
That's just a pattern called "Fluent interface" and has nothing to do with extensions per se
Fluent interface: https://en.wikipedia.org/wiki/Fluent_interface
In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.
thank you, ill check it out!
i like learning about the advanced topics that unity tutorials dont cover
Reposting cause I have found more info - I have some procedural generation and I'm just setting the heights of a terrain with .SetHeights(). However, using the terrain, I get these ridges once I get closer and the LODs change, on the higher LODs it is clearly visible but gets gradually less as the LODs decrease. Seems to me like I'm settings heights for the lower LODs and as the LODs increase the extra vertices that the LODs create, don't have an assigned height, making them the same height as the previous vertex - meaning they will have the same height. Any ideas?
Both the heightmap and the terrain are 512x512
Hello, I'm having a problem, today i made a build of my game but then it suddenly had a like dark gray screen, i'm not able to interact with the game but i hear the background music and only that. Sometimes it flashes up and i can see the game for half a second before it disapears once more. I looked around the Unity forums but non of their solutions seemed to fix mine. It has only being doing this since today. Yesterday everything was working perfectly fine.
I'm on Editor version 2020.3.29f1 if it helps
Please @ me if you found a solution or want to help!
Thanks
Changing the heightmap resolution in the terrain to 257x257 seems to have gotten me the fix / close to it. Don't really understand why it'd need to be half of the actual texture's resolution though.
How were you sampling the texture?
perlin noise, but I'm almost certain it is purely to do with the terrain - especially it's resolutions. Originally I made my own mesh at runtime and applied the heightmap to it - worked perfectly fine. Only recently, I've switched to the terrain instead.
Perlin noise can be a little bit surprising
notably, integer coordinates all have the same value, iirc
the problem isn't with the texture
how did you sample the texture, though? perlin noise is how you filled it with values
It's very possible that your texture has ripples in it, and that they're just hidden by your mesh
(and by the lower-res terrain you switched to)
that contradicts what I've seen up until now
as I increased the heightmap resolutions (inside of the terrain), more of these "ripples" were created
show me your code so I can see how you're sampling the texture
which proves what I said earlier
I don't get what you mean by sampling the texture
How are you getting this texture into the terrain?
I just create a texture2d and assign each pixel's greyscale based on perlin noise
That's how you create the texture
What are you doing to set the terrain's height values?
void GenerateTerrain()
{
var heights = new float[Planet.TextureResolution, Planet.TextureResolution];
for (int y = 0; y < Planet.TextureResolution; y++)
{
for (int x = 0; x < Planet.TextureResolution; x++)
{
heights[y, x] = Planet.HeightMap.GetPixel(x, y).grayscale * _intensity;
}
}
_terrain.terrainData.SetHeights(0, 0, heights);
}
okay, you're just copying 'em in
yeah
are you adding together multiple octaves of noise?
yea
reduce the number of octaves and see if the ripples persist
I'm seeing some boxy artifacts in this image, although it's hard to say much from the resized preview
that might just be the preview
yeah they still do
I'm almost certain it's in the terrain resolutions
increasing the resolutions way over my sample size adds wider ripples
changing the resolution changes the behavior, but that doesn't mean that using high-res heightmaps means you get ripples
That would be expected if you had ripple patterns in the input image
can I see the code that produces the texture?
the difference is that these are consistant
the ripples in the heightmap are every so often and they were sampled fine when I was generating my own mesh
however with the terrain, these "ripples" are new and were never there until after I switched to using terrain
these new ripples happen after every single vertex
they are just the same height as the previous vertex - which might indicate that it's just setting the same height as the previous vertex from the LOD
if that makes sense
for example, this is one of these ripples, it's literally just the next vertex copying the height of the previous one
Your texture only has 256 possible color values. This only gives you 256 possible heights. If your terrain is very tall, you'll get some pretty noticeable banding.
creating a flat plane
note the texture format
If your heightmap is 513x513 and you want to have a slope that rises from min to max height across the whole terrain, it will wind up with banding when you only have 256 possible heights
I'm confused
513 is just the width
these values don't indicate the height
they indicate sample points
Correct.
The height is coming from your texture.
And your texture can only contain 256 different values
yeah but this doesn't make sense to me
to create a smooth slope, you must use 513 unique values
you only have 256 values
the 513 and 256 are completely independent values
suppose you had a heightmap that was a billion pixels across
i ask you to create a smooth slope that goes from one side to the other
you are only allowed to use the numbers 0 through 99
is this possible?
if you could go into decimals I suppose but for the sake of the arguement no
but this isn't the same
100 values, that's it
it is absolutely the same (:
your example is just less extreme
but the pixels on the map never reach anymore than 255
That's the point!
so I don't understand where you're getting this from
You only have 256 values to choose from
yeah and they aren't supposed to
If you try to create a shallow slope, you don't have enough unique values to make it smooth
okay I kinda get what you're trying to say
if the slope covers 20 pixels, but the height only goes from 5 to 15, you get stepping
You don't have enough precision.
this would make sense except I'm not doing a linear slope right?
you're doing a decently shallow slope from left to right in this image
notice how the steeper hill also has some banding artifacts -- they are just subtler
it's lumpy
it's flat not lumpy
that is my issue
your precision does apply, just not in my example
it's lumpy because it's switching back and forth between flat and slope
because I'm trying to set the individual vertices
you don't set individual vertices with Terrain. You fill in a heightmap, and it then creates a mesh that tries to follow that heightmap
here, humor me and update your code a bit
void GenerateTerrain()
{
var heights = new float[Planet.TextureResolution, Planet.TextureResolution];
for (int y = 0; y < Planet.TextureResolution; y++)
{
for (int x = 0; x < Planet.TextureResolution; x++)
{
heights[y, x] = Mathf.PerlinNoise(y / 100f, x / 100f);
}
}
_terrain.terrainData.SetHeights(0, 0, heights);
}
100 was an arbitrary scale factor
you are not directly controlling the mesh
You are telling the terrain how tall it should be at each point
well yeah but it has to set it's height somehow right?
It doesn't matter if you're really far away or up close: the heightmap's resolution is fixed.
The mesh is generated from the heightmap.
Give this a try. I suspect it will give you a terrain mesh with no banding.
I don't really understand how unity sets the heights then. When I generated my own mesh it worked because I set each vertex's height using the greyscale of each pixel
so you wouldn't get banding because each vertex would just "lead" into the next one
you're right about this though, this doesn't have banding
Changing your texture to R32_SFLOAT should also fix it.
one channel, 32-bit signed floats
RGBA8 is particularly inefficient. 32 bits per pixel, but you are only conveying 8 bits of information
I understand now what you meant, I didn't because I'd assumed unity did it this way
wonder how that even works
I don't know the intricacies. It's generating different mesh densities at different distances
yeah I just meant the height setting
because you wouldn't get banding if the heightmap just set individual vertices
at least, it'd be harder to see it
if you had several adjacent pixels that were all equal, you'd get a flat spot (duh)
If you need a texture, then switching color formats is the way to go
Otherwise, I'd consider just not using a texture at all
heightmap textures make sense for importing data
you can download a 16-bit TIFF that stores height data and read that
that gives 65,536 possible heights
so if that covers 1km you're getting 1.5cm precision
notice how the terrain has a "terrain height" setting
600 by default
that's the range that your heightmap has to cover
so 256 values mean each value steps by a little over 2 meters!
so couldn't I just make the height 255?
that would mean you're getting 1 meter steps
you can't express 1.5 meters
only 1 meter and 2 meters
this is just another way to think about the "only 256 values" problem: you didn't have enough values to create a smooth slope over a wide range
and you can't create a smooth slope over a wide range because you can only express 0 meters, 2 meters, 4 meters, 6 meters, ... of height!
quite interesting way they've laid this out
Reducing the Terrain Height would make the banding a bit less obvious...because the terrain is shorter overall
it would be exactly as imprecise
just squashed vertically
yeah I've seen that in my testing
is this RFloat texture format?
your heightmap data is a X-by-X array of floats
that gets stretched over a Terrain Width - by - Terrain Length - by Terrain Height cube
If you increase width or length, you have fewer heightmap pixels per meter
If you increase height, you have a lower density of possible world-space heights
since you are mapping the same 0..1 range of heightmap values over 0..1200 meters instead of 0..600 meters
You may have noticed that your width/length fidelity is way lower than your height fidelity
That's why the terrain renderer smoothly interpolates between pixels in the heightmap
you have hundreds of millions of possible heights, but only 513 different heights on each axis!
so I guess it makes sense that the renderer blows up when you suddenly have 513 different heights...and only 256 possible heights
it was not designed to deal with that situation
that requires smoothing things out horizontally, not vertically
(which is what lowering the resolution accomplished!)
that blurred things out
yeah I understand the issue it has with the interpolation of heights now, thanks
https://docs.unity3d.com/ScriptReference/TextureFormat.html
Yeah, that looks like TextureFormat.RFloat
R16 would also be tolerable: that's a 16-bit integer
(I was looking in the texture format dropdown on a RenderTexture)
but I'd still need to use the getpixel and setpixel functions which only take in colour as parameters
Color uses 32-bit floats
https://docs.unity3d.com/ScriptReference/Texture2D.SetPixel.html this lists all of the valid texture formats (which does indeed include RFloat)
oh the conversion is automatic, got it thanks
I'd guess it just discards the g/b/a components
most likely
Color32 is, mildly confusingly, the one that doesn't use 32-bit floats. That one is four 8-bit integers (thus, 32 bits)
Color might use 32bit floats
but you can only represent 0...1
meaning I'd need to multiply the output by 65536 no?
changing to R16 didn't help
I understand why it might be causing these flat vertices with duplicated heights if the heights exceed the height capacity. However, here you stated that you have 513 different heights which is not true. Even if I was still using 8-bit integers that would still give me 256 different possible heights and since color can only represent 0...1 I would still be well within the limit. That's how I'm understanding it anyway
513 slots you need to put heights into
but these heights wouldn't exceed 256 different values
I mean I guess they could if you're going into decimals with 0.50001 and .50002 for example
then I guess you would
the actual heights in the heightmap would be 0, 0.00390625, 0.0078125, etc.
That is a bit unexpected. How does RFloat behave?
I presume you are setting the format when you construct the Texture2D?
yep
HeightMap = new Texture2D(TextureResolution, TextureResolution, TextureFormat.RFloat, false);
HeightMap.wrapMode = TextureWrapMode.Clamp;
with RFloat still seems to be happening
show me the code that sets the pixel data
for (int y = 0; y < HeightMap.height; y++)
{
for (int x = 0; x < HeightMap.width; x++)
{
var combinedColor = Color.black;
for (int o = 0; o < _octaves.Count; o++)
{
combinedColor += _octaves[o].GetPixel(x, y);
}
HeightMap.SetPixel(x, y, combinedColor);
}
}
perhaps _octaves is still an RGBA8 texture
ooo good call
well, array of em
forgot to change that
By the way, if you're generating lots of perlin noise, you might want to use the Mathematics package
notably, it's Burst-compatible, which gives you a very large speedup
it'd a bit goofy looking
[BurstCompile]
static class NoiseMethods
{
[BurstCompile]
public static float Noise(float t, in float2 vec, in float2 offset)
{
return noise.snoise(vec * t + offset);
}
}
calling noise.snoise doesn't result in that code being burst-compiled
snoise is simplex noise, which is like Perlin noise but with some nicer behaviors
I'll look into optimisation a lot later as this is a one time generation only
reasonable (:
and it's already bearable
If you don't need to use the individual octaves, I'd just compute them on-demand
otherwise, just switch 'em to a different color format and it should behave itself
R16 will double your bit count, so the bands will be 256 times smaller
I only compute them one time during runtime once I need them if that's what you're saying
If you're re-using the octave data over and over, then it makes sense to store it in textures
yeah I've read into it but I had some issues with simplex that I didn't have the time to get around so I just stayed with perlin
nah I only use it for the singular generation and I only stored them so I can preview them for testing. For actual release and optimisation I will be changing a lot of the formatting around, thanks for all the advice - it's great and appreciated
I think this might've solved it...
no problem (:
Hello! I figured I may as well try bumping this question once, if I still don't find an answer I'll stop asking. It's about some low level modding related stuff.
I am experiencing a massive drop in detail on my heightmaps though, with the only thing changed being the textureformat
nope
I'm looking at my changelog
only difference is the textureformat
and sampling with red instead of grayscale
weird thing is, my octaves have actual values except the final image seems to be missing them
just can't figure out why it's not adding properly
could it be that it's because I'm using Color.black which is using RGBA?
nevermind I've fixed it
thanks for all the help @bleak citrus
quick question guys, does anybody know of a better way to go about doing this? I wanna expose the ability to add and remove listeners to other objects but I don't want them to have the ability to invoke the event so I often find myself having to write this giant bit of code for every event I want but I wanted to know if you guys knew a faster way to write this
private UnityEvent onDeath = new();
public event UnityAction OnDeath
{
add => onDeath.AddListener(value);
remove => onDeath.RemoveListener(value);
}
Just prettier syntax
ooo
i like prettier syntax
lmfao
ive never seen that before
the add and remove stuff, thats pretty cool
is that specific to events?
It is
is this taking advantage of like polymorphism with UnityEvent and event at all or is it unrelated
ohh okay so this is like exactly what i was trying to do
like the whole thing of private fields with public properties but for events
dope
thanks for bringing that to my attention
No problem
hey guys would anyone know how to https://pastebin.com/UfmWhxrA
make some minor change such that it loads the assets into the current scene and not a new scene?
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.
It's some boiler plate code I found that I need a small change too
right now it creates a seperate scene and loads that, but this doesn't work for my use case of multiplayer scene management, so I need someway to just basically import the asset/scene into my current/main scene
does anyone know what TryGetComponent does under the hood? is it just getcomponent and a null check? if so, why have people said its better for performance than getcomponent?
It's better because it saves you an extra check afterwards
Or, as some people do - it avoids you doing GetComponent twice
but I think ultimately, for me, the benefit is that it's cleaner code
var comp = GetComponent<Example>();
if (comp != null) {
// blah
}```
is more lines and more noise than:
```cs
if (TryGetComponent(out Example comp)) {
// blah
}```
UnityEngine.Object != null is relatively expensive of a check.
dont they both call UnityEngine.Object == null though? how can people see what some unity functions do under the hood? i dont have that functionality in my ide, can you show me TryGetComponent?
No because TryGetComponent does that check in the native engine side
oops
I'm too slow
but yeah this is an extern call into the engine
actually
let me eat my words a little here
yeah it's still doing the != null check here in C#
I think it's just better because it's cleaner then 😊
And it's definitely better than this form which some people use:
if (GetComponent<Example>() != null) {
GetComponent<Example>().DoSomething();
}```
It also avoids additional allocations when playing in the editor. GetComponent allocates a fake null object to give better error messages if you try to use it afterwards.
ok thank you both, by the way is TryGetComponent the most efficient way to access interfaces? for example if i want to highlight an object when i look at it in 3d, i would have to raycast and call TryGetComponent every frame and check if the raycast target has an interface. is this really the most efficient way to do this, since UnityEngine.Object null checks are pretty expensive?
Actually
fun note here
If you do it with an interface
it DOESN'T do a UnityEngine.Object null check
this will be a regular null check if T is your interface
ooh thats good, wait but if i first check if raycast hit != null, isnt that an UnityEngine.Object null check?
Yes, but just on the raycasthit struct, not on the object
Is this 2d or 3d
in 3D the Raycast call itself returns true or false
you don't do anything like hit == null or hit.collider == null
you just do if (Physics.Raycast(...))
or:
bool hit = Physics.Raycast(..):
if (hit)```
im working on multiple projects at once actually, in the 3d one i am indeed doing "if (physics.raycast)" but in 2d the raycast method was different, also someone suggested to use overlappoint, which had some additional weird functionality with a list or something. does overlappoint do any null checks with UnityEngine.Object?
OverlapPoint itself doesn't do anything
It gives you back a collider reference iirc
overlappoint returns a collider yes, i would have to check if that collider is null every frame, wouldnt i?
Don't quote me on this but it might be more efficient to do this:
Collider2D hit = Phys2D.OverlapXXX(...);
if (!ReferenceEquals(null, hit)) {
// we hit something
}```
I'm just not sure if OverlapXXX gives you a real null or a fake Unity null. It's probably a real null, but you can test it.
what makes ReferenceEquals better than == null?
also how can i test if its a real null or fake null? and which one is better to have?
It's faster, but only checks for real null
ah so if it's a UnityEngine.Object null, then it gives an error? thats a good way to find out which of my null checks are terrible for performance
Doesn't give an error
ReferenceEquals will reveal if you have a null reference
vs. something that merely equals null
that's all
how can i learn c# for unity as efficiently as possible
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Beyond that just reading documentation.
C# for unity isn't that different from just C#. If you know C# and have access to unity docs, you basically know "unity C#".
you should not be trying to learn efficiently, you schould be trying to learn thoughly
it returns false if it's a UnityEngine.Object null?
Yes because unity's fake null is an actual C# object
So not truly null
alright, thats good to know! now i have the ability to check if my null checks are bad for performance
well whats the best way to do that?
practice, practice, practice. And the docs are your best friend
alrighttt, thank you
do you have a project for someone who's only been doing this for a week?
and do i look at the unity docs, or the c# docs
both docs. A 'good' project is difficult to say but think simple, arcade style is not a bad place to start
alright thanks
btw i cant look for stuff here because if i type TryGetComponent into the search it doesnt show me that either... do i really need to pay github for that feature or is there another way to find stuff?
you need to be logged in to use search across an entire repo
ooh ok, thanks! i thought they made it a premium feature or something
wait i logged in but it still doesnt work, how do i search code?
i looked up a tutorial from a couple months ago but that appears to be for an older version of github
wait nvm i found it now
Hello guys is there any way to run some graphics like a simulation (GPU) when i build a dedicated server build?, thanks for any help
142 transform.rotation = ...
should be setting rigidbody.rotation
Thank you @upbeat path 🙂
What exactly do you imply by "graphics like a simulation"? A compute shader?
i'm running a LBM fluid sim on the GPU, so i need to be able to run a shader on the server, code like this: https://www.shadertoy.com/view/7lKXzD
So I would assume you mean a compute shader.
Looking at the docs, it sounds like the graphics device is not initialized at all, so you probably can't use any shaders.
You could bypass that by using a third part graphics library I guess.
Hey guys, any clue as how to solve this?
This is when I am switch to WebGL
the Editor plays fine, and the windows build works too
I will pay to solve this issue haha its during a hackathon due in a few hours
Whatever WalletConnectSharp is(a third party library?), it probably includes features noy supported by il2cpp
Yes, I think it was auto-installed when I dowloaded a diff package
Well, remove it then and try again. Though that "different package" might need to be removed as well, if it depends on it.
Ah so does that mean I cannot use that package at all?
I think that cannot be because
a) it is for a hackathon and the package is coming from one of the 'providers'
b) the provider only supports webgl
thus it must work for webgl + package
unless u are refereing to smth different
Another thing to note that might have caused issue is that
right before this error
I had another error
that was like
conflicting websocket.jslib plugin
cuz 2 libraries where using it
Well, it's hard to say anything specific without having a look at relevant code.
It's clear that il2cpp fails when processing that library though
DUDE
Basically
to fix this
I renamed 1 of the websockets
but this time
I renamed the other one
wow
i've been doing this for HOURS
THANK GOD
THANK U SM
Not sure what I said was of any help, but glad you got it working.
I found an issue in System.Runtime.CompilerServices.ConditionalWeakTable. Should I report it to Unity or to Mono?
I'm actually unclear whether IL2CPP uses Mono.
I have a few of these tables behind the scenes and two of them shit themselves in build at the same time. One keyed by a prefab (potentially unsurprising), but the other is keyed by a plain old C# class.
I know this collection is known to be poorly supported, so I'll happily strip it out, but I would like to report the issue regardless.
yeah compute shaders ok thank you i will try to find a solution
ConditionalWeakTable and IL2CPP do not go well together. I've been avoiding it. It's not a Mono issue, IL2CPP has its own implementation of it.
Is it worth a bug report?
I guess it's known
Based on this thread (which you've already seen) https://forum.unity.com/threads/conditionalweaktable-getting-corrupted.1306215/, they want it to work and have fixed bugs previously. So a bug report doesn't hurt.
I wasn't aware they had fixed the random cast exception
Oh that's the issue I'm hitting
Lol I'm in just thread
Yeah looks like I should update the thread
Okay thanks lol
That's funny, I used it based on the dev's advice in the thread, and just for the first time since then we had the random cast in production
Fyi the linked tracker link is not for the random cast exception
Ah, I missed that.
The cast exception is tricky because it happens randomly. I don't think it requires any specific conditions, it will just happen at some point when trying to access data.
Yeah. We have had many people playing the game for a year with that code in it
This is the first time I've heard of the failure and got the log
i wonder if it's caused by a garbage collection
Surely
you could add a GC.Collect somewhere in Update to cause..very aggressive GC behavior
In my case it was trying to cast a float into the type
I mean... I'll just use a dictionary instead
I'm not that invested
yes, you should use a Dictionary if you don't need the weak-reference behavior
Well I don't need it, it's just a bit of extra memory
There is a small danger of a memory leak but it's just a cache so I can blow it away every time you start a new game or something
I'm keying by a serialised class on an SO
So theoretically if it kept getting unloaded and loaded from assets it would cause a very slow leak
Hello everyone! Working on a backrooms game as a side project. Basically I got this random maze genration working and I wanted to spawn items in certrain cells. Problem is since the maze generation is completely random some cells will end up unreachable. Any way to filter unreachable cells and get a list of only reachable ones?
The script is very simple, selects a random roon type and spawns it.
I would suggest changing your map generator.
Maybe you can make a minimum spanning tree out of all of the rooms.
I've been thinking about using an algorithm that goes through all the rooms starting from a start cell, but the rooms are just placed randomly with no knowledge of where the walls are
an MST will guarantee every room is reachable
Yeah
but it'll be a bit boring, since it's a tree graph
you could do that and then punch out random holes
Never actually implemented one of those, first time making a maze generator. Will look into it, thanks!
what could be causing this error and how on earth do i fix it ?
its in the error, the value is null
it has no value
but the variable in question is _unity_self, that is not one of my variables
its a variable from unity itself
code?
what do you mean with code?
provide the code
but it doesnt specify wich script the error is in, I cant send 11 different scripts
It's an editor bug. You can ignore it.
but it brakes my game, the error dissapears if i add a line of code but then i get another error that makes even less sense
and adding the line delets key frmaes from my animation curve variable causing this error
The first error message is unrelated to the game breaking
the first error only appears when i remove that one line of code tho
and do you know what could cause the second error ? I havn't edited that scrip in a while and it worked yesterday but today i changed a bunch of stuff in other scripts that do not intereact with this script so i havnt changed anything and it brke
It's caused by the animation curve having less than 2 keys
but what could cause them to dissapear ? I ve set it to have two keys in the editor and ive never written a line that deletes stuff from animation curves, i dont even know how to do that
using UnityEngine;
using UnityEngine.InputSystem;
public class PhysicsRig : MonoBehaviour
{
private void Start()
{
og = bodyColl.material;
Keyframe newPos = new Keyframe(head.localPosition.y, PlayerPrefs.GetFloat("baseValue", 0.437f));
heightRemap.MoveKey(1, newPos);
}
private void LateUpdate()
{
Keyframe newPos = new Keyframe(head.localPosition.y, PlayerPrefs.GetFloat("baseValue", 0.437f));
heightRemap.MoveKey(1, newPos);
}
void FixedUpdate()
{
if (calibrateInputSource.action.ReadValue<float>() > 0.1f)
{
Calibrate();
}
float height = head.localPosition.y;
float remappedHeight = height * heightRemap.Evaluate(height);
bodyColl.height = Mathf.Clamp(remappedHeight, minHeight, maxHeight);
bodyColl.center = new Vector3(head.localPosition.x, head.localPosition.y - remappedHeight / 2, head.localPosition.z);
if(head.localPosition.y < PlayerPrefs.GetFloat("playerHeight", 1.6f) * 0.6)
{
bodyColl.material = sliding;
phandL.MM = new Vector3(0.001f, 1, 0.001f);
phandR.MM = new Vector3(0.001f, 1, 0.001f);
}
else
{
bodyColl.material = og;
phandL.MM = new Vector3(1, 1, 1);
phandR.MM = new Vector3(1, 1, 1);
}
}
public void Calibrate()
{
float A = (Vector3.Distance(head.position, handL.position) + Vector3.Distance(head.position, handR.position)) / 2f;
float H = head.localPosition.y;
float baseValue = (A-(A/4))/H;
PlayerPrefs.SetFloat("playerHeight", H);
PlayerPrefs.SetFloat("baseValue", baseValue);
//Calibrate size remapping value
Keyframe newPos = new Keyframe(head.localPosition.y, baseValue);
heightRemap.MoveKey(1, newPos);
//calculate Charachter (Arm) Scale
//reset position
h.Respawn();
}
}```
heres my only script that touches the variable
I'm pretty sure keyframes get deleted if they wind up with the same X position
ill have a look into that
another thing i found just now is that if i call this code only on start the keyframes never get deleted but if i add the same code again in the update function it breaks
thank you, this fixed it
i feel like you should just make an animation curve that ranges from 0 to 1
oh, you're moving on both the X and Y axes, right
modifying the curve is more reasonable
After generating it you can use a walk algorithm to find the reachable cells and trim the rest, if you don't want to change your generation algorithm.
Is it possible to create an enemy that uses machine learning to adapt to the player?
Yes
How possible is it? Can you point out some resources to start out?
Unity has a machine learning package with ML Agents. There is a channel for it ah, there is an ARCHIVED channel for it #archived-machine-learning
It has pinned resources there
Got a pretty big spike in the Editor Loop seems like alot of Garbage collection any way to figure out whats going on ?
The channel is #1202574086115557446 now
Dig through the profiler data
Been thinking about using it but it’ll be very ugly since id have to use raycasts
Cause i basically don’t know where the walls are
Wanted to use mst but I’m not very familiar with graph theory and algorithm
You’d have to have some way to know where the walls are. You’re generating them right? So you do know where they are, you just aren’t saving that information.
I have some prefabs that get picked randomly and rotated
It’s not procedural it’s random
That causes sometimes the room to be completely blocked from the rest of the maze
you still know how the code put the wall even if is randomly rotated
int x=Random.Range(0,10);//is x unknown or something that you cant work with?