#archived-code-advanced

1 messages · Page 102 of 1

obsidian stump
#

It's hard to find because they will be clones. You have to do stuff during instantiation itself.

obsidian stump
#

Can we make a draw like stuff during runtime. Is that really possible in unity. Just like paint.

humble leaf
#

Yes

obsidian stump
timber flame
#

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)
obsidian stump
tired fog
#

Is there any way to debug events that the editor is calling to know which ones are being called when certain actions happen?

regal lava
#

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

sage radish
tired fog
regal lava
#

I use them for editor scripts, sure

tired fog
soft moon
#

It's going to crash if you have an infinite loop

#

It doesn't crash from the break points

sage radish
tired fog
#

It seems that AssetDatabase.Refresh is what breaks it

jagged fiber
#

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.

regal lava
#

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

jagged fiber
finite yew
#

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

untold moth
upbeat path
finite yew
#

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

upbeat path
finite yew
#

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

upbeat path
#

Not on the basis of that, no

finite yew
#

ok so not over riding prefabs is ok?

upbeat path
#

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

finite yew
#

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

upbeat path
#

what do you mean you're not overriding it?

finite yew
#

well if you look at that image you can see a plus next to the script symbol

untold moth
#

What are you using these IDs for? Are you sure you need them to be GUIDs?

finite yew
#

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

upbeat path
#

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

untold moth
finite yew
upbeat path
#

does not matter what he uses, as I understand this the whole technique is flawed logic

finite yew
finite yew
untold moth
finite yew
#

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

upbeat path
untold moth
finite yew
#
    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

upbeat path
#

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?

finite yew
#

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?

upbeat path
#

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

finite yew
#

yes so these are the prefabs

upbeat path
#

no they are not

finite yew
#

so are you saying they are just game objects unless they are instaciated ?

upbeat path
#

they are gameobjects made from prefabs

finite yew
#

yes correct

upbeat path
#

so they aint prefabs, they have their own life

finite yew
#

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

upbeat path
#

no, the only problem with your system is if you are instantiating from prefabs at runtime

finite yew
#

awesome thanks steve. out of interest can you tell me why you would not do it this way? am i making this over complicated?

upbeat path
#

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

untold moth
#

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.

finite yew
upbeat path
#

object.GetInstanceID(). But use wisely. Not to be relied upon for runtime instantiated objects

finite yew
#

and does that id have its own id so if i had 2 gameobjects that where prefabs they each would be uniqie?

upbeat path
#

absolutely, when you copy a prefab into a scene and turn it into a GameObject it gets a unique id

finite yew
#

I really appreciate all your help, thanks so much for your time

#

and you dlich i appreciate your help tp

#

to

untold moth
finite yew
#

thats ok i think i know the direction i want to go now

obsidian stump
#

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.

gentle yew
#

Quite performant as well and simple tbh

#

It's all editor-only links, but the idea is the same during runtime

obsidian stump
#

They look interesting will check tomorrow. Thanks for the links.

tribal zephyr
#

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.

jolly vessel
#

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

sly grove
jolly vessel
#
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

thin mesa
#

base.Awake() not just base()
Your IDE should auto fill this when you autocomplete the override

jolly vessel
#

one sec

#

ah damn

#

base is the class reference

#

I was thinking of it as the base function

#

thanks

regal olive
#

so no one knows how to correctly update backfillTickets?

obsidian stump
regal olive
regal olive
#

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

trim glade
#

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

sly grove
#

Let's say res is 100 then you would have:

0.099 next to 0

#

For example at the edge

trim glade
# sly grove Unless res is 1000 this won't line up

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?

sly grove
#

Terrain world size doesn't matter

trim glade
#

res is 513 currently, it was just the default maybe will change

sly grove
#

You need to also divide the terrain coordinate by the same 1000 if you want it to line up

trim glade
#

I need to factor in the terrain world positions so that the perlin waves flow nicely across

trim glade
upbeat path
upbeat path
#

the other option is to switch iteration depending on terrain number
odd number for 0 to 999
even numbers for 999 to 0

trim glade
#

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

upbeat path
#

that could be floating point error in the positioning, try to close them up by 0.01f

