#archived-code-advanced

1 messages · Page 73 of 1

brisk spruce
#

so I would make a PipeManager service which handles all CRUD operations for PipeSegments

#

Should be at a single point I think?

uneven mauve
#

Right, so a new script called PipeManager then what's that next bit?

brisk spruce
#

Well what Im talking about might not be super relevant to you if you arent setup for doing like a whole service layer architecture

#

I think youd want a SO is the non dependency injection approach?

uneven mauve
#

I have no clue about Unity architecture to be honest

brisk spruce
#

SO called PipeManager or whatever and it has like,

CreatePipe
GetPipe
UpdatePipe
DeletePipe
#

your various CRUD operations to mutate your pipe segments

#

and then prolly a method like

GetSiblings
``` for sure
#

This service handles the job of keeping track of every pipe segment, the sibling relationships between pipe segments, and the Child->Parent lookup table for what children pipe tiles belong to which segment

uneven mauve
#

I'd love to do this but no clue what that means

tiny pewter
#

Now I understand what you means, you maintain a different hashtable for storing coordinate to segment

uneven mauve
#

Like I can make a C# file but from there, actually knowing what needs to be programmed first is a little confusing

#

I get the logic and can program it

brisk spruce
#

And then make an empty class called PipeSegment or whatever as well

#

prolly needs an Id which is randomly generated, I usually use a Guid

uneven mauve
#

What happened to no classes

brisk spruce
#

I dont actually know if you really need a class to be honest for this, the only actual data the pipe itself holds is just an arbitrary ID

#

I guess you need your "pressure" value I suppose

uneven mauve
#

What is the service layer architecture?

#

I'm trying to work close to production first time

brisk spruce
#

So personally I go for 3 layers:

  1. GameState Layer, which holds the "state" of the game for mutable info that can be changed and needs to be read/write from as a sort of Pub/Sub model.

  2. Service Layer, this is where all my logic actually goes for "doing" things, its the "game engine", its where like 99% of my code lives

  3. MonoBehavior or "scene" layer, this layer is all the MonoBehaviors applied to my GameObjects in the scene, and the only stuff that goes here is all the logic for what you actually see in the game

uneven mauve
#

Right and I create the other layers how? Through scripting?

brisk spruce
#

So I have like Assets/Scripts/Services, Assets/Scripts/GameState and Assets/Scripts/Entities (Entity is the term I personally use for the things in layer 3)

uneven mauve
#

Right

#

Well first things first, I need a script to actually store the dictionary

#

That's challenging

#

So no MonoBehaviour is needed?

brisk spruce
#

If you dont have dependency injection setup you'll use a ScriptableObject as your service I believe

#

at which point we start to exit my zone of knowledge as I dont use SOs, I typically use dependency injection for constructing my entire stack

uneven mauve
#

I'm still very confused. idek what dependency injection is lol

brisk spruce
#

at its simplest form its just when you pass a reference of a thing B to another thing A (injecting it), such that now A can "depend" on B. Thus Dependency Injection

uneven mauve
#

ah

brisk spruce
#

the most classic form of it in C# is Constructor Injection

public class MyServiceA
{
    public MyServiceA(MyServiceB serviceB)
    {
        ServiceB = serviceB;
    }

    private MyServiceB ServiceB { get; }

    // and now logic here can use ServiceB as a tool to do stuff
}
#

note how a ref to a "MyServiceB" was injected into MyServiceA which now depends on it and uses it. thus, "Dependency Injection"

uneven mauve
#

right I see, ty

#

I'm gunna make a blank script, attach it to an empty

#

Then define a dictionary

#
public class Pipe
{
    public string type;
    public int health;
    public Vector2Int coordinates;
    public List<Vector2Int> neighbors;
}
#

Is this bad then?

#

Ignore the actual values

#

But the concept

somber pendant
#

hey friends, i'm trying to deserialize an enum that uses bit flags (ie something like)

[Flags]
enum Terrain {
NORMAL = 0,
FOREST = 1,
SWAMP = 2,
DESERT = 4 }```

in json it's something like terrain = "FOREST", however it seems that the deserialization doesn't like human readable string enums (it wants an int) which is especially troubling for me in the case of bit flags, ie. something like FOREST|SWAMP. 

XML handled this stuff fine, why does json, the superior format, seem to struggle with it so bad? Should i be making an enum wrapper for handling the deserialization of this? no matter what i do i feel like my solution will be clunky and i will dislike it.

Ultimately it needs to be human readable and i won't accept a "solution" where my bitflag enum has to be represented as an integer like 145878 in json.
jolly token
somber pendant
#

the unity one,

JsonUtility.FromJsonOverwrite(data, feature);

#

seems like it only accepts integers for enum fields which makes me sad

#

especially for bitflag enums

#

i think newtonsoft json utilities doesn't fare much better

novel plinth
#

Unity's JsonUtility is special... by that I mean, it sucks
I'd avoid newtonsoft personally. and since 2022.2.x and above Unity supports stj

somber pendant
#

stj?

#

newtonsoft actually fails to deserialize my data properly so that alternative i have ruled out for other reasons

#

i mean, i could ptobably debug it but i already spent too much time on this silly issue

novel plinth
#

changing serializer and praying that it'd work sound a bit ...eh

#

debug it

somber pendant
#

i'm not using anything special in my class, so newtonsoft json failing to deserialize it caught me by surprise

#

i think it's the structure of the class that might have messed with it

#

since it's unity i'd rather avoid using other non-stock solutions in this case

#

not sure if [Serializable] and [SerializeField] play nice with newtonsoft

sly grove
ancient jackal
#

Hi, how do I make grid based strategies/games in 3D? I know that's a broad question, so to narrow it down, I'm interested in how I can make grid based placement of units. Do I use tilemaps or just make an Model/View sorta thing where I have non-MonoBeh Grid and Cell classes and a View class which places them in the world?

sly grove
#

You can use Unity's Grid component to make spatial positioning and calculations easy (presentation layer)

ancient jackal
ancient jackal
rare tiger
#

I had a not very fun time with my current project learning how unity's shitty jsonutility works and I'd like to not have to do it again

sly grove
#

I don't serialize Jasons. They're much too emotionally unstable

#

As for JSON, look into Newtonsoft JSON

rare tiger
sly grove
#

Unity's serializer is generally the fastest one around afaik though, if you can work within its limitations

rare tiger
#

Yeah it's fast since it pretty much leaves it up to you to format everything into something usable. Which is fine I guess. It's just fucking annoying and tedious. Especially on the first time

#

Like it took me a day or two to figure it out

sly grove
rare tiger
#

Especially realizing you need the system.serializable tag on all classes you wanted to cast the data to. I had a lot of frustration as to why I had null reference errors

flint sage
sly grove
#

every serializer has rules about what will and won't be serialized

#

you will always need to spend time adjusting your datatypes to fit within those rules

rare tiger
#

Yeah ofc, would've been nice to know that ahead of time tho. Yk, a bit better documentation on how to use it other than some YouTube tutorials and stack exchange code snippets

flint sage
rare tiger
#

When I was look for it originally I didn't find it

sly grove
#

Yeah it's documented.
https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html says:

Internally, this method uses the Unity serializer; therefore the object you pass in must be supported by the serializer: it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied

rare tiger
#

Maybe because I was searching up Json parsing

sly grove
#

same on the FromJson documentation

rare tiger
#

Maybe I just need to read better then. Idk

sly grove
#

when something's not working as expected the docs should be one of the first things you look at

plucky laurel
#

typically you have some shared context object

#

you can look at existing bt/fsm implementations to see what they do

#

its some component, often called "blackboard" where everything writes/reads

#

or just look at mecanim, with its parameters

#

same concept

#

if your fsm is specialized you dont need to abstract variables, you can just declare public properties and use them as is

sleek terrace
plucky laurel
#

it has limitations like 300 triangles per mesh

#

and it does the batching each frame on the cpu

#

you can imagine you merging the whole thing every frame

#

you want it merged, or if you dont want to spend time on the cpu merging you can attempt to use gpu instancing

#

if you want it merged you can use CombineMeshes api

#

if your thing is dynamic, you can chunk it and update /recombine only changed chunks

sleek terrace
#

So, I now have to combine all the meshes on the individual hexes into 1 mega mesh using the CombineInstance api?

#

where can I find this gpu instancing?

plucky laurel
#

google it, unity provides api to instance mesh batches, so you still will have to write it

#

or you can buy gpu instancer asset from the store

#

or try finding open source one on github

sleek terrace
#

ok thanks

plucky laurel
#

mega mesh is typically the fastest option if its chunked on modern gpus

#

but you pay for it with baking time on the cpu

#

gpu instancing is typically desired in highly dynamic scenarios and also has its ceiling

sleek terrace
#

ok

#

my material doesnt have gpu instancing

#

its custom made btw

plucky laurel
#

i dont know what that toggle does but it never did anything significant

#

if you want to use gpu instancing you have to either write it or rely on custom written instancing system

#

that toggle may shave off 10-20% in my experience, a properly written system can reduce it by 80%+

sleek terrace
#

i see

flint geyser
#

