#archived-code-advanced
1 messages · Page 115 of 1
How would ik if something is "advanced"
if you don't know, then it probably isn't
if you don't know then it almost certainly isn't
Ok ill just ask in #archived-code-general
Does it matter what the file type is in terms of reading and writing?
I presume you mean the file extension. Then no
files are just files. the ".exe" ".txt" ".whatever" means nothing other then an indicator of how the data is formated, and how it should be used.
If you open the file just like you would any file and read the bytes of it. You wil get bytes, just like a .txt or a .png, or a .word.
You then need to take those bytes and convert it to usable data. You do that based on the files encoding, thats what the .parqet file type is hinting at. Its saying hey this is how im encoded. Use a parqet decoder to decode me.
If you dont have one, you need to write one
You can write parqet data in a .txt file, nothing changes its just bytes
See above
I aren't sure that this is correct channel to ask.
But here is my question.
I'm trying to use the Blackboards that are at the Behavior package, looking at code it is severy limited and can only be used by the behavior trees.
Looking at the package almost every class is marked as internal or partial.
Is there a proper way to reference a blackboard and get a runtime reference without adding a behavior tree?
Hey all, I'm trying to find clean ways to handle my sprinting animations in Unity 3D with cinemachine. Without any code input the character model goes in the way of the camera. I've made a code adjustment like so:
private void Sprint()
{
_animator.SetBool("Sprinting", true);
speed = sprintSpeed;
transposer.m_FollowOffset.z = 1.25f;
}
private void StopSprint()
{
_animator.SetBool("Sprinting", false);
speed = walkSpeed;
transposer.m_FollowOffset.z = 0.5f;
}
As you can imagine this is quite bad and looks terrible haha
Any assistance would be appreciated :))
is there a way to hide this freaking log without adding an audio listener
i see threads complaining about it since 2015 with no option to disable it
are there benefits to calculating manhattan distance over regular distance with pathfinding?
Not sure what you mean by regular distance but manhattan distance is obviously very fast to calculate
regular distance as in Vector3.Distance
Requires a square root which is slow compared to manhattan distance
chebyshev distance can be a good option too
Is there a way to see the dependency graph between my scripts?
Get rid of damping.
But also using a full character model for first person is probably not a great idea
Yeah I ended up figuring the dampening part out, and why wouldn't you recommend full character model?
Because sometimes you can see it like that 😂
It's also wasteful to draw stuff you can never see
I have another question, primarily around my private GraphicsFormat hdr; outputting this error:
The type or namespace name 'GraphicsFormat' could not be found (are you missing a using directive or an assembly reference?
I trued using Unity.Experimental.Rendering; but that only broke things worse.
What exactly broke after you added the using?
im planning to later turn it into a multiplayer game
Local multiplayer?
idk yet haven't look into it much, don't know how hard it would be to make p2p
😦
But for an online multiplayer game there is no reason to use the same character model for the local player itself as what other player's see.
It's also not somethi8ng you add later
to make a multiplayer game you need to make it multiplayer from the start
or you will have to rebuild everything later basically from scratch
fair enough thanks for the warning ill look into it
checkout netick2, thats what i use and depending on the use case you have its a great free alternative
in the hopes of being able to use this channel one day 🙏
Twin…
WHERE HAVE YOU BEEN?
Has anyone had issues where Rider attached to Unity with a conditional breakpoint just hangs Unity - or seems to. If I detach Rider, then Unity continues.
I feels like it hits it, but a) Unity doesn't pause and b) Rider doesn't trigger any state output. So, the Threads & Variables tab is empty, no stacktrace, no state or local information. It looks like it hasn't hit the breakpoint other than the fact Unity stops responding. 
I tried converting it to a Pause Point which also doesn't pause Unity, but it still stops responding.
Would the fact it's not running on the main thread be an issue with conditional breakpoints specifically? Regular ones are triggering fine.
The same happens with Visual Studio. Sometimes you gotta be patient, other times it is just stuck.
Whenever it happens and I can't get it to work, I usually use if(...), logs or Debug.Break().
Ah thanks, so it's not just me being special and/or unlucky.
I might wing a report to JetBrains just in csae they are not aware of it. As it's handy not to need to add if(...) but it's a good workaround. Thank you! 🚀
is there a way to make this the default visual studio tracepoint behaviour? meaning I want the breakpoints i set to call Debug.Break(), as then i can see the editor window execution also
I do not believe you can without doing anything. You can however pause on exception.
Also, you can just write Debug.Break(); instead of using a break point if that it is what you want.
if i use Debug.Break i have to recompile, i was looking for a quicker way, guess ill stick with mine then, thanks!
also keep in mind that Debug.Break is not quite the same as a breakpoint, it will not pause the editor at that specific line, it will pause after the current frame has finished
oh, i had forgotten about this, then yeah its not great use this way
Not sure why you post this here, but you seem to have forgotten about the while loop
i just posted it as a joke
no way would i keep that unholy line of code in my project
dont cross post, not a code question so remove from code channels and repost in #archived-networking
I have parquet file reading working in my project now via this library https://aloneguid.github.io/parquet-dotnet/starter-topic.html, but now (I assume) I need to partition the data by XY coordinate into smaller files of somewhere around 250-1000 datapoints each. There's about 700k datapoints total, so that's a hell of a lot of partitions.
For those unaware of the context, each of these datapoints are gonna be individual unique gameobjects that are loaded in by chunk so that the game can be performant enough to run on a Quest 3.
What I'm trying to figure out is how that partitioning is gonna work semantically. From what I can tell, the best strategy would be to make each partition an individual Json file, then just call those Json files by chunk index. Is that right, or should these partitions also be Parquet files or something else?
I think it was mentioned before that just straight binary should be used and that I should write my own schema for it
Considering how long just the file reading took to figure out, I'm not sure how feasible that is
how much data is each datapoint?
not much, the entire parquet file is just 75MB
still, how much is it in memory, uncompressed, raw data?
I'm not sure how to tell, admittedly
in any case, if its just around 100MB, just keep the whole thing in memory, no need to stream or partition it
It wouldn't cause any issues going through the entire dataset every time a terrain chunk is loaded in?
not sure what that means
you can still structure the data, you can put it into a spatial lookup and whatnot
also you arent loading gameobjects, you are likely configuring existing (pooled) instances with the data.
you might not even need gameobjects, depending on what the data actually is and what you do with it
Basically, each datapoint is gonna be represented with a plant that you can walk up and interact with inidividually
when you do, you can view the data specific to that plant
and each plant's position is pre-determined by the coordinate assigned to it in the dataset
ok, but there are ways to do this without putting a collider on 100k gameobjects
right, that's what I've been trying to figure out lol
in any case, this sounds like you need to only have maybe 1000 interactive objects at a time, the rest can be "background"?
i think this is actually a pretty neat usecase for Entities
I assume as an LOD kinda thing
maybe just particles or instanced-indirect rending of impostors... many options
how many unique visuals does the project need for the plants?
as many as possible at any given point
Oh, just one
the only difference between plants will be their datapoint ID and their rotation probably
alright, so what you need is not streaming, just LOD and culling
pretty basic stuff
doesn't look like you would have any memory issues that would require streaming
700k instances of the same object render pretty fast with instanced indirect... if you can cull down to 70k at any one time, you can easily do this on a Quest 3
how would that work with getting the ID of each plant?
you just "guess" by associating your pointer/viewport and world location with the data
basically you raycast into your custom data
that sounds insanely inefficient compared to what I've been told about this by the others I've talked with here lol
you can ofc also use a physics engine to do it... but that might cause memory issues, you would have to test that
why would that be inefficient?
From what I can tell, what you're saying is to scan through the entire dataset every single time I load in a terrain chunk, as well as every time a plant is selected, without any form of data chunking
i'm not suggesting anything like that
#1 there are no chunks that are loaded, everything is initialized once into a spatial lookup datastructure, a BVH or KD tree or whatever.
I was told by someone here at some point that trees are only beneficial when writing data to a datapoint
#2 to select a plant you just have to convert your view position into an index into that datastructure, which is an log N operation eliminating almost all the data that is not in your view's proximity form consideration
that makes no sense
spatial lookup is for lookup what you do with the datapoint is irrelevant to that datastructure
maybe reread what he said, it does not contradict what im saying here
I guess I'm confused on what you're saying, then
a grid is just one datastructure you can choose
the point i and burrito are making is that you can calculate the index of the data you need
there is no search required
wait so why are we talking about trees, then?
you started with trees
i just said "spatial lookup" and gave examples
a grid is also a spatial lookup
but one where you have to search in buckets, a BVH/KDTree just optimize that search
convert world position in unity to the coordinate in your dataset -> there is your plant
Is it a search? I thought it was just calling by index
a grid cell is a bucket holding a "list" of all plants inside that cell
you need to search that cell/bucket for the actual plant by comparing all plant's positions in that cell with your "pointer"
what's preventing us from having the ID directly assigned to the plant that way it doesn't have to search anything?
in a "tree" that search is optimized to typically O(log N), where the grid would be O(N) with N = cell capacity
then you cannot separate the representation of the plant from the lookup
and you need to add extra data to all instances that is entirely redundant
ah, so you're saying that doing all of these searches would be more performant than what would be required to do direct lookups
heurstically it is likely, depends on your actual implementation
if you make gameobjects for your instances, you can associate the ID, GOs are very inefficient and an extra integer wont change much
but if you decide to do some instanced indirect rendering, there is no association anymore (between rendered pixels and plant IDs) that you could query
What are the limitations of doing it like that in terms of visuals?
like would I still be able to have wind effects, for example?
wind is just a shader effect
limitations generally depend on the specific implementation you choose
visually you are bounded only by your ability to implement the visual features you want.
Fair enough, that's good to hear
So, when you say that I should just have all of the data stored in memory but that I should still be chunking it, what exactly would that implementation look like?
i cant tell you that since i don't know enough about the specific of the project
I just mean like generally
Are you saying that all of the data should be accessed as just variables in runtime?
idk really what you are asking, you get a datastructure that suits your data and put it into that datastructure.
that datastructure would probably have an index which allows you to efficiently ask "what plants are at grid cell x,y" or "which are within 5 meters of x,y"
you might have to build that structure yourself of find one in some library
you would also have to test if your data is really just 75 MB and how much overhead that datastructure has.
I guess I'm confused on what the "datastructure" is in a literal sense
Are you saying it's just something like an array or list or dataframe?
for rendering you would query "give me the plants with viewdistance of cameraPos" and put that into a hash-set, then render those instances, when your position/view changes, query a new set and modify the difference
In computer science, a data structure is a data organization and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data, i.e., it is an algebraic structure about data.
this is probably the most visually intimidating way of saying that it's actually the most straightforward method of programming lol
the "go-to" data structures for spatial lookup in games are Grid, Quad-/Oct-Tree, BVH and KD-Tree https://en.wikipedia.org/wiki/Bounding_volume_hierarchy
https://en.wikipedia.org/wiki/K-d_tree
https://en.wikipedia.org/wiki/Quadtree
A bounding volume hierarchy (BVH) is a tree structure on a set of geometric objects. All geometric objects, which form the leaf nodes of the tree, are wrapped in bounding volumes. These nodes are then grouped as small sets and enclosed within larger bounding volumes. These, in turn, are also grouped and enclosed within other larger bounding volu...
In computer science, a k-d tree (short for k-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. K-dimensional is that which concerns exactly k orthogonal axes or a space of any number of dimensions. k-d trees are a useful data structure for several applications, such as:
Searches involving a...
A quadtree is a tree data structure in which each internal node has exactly four children. Quadtrees are the two-dimensional analog of octrees and are most often used to partition a two-dimensional space by recursively subdividing it into four quadrants or regions. The data associated with a leaf cell varies by application, but the leaf cell rep...
alright now I'm confused again lmao. I thought we weren't doing trees?
you can't avoid the tree
your grid is also a tree, just a very flat one
any search algorithm that isn't naive will implicitly construct/traverse a tree
its also called "divide and conquer"
Earlier when you were saying that doing searches would be more performant that what would be necessary for doing lookups, did you mean that in the context of using trees?
I mean, the more advanced ones
lookups require a hash-function by which the entries can be indexed and identified uniquely, a search is just a search, for it to be efficient, the data needs to be ordered by some property (x,y coordinates for example)
the "advanced" datastructures organize the data in a way that search and lookup are as efficient as possible.
each of these datastructures is optimized for a specific use-case, spatial structures are typically optimized for lookup (nearest neighbour search) which comes at a significant cost of constructing or modifying the structure.
in a sense the construction of the structure pre-computes a bunch of properties required for efficient lookup.
If that's what you're saying I should do, that might complicate how the actual data viewing for each plant is gonna work
Basically each plant contains a string that's a sentence from a certain document, as well as two integers to represent the index of that string in the document and an arbitrary number assigned to the document itself
at the end of the day you need to pick an approach that you can understand and develop/manage yourself, so if any of the above feels like too much, you surely can find other ways to get to achieve your goals.
when you go up the plant, one of the things you're supposed to be able to do is view all of those strings in order
the datastructure doesn't care what you put into it, its just an index
you can reference any data you like with it
considering that I need a working prototype of this game by the end of the month and it took me like 3 days to figure out how to get file reading working on android, what's the simplest one you think I would be able to get away with?
i don't know what you are capable of, i would however stay away from anything that involved DIY'in rendering or learning Entities if you aren't familiar yet
Cuz idk if I have time to learn how to implement a kd tree
you don't implement datastructures you use one from a library, written by someone with a lot of time and big brains
you can never optimize those things sufficiently in a project with limited time
idk how much of that optimization is necessary in your project just to get it working
that depends on your actual data
maybe find a relatively simple structure on github, see if it works and if not see what doesnt work, then find another solution for that specific problem
Gotcha, I'll see what I can find then
The rendering was another thing I was gonna ask about actually. If they're not gonna be put in the scene as individual gameobjects, what would they be?
Entities or nothing
nothing as in, they are just a list of positions/rotations that gets pushed to the GPU
So it'd just be a shader thing?
but beware of that, you won't get far within a few days with that
you can try rendering them via VFX graph too
(With some exceptions like grid, which can be trivially implemented as Dictionary<Vec2, HashSet<T>>)
with terrible data locality 😉
That's fair, but the biggest gain really is just from cutting down O(n).
You can also wrap the naive implementation and expose only a public contract, then later swap it out to a more CPU cache friendly implementation.
Something like this sounds the most realistic given my situation tbh. This can be improved later, I just need to get it into a state presentable enough for a demo
also, took me a hot minute to parse what that sentence meant lmao
Tbf, it's not any harder to just plug in an existing library that implements quad tree or whatever.
I'm specifically pointing out grid because it's amongst the options the easiest to implement, and the major drawbacks of it doesn't really apply to your case, because your data is static and known at build time.
I'm going crazy, I can't figure out what's going on here.
meshData.SetVertexBufferParams(vertexCount,
new VertexAttributeDescriptor()
)```
Why does this method print ``ArgumentException: Invalid vertex attribute dimension value (0, should be [1,4])``?
I've used the new mesh api before, without issue. But now no matter how many, or what types I define as descriptors, it prints the same error.
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.
Debug vertexCount. Is it 0?
Could it be a bug in Unity 6000.23f?
No, vertexCount is:
int GetVertexCount(int2 dimensions)
{
return dimensions.x * dimensions.y * 64 * 6;
}```
If you're correct and one of my dimensions is 0, I'm going to die
No, it's 393216
Which means I'm gonna change my indices to Uint32 real quick 😄
Ok,then you probably need to initialize the VertexAttributeDescriptor properly
All of the parameters are implicit, and are set to what I want
It worked, thank you
But surely this is a bug, right?
Shouldn't setting the parameters here be exactly equivalent to not setting them?
It's a struct. Without any arguments, it probably uses empty constructor.🤔
Ah, you're probably right
I've never encountered a struct with all optional parameters before
Thank you, now I can work on the new errors that were printed 😄
Why the heq isnt the AudioStuff AudioSource playing, i literally cant seem to find the reason and everything in the code seems to work completely fine other than AudioStuff playing. Is it a code failure or something in the game?
https://hatebin.com/sdcneinckq
Not an advanced issue. You're also calling Play on it every frame after the condition is met. This restarts the audio every frame
Oh whoops, i actually do.. Kinda embarassing i didn't figure that out but thank you!
Shoot, didn't mean to post this on advanced 
I'm using Camera.ScreenpointToRay() in some of my code, but it spams errors if the game window isn't in focus (screen position out of view frustum). Is there an equivalent "TryScreenPointToRay" or some other process to check..?
(Input.mousePosition is the parameter i'm using - but I don't see documentation there [yet] for how to detect if it's offscreen)
Vector3 mousePos = Input.mousePosition;
if (mousePos.x < 0 || mousePos.x > Screen.width || mousePos.y < 0 || mousePos.y > Screen.height)
{
v($"Mouse offscreen: Mouse:{mousePos}, Screen:({Screen.width}, {Screen.height})");
return targetHp;
}
Ray ray = Camera.main.ScreenPointToRay(mousePos);
(this guard clause didn't help)
you could use this for your guard clause https://docs.unity3d.com/ScriptReference/Application-isFocused.html
lemme try - i'm not sure that helps though still if the app is focused but the mouse isn't in the window
I can't seem to figure out why sometimes input.mouseposition returns "infinity, infinity" and other times "nan, nan"
Yeah I can't even repro the issue now.. I'm getting "legal" values (either out of the screen x/y or +/- infinity)
probably dividing by zero
x/0 for x≷0 would be ±infinity, while 0/0 would be nan
the guard clause should catch that..?
My google-fu says that it's unrelated to my code - that potentially there's something going on with cinemachine and the camera at startup - setting the clip plane to 0.0
but I can't try/catch my way out of it unfortunately - it's hard coded in the unity implementation to log.error .. which is potentially problematic for a web game
the result is probably coming from a division by zero; not necessarily dividing by an accessible variable that's zero
fwiw you probably shouldn't say inf is "valid" here; valid values should be finite, not "not nan"
well.. sorta? if the mouse is offscreen to the left or up, Input.mousePosition is https://docs.unity3d.com/ScriptReference/Vector3-negativeInfinity.html - which is "legal" and I can check for
NaN in those error messages isn't something I can check for
you can though?
there's methods for checking for nan specifically
nan will always compare false to everything, so it won't match that guard clause
I mean - I don't have access to anything I can check..? Like, something internal to Camera.main.ScreenPointToRay() is breaking
like - here's the full code - the screenpointtoray call shouldn't even be called if there's a bad mouse position - and yet, somehow it is (but I can't repro it 100% of the time)
im confused now, is Input.mousePosition the thing logged with screen pos or not?
if mousePos.x or mousePos.y are nan, that wouldn't get picked up by your check
my guard clause really should... catch everything, so I'm confused why it's not
because you aren't checking for nan
What design pattern would I use to detect conditions being met in interactions between game objects? I'm thinking of creating tutorial levels for my game, where I introduce mechanics (ex: SF level introducing parrying https://youtu.be/fIobSwzNp4c?si=vOyMLE20yJpKZr8a), but I definitely don't want the counter logic for the events to be handled by the hitbox being parried, nor the character parrying the hitbox.
true.. but.. I don't understand that situation? the docs don't say when that could happen, if at all
well, have you tried just logging out mousePos to see if that's the case or if it's really internal?
yeah - but I can't repro it consistently to catch it
The pos to check against would be Vector3(negativeInf, negativeInf, 0)
not vector3.negativeInf
I would think
In you're screenshot you can see it's only a Vector2
and Input.mousePosition explicitly says z is always 0
yeah but shouldn't the check for .x < 0 specifically catch that?
yeah why not just cast that to Vector2 and use Vector2.positiveInfinity
uhhh... yes
(I assume negative infinity < 0)
It won't work for NaN as they said though so that would be the only other possibility
Basically any comparison with NaN is false
so are you seeing mousePos as having nan at all? im confused
it says NaN here right?
I don't log the "nan" message in the OP screenshot above - that's something that ScreenPointToRay() is doing internally.. unfortunately I can't repro a situation where I can both log a position AND see the issues
oh god, schrodinger's error...
unfortunately that's also confounding this one - I am not sure exactly what is causing it.. some combination of starting the game (in editor) and tabbing out?
I think this can also happen if the camera in question is disabled
I know, it's aggravating the hell out of me
I am doing some camera stuff with cinemachine... I'm wondering if there's some sort of interactionthere that's going on
is there a stack trace for this code?
I don't know the details of what Camera.main is
It points to line 109 - the "boom here" line above
lemme try harder to repro.. standby a min
regardless of being able to log nan vectors, have you tried just checking for it anyways?
I will - PB brought up an interesting point that I'm in 2d with the mouse pos and checking against the vector3.infinity statics
but i'll check for .x and .y = nan
oh
you can use Equals, apparently
or you can check that it's not equal to itself, only nan has that behavior
oh and there's also an IsNaN method specifically
would recommend float.IsNan yes
it was at the bottom of the article lmao
Just as the most readable option
sigh.. I can't even repro this anymore
though you could also use IsFinite, which checks for both ±inf and nan
well I've stopped/restarted the game a few dozen times, trying to tab out, select the scene view (instead of the game view) and all the things that I thought caused the issue before and I can't seem to repro it.. The worst kind of issue. 😐
(I reverted the code too)
I like "story bits" for ad hoc stuff like this - just a hashset of enums for things the user's done.
public enum StoryBitTypes
{
HasParriedOnce,
HasLoggedIn,
}
public class Player
{
public HashSet<StoryBitTypes> StoryBits;
}
... collision code ...
if (!player.StoryBits.Contains(HasParriedOnce))
{
// pause game, show parry info
...
// "complete" the first time user experience for the player
player.StoryBits.Add(HasParriedOnce);
}
It's not really a design pattern per se, but.. I've used it lots for random ad-hoc stuff that you inevitably need to sprinkle through your game for one-off stuff like this, especially with FTUE
hi, im trying to make a lobby broser with facepunch.steamworks, i have this function that creates a lobby with Gameid unique to the game name set with SetData:
{
Debug.Log("host");
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnectedCallback;
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback;
NetworkManager.Singleton.OnServerStarted += OnServerStarted;
NetworkManager.Singleton.StartHost();
CurrentLobby = await SteamMatchmaking.CreateLobbyAsync((int)maxMembers);
CurrentLobby.Value.SetData("game_id", "TOFLOATBOAT");
CurrentLobby.Value.SetJoinable(true);
CurrentLobby.Value.SetPublic();
} ```
then i have this next function that searches for that lobby using the same gameid:
``` public async Task<bool> RefreshLobbies(int maxResults = 5)
{
try
{
Lobbies.Clear();
var findLobbiesQuery = new LobbyQuery();
findLobbiesQuery.WithMaxResults(maxResults);
findLobbiesQuery.WithKeyValue("game_id", "TOFLOATBOAT");
var lobbies = await Task.Run(() => findLobbiesQuery.RequestAsync());
if (lobbies != null)
{
for (int i = 0; i < lobbies.Length; i++)
Lobbies.Add(lobbies[i]);
}
return true;
}
catch (System.Exception ex)
{
Debug.Log("Error fetching lobbies", this);
Debug.LogException(ex, this);
return false;
}
} ```
My steam app ID is set to 480, so when I remove the specific game ID filter in the refresh lobbies function I can see other developers lobbies, but when I do it with the game ID filter I can’t find anything even when hosting the same game on another computer, is this because I need to get my own steam app ID first?
Any help is appreciated!
is there any way to get the resolution of all screens together in unity? (using wallpaper engine for the reference here)
i've found that system.windows.forms has screen.allscreens. i cant seem to import it into unity though
update: kind of figured it out
not exactly what i was going for above but i figured out that you can have a game window open on each monitor by doing display.activate (on each display)
not sure why but a lot of results online just say that its not possible. its working fine for me though
another update: i've been searching around for an hourish and now i've got a new issue
there seems to be a variable for the main window position but i dont think that's going to interact correctly with multiple windows
Just replying to the top level post for simplicity...
This reminds me of the weird untraceable errors I got when trying to use the old 'mirror plane reflection' code for rendering a reflection around a xz plane. It happened infrequently, possibly at specific angles to the plane ( but that might have been my own assumption) that I could never get to the bottom of, regardless of the amount of logging in place. Though I also suspected that adding logging itself made it harder to trigger the issue.
Thinking about it now, maybe adding a recording system would have helped, where by you constantly record all potential values of the properties, scene objects etc at various points within a frame/code, straight to a file. Then you simply run/play the project until the error generates at which point you could look back through the records in the file and hopefully find the culpret, or at least run the last known values through the code and see if that also triggers the error and then find a way to guard against it.
My gut feeling is that the error was introduced a step before the actual error report, that some maths was generating a bad value, or a value that when used by say ScreenpointToRay would produce a bad value.
Alternatively that there was some unrelated issue (to the code) within the editor that for some reason would invalidate the values used in that function. Which again thinking about it, i'm not sure I ever saw the error in builds, so that might be true.
Again having a recorder in the scene, at least for debugging/QA would help answer that question, but inevitably the times when this was a problem I never had the luxury of time to run extensive QA tests.
Still setting up a custom post-processing shader, for a toon shader, but I've run into an issue. Chiefly, this error:
Assets\Scripts\CustomPostProcessPass.cs(22,10): error CS0246: The type or namespace name 'GraphicsFormat' could not be found (are you missing a using directive or an assembly reference?)
Does anyone understand what this error could mean? Or what I might need to fix it?
The correct namespace is Unity.Experimental.Rendering, which you tried adding before IIRC.
What unity version and what render pipeline is this and is it up to date?
And what exactly is CustomPostProcessPass.cs
I tried that, yeah, it broke a bunch of stuff, though.
It's Universal Render Pipeline, in Unity 2022.3.42f1.
With CustomPostProcessPass.cs just being the script it's in.
It didn't really break anything, it just allowed the compiler to progress to the next errors (#archived-code-advanced message)
Fair. Just not sure what to do to resolve those errors.
What are you trying to do? 🤔 Is CustomPostProcessPass.cs the script you made?
All I can see is that you are trying to use members tha aren't there, like m_BloomEffect
Yes, I'm using it in a post-processing renderer I'm making.
I'm trying to follow the tutorial for it so far.
Link the tutorial
Inspired by the release of Hi-Fi Rush by Bethesda, I wanted to see if I could get a similar vibrant and stylized aesthetic in Unity. Little did I know, it would swiftly lead me down a rabbit hole of custom rendering in Unity and, in turn, completely overhaul my entire perception of Unity's Scriptable Render Pipelines. This video is a showcase of...
Start by actually declaring the m_BloomEffect variable in your class
From quickly skimming through I didn't see him declare it in the tutorial. The tutorial probably assumes that you have some programming knowledge
Like having to declare a variable before using it
Alright, I'll throw in Experimental and private Material m_BloomEffect, and see what that churns out.
Alright, I'm not getting this, I'm going to find one of those sites that let me post code just so I can spit out the entire thing and see if I'm missing something easy.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hej! I am trying to port my jump flood algorithm based SDF calculation from the old URP to Unity6 and Render Graph. I managed to get a basic "CopyRenderFeature" example running. That one did not use destination in the execute delegate, but when porting my bigger effect I get issues either on the command buffer type (when doing BlitCameraTexture) and also on setting destination textures to the blitter (also for BlitTexture).
There's a lot of confusion with blitter. Unity's official answer a while ago was to use Blitter but not anymore I think. You should use ScriptableRenderPass.Blit(CommandBuffer, RTHandle dest, RTHandle src) instead. Note this is not CommandBuffer.Blit which has a similar name but was deprecated a while ago.
Pls anyone correct me if I'm wrong, this is just what I remember
Unity keeps pushing changes to URP too quickly and not fully explaining them 😭
If you're writing a SRP you're already inheriting this namespace so it's just Blit fyi
Thank you, I will try the ScriptableRenderPass.Blit one!
Hey guys, this is an unusual problem but I want to be able to tell if a GameObject is directly linked to a file on disk or if it's a child object of a file. For instance the objects with "Empty" icons are children of an fbx but they are not the fbx. The reason is I need to validate some naming conventions and I don't care about the prefab or fbx at this stage, just the models inside it
The ScriptableRenderPass.Blit also does not work with a RasterCommandBuffer... so maybe I have to use another type of buffer...
Have you tried left clicking and looking for "reveal in file explorer/finder"?
Why would I want to do that?
You want to verify if it's a file right?
If I expand an .fbx file and right click on a child object, I can browse to the fbx. Which is exactly the same as if I right click on the fbx
I need to find a difference
Unity things that every child object of an fbx is also the fbx. That's the problem. I need a way to tell if the gameobject is the root object of a file
PrefabUtility.IsAnyPrefabInstanceRoot(transform.gameObject);
This solved it!
It works with a regular cmdbuffer
The solution for me so far was to use an unsafe pass and unsafe buffer to port this more directly. I will dig more into if it makes sense to split it up into several rasterrenderpasses
Is there an ideal channel in this discord to discuss Video API?
I am struggling to solve a black frame on the first frame of playback, it's resulting in a flicker when I call videoPlayer.Play(). The only way I've found myself able to get close to instant playback has been to skip the first frame, which sounds unreliable in case the problem is that different computers might prepare video at different rates, and I also just don't wanna skip the first frame of video.
What am I missing here?
I am using the Prepare() approach and still get this issue.
Hey does someone knows how to setup Proximity chat with Dissonance and Fmod? I am struggeling real bad haha
just because you didn't get an answer in #archived-code-general doesn't mean you should ask in #archived-code-advanced
the reason you didn't get an answer is likely because you should be asking for help with that asset in the asset's support channels
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hi, im trying to make a lobby broser with facepunch.steamworks, i have this function that creates a lobby with Gameid unique to the game name set with SetData:
{
Debug.Log("host");
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnectedCallback;
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback;
NetworkManager.Singleton.OnServerStarted += OnServerStarted;
NetworkManager.Singleton.StartHost();
CurrentLobby = await SteamMatchmaking.CreateLobbyAsync((int)maxMembers);
CurrentLobby.Value.SetData("game_id", "TOFLOATBOAT");
CurrentLobby.Value.SetJoinable(true);
CurrentLobby.Value.SetPublic();
} ```
then i have this next function that searches for that lobby using the same gameid:
``` public async Task<bool> RefreshLobbies(int maxResults = 5)
{
try
{
Lobbies.Clear();
var findLobbiesQuery = new LobbyQuery();
findLobbiesQuery.WithMaxResults(maxResults);
findLobbiesQuery.WithKeyValue("game_id", "TOFLOATBOAT");
var lobbies = await Task.Run(() => findLobbiesQuery.RequestAsync());
if (lobbies != null)
{
for (int i = 0; i < lobbies.Length; i++)
Lobbies.Add(lobbies[i]);
}
return true;
}
catch (System.Exception ex)
{
Debug.Log("Error fetching lobbies", this);
Debug.LogException(ex, this);
return false;
}
} ```
My steam app ID is set to 480, so when I remove the specific game ID filter in the refresh lobbies function I can see other developers lobbies, but when I do it with the game ID filter I can’t find anything even when hosting the same game on another computer, is this because I need to get my own steam app ID first?
Any help is appreciated!
Dynamic Tables via Layouts
I’m scheduling a bunch of IJobs via Schedule method. I expect them to run on the worker threads, not blocking the main thread.
But somehow, each frame, URP’s render loop waits for one of those jobs to complete, while other scheduled jobs run in the background as expected.
I’m completely clueless as to why this is happening. There are no job dependencies associated with that job.
Could you give me a hint? Why this is happening?
I'm using 2022.3 LTS.
At what point are you scheduling it? And do you ever Complete it?
- Update
- No
Interesting. Are you using Mesh.AllocateWriteableMeshData for this?
Nope
So I've worked around this by limiting number of concurrently scheduled jobs. Still, not sure why this is happening.
Someone on the forum told me that this behavior changes version from version. Looks like it isn't documented as well. Sigh
Hi
Currently using RenderPrimitives() to draw some vertices and I noticed that when nothing should be rendered (instanceCount = 0) things still appear on the screen. If I remove the calls with instanceCount = 0, the problem disappear. Is that a known caveat? Should I just avoid calling RenderPrimitives with 0 instances? (which I will because it makes no sense calling this function with nothing to draw... But I'm still curious, is that a bug?)
Anyone know of any assets for implementing a window manager like experience for Unity UI (not UI Toolkit)
Id like to turn UI > Panels into draggable resizable windows... (minimize maximize drag, close, reopen, etc. you know... window behavior) I know this can be rather tricky to implement but was hoping for something on the asset store to help.
I saw this but it doesnt handle resizing... obv the hard part 😦
https://assetstore.unity.com/packages/tools/gui/simple-ui-window-manager-294762
Somewhat seriously wondering if I should invest time into trying to run webview on top of the unity context... idk someting like this https://github.com/gree/unity-webview (sadly no windows support)
but im just asking to spend 3 months on some integration to have a feature that only serves as a "nice to have" and not an actual mechanic lol.
Anyone know if there's any up-to-date header files for Unity's native engine functions? Or is this level of access unsupported? Like I can see useful exported symbols in Unity.dll public: class UnityScene * RuntimeSceneManager::LoadScene(class core::basic_string<char, class core::StringStorageDefault<char>> const &, class core::basic_string<char, class core::StringStorageDefault<char>> const &, class core::basic_string<char, class core::StringStorageDefault<char>> const &, struct UnityGUID const &, int, struct InternalLoadSceneParameters const &)
Does unity's test framework support IEnumerator/async 1 time setup per class?
I see it supports coroutine setup and teardown, but those are run per test, im trying to do something that runs per class
as i have a heavy singleton object i need to initialize, having to do this for each case is quite time consuming
it takes around 1.5 seconds to initialize, and with parameterized tests it adds up a lot, i would like to initialize it once per class test
nvm I see what you mean
no, setup is ran for each case, i want this to run once per class
Not sure - could you just make the setup synchronous? What is it exactly?
I don't think it's supported as you described
its my singleton initializer, it connects clients to servers and sets up a lot of logic, which can be async
A workaround/hack would be something like:
bool setupDone = false;
void Setup() {
StartCoroutine(DoSetup());
}
IEnumerator DoSetup() {
// all setup stuff
setupDone = true;
}
IEnumerator SomeIndividualTest() {
return return new WaitUntil(() => setupDone);
}```
but you'd have to do that yield in each test
i think worst case ill have to check if its inited and then dont reinit in those cases, but its quite ugly that way so i wanted to double check if unity had an out of the box solution, seems sadly not
sad that the test framework is quite powerful but still lacking some obvious use cases
Have you tried UnitySetUp?
thats the one that runs each case
I see
in NUnit they have OneTimeSetUp attribute, not sure why unity doesnt have their unity OneTimeSetUp version of the attribute
Yeah you'll probably have to set up some of your own tool for this I suppose
will do, thanks!
from 2020 
Yeah and annoyingly Unity Staff commented in there multiple times
looks like someone hacked his own way, maybe i can use it
jsut to say it's not available yet
this guy from 2020 seems to have my exact issue
oh it kind of looks like they killed any new work on the test framework lol thats a bummer
Does anyone have any pointers on generating a mesh like in the picture, I have a spline based road generator and want to add sidewalks
My main thought process is to approach it like an image editor such as photoshop outlining text or a shape like this picture, only problem is I don't even know where to begin
I have a list of all the vertices and have managed a basic sidewalk along the splines but the intersections and the sidewalks overlapping is the problem with my current method
Any advice, reading, tutorials or examples is appreciated
Hello! Could you help me please with Zenject and Unity?
Could you help me to implement custom factory?
I've done "basic" one that resolves context from GameObjectContext and returns facade to me from GameObject context to SceneContext. But I can't implement customization. The idea - I have enemy game context, that livespan only when game object alive, and I create it via Zenject and provide EnemyEntity as facade for SceneContext(my manager class) to work with it, while other classes/objects of GameContext are hidden.
This code that works for me:
container
.BindFactory<EnemyEntity, EnemyEntity.Factory>()
.FromSubContainerResolve()
.ByNewContextPrefab(enemyPrefab)
.UnderTransform(worldTransform);
public class Factory : PlaceholderFactory<EnemyEntity> {}
But I want create my enemy using instantiate and pass position righ away to it, like I can do using container
container.InstantiatePrefab(enemyPrefab, position, Quaternion.identity, worldTransform)
Unfortunately I can't make it work, while implementing interface, FromSubContainerResolve not working for me, and using ootb I can't get how can I add some data to my object. This is what I've tried.
public class CustomFactory : IFactory<EnemyEntity>
{
///Injections
public EnemyEntity Create()
{
return _container.InstantiatePrefabForComponent<EnemyEntity>(_enemyPrefab, _worldTransform);
}
}
heya, is anyone familiar with using EF Core in tandem with Unity? I had a game I got this working for a while back but it's been a bit troublesome getting it to work again
Unity server:
[Server]
public static async Task<CharacterData> CREATE_NEW_CHARACTER(
string steamId,
string name, string race, string skinTone, string earStyle, string hairStyle,
Color hairColor, Color eyeColor
) {
Debug.Log($"Sending name: {name}");
CharacterData cd = new() {
Name = name,
Race = race,
SkinTone = skinTone,
EarStyle = earStyle,
HairStyle = hairStyle,
HairColor = "#" + ColorUtility.ToHtmlStringRGB(hairColor),
EyeColor = "#" + ColorUtility.ToHtmlStringRGB(eyeColor)
};
CharacterDataResponse res = await HttpClient.Post<CharacterDataResponse>(
$"{GLOBAL.DATABASE_URL}/character/create/{steamId}",
cd
);
GameManager.LOG_API_RESPONSE(res, GameManager.API_LOG_LEVEL.ALL);
if (res.Status == 200) return res.CharacterData;
else return null;
}
EF Core:
[HttpPost("create/{steamId}")]
public async Task<CharacterDataResponse> CreateCharacter([FromRoute] string steamId, CharacterData request) {
CharacterDataResponse res = new() {
Status = 404,
StatusMessage = "No account found with that Steam Id",
CharacterData = null
};
Console.WriteLine("Checking account for character endpoint.");
AccountData account = cContext.Accounts.FirstOrDefault(a => a.SteamId == steamId);
if (account == null) return res;
Console.WriteLine("Creating new character.");
Console.WriteLine($"Character has name: {request.Name} and Skin: {request.SkinTone}");
var character = new CharacterData() {
SteamId = steamId,
Name = request.Name,
Coin = 0,
Race = request.Race,
SkinTone = request.SkinTone,
EarStyle = request.EarStyle,
HairStyle = request.HairStyle,
HairColor = request.HairColor,
EyeColor = request.EyeColor,
PositionX = 0,
PositionY = 0,
PositionZ = 0,
PositionScene = "WorldMap",
TotalPosts = 0,
LastPost = DateTime.Now,
LastDaily = DateTime.Now.AddDays(-1),
BonusExperiencePosts = 0,
};
cContext.Add(character);
cContext.Config.Add(new SavableConfig() {
CharacterId = character.Id
});
await cContext.SaveChangesAsync();
Console.WriteLine("Got to the end of the character endpoint.");
res.Status = 200;
res.StatusMessage = "Character successfully created";
res.CharacterData = character;
Console.WriteLine("Returning status of: " + res.Status);
return res;
}
on the unity server, everything logs correctly (name, etc.), but on the ef core side, everything inside body logs as null. only SteamId is correct. a row is still inserted into the table though?
then, when receiving the response in Unity, status logs as 0 even though it logs as 200 on the ef core side
i'm very confused, it seems to be some kind of serialization error? the types are shared via a dll between the two projects and those match up
I don't know how you determine intersections off the spline itself, but if you make an outline shader, you can then turn it into a mesh using a simple marching squares algorithm.
Hello, anyone knows of a way to exclude a folder from a local package?
The annoyance more than an issue I'm facing is that I'm developing a package that I have locally added to a project, within that package I do also have a csproj file that defines a dll compile for non unity platform, whenever I run that it created dlls that collide within unity and was wondering if I can easily exclude bin, obj folders from a local package.
Currently I run the build script, publish my nuget and then run a cleanup script which isn't a big problem, but something to always remember.
Extrude every point along the normal of the spline, including the sides of the road intersections, and check for self intersections along each edge loop. Skip or ignore vertices that are between two ends of a line intersection
Or if you just want to check for intersecting faces then you can do that with a triangle-on-triangle check
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Camera))]
public class CameraFrustumIntersectionEditor : Editor
{
private void OnEnable()
{
Debug.Log("CameraFrustumIntersectionEditor enabled!");
}
// Other Functionality ....
}
im trying to make an editor script for the built in Camera Component. But i dont really know how to do, This doesn't work and the script is never run. Anyone know how I could do this??
where did you place trhis script
hello! I'm trying to make a hand display, where cards are displayed in a curve around a point. the problem is, i need the sin wave from 0-180, which would curve around the object this is attached to. however, set to 0-180, it instead gives me the full graph of 0-360.varibles in the code: (maxHandSize = 10, hand = List<GameObject>, hand.count=10), x and y hand scale are set to .1 and 1 respectively
void OnGUI()
{
List<PointF> coords = new List<PointF>();
coords = getPoints(0, 180, maxHandSize, 1f);
if (hand.Count > 0)
{
for (int i = 0; i < hand.Count; i++)
{
if (i % 2 == 0 || i == 0|| true)
{
hand.ElementAt(i).transform.position = new Vector3(xHandScacle*(this.transform.position.x + coords[i].X), Math.Abs(yHandScacle*(this.transform.position.y * coords[i].Y)), this.transform.position.z);
}
else
{
}
}
}
}```
``` List<PointF> getPoints(float start, float end, int count, float ymax)
{
List<PointF> points = new List<PointF>();
float deltaX = (end - start) / count;
for (int i = 0; i < count; i++)
{
float x = i * deltaX;
float y = ymax + (float)Math.Sin(x *1) * ymax;
Debug.Log(y);
points.Add(new PointF(x, y));
}
return points;
}```
what is deltaX?
Sin is looking for radian inputs
Even if it's in degrees your code doens't make sense
Because you're not normalizing to 360 degrees either
(or 180)
Basically you'd do:
float degreesPerCard = 180 / cardCount;
float radiansPerCard = Mathf.Deg2Rad * degreesPerCard;
for (int i = 0; i < cardCount; i++) {
float angleForThisCard = -Mathf.PI + (i * radiansPerCard);
}```
for points around a circle you'd want Vector2(Mathf.Cos(theta), Mathf.Sin(theta)) * dist + origin where float theta = Mathf.PI * i / (count - 1)
sorry about that, i fixed it now that i know its readains
{
List<PointF> points = new List<PointF>();
float deltaX = (end - start) / (count-1);
for (int i = 0; i < count; i++)
{
float angleDegrees = start + i * deltaX;
float angleRadians = angleDegrees * (float)Math.PI / 180f;
float x = angleDegrees;
float y = (float)Math.Sin(angleRadians) * ymax;
Debug.Log($"Angle: {angleDegrees}°, Sin: {y}");
points.Add(new PointF(x, y));
}
return points;
}
don't forget cardCount-1 because n cards is n-1 gaps
also you can skip the degrees step since 180 degrees is π radians
thank you very much for your time, its been a couple hours and i was lost in the sauce
wich line?
the degreesPerCard line in praetor's example
your angleDegrees line
also since we're in unity you could use Vector2 instead of PointF, they have operation overloads for scalar multiplication and such
and Mathf instead of Math, which uses floats instead
in unity test runner, can i use parametrized ignore with a function result? kind of like TestFixtureSource or ValueSource
i need an "parametrizedignoresource"
A bit of a warning regarding U6. If you're doing a non ECS project, U6 is a huge disappointment!
I Just ported over a Quest project, thinking that the GUI was the only thing that had regressed, but that's unfortunately not the case.
Quest hardware monitor shows framerate dropped from steady 72 fps in unity 2020 down to 50 fps in U6!
a 25% performance drop!
Not refuting your claims, but you jumped 4 versions from 2020 to 6. It very well could be the 3 versions in between that's causing the performance regression.
true, but it doesn't matter. i'll let unit sort it out, in the meantime u6 comes with this sizeable caveat
It's also very hard to say whether the engine version is an issue when versions can introduce features that may be enabled and do nothing for your game specifically but hurt performance
You should be looking at where the performance regression is and seeing if it's just a feature you can disable
Often people come and complain about some specific performance problem and it turns out they have all this stuff enabled that is designed for projects with an entirely different structure or optimisation pass
A lot of the new features are designed so you don't have to put in work to optimise, and if you've done prior work to optimising for the old setup then those features don't end up working and only hurt performance instead
A good example is the SRP batcher. If you don't understand how it works and port a project, it'll be enabled and will hurt performance
but if you understand how it works and rework the setups to use it then it'll be a perf boost with much less work involved
I think I am over engineering a problem. The problem: In our game we have multiple shots per gun, i.e the player can build a gun that does 45 shots per 1 click. Right now the shots result in hits, where each hit get a light and a sound from a pool and enables/plays them. With higher fire rates this becomes a bottleneck and we start dropping frames. So I need to limit the number of lights and sounds. My current solution: build a k-d tree of the hit points. Use the tree in an algorithm called DBSCAN to determine the number of needed clusters based on the density of points. After we get the number we run k-means clustering to determine the actual cluster centres. After that we just get our lights/sounds from the pool.
Could you not just do 1/3 shot actually do the light/sounds ?
And for the sound, you could use 1 single sound instead of multiple that would help a lot. (Exception if you are talking about impact sounds)
Obviously, that depends on how much it is a important for your game.
I am talking about impact sounds yes. What heuristic are you suggesting to pick a third of the impacts ?
If you are shooting really fast, I would just literally go with 1/3 of the shot fires (impacts).
Also, you could try to varies it. If there is 10 impact currently playing, then you do 1/5 instead, etc.
You would really need to test it to see if it works though.
It's one of those features where it can still feel correct same if it is not accurate I believe.
And, if you want you could do an alternate VFX without light and only Bloom for those that are not.
For the sound, you could try to make a sounds that is a bit longer, it could hide more easily the fact that it does not trigger a sound each time.
Hmm that vfx idea is not bad. Sounds Im not so worried about since we model the occlusion and reflection and in this case fewer produce a better overall sound scape
No one can tell that 16 impacts are echoing and not the whole 50 for example
I did consider just skipping impacts or choosing at random but quick test showed that it leads to less than desirable visual quality.
is this where i can ask for help?
Depends checkout #🔎┃find-a-channel
A slightly less overengineered solution - run your VFX through your own "middleware" that keeps tabs on how many are playing at once and eats excess calls to play clips. If that many clips are playing at once, it's unlikely which ones are playing matters.
As far as lights.. I'd start with the above and see if you're still dropping frames. If so, then you could probably apply something similar to lighting - but determining which lights to show so it's not obviously "bad" is up to you.
I forgot to mention this but the actual VFX part of the impact is handled. We upload the locations to a graphics buffer and have one vfx graph play them all. About 2500 can play this way before becoming a problem.
So you think the SFX are the source of the framerate issues..? Or is the issue more of a quality of the sfx when there's lots going on at once?
I'd probably just cull the extras if there's more than X calls in the last Y seconds and see how that works
In a recent game of mine I had to have some fancy logic for combo sounds (they increase in length and "quality" as the player gets more and more combos), but if the player is moving fast, you have to interrupt the previous sfx so they don't overlap.. anyway, the end result ended up being pretty good but it was a really big time sink to architect, engineer and debug
(IE - I'd advise keeping it simple since most of the time engineering effort is better spent elsewhere)
Oh, god, looking at the code for this gives me nightmares. I forgot that I also wanted to rapidly fade the previous SFX if a new one (in the combo "channel") arrived
dug through my old video captures - here's the effect
I would not make that assumption yourself, as you sound invested in getting perfect results. Have some normal people play the game and see if they even notice
How to calculate view matrix?
let U vec3 = (0, 1, 0)
let T vec3 = target point
let C vec3 = camera point
let F vec3 = (T- C)/||T - C||
let R vec3 = (F matmul U)/(||F matmul U||)
let U2 vec3 = R matmul F
view matrix = [
Rx, Ry, Rz, -R, matmul C
U2x, U2y, U2z -U2 matmul C
-Fx, -Fy, -Fz, F matmul C
0, 0, 0, 1
]
What do i do with the view matrix to get a shadow map depth value for the target point?
You need to start simpler. Your questions don't make sense, so nobody would be able to answer them. Not to mention that the code is not from any language relevant to unity.
the language is psudocode
what about my questions do not make sense so i can revise them?
You seem to be stuck on the concept of shadowmaps, but multiplying a point by the view matrix is not related to shadowmaps or depth at all. It's just a way to transform the point from world or local space to view space.
As I said, rendering a shadowmap is an involved process that includes many steps. The same very steps that are used for many other things in rendering. Like transform a point to the view space.
so what do i do with the view matrix
Whatever you want. But if you want to get a point in view space you multiply a position vector by it.
multiply a position vector, a 3x1 by a 4x4?
They do if it's matrix multiplication. That's why I'm telling you to go back and start with the basics.
i am very familiar with the fact a 3x1 does not multiply by a 4x4
that is taught in high school
Obviously, you need to make a matrix out of the position vector to multiply it.
oh? how do i do that?
This is also something taught in high school
well its not because its ambigious and has infinite number of interpretations
No it doesn't. There are specific rules of matrix mult with vectors.
Anyways, that's well beyond the topic of this server.
" make a matrix out of the position vector" what size matrix shall i make?
You actually don't multiply 3x1 position vector with 4x4 matrix, but instead your position vector is 4x1: (x, y, z, w) where w is just 1.
4x1 still doesnt multiply by a 4x4
unless you transpose it
Sure, you get the point that you are missing the w.
alright. I take a point. I calculate the view matrix using the previously defined process. I pad the target point with a 1. I transpose target point. I multiply target point by view matrix.
what next?
It's been a long while since I've touched the underlying math, so maybe someone more familiar can answer. But IIRC, once you multiply the point with the projection matrix, you need to normalize the result so that w is 1 again, and the normalized vector would be in screen space.
whats the projection matrix
(I don't think this really has much to do with coding though, it's more math)
same thing as view matrix?
I remember following this when I was learning this stuffs: https://www.scratchapixel.com/lessons/3d-basic-rendering/perspective-and-orthographic-projection-matrix/projection-matrix-introduction.html
Although if you are using a game engine like Unity, most of these are abstracted away from you.
yeah im trying to do them by hand
Software engineering/computer science don't always adhere to pure math if that's where your background is. You know what physicists say, pi and e are both 3.
assuming the projection matrix = the view matrix, what do i do with the normalized "screen space" point?
Draw it on the screen.
Oh I missed that part of the conversation then.
"Assume a spherical cow"
any ideas?
You need a view or clip space point. But when you got it, it's essentially one pixel for you'd depth map.
do you happen to know the transformation from something to a view or clip space point?
No. I just know that you need to transform your point with some sort of matrix. I think it's called a view matrix. Projection matrix might be the same or a combination of several matrices. As I said earlier, you don't deal with these manually normally.
i have the view matrix here
Then you got it.
Assuming it's correct.
so what do i do with the normalized view point
That's your depth value(the z component) of that point. Whatever you do with it after that is up to you.🤷♂️
the depth value is suppose to be a scalar
oh the z
Idk what shadow depth map is, but once you have transformed your point from world space to screen space and normalized it's w value to 1, the z value is the depth of the point and is used for z ordering objects. That's probably relevant.
so for all points in the world, i calculate the z value of the normalized view point
thats the depth from the camera
cool
and then im guessing i take the minimum depth per every x and y value?
set that to 1
then everything else to 0
What for?
well for the shadow map right?
the pixel with the minimum depth is closest to the camera with no obstructions
Well, then you'd want to override the value in the map with the closes point, not set them to 0/1
huh
i thought the goal of the shadow map was to provide a 0 for every obstructed point and a 1 for every point visible to the camera
Assuming we're talking about the same thing, a depth map usually contains values between 0 and 1(or some other range) describing the closest point,(to the camera) at each pixel.
how can the closest point between 0 and 1
I really don't get what you're asking. A closes point would be 0 if there's a pixel rendered right at the close plane of the frustum. And 1 if it's exactly at the far plane.
All kinds of techniques. LOD, occlusion culling, etc... and GPUs can process a lot of data in parallel very quickly.
is the depth different than just taking the difference between the camera pos and the target pos? that seems cheaper
The difference is that depth is in view space. Imagine your monitor/screen as a 3d box. For rendering to happen correctly you need to take 3d objects and place them in that box such that they're able to be projected to the screen. You can't just use world positions to render objects.
I'm currently in the middle of trying to figure out how to use RenderMeshIndirect, and I'm struggling a bit. I'm trying to use this as a base, and on it's own I've gotten it to work, but the part that I'm struggling with is figuring out how to feed in coordinates instead of just using random coordinates https://gist.github.com/Shitakami/bb075299ea9a434426a48e9bd18b57fb#file-forrendermeshindirect-shader
When I tried changing the Create method in TransformMatrixArrayFactory to accept a DataFrame input, it spat out errors about it being a managed type
I then made a method to convert my DataFrame to a useable Vector3[] and changed the Create method to accept that instead, only to get the same error
I then changed it to accept NativeArray<Vector3> instead, and that finally worked, but now I'm getting this error: ```
ArgumentException: SetData(): Accessing 216128 bytes at offset 0 for Buffer of size 640 bytes is not possible.
UnityEngine.GraphicsBuffer.InternalSetNativeData (System.IntPtr data, System.Int32 nativeBufferStartIndex, System.Int32 graphicsBufferStartIndex, System.Int32 count, System.Int32 elemSize) (at <b5bf0c891ea345fe93688f835df32fdc>:0)
UnityEngine.GraphicsBuffer.SetData[T] (Unity.Collections.NativeArray`1[T] data) (at <b5bf0c891ea345fe93688f835df32fdc>:0)
SampleRenderMeshIndirect.StartRender () (at Assets/BitterAloe/Scripts/bb075299ea9a434426a48e9bd18b57fb-6ea5155c75cca519e03a2aa841d1d84545c1eb3a/SampleRenderMeshIndirect.cs:38)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <321eb2db7c6d43ea8fc39b54eaca3452>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <b5bf0c891ea345fe93688f835df32fdc>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <b5bf0c891ea345fe93688f835df32fdc>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <b5bf0c891ea345fe93688f835df32fdc>:0)
This is the file with the error in question
Are there any other options, if this isn't gonna viable in my timeframe? It seems like VFX graph isn't compatible with URP
To clarify my problem though, I need a version of this function that accepts a bunch of coordinates, instead of just generating them randomly:
[BurstCompile]
private struct InitializeMatrixJob : IJobParallelFor
{
[WriteOnly] public NativeArray<Matrix4x4> _transformMatrixArray;
[ReadOnly] public float3 _maxPosition;
[ReadOnly] public float3 _minPosition;
public void Execute(int index)
{
var random = new Unity.Mathematics.Random((uint)index + 1);
var x = random.NextFloat(_minPosition.x, _maxPosition.x);
var y = random.NextFloat(_minPosition.y, _maxPosition.y);
var z = random.NextFloat(_minPosition.z, _maxPosition.z);
_transformMatrixArray[index] = Matrix4x4.TRS(new Vector3(x, y, z), random.NextQuaternionRotation(), Vector3.one);
}
}
All that job does is just filling the matrix array with matrices calculated from randomized positions and rotations. It's using job system and Burst to make that calculation faster, but it doesn't change what it does.
To do what you want, just pass in an array of positions and rotations to the job, and do the same calculation but use the position and rotation of the current index instead of the randomized values.
That's the part I'm struggling with lol
It's weird to have serialized count when presumably it's meant to match the length of the coordinates array
It's pretty basic job system usage though, take a look at the docs on how to pass data in/out of a job.
I can't figure out how to actually get the array in there without getting that error spit at me
Or if you don't have time to learn job system, just rewrite it without job system. It'd just be a plain for loop and that's it. You can always refactor that part of the code later on, since all it does is just making the same calculation faster.
well it looks like your file has something like 13,508 elements and your count is probably 40
The total dataset I'm working with is about 700k datapoints, I'll probably be messing with about 500-1000 at a time
what is the _count set to
this is the default version of this function, I'm not using it in my version
by default it's just a parameter in the unity inspector
Maybe I'm confused, is it not where the problem is coming from?
Or is the error you posted completely unrelated
The error is related to the results I got from trying to solve this problem on my own
That error is entirely to do with the GraphicsBuffer not having the same amount of data as you've set it to
presumably if you initialized it with the correct count it would go away
My substitute for the _count was just getting the length of the array I was passing in
Can I have MonoBehaviors with AddComponentMenu attributes in .dll show up in the add component menu?
Currently targeting Framwork 4.8, and including the UnityEngine.dll, but when I pull the built .dll into the project, my custom MonoBehaviors don't show up in the list.
Or would I need to just have straight .cs files for all MonoBehaviors inside the project, and all none MonoBehavior services in my .dll?
Turns out there were a few places I forgot to substitute _count, it's working now. Sort of
I've actually rendered the plants in, but now they all get culled whenever the origin on the object with the script that loads them in is out of frame
Is there a way to cull them per plant or can I only have all or none?
@cobalt drift
#💻┃unity-talk message
all scripts on loading would call OnValidate() in the editor at least once, so you might put the code there it seeks the component it needs and assigns it in the field you added, if this field is null
I guess it should be at code-general but anyway
Hey all,
I'm using MessagePipe from Cysharp: https://github.com/Cysharp/MessagePipe
I want to know what is the best way to filter subscribers to handle the event when it is published.
For instance, I have multiple characters in the game and they can angle. If I want to publish an event from the fish that bites the bait to that particular character which is fishing, how can I filter that ?
Does it make sense to pass character id to that fish before publishing the event or there is a better way to do that ?
High performance in-memory/distributed messaging pipeline for .NET and Unity. - Cysharp/MessagePipe
"Better way to do that" in my mind would be with a UnityEvent and not a multi-layered boilerplate framework, but appreciate that's probably not what you're looking for
UnityEvent doesn't make sense here when there is no referencing to each other.
You wouldn't need a direct reference between each other. The angler would subscribe to a static event, OnFishBiteSomething, then in its own code, check to see if OnFishBiteSomething was sent with an id that matches AnglerID (or similar, you get the picture).
Not fan of global things. They can make the project messy imo. They might work for communication betwene major systems but not subsystem.
It's not global global, would still be in the scope of whatever script you want it to be. You don't even need references to the listeners when cleaning up either.
Hello everyone, I am new here and I do not know where to start with the Unity program. Can someone help me please?
In message bus or event aggregator, subscribers and publishers don't know about each other. That's the point.
They know about the events they are subscribing to, which is all this would be 😄
for a start, not in the advanced coding channel 😄
use #💻┃code-beginner and read the pinned msgs
thank you so much
❤️
Is anybody here familiar with Zenject for dependency injection?
I'm looking for advice regarding a certain use-case.
Their documentation doesn't cover that particular use-case unfortunately.
Is anybody here familiar with Zenject
Hi all, I need help: transform.SetParent issue, I am calling it with 2nd argument WorldPositionStays=false, and while it gets parented the behavior is very weird. Some of the objects dont follow as they should but rather move "inverse" to the parent. Not sure if this is a code issue or editor issue. Other objects in the same loop get parented and follow correctly. It's weird. https://www.youtube.com/watch?v=AvSL-7KLjcw (edited)
I have one peculiar problem.
I got my health bar as a prefab, it was made in a URP project and exported. It is sprite health bar (sprite renderer).
I import it into the SRP project and as usual materials are broken so i need to set materials to the Sprites-Default
Health bar also has child which is sprite mask which controls how much bar is filled and there is the problem.
Bottom one is identical to the first (same same same process)
only difference is that child mask of the second bar
i deleted that mask child and created it again with the same settings
Notice selection on the left side
Why does this happen
i'm new to coding, but there's a question i want answered for future reference, when i get better at it. how does wavedashing work? like, how would you put it into a game or what would you need for it?
what is wavedashing? It's not a unity term i am familar with
have you tried googling at all? this isn't really an advanced question
Hello, I've been making games for a long time now, and I've been making a level editor. I have all my objects in a scene, and I have a bunch of necessary data that I'm trying to save to text using JsonUtility.ToJson() or EditorJsonUtility.ToJson(). Here are my classes I've got set up for data inside a monobehavior:
[System.Serializable]
public class TerrainShapeData
{
public GameObject prefabBase;
public SpriteShapeController SpriteShape;
public EditorObjectParameters parameters;
public Transform transform;
}
[System.Serializable]
public class ObjectData
{
public EditorObjectParameters parameters;
public GameObject prefabBase;
public Transform transform;
}
[System.Serializable] public class LevelData
{
public TerrainShapeData[] TerrainShapes;
public ObjectData[] objects;
}
[System.Serializable] public class SaveData
{
public string[] TerrainShapeDatas = new string[0];
public string[] TerrainTransformDatas = new string[0];
public string[] TerrainParameterDatas = new string[0];
public string[] TerrainPrefabBaseDatas = new string[0];
public string[] ObjectTransformDatas = new string[0];
public string[] ObjectParameterDatas = new string[0];
public string[] ObjectPrefabBaseDatas = new string[0];
}```
I'm trying to save all of this data to text. However, using ToJson just gives me a bunch of InstanceID. I want to be able to recreate the level later, so InstanceID's do not give enough information. That's what the SaveData class is for, it's supposed to hold all the more specific Json data (because using ToJson on a object gives way more information than an array of classes with the object in it.) However, when rebuilding the level, I can't figure out how to recreate all this data in a scene.
In particular, I can't add the data from the spriteshapecontroller back onto an instantiated object based on the prefabBase
Theoretically, I could do a really big forloop getting and assigning the positions and tangents of the spriteshape
but I'd rather not
here's EditorObjectParameters
I also want to copy the values from this class, without manually copying it
I want to be able to modify this class later without having to add to the load function
(Ping reply please)
You will have to write your own parsing logic and rethink your data: You gather data from your components, you write that to file, you read the data from the file and then you set the data on your components again. Your components will consume that data and work with it.
This way you do not need to actually serialize any MonoBehaviour (it looks like you attempt to do that a couple of times in TerrainShapeData). That's an antipattern. The only thing you might want to serialize is the prefab reference, and for that you only save the instance ID of the prefab and have a lookup dictionary so you can grab the prefab again upon reading the save file. Also, why do you want to save a Transform anyways?
yes lol
Ok I can just save a vector2 and quaternion instead of transform
its a game mechanic, i dont know how to explain it
exactly
don't attempt to save monobehaviours. save data they have.
then it's very hard to help you
But the information I really need is the positions and tangents of spline, position, prefab base, rotation, and the parameters variable in EditorObjectParameters
it's.. a known game mechanic in celeste, risk of rain returns, smash bros(?), and some other games. like it's hard to describe if you don't know what it even is. it's like jumping into the air and using a dash to gain speed as/before you hit the ground and then you jump again and it gives you insane speed. google has zero information on it coding-wise (that i could find, at least). which is why i'm here
like i literally can't do anything but ask here or figure it out myself 2 years later lmao
but i can keep scouring
Or at least the parameters part of editorobjectparameters
i'm not even good at describing things lmao
afaict it's not coded. it's not a mechanic, it's just a side-effect of physics
or i mean, it might not be intentional but it's like a big part of celeste anyway and i just played a new game called wayfinder where there's also wavedashing
it's something i really want to figure out at some point, i know i'm not able to do anything like it yet, but even once i get better at coding it's unlikely i'm going to just figure it out spontaneously and i don't want to stress over it when people already know how it works. it's been mentioned here a few times i think. if it's like.. physics related it'd be nice to understand how to get the physics.. to.. do that..? i don't know
you are fine then, all of those are value types and can be saved easily. The prefab you save by saving its instance ID and then grabbing the prefab using the instance ID from some lookup table
this isn't a #archived-code-advanced question, you'll probably want to move this discussion somewhere else, maybe #⚛️┃physics
i swear it's actually part of celeste but maybe it's just movement tech you don't even need. i swear you need to use it though to progress at some point
ok, ty
Ok thanks!
gotcha! I think i know what you mean with that move. Do you already have some character controller setup?
there are lots of ways to approach the wavedash. In the end you'd want to apply a certain velocity to your character based on some conditions. For example apply some velocity on the character rigidbody when jumping after a dash led to the character hitting the ground.
One way of doing this would be to implement a finite state machine, so you can easily keep track of the states your character has, and you avoid having lots of booleans for keeping track of what happened. It will also allow you to introduce more moves easily later on. This state machine could contain states for Grounded, Airborne, Dashing, Jumping and the Wavedash. You could then put the state machine into the wavedash state when you receive a jump input while the character is currently in the grounded state and the last state was a dash state. The individual states can then take care of modifying the character, which means that your WavedashState applies some force on the character upon being entered, or increases some speed parameter or whatever
basically based on inputs and the current state you can decide if you want to switch states. States can then react to when they are entered or exited and perform some logic.
im not convinced you need all that tbh
its one way of doing it for sure
really seems like it's just emergent behavior from how dashing works in both celeste and ssmb
from what I gathered by the explanation Kat gave it sounds like its coded behaviour, not emergent. So somewhere you need to have checks for what input was pressed in what situation and what to do then. The "what situation" part of that can be described via a finite state machine
ah I misunderstood you, yes it might just be a result of dashing
but even then you'd need to implement the dash so same problem
all resources i found online say it's emergent.
here's someone who made it themselves: https://www.youtube.com/watch?v=8JBGxUR0fnQ
you can see there's no "wavedash" state if you go frame-by-frame
dashing is easy
you just have to make it in a way that permits wavedashing
wavedashing is about interactions, it's not something you have to make specifically
it's also open source, but it godot, not unity
no not yet, i'm still extremely new to coding but i just know it's something i'm going to want to put into a game in the future once i've practiced enough.
i appreciate the answer, btw. though i didn't fully understand it yet. this is just mostly for the near-ish or not too distant future when i'm actually able to understand more than some basics of coding and unity, and i guess to have something to look back at so when i actually do try to implement wavedashing, i have somewhere to hopefully start with i guess
jot those ideas down
the most important thing right now for you is to start
you can come back to these later when you're more experienced
yeah i was planning to write it down for the future, but i'm also not sure i'll understand it much better in the future tbh. but having like answers or notes or ideas on how to do it is going to be useful at least
good luck with your project! There are so many ways of how you can approach it, which might seem overwhelming at first, but actually its exciting (at least to me) because you can tinker around and find your path through it all
here's where wavedashing happens: https://github.com/NyxTheShield/Godot-Smash-Engine/blob/master/Scripts/Player.gd#L807
there's literally nothing
it's just physics, not code
in the end you just want to apply some force to your character based on inputs. Whether you do that within a single script with some conditional checks or more complex with a state machine doesn't really matter for a start
i don't think you're going to be informed enough to write meaningful notes right now
just jot the idea of "wavedash" down, come back to it later when you have the background knowledge to be able to understand your research
i'm more so just taking everything said here verbatim and writing it or screenshotting it for the future
and thank you, i appreciate it
coding's something i really wanna learn but i'm not the smartest person or most motivated but i just gotta push and figure it out eventually lol
everyone can code and that includes you, its just experience thats all
and i've already spent a few several hours on it so i'm kinda starting but it's just very hard lol
If you ever played with Lego or assembled puzzles, you're gonna be fine with coding(assuming you put enough time and effort into learning)
Any rigidbodies involved?
It looks to me like rigidbodies are still using gravity, personally i'd ditch the rigidbody on plate stack alltogether and use joints for stability (assuming there's rigidbodies), if not the plate is definitely latched onto your hand still somehow
they are kinematic, so it doesn't matter
Is there a way to simulate or have a more realistic terrain (like dirt) that you can slowly erode based on wheels spinning?
That’s usually done via lokal masking of a displacement shader. To get sufficient detail you likely need tesselation or very high resolution terrain.
This is an example of that. May or may not suit your needs https://assetstore.unity.com/packages/tools/terrain/microsplat-trax-166218
I really hate WebGL sometimes. So I'm trying to implement a Screenshot function into my app and it works great in the Editor, saving it to a data path folder Save Data; but throws errors in WebGL like on Itch. My friend tells me I need to use JS to have it open the image in a new tab; but I have never used JS before in my life and have no idea how to do this. The Editor also seems to be ignoring my preprocessor directives and am getting an EntryPointNotFound exception. Asking GPT, it suggested I input some code into the index.html file of my build, but it won't build because it doesn't recognize the extern call. I tried adding the function to a .jslib file, but I clearly don't know what I'm doing when it comes to JS or how to get my C# script to figure out where to make this function call. Can anyone provide any insight? I can show the code if that's necessary.
I set IsKinematic to true while they're in this stack.
I set IsKinematic to true while they're in this stack. I also disable gravity. (I've tried joints for this, they're too janky and not smooth like parenting). Might mess around with it more.
Can somebody help me with the ShaderTagID system with the RenderGraph API?
I want the shaderTagID for 2D unlit sprites but nothing seems to work
I have this line:
ShaderTagId shadersToOverride = new ShaderTagId("UniversalPipeline");```
And I've tried Transparent, Universal2D, NormalsRendering, and UniversalForward
which are all present in the default shader
but the only one that has effect is UniversalForward, which renders the 3D objects
Ok, it was down to the FilterSettings which was set to Opaque, my bad
private NativeArray<Vector3> GetYCoordinates(NativeArray<Vector3> array)
{
Debug.Log("Using raycasts to find appropriate Y-axis value of each plant");
NativeArray<Vector3> newArray = new NativeArray<Vector3>(array.Length, Allocator.Persistent);
for (int i = 0; i < array.Length; i++)
{
Debug.Log("Attempting raycast...");
Physics.Raycast(new Vector3(array[i].x, 20, array[i].z), -transform.up, out RaycastHit hit, 200f, LayerMask.GetMask("Terrain Interact"), QueryTriggerInteraction.Ignore);
Debug.Log("Raycast success");
newArray[i] = new Vector3(array[i].x, hit.point.y - 0.43f, array[i].z);
}
Debug.Log($"Returning NativeArray of coordinates with appropriate Y-axis values of length {newArray.Length}");
return newArray;
}```
Currently trying to use this function within another IEnumerator function, but it never makes it past printing `Attempting raycast...` in the console. How would I go about fixing this?
To contextualize further, this is the IEnumerator function in question:
public IEnumerator GetChunkPlantData()
{
//Debug.Log("Waiting for DataFrame to exist before getting plant DataFrame and Array for terrain chunk");
while (parquetParser.df == null)
{
//Debug.Log("Waiting...");
yield return null;
}
//Debug.Log("Getting plant DataFrame and Array for terrain chunk");
Task.Run(() =>
{
//yield return new WaitUntil(() => parquetParser.df != null);
Vector2 rangeMin = parquetParser.GetCoordinateBoundMin(chunkIndex, 0.125f);
Vector2 rangeMax = parquetParser.GetCoordinateBoundMax(chunkIndex, 0.125f);
df = parquetParser.GetTerrainChunkDataFrame(rangeMin, rangeMax).Result;
if (df.Rows.Count >= 1)
{
NativeArray<Vector3> rawCoordinates = parquetParser.GetCoordinatesAsNativeArray(df).Result;
rawCoordinates = parquetParser.LocalizeCoordinateArray(rawCoordinates, rangeMin, rangeMax, 32).Result;
coordinates = DoubleInstanceCount(GetYCoordinates(rawCoordinates));
//Debug.Log(coordinates.Length);
StartRender();
}
});
}```
there you go, you're running it in a separate thread and not checking what happens
most of Unity's API is not thread safe
How do I go about checking what happens, then?
check if the task is faulted. Which it is, because you tried to access Physics.Raycast off the main thread. What are you doing with this? If you're trying to make it multithreaded with jobs, you're going about it the wrong way and what you're doing will be extra slow even once you run it on the main thread
Not exactly, this is gonna be running on a Quest 3 so I don't think I have the option to multi-thread. The intent is to just prevent everything from trying to process all at once and causing hard framedrops, though I only learned how to do that for other parts of my code through trial and error. I assume what I've got here isn't the right way to go about that
so rewrite your code so it does a little work every frame instead. Your current version tries to do all the work as fast as possible, except on a separate thread
Well.. that's the plan. I just don't know how to actually do that yet. Lol
But also, there's several instances of this script that will be running simultaneously
one for each procedurally generated chunk of terrain
Is there an established method for doing that kinda thing?
coroutine is the simplest method in Unity. Tasks can work (on main thread) and jobs, but it sounds like you should skip those for now
well, getting rid of the Task.Run surrounding the majority of the GetChunkPlantData() function freezes Unity lol
I assume parquestParser.LocalizeCoordinateArray is also a task, so you deadlock the main thread waiting on .Result
or GetCoordinatesAsNativeArray
Looks to me like this should be parallelized with jobs, not regular tasks
maybe, but I assume this parquetParser thing is some third party dependency and it'll be easier to get it running using coroutines + await on main thread first if they're struggling already
parquetParser I actually entirely wrote aheheh
It does rely on the Parquet.net library but that specific script is all my work
Here's that script in it's current state
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
honestly due to my lack of experience with optimization techniques, my strategy so far has been to basically just use async, await, and Task wherever I can until it works lmao
which kinda worked up until now
It’s unfortunately not a good strategy regarding concurrency to just ‘try until it works’
I figured lol
systems like jobs try to help you with avoiding most of the synchronization pitfalls
async does too
But you still have a few things that can go wrong
How would I go about converting everything to using jobs instead of what I've got rn?
It’s advisable to never use a void return in an asynchronous method
That would require it to be a Task return type then, I assume
Yes
You run that task synchronously in start with no handle on it. You should at least have it be canceled with the destroy token of the gameobject
TIL this was a thing, that's pretty cool. Would there be any particular reason to not just swap any raycast that doesn't need to happen instantly to this?
How would you go about only having part of the task running asynchronously?
it's designed to be used with the job system, so you'd have to re-architect some code. And just because it's running in parallel doesn't necessarily mean it's faster; you'd have to be doing enough work to justify the overhead of setting up and scheduling jobs
Yeah totally. I might give it a go and see, from my limited use of the job system so far I have seen very little overhead from job setup/scheduling, whereas physics always is noticeable so fingers crossed
also, upon attempting to convert GetParquetAsDataFrame's return type to Task<DataFrame> and throwing the ReadParquet call inside a Task.Run, the freezing returned
nevermind, realized that wasn't one of the things that needed changing
I guess you're referring to the StartRender function, then
private async void StartRender()
{
Debug.Log("Starting terrain chunk plant rendering");
await Task.Run(() =>
{
_drawArgsBuffer = CreateDrawArgsBufferForRenderMeshIndirect(_mesh, coordinates.Length);
_dataBuffer = CreateDataBuffer<Matrix4x4>(coordinates.Length);
var transformMatrixArray = TransformMatrixArrayFactory.Create(coordinates);
_dataBuffer.SetData(transformMatrixArray);
_material.SetBuffer("_TransformMatrixArray", _dataBuffer);
_material.SetVector("_BoundsOffset", transform.position);
transformMatrixArray.Dispose();
});
}```
What should the return type of this be, then?
I guess to contextualize again, this is meant to feed data into a compute shader
If I change it's return type to Task, then I need to call it with an await
but I can't do that because StartRender is called in GetChunkPlantData, which returns as an IEnumerator
You really want to use jobs. But if just want to move easily between main/other thread and coroutine/async you would be helped a lot by getting unitask (free asset). Which offers a lot of convenience to make the transition between all these paradigms
Sounds like exactly what I need, especially since I'm working on a deadline. Thanks ^^
Now I just need to figure out how to use this
I'm having trouble figuring out which functions should be what return type in regards to UniTask
like do I just make basically every function a UniTask?
oh shit wait I think it's working now
well.. kinda
the plant placement of every terrain chunk is identical and they're all being rendered way off from where they should be, but it's at least actually getting to that point now
Yes. And you can use await SwitchToThreadPool/MainThread to do work on a separate actual thread
Gotcha. I doubt I'll be able to take advantage of that, with me making this for Quest 3
That being said, I do now have the scene fully working, at least on windows
it just loads terribly slow
What would I need to do to actually take advantage of what UniTask is for, once basically all of the functions are of that return type?
Unitask just helps with making your async code clearer/explicit/succinct in the context of Unity. It also is supposed to be more performant since it represents tasks as structs and coordinates better with the engine. But performance isn’t really why you use async/await so that’s a marginal aspect (jobs are for performance).
A Quest 3, has an 8-core cpu, you can very much make use of multithreaded code on that platform. Ofc these cores aren’t all meant for performing heavy workloads but you should have at least 2 that you can utilize this way,
I've been avoiding foreach in Unity as it showed GC allocations in the past for me. I just did some testing to verify that, and was surprised that most native collections don't allocate GC anymore.
However, Dictionary still does -- but only on the initial enumeration, as it lazily creates instances of KeyCollection when accessing the Keys property for example. (AttributeTable is a custom class implementing a custom struct-based enumerator that uses Dictionary.Enumerator under the hood, which is why its showing equal results)
Is this consistent with everyone's results? What's the verdict? To use or not to use foreach?
These results seem to confirm to me that it's kinda safe to use nowadays. The tests were done in 2022.3.29f1.
This was fixed a long time ago. It aligns with expectations that iterations on the base collection without intermediate lazily evaluated projection do not allocate. foreach has been fine since 5.5 iirc.
I have created a package with a Unity Editor menu item. It works properly in the package main project, but when I install it as a package (from git), the menu item does not show up. I created an asmdef file for the package, and specified that it should use unity editor, and while that eliminated a warning when the package was installed, that did not help with the menu item not showing up. What are the steps I need to take to make this work, and/or can you help me find the docs for this particular bit?
here is the git repo.. a very simple project (JUST the menu item): https://github.com/glurth/OpenDataPathsWindow
got it looks like a bug, but I did muck around with the file in a text editor at some point, so maybe not. Solution: click select all, save, click deselect all, select editor only, save. fixed.
asmdef:
It keeps saying that the template checker is having an error and it doesn’t let me add items
hi, anyone knows how to create a 3x3 rotation matrix from a quaternion ?
there should be a built in function
quaternion.ToMatrix4x4 doesn't work since there is no translation information
I have implemented a load/save system in my game.
Each component requires to implement an interface with two methods LoadData and SaveData. Then to save data, it should create a new data instance and for loading, after taking the argument it populates and sets its fields
I have decompiled the game Oxygen not included and cannot find any methods like Load and Save methods in its components.
Is there any simpler way to handle it and implement a save/load system or I should decide which data should be saved/loaded for each component? There are over 500 components in my game:/
One alternative is to treat your gamestate as one big blob of data which you can save/load all at once (or in portions that make sense for what your game is)
Im trying to make it so that if this object is over 5 away from target it walks towards it, any ideas on why it doesnt stop?
why do you set the destination every frame?
im not really good with c sharp do you know how else i can do it?
this has nothing to do with C#. It's logic. Think about what you are trying to do
i dont really know , can you help?
no, this is hardly advanced code.
surely your logic should be.
if I have no destination and the destination is > 5 units away set the destination
if I have a destination and I have arrived stop
oh yes, do not cross post
tysm i just got it
just answer me one question, for someone who obviously knows nothing about programming why post in the code advanced channel?
idk i just clicked on a random one
I thought as much. It's a good job we put more thought into what we do than you isn't it?
yess
so next time show some bloody respect
how was i disrespectful?
so? i didnt show any "disrespect" by asking a question
you did by not caring where you posted it
or worse, did not even think you had to care
does it matter? i will post it on the begginer one next time? i was just asking a bloody question
yes it matters and if you don't see that I feel sorry for you
Please stop being aggressive to people, there's no benefit to anyone, if you're annoyed at someone's behaviour either call them out politely or go outside
And yes, please don't cross-post and don't post basic questions in advanced channels. This behaviour doesn't warrant arguing about it from either direction
There are many ways to do it, that single gamestate blob often mentioned is just as complex/annoying as any other option (like your on-demand dump). It really comes down to what the team lead believes is the best way. In reality there isn’t one, or in other words they are all the same thing in the end, just sliced differently. The complexities don’t go away. The hard part, anyway, isn’t saving stuff, it’s loading and data migration.
Looking at the possibility of using jobs to speed up my custom terrain generator https://github.com/BradFitz66/Stylized-Terrain-URP
The basic concept of the algorithm is an extension of marching squares. It loops through a 2D array and compares 4 height values to determine what rule should be used. Since marching squares itself is considered "embarrassingly parallel", I've wondered how easy it work be to utilize the the jobs system for this
However, there isn't much resources on mesh generation with DOTs/Jobs System and I'm not sure where to start
It's done a lot more with compute shaders imho
Why go 10x faster, when you can go 100x faster?
And I think there are a lot more learning materials with that approach.
? learn to use job system to manipulate NativeArrays, assign mesh data using them. I wouldn't use compute shaders for terrain unless you don't need to do anything with it on the cpu
Hi! I'm doing 2d space shooter. I'm trying to understand how to properly despawn enemies that goes offscreen.
I do know that it's better to have pools and reuse objects, but my main issue as of now is how to understand how to get info when to despawn object.
I based my logic on renderer.IsVisible, but I wonder if it's good idea since doing the game for mobile I will have different screens and sometimes I may have like lines on the sides to fit game area properly. Like here, left and right sides will be sill considered renderer as Visible.
Screen not from my game, just an example.
Another option I found is put big collider on scene and use trigger enter trigger exit, but I'm not sure if it's good performance wise.
Could someone please help me understand how it's better done?
Just precalc the visible coordinates of your camera, add some extra margin and remove them once they're out of those bounds?
do you control their movement and if so, why are they going offscreen? should every enemy really just fully disappear the instant it goes offscreen?
as in, the easiest solution is to ensure they never go offscreen, and that also maybe makes sense from a gameplay perspective
it's by desing - enemy flying from top to bottom and if you kill enemy, you get points, if not - it's just flies away.
The big collider option is a good one. That really shouldn't hurt performance noticeably
As dlich has said I recommend compute shaders as well for this.
Just out of curiosity how does marching squares work here? I assume you have a 2D heightmap, but if you wanna make a mesh out of that it should be the same winding pattern for every square—not really marching squares.
This should be reworded as “immediately” on the cpu. GPU readback is not as slow as you might think—the bulk of the time is taken flushing your previous commands so if you can afford a 1 frame delay to use AsyncReadback, it’s almost always faster than a Job implementation.
Even if it compute shaders are faster, it can still lead to less FPS. If your game is GPU bottlenecked, which many are, adding another task for the GPU to finish will make the FPS lower. Whereas the CPU is just waiting around not doing anything anyway.
Plus, the CPU can do things on separate threads and not increase its frame time with additional background threads, while the GPU has many cores but only does one task at a time. Dispatching a compute shader will take away time that could have been spent on graphics. Some GPUs support async compute that can run alongside graphics, but you have to use a special API in Unity to use that and it's not a silver bullet.
But you might also be CPU bottlenecked, or you may add more tasks for the CPU to do later, tasks that are not as easily doable on the GPU as this terrain generation is. In that case, the GPU is the best place to put it.
I agree that it should be considered thoroughly. I just mentioned compute shaders, because I've barely seen any procedural terrain tutorials that use jobs or just a background thread/thread pool.
Hello, someone know is it possible to publish new games in facebook instant games right now?
All I can really say is to look at the code for deeper understanding on the inner workings of the generator - I'm awful at explaining this stuff. https://github.com/BradFitz66/Stylized-Terrain-URP/blob/main/Runtime/Scripts/MarchingSquaresChunk.cs#L134-L521
But basically: loop over 2D heightmap. Every 4 points in the heightmap is the corner of a cell, rules are computed based off the difference in height values of the corners as-well as the edges of the cells.
this is the kind of geometry that is generated
So are you making a vertical face if the height difference is above a certain threshold? That's pretty interesting.
Here's a compute shader implementation for marching squares I made a while ago, it's coded very similarly to the quintessential paper on marching cubes by paul bourke(with a LUT).
A perfect hashmap is used to remove duplicate vertices(i.e. vertices are only created on the lower two edges of the square.
It's based off of t3ssel8r's pixel art terrain system, which they state is also "loosely based off of marching squares"
I'll take a look at that though, thanks!
what am i doing wrong here, I cant for the life of me fix this
What does the error say
(there actually is no error)
it doesnt say anything, it just doesnt work
in what way does it not work
it doesnt put all the GayBoys in itself as children
There are probably simply not any GameObjects with that name
there are hundreds
Why don't you add some Debug.Log statements and see
Make sure the code is even running at all, for example
It runs, but it doesnt have any bugs according to the command line, so i dont think i need to use a debug/log?
but it doesnt have any bugs according to the command line
What?
it definitely has a bug or you wouldn't be here
A bug simply means the code is not working as you expect
it has a bug, but unity didnt detect one, so how would a debug log help me?
It would tell you if the code is even running
That's the whole pooint of Debug.Log. To give you more information
Why would you need one if Unity DID "detect" an error?
Anyway you should really do FindObjectsOfType<GameObject> instead of what you have here
I would do this:
void Update() {
GameObject[] allObjects = FindObjectsOfType<GameObject>();
Debug.Log($"Found {allObjects.Length} objects");
}```
to start with
This is... #💻┃code-beginner btw
im not a beginner though
If you don't understand how to use Debug.Log and your code looks the way it does... I would disagree
nevermind, my code was perfect, i just forgot to put the script on the game object. #BeenthereDoneThatAmIRight?
Adding Debug.Log would have revealed this information to you
(by virtue of not printing anything)
That's why we always check "is this code even running" first
You said that the code runs too. Was that a lie?
no ti was running, the editor did not break
How was it running if the script was not attached to a GameObject in the scene?😅
Compiled != running.
This is also an obvious thing if you're not a beginner.
im not a beginner tho, im just self taught thats all
You can be self though and a beginner at the same time. These things don't contradict each other.
And there's nothing bad about being a beginner. It's worse if you can't admit that and post in the wrong channel.
To make it clear, the channel to post to is not decided by your level of expertise, but rather by the issue. And this issue is definitely not advanced.
Agree to disagree 🙂
im trying to make a racing game and ive got a position tracker which uses checkpoints to see how many a player has, but the ai and player are not going through at checkpoint 15 and im not sure why, they are the exact same as the other checkpoints. the script is in the text shown
What does:
not going through at checkpoint 15
mean exactly?
not going through what
the cars arent going through the checkpoint
arrays start at 0
You mean... it's not detecting them going through it?
Or it's physically not going throught it?
not detecting
so what debugging stps have you taken so far?
It looks like: if (distanceToNextWaypoint < 5f) this is the condition
So presumably that is never true
start debugging and seeing why
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hello! Can someone please suggest me good approach to move objects along trajectory?
The game is space shooter, enemies goes from top to bottom, and player at the bottom shooting them.
I've done movement just down, giving enemy Vector3.down and it works fine.
Now I want to have more advanced movement, so they fly like snake, or zig-zag or in spiral.
I thinking about two approaches.
- Create Prefab with list of Transforms that provides me points where enemy should go, and I iterate through those points and move through those.
- Use Unity3d Splines - I can create Spline and it has Animate option, so basically logic from Option 1 is done by unity.
Do you have some expirience with those two approaches? Which one is better or may be you use for your game?
Splines are great for making specific curved shapes. You could also automatically generate them from control points.
You could combine a spline with a "physics-based" movement. Not an actual Rigidbody, necessarily -- just making the enemy accelerate towards a target position instead of directly moving towards it
Option 3: Animate them with code.
Personally I like the splines.
Option 1 is basically a much less flexible/configurable/usable version of option 2.
So will stick with splines and will see how it goes. At least for "generic" enemies it's good enouhg. And for ones with some specific behaviour I can code it if needed.
Thanks)
Hello, if we change all game object name to be empty, then it can reduce memory usage ?
not noticably, no. Also, not a code question
Not sure if this counts as advanced but general is in use atm.
I keep getting this error message for line 95. The weird part is it only occurs when the IF on line 79 is true, if it's false then there is no error.
I've tried googling it but the results only show for a different error message saying "in state Element Content" and suggest a WriteStartElement() isn't being closed by a WriteEndElement() which isn't the case here.
Please ping me if you have an answer. This has been bugging me for a few days now.
The error message: "InvalidOperationException: Token StartAttribute in state Content would result in an invalid XML document."
it looks like you could hit that line after previously going through the loop above which does start/end element, you wouldn't be able to add new attributes to the outer tag at that point, you've already started adding children to it
just to check does the name of connectedcoordsver have a space in it
Ohhh. I didn't know I couldn't add attributes after children. Thank you very much
think about it as literally printing out the xml character by character, the attributes have to all be in the opening tag, there's no adding them in after the children 😄
ps. you should have start and end element around the whole file idk if you've done it elsewhere
I should?
Just tested it and there is no more error. Thank you both very much 💚
Ye you should have a root element that holds everything else
Silly explanation but XML isn’t totally dissimilar to a bunch of classes right
U don’t want variables just… out in the open not in a class
A full file should be wrapped in one element
Okay. I'll add that too
Hi i have a program whose create a Procedural maze but i have some problems with the code:
The code are:
How i can solve the maze productions
Are you really just gonna dump a big script on us and say "this isn't working, fix it?"
The answer is:
Step 1. Understand the algorithm. You need to know how it's supposed to work in order to write it and debug it properly
Step 2. Debug the code. Step through it with a debugger and/or add log statements to make sure everything is going correctly every step of the way.
Step 3. When you identify where the error is in step 2, fix it.
Why this 2 plugins allow me to choose bewtween different configurations? One doesn't allow me to choose the CPU architecture
wdym the other doesn't allow you to choose the scripting backend?
does it not have options for that selectbox?
Ups, both allow me the scripting backend, but only one the CPU
I think the problem is in the moment of create the maze, no building it
Oh, so Unity automatically detect it. Ok
What's the difference between "creating" the maze and "building" the maze? And how does that change what my answer is?
I'm not sure if this will cause total failure to work on an ARM platform, or if it'll just mean that x86 emulation is needed
I develop on an ARM macbook, so I'm in a prime position to experience this, at least...
The building moment is when the program create a matrix with the positions of the wall = 1 and the roads 0, and the building is when the program put the corresponding prefabs in their places
Mac is not in our target platforms atm. Currently I'm just trying to make this build in Xbox. First time doing that hehe
Hi guys! We keep getting this error in our scene in Unity and we do not know how to fix it. - it currently does not let us edit anything, even if we do not edit anything and press save pc crashes with this exact error every single time. currently using unity version control
Well certianly seems to be a memory issue of some kind. You should look at the editor log itself, as it will contain more information
Oh, i didn´t saw that channel, sorry.
You might have a memory leak, or Unity itself or a package might have a memory leak, or you're actually legitimately running out of memory.
How could I fix the leak?
That's not a memory leak
well, at least...
the pressing issue is that the editor just tried to allocate three gigabytes of memory all at once
That's a lot of memory.
Although it's not a catastrophically large number (e.g. INT_MAX)
I wonder if this is the result of something else getting corrupted. You could try deleting the Library folder to force Unity to reimport everything.
Is this happening to everyone trying to collaborate on the project?
We haven't determined it's a leak yet
I made an Oopsie Woopsie once where an editor script doubled the number of probes in a light probe group over and over
This caused some very funny editor behavior
(it was supposed to copy them into another group, but I accidentally targeted the template!)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
That looks like it's trying to allocate a 3GB string. Doesn't sound normal at all.
Having a look at the logs or attaching a debugger to the editor process might provide more details.
Did they remove the Tree Map from the more recent versions of the Unity Memory Profiler? I can't seem to find it anymore, it was super helpful for visualizing what is actually consuming application memory
what, you don't allocate 3GB strings?
💥
I was trying to figure out if that was some kind of larger data structure or literally just 3 gigs of text
I bet it's just an invalid/released pointer passed somewhere.
You usually don't allocate 3gb in one go no matter what data it is for.
The weird thing is that it's not that huge
it's not 400 petabytes or something really funny
3GB is kind of believable
ish
It's just a matter of what was at that memory address at that time. It's not weird to get any number at all.
How does everyone handle culling and scenes with very large amounts of GO's (1mil+)? Got a relatively fast burstified/jobbed frustrum culler going, uses SetActive and just enables/disables GOs at the moment but not sure if that's the best way to go about it.
I mean 1m GOs sounds like too many culling or not but... is the normal frustum culler not performant enough or something?
It's specifically for trees but also kind of want a system that I can use for other stuff. Builtin terrain (unsurprisingly) doesn't like handling that many, and gets totally blocked on culling (not just frustrum, culling in general).
LODs, frustum culling, occulusion culling, gpu occlusion culling, far clipping plane, proximity deactivation
I have an issue related to the inventory. The inventory itself can hold a reference to CurrentItem, which is a class of type Item. When I try to place my Item in a slot, and in this case, for example, it's itemGun, I cannot access itemGun because it is a child class of Item. Yes, everything works fine with CurrentItem, but even casting it to the specific type doesn’t allow me to access the child object.What I need is to get a reference to the child object from inventorySlot. Imagine I need to calculate the total number of bullets in a gun, but my inventory can hold any type of weapon. However, I can only access the fields of the base class.Please, could you tell me how to access child classes without resulting in null, or how I can organize the logic so that I can still read the required fields?
this is not necessarily an advanced question but i need a lot, pls help!
It's hard to say without seeing your code, but if you have a reference to CurrentItem which is of Type Item and itemGun extends Item then you should be able to something like this:
ItemGun theGun = CurrentItem as ItemGun;
theGun.getNumberOfBulletsInGunOrWhatever();
using "as" is a Type Cast which you said you can't do, but without seeing your code, I can't imagine why that would be
Suppose i have the following folder/file : folder1, folder2, asmdf1.asmdf. Inside folder 1 is test1.cs, and inside folder 2 is test2.cs, asmdf2.asmdf. My question is: is test1.cs part of asmdf1? And is test2.cs part of asmdf1 or asmdf2 ? Does asmdf1 need to reference asmdf2 to use test2.cs?
Im still trying to wrap my head on how nested asmdf work in unity
I meant asmdef not asmdf sorry i forgot the e
The scripts are a part of the assembly that is their nearest ancestor (including the current folder)
Yes, you need to create references between assemblies
Also, if you just made these folders and files, you would've seen what's part of what and what can reference what 😛
Instead of enabling/disabling the whole GO you could use https://docs.unity3d.com/ScriptReference/Renderer-forceRenderingOff.html
Although then you'd probably need to cache references to the renderers somewhere
Ah that looks exactly like what I was missing, thanks
Yeah I'm caching LODGroups anyway
Ok thanks
can anyone help with this error for user authentication, everything works but i still get this error?
Hey, I am building an IOS app and while everything works fine in editor. I am unable to build to test on device. I am getting this error when attempting to build. I am using this Macfor building and testing but using my Windows PC for coding and such and version control to marry the 2.
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.Rendering.RenderPipelineGraphicsSettingsStripper.PerformStripping (System.Collections.Generic.List`1[T] settingsList, System.Collections.Generic.List`1[T] runtimeSettingsList) (at ./Library/PackageCache/com.unity.render-pipelines.core@16.0.6/Runtime/Stripping/RenderPipelineGraphicsSettingsStripper.cs:43)
UnityEngine.Rendering.RenderPipelineGraphicsSettingsContainer.OnBeforeSerialize () (at ./Library/PackageCache/com.unity.render-pipelines.core@16.0.6/Runtime/RenderPipeline/RenderPipelineGraphicsSettingsContainer.cs:44)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&) (at /Users/bokken/build/output/unity/unity/Modules/IMGUI/GUIUtility.cs:219)
I would not render with go’s at all. For one mill plus the only way is drawinstancedindirect and culling on the gpu
The fact that you will have to iterate over the renderers will kill performance
yeah -- imagine that you somehow do culling on each game object in one cpu cycle
a 1ghz processor would still need a millisecond to do that
trees aren't moving around, so you shouldn't need to shove that much data onto the GPU every frame
You do that kind of thing via GPU instancing where you calculate the culling and transforms in a compute shader, leave them in a buffer on the GPU and render meshes with an indexed shader into that buffer. Have a look at assets like Foliage Renderer, GPU Instancer, Nature Renderer, Vegetation Studio and even VFX Graph. Culling and streaming chunks/masks into that buffer in a performant way are usually non trivial. Most people end up using an asset that already solves all this for complex projects. See also https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstancedIndirect.html
Alternatively you can use Entities. The Unite 24 cinematic trailer does the culling/tranforms of its grass via Entities on top of a point cloud (so no instancing).
I'm old fashion, just toss some fog onto the scene and change that clipping plane then call it a day. If anything I'm more concerned about the colliders so the entities idea is probably the ideal solution if the collision isn't baked onto a bunch.
Entities + colliders removes most of the performance from entities. Everything that’s supposed to be performant needs to stick to very rigid protocols for maintaining data locality. those usually are not transferable to/from object-oriented thinking. Colliders, as a concept, hint at non deterministic random references between objects, those usually break locality and require sync points which break parallelism
If the trees cant be moved then I'd just bake it into static chunks and use unity's 'new' gpu culling if we want an uncapped clipping plane
and similarly you handle the collision by the chunks so you aren't iterating through each individual gameobject
you would handle collisions by a nearest neighbor lookup in an indexed data structure, iterating all objects would be absurd even in trivial cases
is it just me or does the economy api feel kinda half-assed?
it seems like its designed for singleplayer mobile games
what do you expect from it?
the ability to have server authority over player economy
my game uses dedicated servers and i want the server to give players money for a win, for example
but the economy api isnt designed for that
wow I've never even heard of this but it seems like it's designed for if you don't have your own servers
It’s aimed at enabling microtransactions
if you do, why not just track this stuff on there?
my "own servers" are unity multiplay
it feels like they offered a dedicated server solution and then half assed everything else to exclude it
i wanted to keep everything in the unity ecosystem but i dont see how i can make this work
at this point i might just write my own full backend and host on a vps
you may want to compare ugs with playfab, which is the opposite of simple, but can do anything
yeah, this is unity so I wouldn't be surprised if you're right, and everything is being made by varying teams who don't really communicate with no clear overall vision
but there are full service platforms out there that do actually work (like playfab)
DIY‘ing s backend of a live service game is a significant investment
its nothing crazy
except for the whole
dynamically opening and reserving server instances to scale with the player count and somehow have those communicate with a master server that manages the database part
that seems a bit tricky
the complexity is in silly and annoying stuff that has nothing to do with your game, like security, availability, provisioning, scaling etc.
yup
is it a realtime game?
mmm yeah I wouldn't wing that
structurally its the same as a game like among us
players join a lobby, blah blah, winners and losers, taken back to main menu afterwards
have you looked at photon's solutions at all?
maybe they don't solve for stuff like microtransactions either
but honestly, having your microtransactions handled by a backend that is mostly decoupled from your game seems good to me
i guess i could just use firebase or something for that
but id have to figure out how to allow the game servers on multiplay to communicate with firebase
ive never used cloud solutions like multiplay tbh
ive always just self hosted on a dell optiplex
but i cant imagine something like an ip filter on firebase would work
just use playfab, seriously
but the pricing 😭
firebase is not designed for games
well itd just be for storing player data
thats what im caught up on really
my game will have currency, accessories, loadouts, etc
that arent rapidly changing
something like dead by daylight
yeah I do imagine that there is some way for multiplay to do what you need but I don't know what it is, and I wouldn't be taht surprised if there actually isn't a reasonable one
actually dbd is a perfect model for what im trying to pull off
dbd uses amazon gamelift
with playfab you can start with managed services and gradually run your own backend if you like, it’s just azure at the end of the day
what about it gets in your way here?
its not server authoritative
my dedicated server should have control over giving the player items
well, yeah, nothing will be if the game client is allowed to hit the "set currency" endpoint
the game server is supposed to be doing that, not the clients
"round ends, give player 500 coins" sorta thing