trim glade
#

what do you mean by closing them up, sorry?

upbeat path
#

when you position your terrains dont try to position exactly next to each other, make a very small overlap

trim glade
#

I've positioend them all at 999.99 increments, still have that small line looked exactly the same whe nI loaded

upbeat path
#

that would tend to suggest that your terrain is larger than the number of iterations

remote oar
#

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.

trim glade
#

I'm iterating through the heightmap as that's what I'm assigning to

upbeat path
trim glade
#
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

obsidian stump
gentle yew
#

Glad you know how to proceed

tired fog
#

How can i make a window popup after the asset is imported?

obsidian stump
upbeat path
obsidian stump
#

I never used such assetpostprocessor Steve is there really such thing.

upbeat path
obsidian stump
#

Assetpostprocessor got plenty of options. And you are genius person Steve. You can make it if you want to. I believe in you.👍.

upbeat path
#

wtf are you talking about?

obsidian stump
upbeat path
#

I would have thought you were experienced enough to teach yourself, just read the docs

glass pagoda
#

Hey,
is there maybe someone who knows OneSignal and used it before?

robust kindle
#

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

robust kindle
#

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

robust kindle
#

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.

regal olive
steel snow
#

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

steel snow
#

ah i fixed it \o/

ivory salmon
#

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:

  1. Get sqlite3.dll (from SQLite.org) and put in Assets/Plugins
  2. Get the "precompiled for .Net Framework 4.5.1", but the one that contains SQLite.Interop.dll, not the one that doesn't
  3. .. and put "System.Data.SQLite.dll" and "SQLite.Interop.dll" into Assets/Plugins
  4. 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

flint sage
#

Advertisement doesn't belong in this channel @upbeat path

upbeat path
frozen imp
#

@upbeat path They did not ask for alternatives. This is not a place to plug ads

upbeat path
frozen imp
scenic forge
#

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

frail umbra
#

local sqlite for cross platform? 😵

upbeat path
#

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

frail umbra
#

I don't think there's any open source binaries that properly work for all .net platforms

sage radish
ivory salmon
#

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

sage radish
#

3.9k stars and release from 2 months ago doesn't sound so bad.

#

(and started over 8 years ago)

ivory salmon
#

e.g. I've seen 3 different versions of that sqlite-net which are all variations on a theme, recommended by different Unity projects 😄

ivory salmon
flint sage
#

I think I did always provide the native sqlite assembly though

#

(wasn't aware that some platforms allow you to use theirs)

ivory salmon
#

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 🙂

ivory salmon
# upbeat path SQLite implementation are fraught with danger, especially when shipping to conso...

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)

upbeat path
ivory salmon
#

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" 🙂

upbeat path
#

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

ivory salmon
#

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?

sage radish
#

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?

ivory salmon
#

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.

upbeat path
deep jasper
#

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

cold breach
#

You need to take resolution into account to a certain degree, it's mainly subpixel triangles that tank performance.

deep jasper
#

you mean textures are eating performance?

#

of leaves/grass etc

cold breach
#

No it's like, when your triangles get small enough to the point there's multiple per pixel, rendering time increases exponentially.

deep jasper
#

and also if i won't render trees which are too far

deep jasper
#

might be just my country blocking

#

is it loading alr for you?

cold breach
#

Medium is so/so

#

Really good quality articles but I use Firefox to dodge the paywalls

deep jasper
#

VPN time

bold berry
#

How would i create a drag and drop system within unity to influence objects. something like scratch. is it a complex process?

sly grove
#

It's just the command pattern.

peak spire
#

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.
cold breach
#

So a splatmap?

peak spire
#

Maybe? I haven't looked into those?

cold breach
#

That's how unity paints it's terrain textures.

sage radish
#

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?

peak spire
#

And again, maybe the solution already exists and I've been looking in the wrong place for a solution but I'm stumped. queenk4TwT

sage radish
#

You will probably need both a heightmap and a mask texture.

lament salmon
#

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

deep jasper
#

come to vc

#

if you are still on grass problem

peak spire
deep jasper
#

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

peak spire
#

So, I'm trying to avoid using the bilboarding method