Can I have a class' value be tweekable in inspector without putting [SerializeField] in front of them? Perhaps with Odin?

pure dock
#

not really a viable solution though . . .

novel plinth
sleek terrace
#

How can nothing be rendered and I still only have 130-ish fps?

#

just curious btw

mortal gust
dusty wigeon
shy glacier
#

when i use Physics2D.Raycast are all RaycastHit2D properties computed, or just the ones i refer in code?

#

also, if so, instead of getting RaycastHit2D.distance, could i somehow get square distance instead, to not compute a square root operation?

shy glacier
#

ok, and is there anything i can do to speed up the process, or no?

dusty wigeon
sly grove
shy glacier
dusty wigeon
#

Unity GameObject is not made for that.

shy glacier
#

yeah, i know, especially the fact that unity uses C# and doesnt let me treat bools like numbers and forcing me to use branches

#

if not the unity profiler, i'd propably be stitting in unreal rn

tiny pewter
#

i remember you can trun bool into int by something like
*(byte*)&bool

dusty wigeon
sleek terrace
#

anyone know why combined mesh isnt working?

shy glacier
shy glacier
#

instead of creating a branch i can just do something like

void OnJump
{
  velocity += Vector3(0, jumpHeight * Isgrounded(), 0);
}
#

isgrounded is meant to be function that returns bool here

sly grove
shy glacier
#

both

#

it is a little optimization and looks cleaner

#

well this is not the biggest example of C++ having better performance than C#

sly grove
#

you've tracked down a noticeable performance issue in your game to the fact that C# can't convert bools to ints without branches?

#

Kinda sems more like you just don't like it, which is fair

shy glacier
#

those are 2 different examples

tiny pewter
#

use unasfe code....

shy glacier
#

also i already dealt with it, i will use raycasthit2d.distance

dusty wigeon
shy glacier
#

no way

#

you are multipying by either 0 or 1

#

if this was a branch, then CPU could misspredict

dusty wigeon
#

You are multiplaying and adding every frame

shy glacier
#

not every, this is a function OnJump

dusty wigeon
#

Nvm, I see that you use OnJump

tiny pewter
#
switch(bool){
case true:break;
case false:break;
}

i try this and the compiler compile this.....
you may believe the compiler will generate jump table instead of cmp
though mispredict still happens

dusty wigeon
#

However, you are still doing addition for no reason

shy glacier
#

switch is also a branch

dusty wigeon
#

Branch is better here

tiny pewter
#

but for bool?a:b
branching is faster than a*bool|b*!bool in my machine

shy glacier
#

this is a ternary operator

#

its also a branch

tiny pewter
#

two multiplications cost more on my machine

#

idk if you have a fast multiplication unit in your cpu

dusty wigeon
#

You also have 3 additional addition (with his code)

shy glacier
dusty wigeon
#
if(IsGrounded())
{
  velocity += new Vector3(0, jumpHeight, 0);
}
shy glacier
#
void OnJump
{
  velocity = new Vector3(velocity.x, velocity.y + jumpHeight * Isgrounded(), velocity.z);
}
#

only 1 addition now

dusty wigeon
#

Still one more than necessary

shy glacier
#

ok i got another point

#

in C# you cant give CPU hints

sleek terrace
#

i dont see the point of arguing over c# vs c++

#

unity uses c#, nothing we can do about it

shy glacier
#

i know

#

its not arguing

#

its discussion

sleek terrace
#

its a pointless discussion

dusty wigeon
#

We all agree that C++ is better than C# for performance. Does not make Unreal suitable for performance junkies

sleek terrace
dusty wigeon
tiny pewter
#

actually you may predict the c-code equivalent

  *(some address+some offset0)=*(some address+some offset0)
  *(some address+some offset1)=*(some address+some offset1)+some reg*return reg//i forgot what is called
  *(some address+some offset2)=*(some address+some offset2)
if(return reg){
  *(some address+some offset0)=*(some address+some offset0)
  *(some address+some offset1)=*(some address+some offset1)+some reg
  *(some address+some offset2)=*(some address+some offset2)
}

the compiler should ofc eliminate the first and third but you have to trust your compiler

dusty wigeon
shy glacier
#

well i just thought so, because i saw way more AAA games made with unreal than unity

dusty wigeon
tiny pewter
#

i always suggest before you doing some micro optimizations please ensure you have a good algorithm first by reading paper or copy and paste

dusty wigeon
#

It is also harder, which make smaller studio use Unity instead

sleek terrace
shy glacier
#

it would be easier with unity, but the game wouldnt look realistic, what imo is essential to GTA

dusty wigeon
sleek terrace
#

I see

dapper pumice
#

but you can have nearly similar grpahics in unity too

sleek terrace
dapper pumice
#

if you fully understand all the features hdrp provides.

dusty wigeon
tiny pewter
#

studying computer architecture and algorithm is easier

dusty wigeon
uneven mauve
#

Just going back to where I was yesterday, how should I do storage for user builds? If a user places objects in the world on a grid, I'm using a dictionary for coordinates but no clue how to structure the c# scripts?

tiny pewter
#

the placing pile game?

uneven mauve
#

Pipes

#

Yeah

#

Well I got to here

sleek terrace
#

amazing

#

you got the right idea thus far

uneven mauve
#

I never established if I could use classes

#

I was told "classes bad, use classes"

#

Each pipe stores its neighbours and type

sleek terrace
#

you could use scriptable objects
which hold the object world position

dusty wigeon
#

Nobody said that class are bad. We just said that it is less performant.

uneven mauve
#

Ah right

#

What's the class substitute?

dusty wigeon
#

They are better in many more ways

uneven mauve
dusty wigeon
#

struct

uneven mauve
#

Ok, I'll have a quick read on them

#
struct Coordinate
{
    public int x;
    public int y;
}
#

Like that?

#

Basically a class but no functions

tiny pewter
#

the struct should consists of coordinate, type and neighbor which represented by four bits
struct can have methods

uneven mauve
#

When storing pipe health, I was considering a class because then a function could "damage" the pipe

uneven mauve
#

For the struct, I'd just have an external function to "damage" a specific coordinate

#

So each item doesn't have the same bit of code

#

brb

tiny pewter
#

if the number of type<=16 you can even bitmask it into the one byte with neighbors
the sturct should look like
x,y,a byte, and you have 24 padding bits left......

sleek terrace
sly grove
#

so - open the profiler and see what's up. I bet a lot of it is editor overhead

sleek terrace
#

but I generated the mesh once?

sly grove
#

don't guess

#

profile

sleek terrace
#

others is taking up all my performance

dusty wigeon
sly grove
#

yeah try a build

sleek terrace
dusty wigeon
uneven mauve
tiny pewter
#

what is from storage? disk?
yes create a new struct then assign it to dictionary if user places a pipe

sleek terrace
dusty wigeon
#

At the moment, your issue is that you are running a development build

#

Which is slower

#

If you want real FPS data, you need to make a release build and print the FPS.

#

Or use native tooling

sleek terrace
#

how did u know it was dev build?

dusty wigeon
#

You cant profile a release build

#

A development build adds the necessary code to profile which make things slower.

sleek terrace
#

ok

#

but still even in editor mode, should I be getting higher fps?

dusty wigeon
#

No.

sleek terrace
dusty wigeon
#

It depends of a lot of things

#

I'm not even sure if he is in the editor

uneven mauve
#

Or am I too early on for that?

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public struct Component
{

    public enum ComponentConnections
    {
        None = 0,
        North = 1,
        East = 2,
        South = 4,
        West = 8,
    }

    public string type;
    public int health;
    public int pressure;
    public ComponentConnections neighbors;
}

public class ComponentManager : MonoBehaviour
{

    private Dictionary<Vector2Int, Component> ComponentDictionary = new Dictionary<Vector2Int, Component>();

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

I currently have this but I'm struggling with the key. Each pipe is 3x3 unity coordinate units, but I'm technically calling it 1x1 on my internals for ease. Should I still do Vector2 (1, 1) even though in scene space it would be (3, 3)

#

To get the actual location of the component, multiply coordinates by 3

dusty wigeon
#

You should dissociate the visual from the data

#

So yes

uneven mauve
#

Right so the key will be 1, 1 and scenespace will be 3,3

#

Thanks

#

So "start" function should be where it loads components from save data to the dictionary

dusty wigeon
#

That would be a start

#

At this point, you just need to get somthing working.

uneven mauve
#

Yeah totally

tiny pewter
#

you should use a int or byte to represent neighbors since you may have multiple neighbors

uneven mauve
#

I've been fully thinking about theory for performance all day

dusty wigeon
#

Usually you do:

  1. Work
  2. Clean
  3. Optimize
uneven mauve
#

Ah right

#

I was a little cautious on this as it's hard to optimize if I totally go the wrong way

tiny pewter
#

eg if some tile has east and north then neighbor=East|North

dusty wigeon
#

This is why you have short iteration.

uneven mauve
#

It'll return 0-8

tiny pewter
#

no

#

is 0-15 actually from 0b0000 to ob1111

uneven mauve
#

Oh right I missed a digit

#

So the current enum format is wrong?

tiny pewter
#

no, but the way than how you store the neighbors, you should not use enum as its type

uneven mauve
#

oh

#

I'm totally lost then

#

Surely its in that format to allow easy conversions back and forth while only being 4 bits

dusty wigeon
#

You can add value in your enum:

