#archived-code-advanced
1 messages · Page 73 of 1
Right, so a new script called PipeManager then what's that next bit?
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?
I have no clue about Unity architecture to be honest
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
I'd love to do this but no clue what that means
Now I understand what you means, you maintain a different hashtable for storing coordinate to segment
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
start by writing our the methods you probably need, I presume you probably want your basic CRUD functions for a "Pipe Segment"
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
What happened to no classes
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
What is the service layer architecture?
I'm trying to work close to production first time
its the concept of breaking your logic into "layers" by responsibility
So personally I go for 3 layers:
-
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.
-
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
-
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
Right and I create the other layers how? Through scripting?
its an organizational concept but typically I just make sure to keep em organized by folder structure and matching namespace
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)
Right
Well first things first, I need a script to actually store the dictionary
That's challenging
So no MonoBehaviour is needed?
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
I'm still very confused. idek what dependency injection is lol
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
ah
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"
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
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.
What Json serializer are you using
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
I believe it supports it
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Converters_StringEnumConverter.htm
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
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
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
Newtonsoft has totally different rules about what it does and doesn't serialize. Those attributes are irrelevant to it. You'll want to check their docs if you want to use it
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?
Yes a model/view architecture is pretty standard for strategy games
You can use Unity's Grid component to make spatial positioning and calculations easy (presentation layer)
Do you have any docs/tuts for them online? Couldn't find documentation for this separate component, although it was the first thing that came to midn for my task
oh thanks so much
Speaking of which, does anyone have recommendations for unity c# Json serializers
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
I don't serialize Jasons. They're much too emotionally unstable
As for JSON, look into Newtonsoft JSON
What about mikes
Unity's serializer is generally the fastest one around afaik though, if you can work within its limitations
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
well the list of things it can serialize are here: https://docs.unity3d.com/Manual/script-Serialization.html#SerializationRules
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
That's pretty normal in serializers though
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
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
I uuh.. did you see this link?
When I was look for it originally I didn't find it
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
Maybe because I was searching up Json parsing
same on the FromJson documentation
Maybe I just need to read better then. Idk
when something's not working as expected the docs should be one of the first things you look at
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
👍
With my mesh procedural generator, even with dynamic batching on, there is barely a difference in fps
I have seen people render far more triangles wih better FPS, what im I missing?
dynamic batching would not improve performance with massive amount of meshes
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
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?
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
ok thanks
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
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%+
i see
Can I have a class' value be tweekable in inspector without putting [SerializeField] in front of them? Perhaps with Odin?
i believe you can switch the inspector to Debug mode . . .
not really a viable solution though . . .
you can with custom editor and with your custom classes be contained in a ScriptableSingleton and set it's filePath so the data will be persistent (assuming this for edit mode) if not for edit mode, then you'd need to store it somewhere which might end up using a serializer 😅
that's sorta weird use case you have there
Not coding, not advanced. You're either bottlenecked on either GPU or CPU side. Might be slow hardware, might be running computational expensive code in background.
https://docs.unity3d.com/Manual/Profiler.html only this can answer your question.
[ShowInInspector] with odin
Most likely because of editor code.
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?
They're already computed by the time you see the struct. The properties are just straightforward passthroughs:
https://github.com/Unity-Technologies/UnityCsReference/blob/076ffb2c16d2aec23c2df1cb6cec03562186ec33/Modules/Physics2D/ScriptBindings/Physics2D.bindings.cs#L3167
ok, and is there anything i can do to speed up the process, or no?
You are doing micro optimization
is there a reason you're asking this? Are you seeing a performance issue?
yes im truly am
Then, change to DOTS if it matters
Unity GameObject is not made for that.
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
i remember you can trun bool into int by something like
*(byte*)&bool
I really doubt that Unreal is better for that. Both engine are not made for hyper performant games.
anyone know why combined mesh isnt working?
thats unsafe code, which needs extra enabling and messing with settings, not fo rme
unreal uses C++, which is already a win in performance
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
ok but... are you wanting this because you are seeing performance issues or because you're an optimization junkie?
both
it is a little optimization and looks cleaner
well this is not the biggest example of C++ having better performance than C#
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
those are 2 different examples
use unasfe code....
also i already dealt with it, i will use raycasthit2d.distance
First, it is not cleaner. Second, it is less performant.
no way
you are multipying by either 0 or 1
if this was a branch, then CPU could misspredict
You are multiplaying and adding every frame
not every, this is a function OnJump
Nvm, I see that you use OnJump
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
However, you are still doing addition for no reason
switch is also a branch
Branch is better here
but for bool?a:b
branching is faster than a*bool|b*!bool in my machine
two multiplications cost more on my machine
idk if you have a fast multiplication unit in your cpu
You also have 3 additional addition (with his code)
ok rewrite the code without 3 additions
if(IsGrounded())
{
velocity += new Vector3(0, jumpHeight, 0);
}
void OnJump
{
velocity = new Vector3(velocity.x, velocity.y + jumpHeight * Isgrounded(), velocity.z);
}
only 1 addition now
Still one more than necessary
ok i got another point
in C# you cant give CPU hints
i dont see the point of arguing over c# vs c++
unity uses c#, nothing we can do about it
its a pointless discussion
We all agree that C++ is better than C# for performance. Does not make Unreal suitable for performance junkies
Was able to double fps by combining them
Ive heard conflicting views on this,
is it true that towards the high end of performance, it really comes down to the individual programmers themselves?
what really differentiates unity/unreal is workflows
Neither of them has been made with performance as a priority
how come?
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
Because, there is other priority such as Visual Quality, Flexibility, Compatibility, etc.
well i just thought so, because i saw way more AAA games made with unreal than unity
Visual Quality is higher with Unreal which attract bigger studio
i always suggest before you doing some micro optimizations please ensure you have a good algorithm first by reading paper or copy and paste
It is also harder, which make smaller studio use Unity instead
i do this everytime
making a game like gta easier with unreal than unity?
it would be easier with unity, but the game wouldnt look realistic, what imo is essential to GTA
For a bigger studio, you would want to use Unreal for it's better graphical capacities.
For a smaller studio, Unity will help you finish your project by being easier to work with.
I see
but you can have nearly similar grpahics in unity too
what about maximzing performance? which one is easier?
if you fully understand all the features hdrp provides.
Unfortunately, Unity is clearly worst than Unreal in this category.
studying computer architecture and algorithm is easier
No idea, both has not been made for that. That being said, Unity has DOTS which is partially made for that.
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?
This is where I left off
#archived-code-advanced message
the placing pile game?
I never established if I could use classes
I was told "classes bad, use classes"
Each pipe stores its neighbours and type
you could use scriptable objects
which hold the object world position
Nobody said that class are bad. We just said that it is less performant.
They are better in many more ways
I'm totally new to Unity scripting
struct
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
the struct should consists of coordinate, type and neighbor which represented by four bits
struct can have methods
When storing pipe health, I was considering a class because then a function could "damage" the pipe
I've got the enum down! Good bit of learning, interesting!
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
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......
after doing mesh combining and with dynamic batching on
does anyone know if I can get better FPS than this?
most of your issue is on the CPU side now
so - open the profiler and see what's up. I bet a lot of it is editor overhead
but I generated the mesh once?
others is taking up all my performance
Others is usally the editor
yeah try a build
editor loop is taking up all my time
Yes, this is why you profile a build and not the editor
Sorry for the delay. I'm back. So I assume I create a struct for the components, then load each one from storage? idk much about storage yet so I'll research that. When the player places a pipe, I just create a new struct and add it to the dictionary?
what is from storage? disk?
yes create a new struct then assign it to dictionary if user places a pipe
Still only hittin 250
Way better than what you had before
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
how did u know it was dev build?
You cant profile a release build
A development build adds the necessary code to profile which make things slower.
No.
Project files: https://github.com/Matthew-J-Spencer/pushing-unity
Let's discover the true potential of Unity by pushing its limits. In this video, we'll explore a variety of techniques, from straightforward tweaks like data-oriented design, to more advanced methods such as direct GPU rendering and compute shaders. Join us as we uncover the powe...
Save Data i guess, when the user has saves of the game
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
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
Yeah totally
you should use a int or byte to represent neighbors since you may have multiple neighbors
I've been fully thinking about theory for performance all day
Usually you do:
- Work
- Clean
- Optimize
Ah right
I was a little cautious on this as it's hard to optimize if I totally go the wrong way
eg if some tile has east and north then neighbor=East|North
This is why you have short iteration.
Surely that's handled by enum?
It'll return 0-8
no, but the way than how you store the neighbors, you should not use enum as its type
oh
I'm totally lost then
Surely its in that format to allow easy conversions back and forth while only being 4 bits
You can add value in your enum:
public enum ComponentConnections
{
None = 0,
North = 1,
East = 2,
NorthEast = North | East,
South = 4,
West = 8,
}
This is even more confusing, surely north and east would just be 3?
Yes, it is.
I mean, in your situation it would means that there is a connection North AND East
Right, but doesn't enum just handle that by adding the numbers from directions passed in?
Yes.
So why do the math twice
To have a meaning
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
16 values is good no?
That's the lowest it could be?
It can have upto 4 connections from any direction, potentially 0
eg if there is a new tile in north then tile.neighbors|=(int)enum.north
If there's a new tile to the north, add 1
Yes and no
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
Right
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 🙏 )
2 cameras
with culling?
hell, you can actually render both images far apart
and simply move the player and camera accordingly
oo thanks! to switch between them would u use a collider at the door or for the whole inside part of the room?
use a collider inside and outside the house
So how do I apply this then? I thought this was the enum
when the user collider is hit and u have determined the user wants to exit,
load the outside image immediately, move camera and player around
then disable image 1, enable image 2,
from the player POV, it will look seamless
gotcha! so you're just teleporting the player to some random far away location with that room and teleporting them back afterwards?
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
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 👷
in that case, spawn the interior away from the main game area, place user in said area ... boom!
all other objects will still be visible and rendered, but player wont know it
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
sleep is for the weak
this is how to not make a game (:
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
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
game development is so depressing
better to run than curse the road
humans arent meant to sit behind computers all day
too late for running
instructions unclear, sitting on top of my computer now D:
i spent an hour in a chair for the first time in like a week today
i didn't like it
moving around frequently makes things a lot nicer
yeah but you wont get anything done
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?
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
System.Flags as it's not using System; by default in Unity
And hello again!
ah
hey
haha
ty lol
Moved back over as I was moving from general editor to actual unity
can make it a bit easier maintain by using bit shifting
[Flags]
public enum ComponentConnections : byte
{
None = 0,
North = 1 << 0,
East = 1 << 1,
South = 1 << 2,
West = 1 << 3,
All = (1 << 4)-1
}
Beginner, slow down (source: posted in another server)
The numbers symbols Mason, what do they mean?
Hey if its posted in #archived-code-advanced Im gonna give advanced advice :p
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
I think js has the same operator for bit shifting IIRC
Yeah
Unity used to support JS, that's probably where we got the Geneva-convention-breaking naming of everything in Unity
and yeah it can be nice to include an "All" flag at the bottom for your flags for easy of checking
Well UnityScript was still very far from JS
Ah right I see, ty
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
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
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?
hmm
I like this idea, however, I want to have the freedom to individually change each hex, as I see fit
With your method, I would have to rerender the entire mesh grid wouldnt i?
I'd advise you to build a proper graph structure that you can easily traverse instead of plonking everything into a dictionary
But honestly it depends on how many pieps
100? 1000? 10.000?
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"
Suggest looking into graph theory and specifically connected components
I was discussing the best storage method earlier and it was the best starting point to optimize later if needed
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
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
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
Just move it to a seperate method if update is too sloe
I was doing the "waterfall" idea but that might be bad
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
So if neighbour pressure isn't the same as current pressure, I average the values for both?
If that's the behaviour that you want
yeah, if you need to update individual hexes a lot without each one being an individual mesh, you need some other way of identifying which texture to use at each coordinate... maybe you could pass a separate buffer of that info to the shader or something like that?
Well if one has a hole, I want the entire section to copy its pressure
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
Good starting point
I'm just going to implement waterfall for now maybe
It's easiest and no issues can occur
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
That won't work
For performance?
You don't control update order
Say you have 100 and 99
Should 100 become 99 or 99 become 100?
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
Okay but then the next pipe is at 85m
In what order?
Does it do 90 - 85 or 95 - 85?
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
Yeah so you can't compute it just based in the neighbours
You are going to have to use proper graph algorithms
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
BFS makes more sense.
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
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?
send code soldier
s
now you sir, have sparked a new idea in my brain. thank you
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
I wouldn't say option 2 is wrong. It is natural to separate runtime data from immutable design data.
at the moment I am using the same type for both, but I ended up going with adding this method to my struct:
public RoundAction TimeScale(float multiplier)
{
if (Math.Abs(multiplier - 1.0f) < 0.01f)
{
return this;
}
return new RoundAction(ActionType, Direction, Target, MinTime * multiplier);
}
lets me still keep it sort of compartmentalized away but keeps the struct as a readonly one
If record struct was in Unity you could do 😛
return this with { Time = MinTime * multiplier };
Anyways I think that is alright
That's what custom numeric types usually do
tried making an object that would go where the mouse does but that seems to be working, it almost looks like the guns are shooting at the camera when its acting weird
Im not sure what you are trying to say
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.
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.
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?
Is this a build with development mode turned on or in the editor?
Because the editor is super unreliable (textures, meshes, etc being double the size for one)
Development build
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
Snap shot is created after level loading and Resources.UnloadUnusedAssets function
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
Do you mean Memory usage overview or someting else?
How can I fix memory fragmentation?
Reuse objects, don't create short lived objects often
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?
Yes we are using World Streamer asset for loading/unloading chunks of open world
hmm
We are not using those
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
Is it way to find out other reserved memory?
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
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?
Yes, no quick fix unfortunately
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
I will definetly try it. Thank you very much for your help
About this memory fragment, I come up a thought. I've heard that C# GC provided by .NetFramework will release unused obj and compress the rest memory to remove those fragment. So in Unity it doesn't work this way based on what u r saying, I guess this is because Unity uses Mono or IL2CPP? Is that right?
@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.
@trail cedar For this, I guess all kinds of plugins and built-in packages can contribute.
I don't have much of this kind of stuff, but the World Streamer asset definitely takes a significant chunk of it.
Not 100% sure what that could be
Not necessarily, the actual C# garbage collector is a well oiled machine with a ton of complex parts. Sometimes it does compact, most of the time it doesn't.
Unity on the other hand does not use the same garbage collector, they use this gc https://www.hboehm.info/gc/
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
Anyone here happen to know if unity meshes use shared vertices or not?
Across one mesh or multiple?
One mesh
Yeah they can share verts
aight, thanks!
Pretty sure it is expected to have that much memory untracked.
Here is a snapshot of the memory distribution of our game
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:
what really differentiates performance is not language or engine, its the concepts and algorithms and how they are utilized
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
Does anyone have experience with OpenFracture?
It just does not fracture my custom meshes no matter what
What have I done wrong..?
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.
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?
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?
before the installers work?
By installers do you mean before the injection occurs?
Yep
I want the injection to depend on something I pass
Have you tried creating the object from a method?
Without Zenject it won't do
Container.Bind<Foo>().FromMethod(GetFoo);
Without injection I mean
I meant like so.
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
Any reason a factory would not be suitable for this?
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
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
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 :/
- Namespaces are not relevant to assembly definitions at all. Only Assemblies matter
- those errors have nothign to do with assemblies
honestly they seem like they should be warnings, not sure why they're errors
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
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
when someone says "compute shaders are faster than multithreading" is the reason just because gpus have more cores than a cpu?
I would say that whoever said "compute shaders are faster than multithreading" is confused because compute shaders are an example of multithreading.
multi threading on gpu faster than MT on cpu, no?
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
you know what I mean
@sly grove is helping people on unity your job? your always here
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
still waiting for my paycheck
lmao
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
Is there any way to check how big (size in bytes) a compute buffer is?
transfrom it into a gpu instanced objects, so no gameobjects
You'll want logic to stop accessing individually and lower the resolution when you zoom out prolly
Combine like radius of 5 hexes into one big hex at a certain zoom, then do it again at even farther zoom
I want each hex to be modifiable
mmmm, okay
How can they modify something they can't even click on at a large enough zoom out?
O, I see what you mean
Your hexes look less than 1 pixel big on your bottom pic
thats just so I can render all of them to test true fps
lets not worry about that
Oh well, depends on your actual goal then. I'd start by testing rendering at an appropriate zoom
so as long as all the hexes are on the camera, it will render all of them
with same fps
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
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
you'll probably need to load/decompress it to pixel data manually, then do the downscaling, then load it into the texture2d
even that is too slow
only 120 fps at 1.9m vertices
something like bilinear sampling is pretty simple to implement, loading it into a texture and manipulating the pixels should be ok, it's basically just in an array until you call Apply after all
oops, that was meant to be a reply to @torpid smelt
Annoying, but thanks. I'll look into it at a later date 👍
That is pretty slow. Are you generating that mesh every frame perchance? That would slow things down significantly
nope generated once,
It's explained on the page, if you scroll down a bit.
why is it a list tho?
presumably one for each instance?
your shader would need to take the instance id into account in order to position the meshes
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
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
thats the only mention of shader
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?
bfs and dfs are methods to search through a graph, which you can use to list out all connected pipes. The only difference is the order in which they search through
And it wouldn't be more efficient to just check the neighbours of the pipe I want to find links for? Not the entire thing
well i dont really know what you're checking for tbh, or how these things are even linked. Its not like dfs/bfs is some super unoptimized algorithm, its quite literally just different methods of going through a graph.
It sounds like you want BFS though since that will get everything directly related to the current pipe, then search out more from each neighbour if it didnt find anything
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
Ah ty maybe I need to just do a bit of reading
ty yeah this is exactly what I was describing lol. Got totally lost. Now to implement!
I'm still a little stuck on how to feed in my data. All the examples already have all the nodes that are connected in a list. My system is the initial node which has the coordinates of its neighbours. Where would I make changes to get it to work?
does it only have the coordinates of its neighbour? or do you have a reference to the actual object
I just reference the direction of all of the pipe's connections
Such as up, down, left, right
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
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
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
alr ty
https://dotnetfiddle.net/ktEoj5
just wrote a quick example if you wanted to see. i just hardcoded some connections so the connections itself fully doesnt make sense but you can see how it works.
thanks!
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 :
why is object involved here?
use the generic Queue<T> not the non-generic one that stores things as object
Ah I see it now, I thought it was from ComponentDictionary or something I couldn't see
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 }
Probably the wrong place Queue<T> queue = new Queue<T>();
why are you in the advanced channel if you don't know how to use a generic class
Why are you sending screenshots of your console, is your IDE not configured?
No
No, as in not configured?
Because the original topic was advanced and I'm following on
So where did I go wrong?
C# Queue and configure your IDE if it's not configured
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
xml is awful
lmao
why not JSON?
the syntax feels so cursed to me but im just unfamiliar with it
but it might be better
it's much simpler, and also faster to parse
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
why write a custom parser?
also why would CSV be good for a filesystem?
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
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
what does the file format of this save data have to do with decompilation?
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?
there's no right way of doing it. It depends on the particulars of your game
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
An archive file format like tar or zip would be more suitable for storing a representation of a file system.
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.
How granular do you need? Recreating a fake Linux enviro? What sorta commands/files need support?
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.
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'
}
}
}
}
}
Nevermind ChatGPT rules xD
thanks 😉
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
CAn't you just change the file name?
It shows the path at the bottom iirc but yeah it's annoying
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
Ah 😬
You can write a custom property drawer that displays a popup where you can name them?
yeah but I'm trying to figure out how to name them
Or a custom editor that automatically assigns the meta data as I'm assuming there's a main character file you're also selected?
Ah sorry I thought you just wanted the names to show up differently in that object selection window, not to rename them.
wait
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"
but I don't see how a custom property drawer would help me. I'm just trying to figure out how I can set my own names for the objects in code
I guess theoretically you can write a project view extension that loads the file and draws the new filename on top
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
I'll check that out
Is the linked object going to be shown in the inspector apart from the object property field?
Definitely a hacky way though
only here
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.
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
I have access to the scripted importer just fine, but I'm not sure how to set that proper name
This would just help for the inspector appearance though right?
I guess along with Navi's solution it would work
if you can modify the importer i think you can just set the name property on the subassets as it adds them
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
I'm guessing this is what you mean? I think it will just always use the file name for the main object:
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..?
hmm are the characters imported as subassets or main assets? i assumed they were subassets if they come from one source file
subassets, they come from lots of different files in the same folder
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
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
[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
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
Yeah I thought so, do you think making it abstract helps making it a good modular system? I am not familiar with abstract. It can change at runtime, the abilities container
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
Ok thanks I will look into it 🙂 
You either use SubAsset or SerializeReference.
https://docs.unity3d.com/ScriptReference/AssetDatabase.AddObjectToAsset.html
with SerializeReference the list is shown but I cannot add the interface object to the list.
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.
FWIW if you use odin inspector (i couldn't live without it lol) you get much better support for serialized ref fields
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Not an answer to your question, but there's this repository if you're interested: https://github.com/SebLague/Marching-Cubes and they also did it in a compute shader: https://github.com/SebLague/Marching-Cubes/blob/master/Assets/Scripts/Compute/MarchingCubes.compute
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 : )
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?
Decals?
Aight got it
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?
how are you creating rooms?
basically it sounds like you need to do some procedural mesh creation
i place down wall prefabs
the blue gizmo is the start point, red is the end.
the green is where the prefab is spawned
this is probably not a very efficient way to make a room...
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?
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
so when a complete room is detected you want a roof to automatically be created?
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
how would you do flood fill of the room area?
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
how would you know that?
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
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
that makes a lot of sense 👀
i wanna a tutorial of how to mute in this server
check boxes where appropriate
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.
Not an advanced code topic but you can follow the instructions in #854851968446365696 for configuring your !ide
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?
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,
}
If you can't change it then either you're using a custom editor that's not correctly dirtying changes, or you're resetting them
I can see it in the inspector for the script
can you show how you defined the field for this?
public class PrefabManager : MonoBehaviour
{
public string BuildingName;
public GameObject BuildingPrefab;
public GameObject BuildingHolographicPrefab;
public BuildingNeighbours BuildingNeighbours;
public int Health = 100;
}
https://forum.unity.com/threads/byte-enum-inspector-issues.1078073/
Found this, since there’s only 5 options you can change it to sbyte and it should work fine
Well step in the right direciton
Oh yeah there are several versions of Unity where byte flags were just busted, I forgot because I'm on a release where it's fixed
was very annoying to make settings pages that just didn't work for no reason
Is it possible you're using code that's not supported on android or something? com.xxx.xxx is the standard naming convention for packages in java.
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
You have to define your own delegate
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?
@austere jewel I have it like this now, Im hoping that this small change should further improve performance for very low effort, it feels good having it be in variables from top to bottom now
https://gist.github.com/SteffenBlake/ace74a893d0b16c30a7eb2a42d6d9230#file-propertywatcherbase-cs-L177-L192
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
it'd only matter with readonly structs. If you do it with reference types it's doing nothing, and if your struct isn't marked as readonly it does a defensive copy anyway and you incur that cost
most of my structs are marked as readonly yup
is there a readonly version of int, string, etc?
Primitive numeric types are immutable. String is also immutable and reference type so no point of using in.
I'm supporting generic types so any struct
Just updated C# extension in VS Code, what is this?
It literally tells you?
no, it wasn't there before updating so why does it show now
So what does it mean?
What are you not understanding?
how can I not be using it when its working in game?
Where do you call it?
this even shows in the update method
and the start
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.
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
Are you using OmniSharp, or the new C# Dev Kit?
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
Show your coroutine code.
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;
}
}
}
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
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?
Ok, I solved, the problem i was facing inside OnDestroy were 2 differents:
- when the job was in progress. I couldn't dispose the array used by the job
- 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();
}
}
Complete blocks the thread though, might want to rethink the approach if the job takes long.
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?
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?
Do you have pause in background enabled?
In the project settings, we have "Run In Background" enabled, because we handle the suspended state manually for different platforms.
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.
Thank you 🙏
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?
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
The thing is that I never opened the overlay, but it still pauses 🤔
You'll probably start getting focus events if you disable it
Please don't post your question into multiple channels at once. Also post !code correctly, not everyone can see these embeds
📃 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.
beside that, this is more beginner code
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
what kind of code is not supported on android? i check the unity docs and could only find "openGL" and other things i don't use
Im not sure, it was a guess. If that’s your only error no idea
no, i have a few others lol
You should post everything
> 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
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
First suggestion is to update unity. What unity version are you using?
Second, do you have any lambda-style code? Reduce that if updating doesn’t work.
Before updating i suggest you use some sort of version control software so you can revert if anything goes wrong.
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
Try .AsSpan()?
And iterate over a span collection
Also don’t convert idata to an array in the loop
never heard of this, what is it soldier
convert allData an array of arrays, then a span generated from allData.AsSpan().
It’s in namespace System, I don’t fully understand it, but it’s the fastest loop in C# according to user benchmarks from stackoverflow.
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.
as so?
no, ill provide an example.
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'll leave this here for you @sleek terrace as I have to go:
https://learn.microsoft.com/en-us/dotnet/api/system.span-1?view=net-7.0
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.
Thank you very much!
also, span is a ref struct so you can't have it as an instance field, you have to construct it in the method.
just noticed lol
15 - 20+ fps
yeah those are just checking for input
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
right now i only have 2 weapons but if i add another weapon that is a pistol(secondary weapon) it will drop that aswell
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
yeah i can hold 3 slots and the 3rd one is used for knife which cant be dropped
are you checking if ur inventory has space for an additional weapon before dropping?
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
you should benchmark it in a build btw, editor can be slower.
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.
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
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
step through it with a debugger or add a lot more logging
Too far
Why'd you ping me to add zero context?
What I guess you’re a discord mod so makes sense
Video game developer | 80's inspired slasher horror | Follow my tumblr for daily screams!
ITCH.IO | PATREON | MERCH | OFFICIAL SITE
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
Google "unity carousel"
its that easy?
apparently not
I mean, that really covers pretty much all of it
I know it does
the thing is that im too stupid to understand this part
everything else is something I understand
Then why are you asking in #archived-code-advanced
Whats the formula for the circumference of a circle?
3.14?
thats uh, thats just a number mate
im a little slow
I mean thats pi which is indeed part of the formula
I mean its straightforward though, how many degrees are in a full circle?
multiple the radius by 2 to get the diameter, multiple by pi, thats circumference
i see
Like if you have 6 items in the circle equally spaced out, how many degrees are between each one?
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.
uhh 60
also i do a lot of research before coming here, i dont mean to bother anyone whos really good at this stuff as i find getting help embarassing - i do really like to learn on my own
however i thought this code was advanced
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.
this is always an option:
https://assetstore.unity.com/packages/tools/game-toolkits/rayfire-for-unity-148690
I unfortunately am completely broke for I am still a child
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...
You can manually break a mesh in multiple part in Blender. This is the cheapest way of doing that.
I'd rather not have to do that with everything I create, plus it wouldn't work if a bullet is shot into different places on the glass
well, okay it would work, but it would look awful
Then your only option is to break the mesh following a fracture pattern.
indeed, but my question is how to do that
surely I don't have to learn a new coding language and write a shader right
With the Mesh API
Yes, otherwise performance are going to be atroce.
which is yes for?
write shader or no write shader
You gonna need to use a computer shader
Here something I have done in 6-8 hours trying to learn that.
https://pastecode.io/s/ep5x8s6z
It splits a mesh in two
do you guys know how to fix jitter on wheeljoint2d when on high speed?
thats a computer shader?
Also in this video I, from 0:30 to 0:40 seems to make it at least look very simple, and also if your code only splits it into 2 then how would I be able to accomplish anything like that
^
also 1:00 to 1:15 seems to explain how it was done, but I dont exactly get how to reproduce it
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.
I mean, I dont think they used a computer shader, but it seems to run really smoothly
Either way, it is always better to have a version that runs on the CPU for development. In other words, you should start with a CPU version.
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.
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
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
I am not a helper, since I am fairly new to Unity, but maybe it is because the bullet hasn't got the collider on convex? Also, fast small colliders might clip through walls to some extent, mostly when the wall is a plane