deep jasper
#

oh, so you are trying the grass blades stuff

#

or more of a geometry grass

peak spire
#

Yes. As an example, I would need the grass to be generated on the inner face of this, and not the exterior

deep jasper
#

like 32+ poligons

#

well, you can probably use the raycast hit.normal rotated 180 degrees

lament salmon
peak spire
deep jasper
#

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

peak spire
# lament salmon I dont think a heightmap is suitable for this kinda geometry

And I agree. That's why I was trying to combine these two methods:

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

▶ Play video
deep jasper
#

as i'm thinking, you need to pass the grass direction inside the grass shader

half swan
deep jasper
#

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

lament salmon
#

Or both

deep jasper
#

yeah, but i need a way to create those impostors

#

From 3d mesh to 2 separate textures

lament salmon
#

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

peak spire
lament salmon
#

Manually with Camera.Render for example

deep jasper
#

and that's the thing i want to apply the resulting textures to

lament salmon
#

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

lament salmon
#

Billboard looks better on most objects

deep jasper
#

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

lament salmon
#

Yeah, just gotta figure out the shader for that billboarding effect. Probably not too complex to make

deep jasper
#

yeah, just some shadergraph logic ig

lament salmon
#

Rotating the trees via script might be a bit heavy, but worth a try too

rocky mica
#

I can try to find the logic for baking and the shader when I am home

deep jasper
#

Thanks

icy wadi
#

can anyone help me with an issue i'm facing when i'm trying to run a thread inside of a coroutine?

sly grove
#

Well, depending on what you mean I guess

upbeat path
#

!code

thorn flintBOT
icy wadi
#

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

sly grove
#

And when you do something else...?

icy wadi
#

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

sly grove
icy wadi
#

it bascially runs an A* algorithm for pathfinding, i can show it too, sec

sly grove
# icy wadi it bascially runs an A* algorithm for pathfinding, i can show it too, sec

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

upbeat path
#

indeed ^^

sly grove
#

e.g. pathNode.gCost = int.MaxValue;

icy wadi
#

huh, i see

sly grove
#

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

upbeat path
#

you need data isolation so that FindPath is never called with overlapping parameters

icy wadi
#

i thought doing stuff like:

PathNode pathnode = grid.grid.GetGridObject(x, y);

creates local copy of that node inside of this function

sly grove
#

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

icy wadi
#

yeah i see

#

well, this is problematic

sly grove
#

Nobody ever said multithreading was easy 😉

icy wadi
#

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

scenic forge
#

Have you positively identified it's a performance bottleneck? Have you profiled to see how long it takes to find a really long route?

icy wadi
#

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

scenic forge
#

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)

icy wadi
#

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

scenic forge
#

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.

icy wadi
#

thanks again for help and the suggestions

wary spruce
#

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?

scenic forge
#

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.

wary spruce
#

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 😄

scenic forge
#

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.

half swan
wary spruce
#

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 😄

half swan
#

The general discussion thread gets some real quick responses

wary spruce
#

let me try

outer barn
#

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.

untold moth
outer barn
#

@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

half swan
outer barn
half swan
thorn flintBOT
outer barn
#

@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

half swan
outer barn
#

yeah 😄

untold moth
outer barn
untold moth
outer barn
#

@untold moth I will do that , did not think about it like that

outer barn
half swan
outer barn
#

@half swan poco ??

half swan
#

public class MyData { }

outer barn
#

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 .

half swan
#

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

outer barn
#

Makes sense ,

untold moth
outer barn
#

Just about the overall code and the structure of it . Its tendancy to break if i extend it

untold moth
#

But to be honest, it's not great of a deal at this scale.

outer barn
#

alright thanks for the feedback 😄

tall ferry
# outer barn https://github.com/Unrealshadow/Smash_Code_Review

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.

outer barn
#

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

tall ferry
outer barn
#

@tall ferry tween is used for movement of the player between two points and they are used for text animations simple appear scale rotate

outer barn
steel snow
#

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

steel snow
#

so i have to use their library -_-

#

lame

steel snow
#

their meshes still use Vector3 so have to convert arrays all the time kind've annoying