    public enum ComponentConnections
    {
        None = 0,
        North = 1,
        East = 2,
        NorthEast = North | East, 
        South = 4,
        West = 8,
    }
uneven mauve
dusty wigeon
#

Yes, it is.

uneven mauve
#

oh

#

Right no I only need to do the main 4 directions

#

No diagonals matter

dusty wigeon
#

I mean, in your situation it would means that there is a connection North AND East

uneven mauve
#

Right, but doesn't enum just handle that by adding the numbers from directions passed in?

dusty wigeon
#

Yes.

uneven mauve
#

So why do the math twice

dusty wigeon
#

To have a meaning

tiny pewter
#

you will have 16 values if you do that in this way....just bitwise or them it directly assign will override the neighbors tile has

uneven mauve
#

16 values is good no?

#

That's the lowest it could be?

#

It can have upto 4 connections from any direction, potentially 0

tiny pewter
#

eg if there is a new tile in north then tile.neighbors|=(int)enum.north

uneven mauve
#

If there's a new tile to the north, add 1

dusty wigeon
#

Yes and no

tiny pewter
#

let start with the basic
normally you will use four bool to store if there is neighbor in given direction
eg northExists=true/false
now you need 4 bytes to store them but they are just 1 (true) or 0(false)
so you now use a bit vector of 4 bits to store them

uneven mauve
#

Right

daring spire
#

does anyone know how to get started on coding this effect? (i dont rly know what to search on google either so any link will be appreciated 🙏 )

sleek terrace
#

2 cameras

#

with culling?

#

hell, you can actually render both images far apart

#

and simply move the player and camera accordingly

daring spire
#

oo thanks! to switch between them would u use a collider at the door or for the whole inside part of the room?

sleek terrace
#

yea

sleek terrace
uneven mauve
sleek terrace
daring spire
#

gotcha! so you're just teleporting the player to some random far away location with that room and teleporting them back afterwards?

sleek terrace
#

yea

#

it doesnt have to be far away

#

but all your really doing is enabling and displaying images

#

the reason you might want the interior far away is because of colliders

#

so what I did was that, I would spawn the interior far away where I was sure there were no colliders or anything of the sort

#

then when the user spawned back in, I placed him in the original world map

daring spire
#

ahh ok but i think my issue is the scene has some game objects that i cant disable (persistant logic on them)

#

thanks for the input! ill get working on it 👷

sleek terrace
#

all other objects will still be visible and rendered, but player wont know it

tiny pewter
#

I have to sleep now,
Since enum not allow you to store other value and the enum is just for helping you to set different bit in your bit vector ie the byte that storing neighbours exists or not

harsh canyon
#

sleep is for the weak

bleak citrus
#

I think a healthier approach is to get something working, and then spend all day thinking about how you'd change it

#

Not too much, or you'll wind up a huge sunk cost

#

You need some context to make those tougher choices

#

I'm doing that right now with my largest project. I'm making some big design changes informed by headaches I had

brisk spruce
#

Eh I mean, its all about striking the balance.

You also dont wanna just start throwing stuff at the wall and building on top of a bunch of poorly designed code.

Finding the right balance between Tech Debt and Over Optimization is honestly one of the most important skills in development, and its a skill that you just always keep honing for literally your entire life

harsh canyon
#

game development is so depressing

bleak citrus
#

better to run than curse the road

harsh canyon
#

humans arent meant to sit behind computers all day

harsh canyon
brisk spruce
#

instructions unclear, sitting on top of my computer now D:

bleak citrus
#

i didn't like it

#

moving around frequently makes things a lot nicer

harsh canyon
#

yeah but you wont get anything done

brisk spruce
#

Aight so, I have a bunch of logic that effectively has the job of constructing one "round" worth of actions for all entities in the scene.

I need to normalize their animation times however, so I am facing two options and I am not sure which one is going to be easier to maintain vs better performing.

Effectively my struct is a RoundAction, so I have a List/array/whatever of em.

public struct RoundAction
{
    public ActionType ActionType { get; }
    public Direction Direction { get; }
    public Vector2Int Target { get; }
    public float Time { get; }
}

Option one: now that I have all the actions times, I go through and mutate all their times to normalize them, this makes it though that my RoundActions are now mutable and not readonly

Option two: I create a new list of structs, copying the data over, but whats important is I can have 2 seperate types of structs, such that the returned struct only has the necessary data I need for the time calculations and then the output struct has potentially other stuff on it I may need, keeping the "calculate" vs "actual" structs as 2 distinct structs that may diverge over time cuz they might need to have different stuff on em

#

Option two is definitely crazy wrong right? Im overthinking this one and should just make it the struct mutable?

uneven mauve
#

I'm getting an error with this:

[Flags]
public enum ComponentConnections : byte
{
    None = 0,
    North = 1,
    East = 2,
    South = 4,
    West = 8,
}

The type or namespace name 'FlagsAttribute' could not be found

fresh salmon
#

System.Flags as it's not using System; by default in Unity
And hello again!

uneven mauve
#

ah

#

hey

#

haha

#

ty lol

#

Moved back over as I was moving from general editor to actual unity

brisk spruce
fresh salmon
#

Beginner, slow down (source: posted in another server)

#

The numbers symbols Mason, what do they mean?

brisk spruce
uneven mauve
#

There was more of a gap than expected jumping from standard programming like websites and apps into C# games

#

Js is great, I'm not totally familliar with C# but it's a similar programming concept

#

The logical thinking also carries over

#

But gotta keep performance in mind now

brisk spruce
#

I think js has the same operator for bit shifting IIRC

uneven mauve
#

Yeah

fresh salmon
#

Unity used to support JS, that's probably where we got the Geneva-convention-breaking naming of everything in Unity

brisk spruce
#

and yeah it can be nice to include an "All" flag at the bottom for your flags for easy of checking

uneven mauve
#

Well UnityScript was still very far from JS

uneven mauve
#

Moving on to the next issue, after the user has placed a ton of pipes and they are in the dictionary, there's a system to manage internal pipe pressure. I have an idea on how to do it but idk if it would be bad for performance.

#

My initial idea was every update, check each pipe for pressure less than 100 but greater than 0 (100 would be the default). If a pipe is in that range, take the neighbour and also set it's pressure to that amount. This would then be like a waterfall effect through the entire pipe system

sleek terrace
#

Is it possible to combine meshes that use thesame material, but each mesh may use a different texture?

#

My hexes all use thesame material, but i use the material property block to change the texture, however, it seems when i later on combine these hexes into 1 mesh, they all share thesame mesh

stuck plinth
#

you could put all the hexes with each texture in their own submesh, then you could fill up the materials array on the renderer with your material and set a different property block at each material index?

sleek terrace
#

hmm

sleek terrace
#

With your method, I would have to rerender the entire mesh grid wouldnt i?

devout coyote
#

But honestly it depends on how many pieps

#

100? 1000? 10.000?

uneven mauve
#

Well they can build as much as they like, but for their best chance to "succeed" at the game, they'll ideally not want more than 50 "connected"

devout coyote
#

Suggest looking into graph theory and specifically connected components

uneven mauve
devout coyote
#

Build it

#

See if it's fast enough

#

Only optimize if you know you need to

uneven mauve
#

Well I don't know how to do the pressure to test

#

I don't know if that pressure check should go in the update function, or some other method

devout coyote
#

I'd update it once you place the piece

#

Register it as part of a whole

#

And then once the whole changes update the whole

#

Or just chuck it all in update

#

Really depends on the amount of game objects

#

50 shouldn't be a problem

#

If you think about it, it doesn't matter where the code goes

uneven mauve
#

I'm totally lost. I don't know how to "spread" the pressure. If one pipe has a leak, how does it join to the other neighbour pipes

devout coyote
#

Just move it to a seperate method if update is too sloe

uneven mauve
#

I was doing the "waterfall" idea but that might be bad

devout coyote
#

Waterfall is fine

#

It's a basic way to traverse a graph

#

Again, look up graph theory, connected components is what you are looking for

uneven mauve
#

So if neighbour pressure isn't the same as current pressure, I average the values for both?

devout coyote
#

If that's the behaviour that you want

stuck plinth
uneven mauve
#

Well if one has a hole, I want the entire section to copy its pressure

devout coyote
#

So

#

You need to find which nodes (pipe pieces) that are connected (have edges)

uneven mauve
#

Yeah, that makes sense

#

I could treat this as "this is a list of every connected component" but I feel like there is a more proceedural method

#

I heard about BFS and DFS algorithms

devout coyote
#

Good starting point

uneven mauve
#

I'm just going to implement waterfall for now maybe

#

It's easiest and no issues can occur

devout coyote
#

Your waterfall method is DFS or bfs

#

Depends on how you implement it really

uneven mauve
#

Well I didn't think that far

#

It's just, every update, check if a pipe has pressure that isn't 100. If that pipe isn't 100, check if it has neighbours. If those neighbours don't have the same pressure, change the pressure to something

devout coyote
#

That won't work

uneven mauve
#

For performance?

devout coyote
#

You don't control update order

#

Say you have 100 and 99

#

Should 100 become 99 or 99 become 100?

uneven mauve
#

Right yeah that's why I said "something". I could either set it to an average of both, so 90 and 100 would make both 95

#

That then allows simulation of larger areas to lose pressure slower

#

So then if a pipe has pressure 100, the others will fill

devout coyote
#

Okay but then the next pipe is at 85m

uneven mauve
#

In what order?

devout coyote
#

Does it do 90 - 85 or 95 - 85?

uneven mauve
#

No clue honestly

#

One issue I face is that pipe valves can be opened and closed (Not en mass hopefully) but this could impact sudden changes

devout coyote
#

Yeah so you can't compute it just based in the neighbours

#

You are going to have to use proper graph algorithms

uneven mauve
#

Wow that's hard i see

#

ty

#

I'll investigate and not panic

#

Do you think DFS or BFS given this concept?

#

I'm thinking BFS

dusty wigeon
#

BFS makes more sense.

uneven mauve
#

I don't even know how I would pass in the data needed

#

I don't even have anything set up to test on, like default pipes

desert ember
#

Ive got this problem going on with my car shooting, heres a clip of it. for some reason when i turn at a certain angle it decides to shoot backwards instead of at the point I want, i have a plane that uses the same script and it has no problems, any advice?

desert ember
#

thats what ive got so far for the shooting

sleek terrace
#

have you identified that the mouse position in within the confines of the game?

sleek terrace
desert ember
#

now you sir, have sparked a new idea in my brain. thank you

sleek terrace
#

your welcome, Im guessing as you are moving the scene around with your mouse, your mouse position is changing, causing the ray to shoot of in a different direction

jolly token
brisk spruce
#

lets me still keep it sort of compartmentalized away but keeps the struct as a readonly one

jolly token
#

Anyways I think that is alright

#

That's what custom numeric types usually do

desert ember
sleek terrace
trail cedar
#

Hello, I've been working on the project for a few weeks now, and I'm having a memory issue. I'm taking a snapshot of the device, but I'm unsure what's consuming the rest of the memory. Does anyone have an idea on how to identify the cause of the problem? Thank you in advance for your response.

flint sage
#

You should probably look in the other memory profiler tabs

trail cedar
# flint sage You should probably look in the other memory profiler tabs

Could you explain what you mean? I've looked through other tabs, but the memory breakdown is not available in this version of Unity, and in the tree map I still can't find the cause of the problem. It doesn't seem like anything from the tree map is causing such a significant consumption, but as you can see, most of it is taken up by native memory, executable dll, and untracked, which I don't know where they come from and how to reduce them.

flint sage
#

Well you've got 330mb of meshes

#

160mb of textures

trail cedar
#

I know that and I can't reduced it anymore

#

As you can observe, the tree map is only utilizing 1.3GB, while the entire game is consuming 3.6GB. Therefore, my question is, how can we reduce the remaining 2.3GB of memory usage?

clever urchin
#

Because the editor is super unreliable (textures, meshes, etc being double the size for one)

clever urchin
#

Do you create textures on the fly in script?

#

Try marking them as read only, should halve the RAM usage per texture if you're not needing to read/write the pixel data

#

Try benchmarking before and after a Resources.UnloadUnusedAssets call as well to see if you have some native memory leaks

#

I love this sort of optimization stuff, I recently optimized the hell out of our app at work

trail cedar
clever urchin
#

Ok you'll need to look into the lifecycle of your objects then

#

Can you screenshot the other tab with the bars in it?

#

Should be light blue, dark blue, yellow, etc horizontal bars

#

Unfortunately Unity's garbage collector is absolutely horrific and quite frankly needs urgent work on it

#

So you might have fragmentation issues, or reserving a lot of pages

trail cedar
trail cedar
clever urchin
#

Other view

#

"Summary"

#

That one shows a dcent amount of memory fragmentation

trail cedar
trail cedar
clever urchin
#

Unity is terrible with fragmented memory because it uses a non generational, non compacting garbage collector

#

You do have 600 mb of native memory thats sort of just chilling unused but reserved

#

Managed C# memory looks fineish apart from a bit of fragmentation

#

Are you loading a ton of large amount of unity objects or some large ones and then unloading them?

#

Asset bundles perhaps or addressables?

trail cedar
clever urchin
#

hmm

trail cedar
clever urchin
#

Without knowing exactly how your code is laid out, and whether that asset reuses the memory it loads/unloads its hard to tell

#

But putting in some guess UnloadUnusedAssets calls at certain points and comparing snapshots might help

#

Look up how to compare snapshots

trail cedar
#

Is it way to find out other reserved memory?

clever urchin
#

Unfortunately Unity handles it all in a black box

#

They're hard to track down

#

But native is Unity's own memory for the engine

trail cedar
#

If I understand correctly, there is no simple way to solve this issue, and I need to manually search for the problem in the code, right?

clever urchin
#

I would 100% do some comparisons between two memory snapshots

#

When you load one chunk for instance, then load and unload a chunk and see what happens

#

Then do a few other things like that

trail cedar
#

I will definetly try it. Thank you very much for your help

soft shoal
soft shoal
# trail cedar

@clever urchin And for this, do you have any idea what this untracked memory can be? like why it happens? Here it's 480 MB, quite a lot.

soft shoal
trail cedar
clever urchin
clever urchin
#

The actual C# gc is generational, and splits up into chunks depending on how long the object has lived, and the size of it whereas Unity doesnt do any of that

#

So it's much less efficient from that regard

lofty solstice
#

Anyone here happen to know if unity meshes use shared vertices or not?

clever urchin
#

Across one mesh or multiple?

lofty solstice
#

One mesh

clever urchin
#

Yeah they can share verts

lofty solstice
#

aight, thanks!

dusty wigeon
#

Also, you should use 2022 to analyze your snapshot

#

It can open older snapshot

#

Fragmentation will most of the time get to 50%. At least in the managed memory

#

Finding leak is pretty easy with 2022. Here an example of a leak we found:

plucky laurel
#

just look at DLSS which made conceptual shift is optimization

#

same thing for any low level code, a small change in how algorithm approaches a problem can gain orders of magnitude performance

#

or a massive shift from one paradigm to another, like OOP > ECS

#

when approaching any problem one needs to understand the domain of the problem and requirements, what are the budgets placed, there is no point in sweating over a problem if the performance is simply not required or lies within the budget

molten socket
#

Does anyone have experience with OpenFracture?

#

It just does not fracture my custom meshes no matter what

#

What have I done wrong..?

valid tapir
#

Is there really no way of getting single MeshData from Mesh? I need to create custom NativeList of MeshData but I can only retrieve MeshDataArray. Getting first element would be okay but the problem is now the array stays in the memory and when disposed it will dispose of the copy you get for custom NativeList.

stoic python
#

Hoi people! I'm trying to capture video clips out of a built windows app, something like scripted recorder from the recorder package (which only works in edit mode)

What are my options?

flint geyser
#

In Zenject when a Context appears, when is it installed? Can't find Awake or Start in it

#

When creating an object with Zenject, how to pass to it some data before the installers work?

misty walrus
flint geyser
#

I want the injection to depend on something I pass

misty walrus
#

Have you tried creating the object from a method?

flint geyser
#

Without Zenject it won't do

misty walrus
#

Container.Bind<Foo>().FromMethod(GetFoo);

flint geyser
#

Without injection I mean

misty walrus
#

I meant like so.

flint geyser
#

I have packs with cards which are meant to spit cards when clicked upon, so installers on cards won't have access to the method

#

Cards are meant to be created following a template and I want to pass the template somehow

misty walrus
#

Any reason a factory would not be suitable for this?

flint geyser
#

I mean I AM using a factory

#

For instantiating the cards

#

But I can't figure out how to give created cards the template before their installer works

misty walrus
#
    public class Factory : PlaceholderFactory<float, Enemy>
    {
    }

I haven't used Zenject in a long time but it looks like you can pass in arguments like so. In this example first argument is passed in.

#

You can pass the template as an argument, that you can then use in the constructor if the Card class

hybrid belfry
#

Hello, I am attempting to add some files to my Project. I had errors with Namespaces before referencing the new Assembly Definition with the "master" one as shown in the image. This solved those missing file errors. However, I now receieve the errors shown in the image too and I can't figure out why they are errors and not warnings :/

sly grove
#

honestly they seem like they should be warnings, not sure why they're errors

hybrid belfry
#

I see thanks

#

I can get around it using #pragma warning disable 414 but this is for warnings not errors but resolves the issue haha?

#

Odd

light hamlet
#

is there a way to apply materials to TMP_Text? I want the color of all the text in my game to match a material color so I don't have to change all the text at the start of every scene

sleek marsh
#

when someone says "compute shaders are faster than multithreading" is the reason just because gpus have more cores than a cpu?

sly grove
sleek terrace
sly grove
#

a GPU generally has overall more "computing power" than a CPU when measured in terms of like... total operations per second.

#

"faster" is a very loaded/vague term

sleek terrace
#

you know what I mean

#

@sly grove is helping people on unity your job? your always here

sly grove
#

for certain embarassingly parallel use cases (rendering a scene, doing per-pixel texture operations, etc) the GPU can generally do it much faster than a CPU

sly grove
sleek terrace
#

I want to get 1000fps out of this

#

thoughts?

#

its just a bunch of hex meshes which are their down objects

#

combining only doubles the fps and I want to be able ot access them individually

tired fog
#

Is there any way to check how big (size in bytes) a compute buffer is?

tired fog
brisk spruce
#

Combine like radius of 5 hexes into one big hex at a certain zoom, then do it again at even farther zoom

sleek terrace
#

I want each hex to be modifiable

tired fog
#

mmmm, okay

brisk spruce
#

How can they modify something they can't even click on at a large enough zoom out?

sleek terrace
#

O, I see what you mean

brisk spruce
#

Your hexes look less than 1 pixel big on your bottom pic

sleek terrace
#

lets not worry about that

brisk spruce
#

Oh well, depends on your actual goal then. I'd start by testing rendering at an appropriate zoom

sleek terrace
#

so as long as all the hexes are on the camera, it will render all of them

#

with same fps

sleek terrace
plucky trellis
# sleek terrace I will try this

If that doesn't give enough control, try generating a mesh for chunks of hexes as a combined mesh, and update the mesh as needed when chunks change

torpid smelt
#

Hello. I'm attempting to load a JPG into a texture2d, however, the size of the JPG is far too big and needs to get downscaled. is there a sane way to do this in Unity? I've looked around but couldn't find any solid resources about it

urban trellis
#

you'll probably need to load/decompress it to pixel data manually, then do the downscaling, then load it into the texture2d

sleek terrace
#

only 120 fps at 1.9m vertices

stuck plinth
#

oops, that was meant to be a reply to @torpid smelt

torpid smelt
#

Annoying, but thanks. I'll look into it at a later date 👍

plucky trellis
sleek terrace
#

What does the instance array do?

sage radish
sleek terrace
#

why is it a list tho?

sly grove
#

presumably one for each instance?

sleek terrace
#

so it says...

#

hmm it sames all my instances have thesame position...

sly grove
sleek terrace
#

hmmm

#

how?

#

😦

sly grove
#

The passed instanceData can either be an array of Matrix4x4 (object-to-world transformation per instance) or a custom data structure

#

it's almost like the docs talk about it

sleek terrace
sly grove
#

actually it looks like in this case it will handle it without a custom shader possibly?
I'm more familiar with Graphics.DrawMeshInstancedIndirect

#

which does require a custom shader

sleek terrace
#

thats the only mention of shader

uneven mauve
#

So I was looking at algorithms such as DFS and BFS. I have a player-built pipe system where they can layout a network of pipes. They are in a grid pattern where one pipe section is 1x1 and can have upto 4 connected neighbours. I need a function that given a coordinate of a pipe, list all connected pipes in that area to manage internal pressure. I am not sure if BFS is best, or if I should just recursively list all neighbours of that pipe, then search those neighbours and so on till no more are found?

tall ferry
uneven mauve
tall ferry
#

what youve described

recursively list all neighbours of that pipe, then search those neighbours and so on till no more are found
is quite literally BFS

#

except you dont have to use recursion, you can use a queue or whatever other implementation you desire

uneven mauve
#

Ah ty maybe I need to just do a bit of reading

uneven mauve
uneven mauve
tall ferry
uneven mauve
#

I just reference the direction of all of the pipe's connections

#

Such as up, down, left, right

tall ferry
#

for an actual graph, you'll want the reference to the actual pipe stored. otherwise im not sure how you'll really reference another pipe

uneven mauve
#

They have coordinates in a dictionary so it knows its own coordiantes and can easily work out what's to the left or right

#

From what I guess:

  • Take the current pipe and add it to the queue. Add it to the connected list. Add its neighbours to the queue. Repeat
tall ferry
#

im slightly confused from what you have stored because you said it was the coordinates of its neighbours. If you're storing a pipe itself in some variables called up, down, left, right, then yea you would just add those to the queue. The coordinates of it dont actually matter

uneven mauve
#

alr ty

tall ferry
uneven mauve
#

thanks!

uneven mauve
#
    public void FindConnectedComponents(Vector2Int coordinates)
    {
        HashSet<Vector2Int> connected = new HashSet<Vector2Int>();
        Queue queue = new Queue();

        queue.Enqueue(coordinates);

        while (queue.Count > 0)
        {
            var element = queue.Dequeue();
            if(connected.Contains(element))
                continue;
            else
            {
                connected.Add(element);
                if(ComponentDictionary[element].Neighbors.HasFlag(ComponentConnections.North))
                    queue.Enqueue(element + new Vector2Int(0, 1));
                else if(ComponentDictionary[element].Neighbors.HasFlag(ComponentConnections.East))
                    queue.Enqueue(element + new Vector2Int(1, 0));
                else if(ComponentDictionary[element].Neighbors.HasFlag(ComponentConnections.South))
                    queue.Enqueue(element + new Vector2Int(0, -1));
                else if(ComponentDictionary[element].Neighbors.HasFlag(ComponentConnections.West))
                    queue.Enqueue(element + new Vector2Int(-1, 0));
            }

        }
        Debug.Log("CONNECTED:  " + connected.Count);
    }

I ended up with this but have an issue when trying to modify the current coordinate to get the neighbour. These are the errors :

austere jewel
thin mesa
austere jewel
#

Ah I see it now, I thought it was from ComponentDictionary or something I couldn't see

thin mesa
#

also HashSet.Add returns a bool, so you don't need to do the Contains check then add it, just if(contained.Add(element)) { //do shit }

uneven mauve
#

Probably the wrong place Queue<T> queue = new Queue<T>();

thin mesa
# uneven mauve

why are you in the advanced channel if you don't know how to use a generic class

austere jewel
#

Why are you sending screenshots of your console, is your IDE not configured?

austere jewel
#

No, as in not configured?

uneven mauve
austere jewel
#

google C# Queue and configure your IDE if it's not configured

frank peak
#

hmm so if Im working on a terminal based programming game but wanna store some representation of the in-game computers file system, as well as other devices (again, in-game). Does XML seem like an alright choice lol? It sort of suits the hierarchical nature of a file system, and for other devices it works more like a single layer deep definition

#

just as a way to save data I guess

frank peak
#

lmao

sly grove
#

why not JSON?

frank peak
#

the syntax feels so cursed to me but im just unfamiliar with it

#

but it might be better

sly grove
#

it's much simpler, and also faster to parse

frank peak
#

hmm i see

#

part of me wants to do it in csv and then write a custom parser but i might also have to adjust the format by having a specific encoding for certain objects just to parse it lol

#

but itd probably be slower than what i have now, and def slower than json

frank peak
#

idk

#

fun i guess

sly grove
#

also why would CSV be good for a filesystem?

frank peak
#

it seems like it could be easy to store records of some abritrary content if i agreed to encode them in specific ways. like every 10 elements is a row or smth, and then from there on I could build substructures? maybe its more work than its work 😓

#

ill try json

sly grove
#

that sounds awful

#

all kinds of weird undocumented black magic

frank peak
#

i do want it to be obscure so that its harder to cheat the game hehe

#

assuming someone was looking at decompiled code or smth

sly grove
#

what does the file format of this save data have to do with decompilation?

nimble nest
#

A little philosophical question...
Assuming that I have 2 classes, e.g. Player and EnemyProjectile. In which class I should handle collision between this 2 objects - Player or EnemyProjectile? Is there a right way of doing this?

sly grove
#

additionally, it's not a binary choice. There are parts of that interaction that might be handled by the bullet, and parts that might be handled by a script on the player

#

it's not necessarily one or the other

sage radish
#

Zip comes with the added benefit of per-file compression and encryption, but those two will also make reading and writing slower and memory intensive.

frank peak
#

makes sense, fair bit to think about i guess

#

and yeah archives eh

brisk spruce
#

I would use Protobuf personally for fast serialization, though you really wand lazy loading of data tbh so perhaps a proper sql DB

#

You don't want to have to load anything greedy, just load stuff lazy at last possible minute

#

Could use a proto set to define the hierarchy as a bin file, and raw "text" files are all stored in a text file with id numbers per text block.

frank peak
#

👍

#

sounds good to me tbh

eternal frigate
#

Is it possible to manually add it to an abilities List and set the values?

[System.Serializable]
public class PunchAbility : ActionAbility {
public float punchPower = 10f;