flint sage
#

Isn't there a burst compatible mesh api

steel snow
# flint sage https://github.com/Unity-Technologies/MeshApiExamples

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

flint sage
#

I don't really know about the API just mentioning that it exists

steel snow
#

well even the code you linked uses V3 native arrays in the example

tiny pewter
#

you can do this in both c# and cpp and c

float3 *arr=(float3*)vec3_ptr;
steel snow
#

what does that do exactly?

#

type punning?

tiny pewter
#

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

tiny pewter
#

yes

deep jasper
deep jasper
#

yo

#

i used some magic and got this

fallow dune
#

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.

midnight violet
# fallow dune Hey! I am looking for some good resources on connecting code to UI elements. My ...

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.

fallow dune
midnight violet
fallow dune
#

Alright. Let me give it a whirl Thanks a bunch !

midnight violet
# fallow dune 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

fallow dune
#

Ya, I got some idea now! Thank you

violet otter
#

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

violet otter
#

alr tried setting the renderinglayermask in renderparams

#

unity just ignores it

sage radish
#

RenderParams.layer matches GameObject layers.

violet otter
#

ty

#

that worked

obsidian stump
mystic pike
#

I put this is networking but I guess it also applies here since it's code

#

Does anyone know a fix to my problem

exotic trout
#

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

untold moth
#

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.

exotic trout
#

oh nono i mean like

#

c#

untold moth
#

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.

jolly token
exotic trout
#

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

jolly token
sly grove
#

It can be mitigated by caching the data aggressively

#

e.g. caching MethodInfo or PropertyInfo instances

jolly token
untold moth
# exotic trout Mostly performance wise, Just was curious about any sort of additional context o...

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..?🤷‍♂️

exotic trout
exotic trout
#

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

sly grove
exotic trout
#

unless i'm mistaken it doesn't copy over values too does it?

sly grove
#

of course it does

#

what would be the point if it didn't

jolly token
#

If your value is unity-serialized that is

exotic trout
#

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

sly grove
#

You would get that warning when using a Constructor

exotic trout
#

wow ok

#

i guess i messed up then

#

tyvm

urban warren
#

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)

  1. 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.
  1. Use quads, and a use a shader for all of the styling.
  2. Procedural meshes with tessellated corners and stuff.
#

Any suggestions or recommendations of resources?

untold moth
urban warren
untold moth
#

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.

urban warren
#

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
untold moth
#

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.

urban warren
#

I don't think UGUI supports anything sort of procedural textures/styling.

Yeah, I think UITK does mesh generation mostly

jaunty swallow
#

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

untold moth
dreamy crescent
#

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!

flint sage
#

They're not available at runtime

tall ferry
#

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

deep jasper
#

are trees usually a single mesh

#

or one mesh for tree and several different for leaves

flint sage
#

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

stray bridge
#

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?

flint sage
#

Run it in a different thread

#

E.g. using Task.Run

#

Coroutines still block the main thread

stray bridge
#

Okay, so outside the coroutine then?

flint sage
#

Yeah

#

coroutines just spread work over multiple frames

stray bridge
#

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?

flint sage
#

Depends on your implementation?

stray bridge
#

Asking since I tried Thread (not Task) and it wouldnt let me outside of Awake and STart

stray bridge
dreamy crescent
flint sage
#

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

dreamy crescent
#

oh, that makes sense, thank you!!

flint sage
#

Anyways, no idea if it's possible to replicate the behaviour

flint sage
#

But there's plenty of terrian tools out there, no idea how they work

dreamy crescent
regal olive
#

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

silent acorn
#

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 !

silent acorn
#

Hi everyone !

deep jasper
#

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

sly grove
#

not reallty a code question

jaunty swallow
regal lava
#

Leaves and particles can be gpu instances via vfx graph

deep jasper
deep jasper
#

and well, not a 3d modelling question

regal lava
#

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

deep jasper
regal lava
deep jasper
#

you mean static gameobject with collider component

regal lava
#

Yeah, basically.

#

You can still change the rendering, but the collider should stay the same

zealous lark
#

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?

jaunty swallow
#

Define "gravity switcher"

zealous lark
#

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

obsidian stump
misty hedge
#

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 🤷‍♂️

bleak citrus
#

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

native raven
#

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

jaunty swallow
#

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

native raven
#

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

jaunty swallow
#

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

jaunty swallow
native raven
#

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

jaunty swallow
#

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

native raven
#

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

jaunty swallow
#

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

noble bough
#

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

native raven
#

got this working

pastel wedge
#

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

pastel wedge
#

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

analog fossil
#

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?

sly grove
analog fossil
#

Thanks @sly grove , I appreciate it! I will give it a watch.

serene pawn
#

does anyone know how dotween made it so you can call any dotween method through a gameobject's transform? like transform.DOScale() etc

jaunty swallow
sly grove
serene pawn
# sly grove 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

sly grove
#

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.

serene pawn
#

thank you, ill check it out!

#

i like learning about the advanced topics that unity tutorials dont cover

jaunty swallow
#

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

flint wharf
#

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

jaunty swallow
bleak citrus
jaunty swallow
# bleak citrus 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.

bleak citrus
#

Perlin noise can be a little bit surprising

#

notably, integer coordinates all have the same value, iirc

jaunty swallow
#

the problem isn't with the texture

bleak citrus
jaunty swallow
bleak citrus
#

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)

jaunty swallow
#

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

bleak citrus
#

show me your code so I can see how you're sampling the texture

jaunty swallow
#

I don't get what you mean by sampling the texture

bleak citrus
#

How are you getting this texture into the terrain?

jaunty swallow
#

I just create a texture2d and assign each pixel's greyscale based on perlin noise

bleak citrus
#

That's how you create the texture

#

What are you doing to set the terrain's height values?

jaunty swallow
#
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);
}
bleak citrus
#

okay, you're just copying 'em in

jaunty swallow
#

yeah

bleak citrus
#

are you adding together multiple octaves of noise?

jaunty swallow
#

yea

bleak citrus
#

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

jaunty swallow
#

I'm almost certain it's in the terrain resolutions

#

increasing the resolutions way over my sample size adds wider ripples

bleak citrus
#

changing the resolution changes the behavior, but that doesn't mean that using high-res heightmaps means you get ripples

bleak citrus
#

can I see the code that produces the texture?

jaunty swallow
#

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

bleak citrus
#

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.

jaunty swallow
#

creating a flat plane

bleak citrus
#

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

jaunty swallow
#

I'm confused

#

513 is just the width

#

these values don't indicate the height

#

they indicate sample points

bleak citrus
bleak citrus
#

And your texture can only contain 256 different values

jaunty swallow
bleak citrus
#

you only have 256 values

jaunty swallow
#

the 513 and 256 are completely independent values

bleak citrus
#

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?

jaunty swallow
#

if you could go into decimals I suppose but for the sake of the arguement no

#

but this isn't the same

bleak citrus
#

100 values, that's it

#

it is absolutely the same (:

#

your example is just less extreme

jaunty swallow
#

but the pixels on the map never reach anymore than 255

bleak citrus
jaunty swallow
#

so I don't understand where you're getting this from

bleak citrus
#

You only have 256 values to choose from

jaunty swallow
#

yeah and they aren't supposed to

bleak citrus
jaunty swallow
#

okay I kinda get what you're trying to say

bleak citrus
#

if the slope covers 20 pixels, but the height only goes from 5 to 15, you get stepping

#

You don't have enough precision.

jaunty swallow
#

this would make sense except I'm not doing a linear slope right?

bleak citrus
#

notice how the steeper hill also has some banding artifacts -- they are just subtler

#

it's lumpy

jaunty swallow
#

it's flat not lumpy

#

that is my issue

#

your precision does apply, just not in my example

bleak citrus
#

it's lumpy because it's switching back and forth between flat and slope

jaunty swallow
#

because I'm trying to set the individual vertices

bleak citrus
#

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

jaunty swallow
#

wait a second

#

the setheights, sets faces and not vertices?

bleak citrus
#

you are not directly controlling the mesh

bleak citrus
jaunty swallow
#

well yeah but it has to set it's height somehow right?

bleak citrus
#

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.

bleak citrus
jaunty swallow
#

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

jaunty swallow
bleak citrus
#

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

jaunty swallow
#

wonder how that even works

bleak citrus
#

I don't know the intricacies. It's generating different mesh densities at different distances

jaunty swallow
#

yeah I just meant the height setting

#

because you wouldn't get banding if the heightmap just set individual vertices

bleak citrus
#

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)