    public override void PerformAction(params object[] parameters) {
        if (parameters.Length > 0 && parameters[0] is bool shouldPunch) {
            if (shouldPunch) {
                if (parameters.Length > 1 && parameters[1] is GameObject target) {
                    Debug.Log("Punch with power: " + punchPower.ToString() + " at target: " + target.name);
                    // Implement your punch logic here using 'punchPower' and 'target'
                }
            }
        }
    }
}
flint sage
#

Make what editable

#

Maybe serializereference

eternal frigate
#

Nevermind ChatGPT rules xD

eternal frigate
tough ibex
#

hey guys, is there a way I can change the "names" of the objects that show up in the object selector? I have a bunch of scriptable objects that come from the same filename (see screenshot) and as my game grows, I find it'll be difficult to scale this, given that I currently have to click and search through each one to find the one I want. I can't even search since the search bar doesn't filter the path of the object

#

like presumably it's just taking that name from the meta.character filename

flint sage
#

CAn't you just change the file name?

#

It shows the path at the bottom iirc but yeah it's annoying

tough ibex
#

the files come from an external program that uses the meta.character to get info about the character, since the folder contains other things like portraits and other assets

#

so I'd prefer if I can keep the file name

flint sage
#

Ah 😬

misty walrus
tough ibex
#

yeah but I'm trying to figure out how to name them

flint sage
#

Or a custom editor that automatically assigns the meta data as I'm assuming there's a main character file you're also selected?

misty walrus
misty walrus
tough ibex
#

I think I am? like, say these characters are called "jen", "jack", "john", "jade" etc, then I'd want those names to be there instead of "meta", "meta", "meta", "meta"

tough ibex
flint sage
#

I guess theoretically you can write a project view extension that loads the file and draws the new filename on top

tough ibex
#

well I tried diving into the Unity decomp to find where they render the name, but it's a labrynth

#

I won't spend too much time on this, I was more just wondering if there's a utility

#

I found ObjectNames.SetNameSmart but that doesn't seem to have helped

flint sage
#

That then lets you load the file and do magic to draw a new name on top

tough ibex
#

I'll check that out

misty walrus
#

Is the linked object going to be shown in the inspector apart from the object property field?

flint sage
#

Definitely a hacky way though

misty walrus
#

Then I would suggest, for an easier way, to write a small custom property drawer. Then use EditorGUI.Popup where you can name them.

#

This is probably just as hacky though. It should however be around a 20~ line solution.

stuck plinth
#

is this asset imported by some plugin's importer that you don't have the ability to change? it should be up to the importer to set a proper name

tough ibex
#

I have access to the scripted importer just fine, but I'm not sure how to set that proper name

tough ibex
#

I guess along with Navi's solution it would work

stuck plinth
#

if you can modify the importer i think you can just set the name property on the subassets as it adds them

tough ibex
#

I keep reaching deadends like this

#

thanks guys, I'll try do what you've suggested in a bit and let you know how it goes

tough ibex
#

because the sub-assets that aren't the main object have names:

#

and these do have the right names in the object selector

#

do importers need to set a main object..?

stuck plinth
#

hmm are the characters imported as subassets or main assets? i assumed they were subassets if they come from one source file

tough ibex
#

subassets, they come from lots of different files in the same folder

stuck plinth
#

in that case there should be other calls to AddObjectToAsset where you add each character i think? you should be able to set their names separately

tough ibex
#

oh sorry I misread

#

no the characters are imported as main assets, the portraits are imported as subassets

#

oh hey I got it

#

I just got it working by not setting a main object with the importer, which lets me just set the object name like you suggested

#

thanks everyone for the ideas 🙂

#

also, if there are no other sub-assets, I guess that Unity automatically designates it as the main object, so it can't have a name. as a hacky workaround, I just set a null object as the main one.

hope this helps anyone else in the future

eternal frigate
#
[CreateAssetMenu(fileName = "JumpData", menuName = "ScriptableObjects/Action/AbilitiesContainer")]
    public class AbilityContainer : ScriptableObject
    {
        public List<IActionAbilityData> abilities;
    }