bleak citrus
#

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!

jaunty swallow
bleak citrus
#

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!

jaunty swallow
#

quite interesting way they've laid this out

bleak citrus
#

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

jaunty swallow
#

yeah I've seen that in my testing

jaunty swallow
bleak citrus
#

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

jaunty swallow
#

yeah I understand the issue it has with the interpolation of heights now, thanks

bleak citrus
#

R16 would also be tolerable: that's a 16-bit integer

bleak citrus
jaunty swallow
bleak citrus
#

Color uses 32-bit floats

jaunty swallow
#

oh the conversion is automatic, got it thanks

bleak citrus
#

I'd guess it just discards the g/b/a components

jaunty swallow
#

most likely

bleak citrus
#

Color32 is, mildly confusingly, the one that doesn't use 32-bit floats. That one is four 8-bit integers (thus, 32 bits)

jaunty swallow
#

Color might use 32bit floats

#

but you can only represent 0...1

#

meaning I'd need to multiply the output by 65536 no?

jaunty swallow
jaunty swallow
# bleak citrus so I guess it makes sense that the renderer blows up when you suddenly have 513 ...

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

bleak citrus
#

513 slots you need to put heights into

jaunty swallow
#

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

bleak citrus
#

the actual heights in the heightmap would be 0, 0.00390625, 0.0078125, etc.

jaunty swallow
#

yeah

#

I am using R16 now though and the heights are still the same

bleak citrus
#

That is a bit unexpected. How does RFloat behave?

#

I presume you are setting the format when you construct the Texture2D?

jaunty swallow
#
HeightMap = new Texture2D(TextureResolution, TextureResolution, TextureFormat.RFloat, false);
HeightMap.wrapMode = TextureWrapMode.Clamp;
#

with RFloat still seems to be happening

bleak citrus
#

show me the code that sets the pixel data

jaunty swallow
#
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);
    }
}
bleak citrus
#

perhaps _octaves is still an RGBA8 texture

jaunty swallow
#

ooo good call

bleak citrus
#

well, array of em

jaunty swallow
#

forgot to change that

bleak citrus
#

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

jaunty swallow
#

I'll look into optimisation a lot later as this is a one time generation only

bleak citrus
#

reasonable (:

jaunty swallow
#

and it's already bearable

bleak citrus
#

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

jaunty swallow
bleak citrus
#

If you're re-using the octave data over and over, then it makes sense to store it in textures

jaunty swallow
jaunty swallow
jaunty swallow
bleak citrus
#

no problem (:

noble bough
jaunty swallow
# bleak citrus no problem (:

I am experiencing a massive drop in detail on my heightmaps though, with the only thing changed being the textureformat

bleak citrus
#

turn the octaves back up

#

you probably still have those reduced

jaunty swallow
#

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

dusky kettle
#

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

jolly token
dusky kettle
#

ooo

#

i like prettier syntax

#

lmfao

#

ive never seen that before

#

the add and remove stuff, thats pretty cool

#

is that specific to events?

jolly token
#

It is

dusky kettle
#

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

jolly token
#

No problem

steep herald
#

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

serene pawn
#

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?

sly grove
#

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.

serene pawn
sly grove
sly grove
#

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();
}```
sage radish
#

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.

serene pawn
#

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?

sly grove
#

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

serene pawn
#

ooh thats good, wait but if i first check if raycast hit != null, isnt that an UnityEngine.Object null check?

half swan
sly grove
#

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)```
serene pawn
# sly grove Is this 2d or 3d

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?

sly grove
#

It gives you back a collider reference iirc

serene pawn
#

overlappoint returns a collider yes, i would have to check if that collider is null every frame, wouldnt i?

sly grove
#

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.

serene pawn
#

what makes ReferenceEquals better than == null?

serene pawn
sly grove
serene pawn
bleak citrus
#

ReferenceEquals will reveal if you have a null reference

#

vs. something that merely equals null

#

that's all

mortal halo
#

how can i learn c# for unity as efficiently as possible

untold moth
#

!learn

thorn flintBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

untold moth
#

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

upbeat path
serene pawn
sly grove
#

So not truly null

serene pawn
#

alright, thats good to know! now i have the ability to check if my null checks are bad for performance

mortal halo
upbeat path
mortal halo
mortal halo
#

and do i look at the unity docs, or the c# docs

upbeat path
#

both docs. A 'good' project is difficult to say but think simple, arcade style is not a bad place to start

serene pawn
bleak citrus
#

you need to be logged in to use search across an entire repo

serene pawn
serene pawn
#

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

mint lake
#

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

upbeat path
#

142 transform.rotation = ...
should be setting rigidbody.rotation

novel storm
untold moth
mint lake
untold moth
#

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.

steep herald
#

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

untold moth
steep herald
untold moth
#

Well, remove it then and try again. Though that "different package" might need to be removed as well, if it depends on it.

steep herald
#

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

untold moth
#

It's clear that il2cpp fails when processing that library though

steep herald
#

DUDE I fixed it

#

thank u

steep herald
#

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

untold moth
#

Not sure what I said was of any help, but glad you got it working.

steep herald
#

nah bro

#

u gave me the mental strength

#

and u stayed through with me

kindred tusk
#

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.

mint lake
sage radish
kindred tusk
#

I guess it's known

sage radish
#

I wasn't aware they had fixed the random cast exception

kindred tusk
kindred tusk
#

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

kindred tusk
kindred tusk
#

At least by my read of the issue

#

I won't be able to repro though

sage radish
#

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.

kindred tusk
#

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

bleak citrus
#

i wonder if it's caused by a garbage collection

kindred tusk
#

Surely

bleak citrus
#

you could add a GC.Collect somewhere in Update to cause..very aggressive GC behavior

kindred tusk
#

In my case it was trying to cast a float into the type

kindred tusk
#

I'm not that invested

bleak citrus
#

yes, you should use a Dictionary if you don't need the weak-reference behavior

kindred tusk
#

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

gray parcel
#

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.

bleak citrus
#

I would suggest changing your map generator.

#

Maybe you can make a minimum spanning tree out of all of the rooms.

gray parcel
#

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

bleak citrus
#

an MST will guarantee every room is reachable

bleak citrus
#

but it'll be a bit boring, since it's a tree graph

#

you could do that and then punch out random holes

gray parcel
#

Never actually implemented one of those, first time making a maze generator. Will look into it, thanks!

cedar cradle
#

what could be causing this error and how on earth do i fix it ?

mortal halo
#

it has no value

cedar cradle
#

but the variable in question is _unity_self, that is not one of my variables

#

its a variable from unity itself

mortal halo
#

code?

cedar cradle
mortal halo
#

provide the code

cedar cradle
#

but it doesnt specify wich script the error is in, I cant send 11 different scripts

devout hare
#

It's an editor bug. You can ignore it.

cedar cradle
#

and adding the line delets key frmaes from my animation curve variable causing this error

devout hare
#

The first error message is unrelated to the game breaking

cedar cradle
#

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

devout hare
#

It's caused by the animation curve having less than 2 keys

cedar cradle
#
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

bleak citrus
#

I'm pretty sure keyframes get deleted if they wind up with the same X position

cedar cradle
#

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

bleak citrus
#

oh, you're moving on both the X and Y axes, right

#

modifying the curve is more reasonable

lilac lantern
molten plaza
#

Is it possible to create an enemy that uses machine learning to adapt to the player?

molten plaza
#

How possible is it? Can you point out some resources to start out?

half swan
#

It has pinned resources there

neon talon
#

Got a pretty big spike in the Editor Loop seems like alot of Garbage collection any way to figure out whats going on ?

gray parcel
#

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

lilac lantern
gray parcel
#

It’s not procedural it’s random

#

That causes sometimes the room to be completely blocked from the rest of the maze

tiny pewter
#

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?