    public interface IActionAbilityData {
        string Type { get; }
    }

    [CreateAssetMenu(fileName = "JumpData", menuName = "ScriptableObjects/Action/Abilities/Jump")]
    public class ActionJumpData : ScriptableObject, IActionAbilityData {
        public string Type => "jump";
        public float jumpForce = 5f;
    }

Does Anyone knows how I can make the list editable in Editor? I want to manually drag the abilities like Jump into the Abilities Container. Thanks for any help

stuck plinth
#

unity serialization doesn't really do interfaces unless you want to mess with SerializeReference, the usual workaround would be to make IActionAbilityData an abstract base class instead

eternal frigate
stuck plinth
#

it's basically exactly the same as using an interface, the only restriction is that you couldn't make another implementation that wasn't a ScriptableObject because you're stuck with one base class

eternal frigate
eternal frigate
dusty wigeon
#

Yes, it is expected. You need to add them manually or create a PropertyDrawer.

#

It is an oversight of Unity I would guess. Pretty dumb in my opinion.

stuck plinth
#

FWIW if you use odin inspector (i couldn't live without it lol) you get much better support for serialized ref fields

loud wadi
#

Why threads who's SV_DispatchThreadID still continue executing code even if I write a if to stop these threads?
This array is only for testing, and the code below shows what these numbers mean.

Triangle a;
a.a = vert[0];
a.b = id;
a.c = float3(sizeX, sizeY, vert[0].w);

Here is the whole file: https://pastebin.com/mpbRk3Lv
I'm trying to implement an algorithm called Marching Cubes

misty walrus
loud wadi
#

I was watching his tutorial just now XD. He also stopped these threads by adding a if at the beginning of main function, and in my other project I also used compute shader to generate terrain, and worked fine. But this time the if statement didn't work, maybe that's because that project writes data using the id instead of reads data using the id, and I just did't aware of it...

#

So the if statement CAN stop the thread theoretically, but the array tells me it can't

#

Ok problem solved...I just typed > instead of || . This silly mistake confused me half an hour... I need to see the eye doctor as soon as possible : )

vale spindle
#

I want to make simple visuals for aoe attacks: shapes like cones, circles, curves etc.. But i need to project them on slopes and stairs. How would i do that?

west nexus
#

Aight got it

calm mica
#

I'd appreciate it if anyone can give me an idea on how I might solve this problem.
I'm trying to make it so that ceilings are automatically added when I create a room. I was thinking of basically spawning a ceiling prefab at each point within a room but how would I even detect those points?

sly grove
#

basically it sounds like you need to do some procedural mesh creation

calm mica
#

i place down wall prefabs
the blue gizmo is the start point, red is the end.
the green is where the prefab is spawned

sly grove
#

either way you will need to do some procedural mesh generation here

#

you could also make roof prefabs if you want the player to manually place roofs

#

it's unclear what the desired gameplay is

#

how do you detect when a room should get a roof?

#

or when a room is complete?

calm mica
#

basically each wall has a list of connected walls

#

then a different script uses depth first search to go through each of these connected walls until it loops back to the start

#

the gameplay is a building game like the sims

sly grove
#

so when a complete room is detected you want a roof to automatically be created?

calm mica
#

yup

sly grove
# calm mica yup

Ok so you're essentially going to have to solve this problem in order to generate such a mesh:
https://en.wikipedia.org/wiki/Polygon_triangulation

In computational geometry, polygon triangulation is the partition of a polygonal area (simple polygon) P into a set of triangles, i.e., finding a set of triangles with pairwise non-intersecting interiors whose union is P.
Triangulations may be viewed as special cases of planar straight-line graphs. When there are no holes or added points, triang...

#

that article should be a pretty good jumping off point to find algorithms

#

I love how nicely that preview image captures the problem haha

plucky laurel
calm mica
#

Do you mean this? I suppose I would need to know which squares/nodes/points are inside of the room and from there just use a foreach loop to change the material of them all

plucky laurel
#

how would you know that?

calm mica
#

one way i guess would be to check for nodes around each wall
and then qualify and disqualify them based on direction? perhaps

#

and once those are done go for each neighbour until one of the wall nodes are found

#

and on and on until everything has been visited

plucky laurel
#

if you have a way to get the area inside walls, then you can marching square it for the ceiling tiles

#

or to generate a mesh

calm mica
#

that makes a lot of sense 👀

torpid birch
#

i wanna a tutorial of how to mute in this server

formal lichen
#

check boxes where appropriate

bitter elm
#

Why wont visual studio highlight errors anymore?

#

For some reason when I changed computers it no longer shows a red underline one the error

#

Why doesn’t it show me the error like it used too.

humble leaf
#

Not an advanced code topic but you can follow the instructions in #854851968446365696 for configuring your !ide

bitter elm
#

i tried it and it doesnt work

#

gonna move this in code beginner

proper bronze
#

I am trying to build an android build of my project, but i am having this error:

java.lang.AssertionError: annotationType(): unrecognized Attribute name MODULE (class com.sun.tools.javac.util.UnsharedNameTable$NameImpl)
    at com.sun.tools.javac.util.Assert.error(Assert.java:133)```
and then it lists a bunch more "at com." things. What is this and how do I fix it?
uneven mauve
#

Moving to advanced because this is tough:

I am trying to tick all of the properties on this enum for an object but I can't. It just won't let me tick them individually, or the "Everything" item

[System.Flags]
public enum BuildingNeighbours : byte
{
    None = 0,
    North = 1,
    East = 2,
    South = 4,
    West = 8,
}
austere jewel
uneven mauve
sly grove
uneven mauve
#
public class PrefabManager : MonoBehaviour
{
  public string BuildingName;
  public GameObject BuildingPrefab;
  public GameObject BuildingHolographicPrefab;
  public BuildingNeighbours BuildingNeighbours;
  public int Health = 100;
}
ember temple
sleek terrace
#

Well step in the right direciton

austere jewel
#

was very annoying to make settings pages that just didn't work for no reason

lilac lantern
brisk spruce
#

Anyone know if its possible to support in or readonly ref variables with <Action<T>> when you invoke it

#

or anything equivalent, I want to bind to an event that is utilizing an in / readonly ref variable but the binding is handled inside a function

#

IE:

void Bind(Action<int> method) { ... }

But Id like to be able to utilize one with a ref instead

austere jewel
brisk spruce
#

ah yeah perfect, that does it

#

thanks!

#

am I correct in understanding that by utilizing in variables readonly as much as possible, that should be more performant?

#

as that just passes a readonly ref of the var, instead of a copy of the var, to each method call?

#

Part of me is considering if its worth it to also add in support for binding to an old + new delegate, though I havent had personal use for it yet

austere jewel
brisk spruce
#

is there a readonly version of int, string, etc?

jolly token
brisk spruce
#

I'm supporting generic types so any struct

heavy salmon
#

Just updated C# extension in VS Code, what is this?

austere jewel
#

It literally tells you?

heavy salmon
austere jewel
heavy salmon
austere jewel
heavy salmon
austere jewel
#

Where do you call it?

heavy salmon
#

and the start

austere jewel
#

well, those two methods are called magically by Unity, so you'd need proper Unity support for that to be detected as used. VS Code's extensions are deprecated, so I have no idea what the state of things with it are. I'd recommend using Rider if you can, or VS Community if you're having issues with VS Code.

glacial wedge
#

Hi,

Unity.Collections.NativeArray`1:.ctor(Int32, Allocator, NativeArrayOptions)
GOAP.Core.<GetAGoalCO>d__37:MoveNext() (at Assets\_Scripts\GOAP\Core\CAgent.cs:409)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)```
I gets this errors on application quit
#

I have a coroutine thats launch a job with nativearray, and when the job is completed it disposes the array

scenic forge
glacial wedge
#

all works fine until i quit the playmode

#

I tried to add the Disposes call in destroy method of Monobehaviour, but it gives me more errors because it is triyng to access to something deallocated

scenic forge
#

Show your coroutine code.

glacial wedge
#
protected virtual IEnumerator GetAGoalCO()
        {
            currentGoal = null;
            currentAction = null;
            actionQueue = null;
            List<CGoal> sortedGoal = new(goalList.OrderByDescending(g => g.Important));

            foreach (CGoal goal in sortedGoal)
            {
                NativeArray<NativeFuzzyFact> goalFacts = new(goal.goalList.Count, Allocator.TempJob,
                    NativeArrayOptions.UninitializedMemory);
                for (int j = 0; j < goal.goalList.Count; j++)
                {
                    goalFacts[j] = new NativeFuzzyFact(goal.goalList[j]);
                }

                NativeArray<NativeAction> alist = new(actionList.Count, Allocator.TempJob,
                    NativeArrayOptions.UninitializedMemory);
                for (int j = 0; j < actionList.Count; j++)
                {
                    alist[j] = new NativeAction(actionList[j]);
                }

                List<CWorldFact> facts = agentFact.GetFactList();
                List<CWorldFact> worldFacts = CWorld.Instance.GetFacts().GetFactList();
                NativeArray<NativeWorldFact> agentFacts = new(facts.Count + worldFacts.Count, Allocator.TempJob,
                    NativeArrayOptions.UninitializedMemory);
                int count;
                for (count = 0; count < facts.Count; count++)
                {
                    agentFacts[count] = new NativeWorldFact(facts[count]);
                }

                for(int k=0; k < worldFacts.Count; k++,count++)
                {
                    agentFacts[count] = new NativeWorldFact(worldFacts[k]);

                }

                // ci salvo il risultato, è importante che la memoria sia pulita
                NativeArray<NativeAction> plan = new(8, Allocator.TempJob, NativeArrayOptions.ClearMemory);

                AgentFindPlanJob job = new()
                {
                    goalFacts = goalFacts,
                    plan = plan,
                    actionList = alist,
                    agentFacts = agentFacts,
                };

                if (isDebug)
                {
                    Debug.Log($"Agent Tick search plan. goal={goal.goalName}", gameObject);
                }

                JobHandle jobHandle = job.Schedule();
                yield return new WaitForJobCompleted(jobHandle);

                // se mi restituisce un piano valido
                if (plan[0].actionName != 0)
                {
                    actionQueue = new Queue<CActionBase>();
                    foreach (NativeAction plannedAction in plan)
                    {
                        if (plannedAction.actionName == 0)
                        {
                            // le azioni sono contigue, quindi alla prima assente so che ho finito
                            break;
                        }

                        if (isDebug)
                        {
                            Debug.Log(
                                $"Agent Tick found plan! - action: name={plannedAction.actionName}, cost={plannedAction.cost}",
                                gameObject);
                        }

                        actionQueue.Enqueue(actionList.Find((x) =>
                            Animator.StringToHash(x.actionName) == plannedAction.actionName));
                    }
                }

                goalFacts.Dispose();
                alist.Dispose();
                agentFacts.Dispose();
                plan.Dispose();

                if (actionQueue != null)
                {
                    currentGoal = goal;
                    currentGoal.OnStart();
                    break;
                }
            }
        }
glacial wedge
# scenic forge Show your coroutine code.
    public class WaitForJobCompleted : CustomYieldInstruction
    {
        private JobHandle _jobHandle;

        public override bool keepWaiting => UpdateState();

        public WaitForJobCompleted(JobHandle jobHandle)
        {
            _jobHandle = jobHandle;
        }

        private bool UpdateState()
        {
            bool result = _jobHandle.IsCompleted;
            if (result)
            {
                _jobHandle.Complete();
            }

            return !result;
        }
    }

this is the waiter

stuck plinth
#

the coroutine should stop when you exit so disposing it in OnDestroy or something like that is probably the way to go, what errors did that give you? i guess maybe the job still tries to access it on the last frame?

glacial wedge
#

Ok, I solved, the problem i was facing inside OnDestroy were 2 differents:

  1. when the job was in progress. I couldn't dispose the array used by the job
  2. when the job was finished. I couldn't dispose the array because was already disposed.
#

fix:

        protected virtual void OnDestroy()
        {
            if (!_jobHandle.IsCompleted)
            {
                _jobHandle.Complete();
                _goalFacts.Dispose();
                _actions.Dispose();
                _facts.Dispose();
                _plan.Dispose();
            }
        }
scenic forge
#

Complete blocks the thread though, might want to rethink the approach if the job takes long.

versed coyote
#

I just discovered Unity Recorder and have a question.
So I have my primary camera using for gameplay on Display 1.
Then I added a camera that "films" the player character moving around - I set this camera to Display 2 so I can still play the game on Display 1.
However it seems even to I set the filmcamera in the Recorder settings the visuals are not recorded because the filming camera was not set to Display 1.

What is the correct way to achieve recording from a different camera then my Player camera?

polar oxide
#

Hello everyone, quick question:
Has anyone here experience with developing for the steamdeck? I'm having issues with the case that the steamdeck goes into sleep mode while the game is running. As it wakes up, it may require a PIN to activate again, and I would like to suspend the game and the input system until that lockscreen disappears. Unity's onApplicationFocus does not fire. And I'm struggling to find related events, etc. in the steam documentation.

What is everyone else using to avoid that problematic state?

flint sage
#

Do you have pause in background enabled?

polar oxide
#

In the project settings, we have "Run In Background" enabled, because we handle the suspended state manually for different platforms.

green crane
#

This unity button works just fine when in screen space positioning, but when turned into world space positioning, the game does not register the button press, or even react to a mouse over.

It is placed the highest on the hierarchy (ui, highest tier), and has a level 10 on hierarchy.

sly grove
empty shell
#

Hello,

I have a problem where I try to pause the game when the Steam overlay is enabled. Right now the game pauses and unpauses between each frames.

    private void Update()
    {
        if (SteamManager.Initialized && SteamUtils.IsOverlayEnabled())
        {
            pauseMenu.ButtonPausePressed();
        }
    }

This is in a SteamAdapter class.

#

Can anyone help me find a way to pause/unpause the game when the Steam Overlay is enabled?

long ivy
#

your code is doing what you told it to do. Don't press the pause button if the game is already paused

#

if you're pausing based on TimeScale, Update will still be called at the normal rate

empty shell
flint sage
fresh salmon
#

Please don't post your question into multiple channels at once. Also post !code correctly, not everyone can see these embeds

thorn flintBOT
#
Posting code

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

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

dapper pumice
#

beside that, this is more beginner code

sleek terrace
#

Your code every crashed editor this bad fellas?

#

seems using parrelel for each with graphic render causes the issue

#

I know unity isnt thread safe buit damn

proper bronze
lilac lantern
proper bronze
#

no, i have a few others lol

lilac lantern
#

You should post everything

proper bronze
#

> Configure project :launcher
WARNING: The option 'android.enableR8' is deprecated and should not be used anymore.
It will be removed in a future version of the Android Gradle plugin, and will no longer allow you to disable R8.

> Task :launcher:preBuild UP-TO-DATE
[+ a bunch of other tasks]
aapt2.exe W 08-03 19:02:39 10328 12580 LoadedArsc.cpp:657] Unknown chunk type '200'.

aapt2.exe W 08-03 19:02:41  6844  1820 LoadedArsc.cpp:657] Unknown chunk type '200'.

> Task :launcher:processReleaseResources
[+ a bunch of other tasks]

> Task :unityLibrary:compileReleaseJavaWithJavac

> Task :unityLibrary:compileReleaseJavaWithJavac FAILED
33 actionable tasks: 33 executed

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

#

heres another error

proper bronze
# lilac lantern You should post everything
C:\Program Files\Unity\Hub\Editor\2020.2.2f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2020.2.2f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-5.6.4.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "bundleRelease"

stderr[
An exception has occurred in the compiler (1.8.0-adoptopenjdk). Please file a bug against the Java compiler via the Java bug reporting page (http://bugreport.java.com) after checking the Bug Database (http://bugs.java.com) for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.lang.AssertionError: annotationType(): unrecognized Attribute name MODULE (class com.sun.tools.javac.util.UnsharedNameTable$NameImpl)
    at com.sun.tools.javac.util.Assert.error(Assert.java:133)
    [+ a bunch of other ones. this is the same body of text as the one i sent before]
    

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':unityLibrary:compileReleaseJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org
#

another

#

the error is pretty much the same as the first one i sent, but this has more on the top and bottom. i dont know why they have two different errors for this

lilac lantern
sleek terrace
#

I need a better/faster way to run this loop.
Im generating a 500 x 500 grid mesh, I need 500+fps

#

help a brother ouyt

lilac lantern
#

And iterate over a span collection

#

Also don’t convert idata to an array in the loop

sleek terrace
lilac lantern
#

convert allData an array of arrays, then a span generated from allData.AsSpan().

lilac lantern
#

So have a new variable and on start convert the list allData to an array of arrays. Then use .AsSpan to get it as a span in the update method, then iterate over that with a regular for loop and indexing.

sleek terrace
#

as so?

lilac lantern
#

something like:

void Update() 
{
  if(useGPU && ready) {
    Span<InstanceData[]> spanData = newData.AsSpan(); // new data being allData but converted to an array in start / awake.
    for(int i = 0; i < spanData.Length; i++)
    {
      Graphics.RenderMeshInstanced(rp, hex.HexMesh, 0, spanData[i]);
    }
  }
}
#

I'm sure you can figure it all out, but you can test that and see if it's faster, I believe it will be, although I don't know if it will achieve your 500 fps.

lilac lantern
#

also, span is a ref struct so you can't have it as an instance field, you have to construct it in the method.

sleek terrace
#

its called in update?

plain temple
#

yeah those are just checking for input

sleek terrace
#

it looks like ur code worked as expected tho

#

u bought the weapon and it dropped

plain temple
#

im trying to make if for instance i have a beretta in my inventory and then im buying a beretta it will drop the purchased one

#

but to equip weapons it has to be in the inventory array

#

and it says missing in the inv array

plain temple
sleek terrace
#

so im guessing you can hold 3 weapons...

#

since your looping through all your guns before checking if u have additional space

#

you end up dropping the weapon

#

Im guessing

plain temple
#

yeah i can hold 3 slots and the 3rd one is used for knife which cant be dropped

sleek terrace
#

are you checking if ur inventory has space for an additional weapon before dropping?

plain temple
#

no because the space is limited to 2 weapons

#

well 3 gameobjects but the 3rd one is used for a knife so we can exclude that

lilac lantern
#

also, if you don't care about actual time and just want more fps, you can limit it to a certain number of loops per frame.

winter folio
#

I really need help Ive been sitting here for a few hours and I cant get my head around this

https://hatebin.com/rnuttrauot
So my first script here is linked to another script for a door (yes Ive done a door script like this because I wanted a small cutscene animation to play while opening it because I also need to additively load a scene)

https://hatebin.com/qqbyqsnauv
On THIS loadout script I need my weapons to be holstered automatically. It works perfectly fine with my keys 1,2,3. 3 is just an empty object for hands or whatever, 1 is a pistol and 2 is for a rifle. But for some reason if I call it from that first door script (need them to holster) then it is stuck in a loop of holstering and equipping constantly. The m4IsEquipped does turn false and the pistolIsEquipped does aswell and the selected weapon int also changes, but the weapon I just had out is stuck in that loop

winter folio
#

it DOES THE SAME THING and its driving me crazy because I dont understand why or how its doing that

#

tried everything I can think of

long ivy
#

step through it with a debugger or add a lot more logging

winter folio
#

debugger?

#

fuck it im just gonna redo everything i cannot be asked for this shit

austere jewel
austere jewel
fathom sail
#

What I guess you’re a discord mod so makes sense

sacred zephyr
#

ok so..this is sort of complicated

#

but i like to think its easier doable

#

how would you go about creating a circular inventory?

#

ive been basing all my info off this one reddit comment as there is literally nothing on the internet as far as tutorials for silent hill-esque inventory systems

austere jewel
#

Google "unity carousel"

sacred zephyr
#

its that easy?

sacred zephyr
brisk spruce
sacred zephyr
#

I know it does

#

the thing is that im too stupid to understand this part

#

everything else is something I understand

austere jewel
brisk spruce
sacred zephyr
#

3.14?

brisk spruce
sacred zephyr
#

im a little slow

brisk spruce
#

I mean thats pi which is indeed part of the formula

#

I mean its straightforward though, how many degrees are in a full circle?

sacred zephyr
#

multiple the radius by 2 to get the diameter, multiple by pi, thats circumference

#

i see

brisk spruce
#

Like if you have 6 items in the circle equally spaced out, how many degrees are between each one?

austere jewel
#

You can take this to #💻┃code-beginner or #archived-code-general where it'd be more suited, or just look at the numerous results for carousel UIs/inventory in google which you can pull together to get all the info you could ever need.

sacred zephyr
#

however i thought this code was advanced

inland knoll
#

Hey, so if I want to have glass shattering in my game realistically then how would I do that? I watched some videos and googled on the topic so I roughly know what to do, but not how to do it. I think my best bet would be to create a fracture pattern (as seen on the picture) and then split the glass from those lines into new gameobjects, but I am unsure about how to do that.

inland knoll
#

so no

#

it is not an option

#

I am looking for what is being explained in this video: https://www.youtube.com/watch?v=nuHg6_IIyK8

In this video, David shows you how we made the glass breaking effect in Receiver 2.

• Get Receiver 2 - https://store.steampowered.com/app/1129310/Receiver_2/
• Discord - https://discord.gg/Wolfire
• Reddit - http://www.reddit.com/r/Receiver
• Instagram - https://www.instagram.com/WolfireGram
• Twitter - http://www.twitter.com/Wolfire
• Facebook...

▶ Play video
dusty wigeon
inland knoll
#

well, okay it would work, but it would look awful

dusty wigeon
#

Then your only option is to break the mesh following a fracture pattern.

inland knoll
#

indeed, but my question is how to do that

dusty wigeon
#

With computer shader ?

#

You can also do it on the CPU

inland knoll
dusty wigeon
#

With the Mesh API

dusty wigeon
inland knoll
#

write shader or no write shader

dusty wigeon
#

You gonna need to use a computer shader

dusty wigeon
#

It splits a mesh in two

mellow sail
#

do you guys know how to fix jitter on wheeljoint2d when on high speed?

inland knoll
inland knoll
#

also 1:00 to 1:15 seems to explain how it was done, but I dont exactly get how to reproduce it

dusty wigeon
#

No idea. However, it is expensive to do those calculation and if you want appropriate performance you might want to use a Computer Shader. I'm not saying it is impossible, I'm just saying that should be your aim.

inland knoll
dusty wigeon
#

And extrude them back to 3D models.

#

This is how he did it.

dusty wigeon
inland knoll
#

I believe that I can do this with help, so I'm gonna try to break this down to smaller steps and ask this server for help if I can't figure out how to do the step then.

inland knoll
#

Hello, I am back here, with some help I figured out the next step I need to do, which is: Deleting my shatter map's every vertex outside of the glass and giving the shatter map a new border with the shape of the glass's border

#

(Sorry I couldn't think of a better way to explain it)

#

I'll try to make a picture so it would be easier to understand

tardy bobcat
#

i normally would never go in here for help but tbh no one ive talked to can help, ive got a bullet pooling script and a bullet script, the bullet script is supposed to invoke destroy after a despawn time or if it collides with an object it is supposed to call the function and cancel the invoke, very simple however, the collsion arent detecting i have a kinematic rigidbody on my bullets with continous and interpolate on with always awake for collison detection and i have static rigidbodies and on trigger colliders on all my walls and ground so they should detect and its a basic on collison enter fucntion but it just is not running all the alyers can interact in the collsion amtrix and i have even changed them to the same layer and there was no lukc and i just do not know how to solve it

inland knoll