#archived-code-advanced
1 messages Β· Page 2 of 1
"the type or namespace 'mirror' could not be found"
so once you stopped ReadPixels you stopped waiting for the render thread to finish
why cant it find mirror anymore?
not really though - you stopped waiting on the GPU to finish, which happens after render thread's job is done
that's why async gpu readback is talking about "latency"
they mean with respect to which game frame you are on at the moment you receive the callback
when you do async request on game frame 0, by the time the callback is called, you are usually on the main thread executing game thread 1 or 2
then again, if your main thread + render thread + gpu work is altogether less than 16ms, you will get the callback on the same frame.
i am on my macOS laptop so i just can't show you the GPU work bar in the hierarchy
but i think you can see now
that suppose render thread was also gpu work
well they overlap
so don't wait for it
why is my scene so slow? i have like a million tris and a complex interaction with shadows
here you mean GPU or CPU?
ah sorry
what it really is is
"all the work here, there is no gameplay (meaning main thread) dependencies on it"
when you do readpixels
aha
as far as unity is concerned, you are using the texture for gameplay
main thread == gameplay
got it
part of this is that it was always a bad idea to let people use X which 99% of the time does not impact gameplay but because of the 1% of the 1% that does, it assumes all 100% impacts gameplay
exhibit A: physics
so... basically... unity thought i was going to use that texture... and i was blocking the main thread because of it
because
it thought it was for gameplay
shit but... yeah got it but, damn,
they tell you, " do this inside the lateupdate bla blΓ±a bla"
but dont tell you that
when you do the other api calls they internally create a dependency graph
of operations
called command buffers (really appending to the current frame's command buffer)
that expresses inputs and outputs, like a visual programming tool / shader graph
you don't get access to any of the data on the main thread
that's the point
alright good luck out there
just this last thing
i read and read again, as i said today is not my best day
this api call thing
AsyncGPUReadback.RequestIntoNativeArray
what we did with that is ignore the dependencies youre mentioning?
and simply tell unity... do this and shut the fuck up
is it like that?
what we did is say we DO have a dependency but not on this frame
so rendering gameplay frame 0 might finish in the middle of computing gameplay frame 1 or 2
async gpu readback is a way to get rendered content of frame 0 in the "middle" of doing the gameplay for frame 2, for example
instead of in gameplay frame 0
because rendering overlaps with gameplay
clearly you still have a dependency - it's just limited to the code in the callback
instead of potentially everything that takes place while doing gameplay
I like seeing that "saved by batching" stat π
just wanted to confirm one thing, Graphics.RenderMeshInstanced in Update is not an anti-pattern right ?
my other high priority is to cut the gameobject count, even more than optimizing the rendering, that seems to help too
also need to reread your advice on shadows, noticed that there're no shadows being cast by those trees
but are your trees actually static?
no
you're adding a command to a big queue
that's pretty standard
I'm very new to rendering, afaik trees are animated by vertex shaders and I'm not sure if that is considered static or not
I was agreeing with you doc π
As long as the GameObject is not moving (the Transform) it's static afaik
right now they are static, but I do want to add animation down the line
In the context of batching you have to mark it as static
and it doesn't care about vertex shaders
In fact, you could mark it as static and then move it, although the mesh itself won't move with the transform : p
still not sure if gpu instancing will fit my case, but it's definitely good information to learn and keep in mind π
Definitely test
I recently discovered that on older hardware my game is about 10fps slower with GPU instancing enabled : S
I'll need to see how fast it works when there're conditions involved
I shouldn't use instanced meshes when the player is nearby, which means I have to filter the array of transform matrices, which may be worse in the end
so yeah, need to benchmark different methods
is this in Metal?
My uneducated guess is that since there's a small initial overhead when rendering GPU instanced objects and we weren't actually drawing that many objects, it came out worse. That probably is irrelevant to you rendering 6 million trees tho
metal as in metal workflow ?
Also, impostors
for vegetation is definitely an option
If you have like a LOT of it, from far away it probably won't be very noticeable
I had 2 questions hoping someone can answer, I have been reading the documentation a ton but cannot seem to find exactly what I am looking for.
- Is there any way to know on a tilemap what tiles have something placed in them?
- Is there any way to place tile grouping on the same tilemap
I have a lot, but not that much, it was just a technical test lol
I can elaborate far better for my exact situation
metal as in macOS metal
can anyone help me i keep getting these errors
Assets\Scripts\GamePlayScripts\CollectableTrashScript.cs(5,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'CollectableTrashScript'
Assets\Scripts\GamePlayScripts\CollectableTrashScript.cs(11,10): error CS0111: Type 'CollectableTrashScript' already defines a member called 'Update' with the same parameter types
Assets\Scripts\GamePlayScripts\CollectableTrashScript.cs(16,18): error CS0111: Type 'CollectableTrashScript' already defines a member called 'OnTriggerEnter2D' with the same parameter types
it's telling you what hte issue is
#π»βcode-beginner you have duplicated the script or class
something placed in them
you have to keep track of where your character or props are on a tilemap
yeah i just have no clue how to pin point the issue
Is there any way to place tile grouping on the same tilemap
you can create your own array of indices if you need "groups". not sure what you mean by tile grouping though, maybe that's something specific to tilemaps
i think if you're at 144 fps you're fine
change nothing
its specifically in the sense that, right now the way my system works is that i create these room prefabs that all have their own tile map and renderers, but i was trying to figure out if I can instantiate onto the same tilemap
and I see, i might need to figure out a system for trying to remember that then
i think you can define a brush, but no, the unity built in tilemap isn't powerful enough for something like that out of the box
you can search for an asset store asset that might help you
I see I see. Thank you for the help
I do not know if this is advanced per se, but I'd like to find a random point along the edge of a box. I know I can use something like Random.randomOnUintSphere, but I can't think of the maths to get a distance from the center of a box to that direction intersecting with a face of said box
I guess that would not be exactly a random point though, as it would be more prevalant towards the centers of the faces
when you say edge of a box
do you mean edge of a 2d rectangle?
edges of a 3d rectangular prism (i.e. scaled cube)...
you can sample a random point on the surface of a 3d shape using its UV mapping
for a 2d shape, you can do something similar using its outline. it's up to you to define the mapping
UVs do not guarantee the likelihood of sampling any point on the surface is the same
in principle, for 3d you can do something of the form
random triangle = float between 0...1 sampling a normalized map of triangle areas to triangles
random point on triangle = random barycentric normalized coordinate to world space
for 2d, you can think of it the same way. sort the line segments into an interval map (interval length is segment length) and sample it using a random number.
@gritty nacelle does that make sense?
π€ random point on an edge of a box?
- have a list of edges (there should be 12, each connect the 2 of the 8 corners of the box)
- get random edge from the list
- interpolate between the edge's corners position using random value
it's trickier if you want equal density of probability throughout the shape
otherwise the shape might as well not matter
your method will put way more points on the short edge than the long edge of a rectangle
that if you drew a rectangle over a field of random points and counted the ones that fell on every line
How do people do serialization? All the tutorials I've found are super basic, they don't go into serializing object relations. For example if I have a list of GameObjects, I can fairly easily serialize the data in it, but the problem is instantiating the actual prefab for it.
Put everything in a Resource folder & then generate an association to it with its path in an editor script?
as you said, you already have a list of gos... then instantiate those? π
I see zero correlation between serialization and instantiation
Yeah, I usually go that route, either using prefab name and load only the file with said name, or load all files in specific directory and get prefab with matching ID.
I usually use the later for in game items where I would mosy likely ends up loading multiple items
The problem is that those GOs are created during gameplay, when the scene is loaded during loading they won't be there, so they must first be instantiated before being fed the deserialized data. Unless one wants to serialize all the components and all their associated data, which I don't think really is feasible.
you cant serialize gameobject into a plain string and expect that it can be deserialized back into the same gameobject
Cool, then I know that I'm not the only one going down that route
You are. They're doing something different I think, using prefabs
I use addressables to instantiate prefabs at runtime
the system has lots of nice things like async load, usage tracking, async loading for groups of resources by tag, and so on
not sure if that was your question though
I believe you have to come up with your own ID system to serialize references. All prefabs that you spawn and want to save probably should have some component (or external lookup) that has their prefab ID.
it's complicated, my work station is way above the hardware I want to target
so I look at the resource load values and compare to games that have similar hardware requirements
it's a very rough estimate, but I don't have anything better rn
Sweet I'll have a look at that
Yeah I'll go with putting everything in resources & associating their resource path with a component on the prefab such that I can serialize that path & instantiate it again at load time to fill it up with the deserialized data
Also might look into AssetDatabase, think it has a method for creating a prefab
Sounds like it could simplify what you're trying to do maybe
Nvm, PrefabUtility not AssetDatabase: https://docs.unity3d.com/ScriptReference/PrefabUtility.SaveAsPrefabAsset.html
Yea my advice was made with the assumption that you would need this in build
Editor should have more options and IDs available
Why not have a manager to handle those prefabs, so when the go intantiated, you'd want to keep the stats/state of that go e.g: guid, position, name, rotation etc.. just the stats, nothing else.. and serialize with whatever
Then later on, when loading your save file, you re-create those objects. which a common way to do for save system
you said Unless one wants to serialize all the components and all their associated data , not quite sure what you mean by saving a component.. all and all, just the important bits
is there anyway to grab an enumerator out of a dll file or should i just manually recreate them in c#?
Man you're doing this blindly since yesterday π« recreate the enum on c# side, then do marshalling,,,
I bet you wont get this kind of answer here, you'll have much luck on c# discord instead
Speaking of which, any chance I could get a link to that? I figure there are many
Marshalling?
The C# discord, sorry
Sorry on my phone, dont know how to send invite
ok thank you so much! Doing stuff blindly is the way i do most of my stuff in unity lol!
Someone else got me, thanks @novel plinth
See.. the bot wont allow me to post c# discord link. Lol
Ah yeah forgot it'll eat them
C# discord team will do a live conf soon regarding editor tooling for game development.
Im not sure if this is proper to post it here, if not then feel free to delete it
Might be useful to broaden your editor tooling skills
Sounds useful, thanks
just FYI, the link to it is pinned in #archived-code-general if you ever need to redirect someone to it again
is someone familiar with this?
the first 2 captures got that weird texture
for them im trying to use this
I wanna say I've seen this before and the solution was clearing the GPU's buffer before changing the data in it
Question seems better suited for #archived-shaders imo
thanks
Collider[] hitColliders = Physics.OverlapSphere(center, (float)0.1);
how to use it in a thread that is not the main thread?
Unity physics doesn't support multithread at all
And there is no way to trick it?
you don't need to trick it
they do provide some tools to perform physics queries in other threads. e.g. https://docs.unity3d.com/ScriptReference/SpherecastCommand.html
I don't understand how to change this Collider[] hitColliders = Physics.OverlapSphere(center, (float)0.1); to a SpherecastCommand
start by looking at the example in the docs
And how to do it?
yeah the error tells you exactly what to do
It says right there
you should be starting your job from the main thread basically
Main thread and dispose the NativeArray
How to do that?
well right now you're running your code in a separate managed thread:
Thread thread1 = new Thread(checkChunksForever);
thread1.Start();```
don't do that
Hiya, not sure if there's a channel for Unity Cloud Build specifically, so I think this is the next best channel? Is it possible to push a build into a docker repository with a post-build script in UCB?
how to set the device so it pauses when we are looking at the profiler ?
You can stop recording on the profiler
yeah but i've seen its possible to set it so the device stops
You can use breakpoints with a debugger
I've not seen pausing the game via the profiler when you're looking at a build tho
yes, theres an option hidden somewhere called run in background that you turn off but i cant find it
but maybe ill do the breakpoint thing
Hmm, I don't recall that option
saw it on a video and seemed like it was in build settings but now i cant find the video or the option π€£ anyway its ok
can anyone help with Search Windows?
it is very hot here, and I am struggling to find a solution
it has a lot of elements in it, and is very laggy, as the elements inside folders are also added, even if you don't open any of the folders
a solution I found was to open a new window every time you select a "fake" folder
however I have no idea what the best way to design this would be
Is stopWatch a wrong way to measure performance on scripts? im seeing a huge difference of what the StopWatch calculated and what the profiler is showing
It is good at getting rough idea of performance of certain parts of scripts but its not that good if you want to profile very small period of time or want very accurate results. For example if you want to know which of two methods would be faster, stopwatch should work well enough (if the methods takes small amount of time, just put them inside for loop for better measure)
thanks AleksiH
I'm trying to write an algorithm that computes belief/likelihood based on uncertain evidence, but I'm having some trouble and would appreciate any help.
I have a list of 'event evidence' objects.
- Each of these evidence objects is a struct with a set of attribute variables that describe a specific hypothetical event (like 'time', 'place', 'subject', verb' etc..).
- Any of these attribute variables can be null, which would make the evidence object an incomplete description.
- Evidence objects conflict with one other when they have different (and not null) values for the same attribute. (eg. an evidence that contains place=school would conflict with an evidence that contains place=church).
- Each evidence object also has a 'source' variable that points to the specific person who gave the description, and a trust variable which denotes how much I trust this source.
I want to compute, based only on this list of evidence, the belief that at least one of the event descriptions in the list describes a true event.
- This belief should be higher if multiple different sources give descriptions that align(don't conflict) with each other. But if one source gives multiple aligning descriptions, this shouldn't count more than if they had just given one combined description.
- It's possible that none of the descriptions are true, meaning all the sources mistakenly shared false descriptions, and none of the events happened.
- It's also possible that multiple conflicting descriptions are all true, and refer to multiple different true events that all happened. The list of evidence objects could contain descriptions for any number of true events.
I've tried so many different approaches, but I can't find the right one. I think the answer may be in Bayesian Networks, fuzzy clustering algorithms, or Dempster-Shafer Belief functions. Can anyone help point me in the right direction? Thanks in advance.
I want to create an effect with line renderer like in those fps games where you start throwing a granade and the line of where you are going to drop shows up
I tried with vector3.slerp but curvature direction is different if start position and end positions change
Could you recommend what to use?
I am not asking for the code, but just an input where to start
you basically need to do the physics simulation. keep track of position and velocity of the imaginary thrown object and loop through each Time.fixedTimeStep and simulate how the position and velocity will change in each step, and save the positions to use for your line renderer
I am not going to use physics in my game
I have preset start and end position
I only need a curvature between start and end points
you are looking for a bayesian network
raycast finds end position
and start position is camera
and camera is always above the raycast hit position
ok so set those as the two points on your LineRenderer, done.
But I need it to be curved
curved according to what rules
is it always the first two captures? you might have to specify the graphics formats on both the destination texture and the redner texture. however in URP they should never change between camera renders...
I don't know, could you elaborate more, I probably don't understand something. So you are saying that I need physics to make a curvature? Can't I just create mathematically curvature?
Physics and math are one and the same
I'm saying you want to draw some curvature
presumably this is in advance of you actually throwing some object in your game right?
Yes
Is this curvature also what you will use to prescribe the path of that object?
Or does that object already have a way of moving a curved path from a to b?
grenade will follow the line
I mean you could use a bezier curve I guess
just generate a control point, maybe it's just directly above the target position, and use A, B and the control point to generate the curve
Honestly would recommend using a spline library to avoid doing the maths yourself
then you can sample the spline for your line renderer
and also sample it for your grenade path
Bazier curve makes sense
It's also my learning project so I don't mind learning how to do it myself
i'll check spline library too
But how do I structure the network to account for different descriptions and different sources?
On YouTube, thereβs a channel called Tarodev, and he has a great tutorial on how to do this.
i think if you read about it and look at an example it will be clear
As a non-artist, I am interested in leveraging asset store equipment meshes (e.g. armor) and programmatically binding the mesh to my character rig by copying over bones, bone weights, poses, etc (in editor or at runtime). Essentially, eliminate the step of importing the armor mesh into Blender, rigging it to my character, and exporting it to Unity. Is this theoretically possible?
I've been reading about it for a while. I think bayesian networks don't work here because they require independent priors, but evidence from the same source is not independent.
i think you can model "eivdence from the same source" as writing a "source is trustworthy" node and connecting it as part of the joint probability of the evidence nodes
does that make sense
the nodes can only be observations / facts
because they're modeling variables in a joint probability distribution.
so if this is important to your game
you would do something like "the npc is telling the truth" as a descendent of "the npc is trustworthy"
But the likelihood that the npc is telling the truth is also dependent on the testimonies from other sources
(eg. an evidence that contains place=school would conflict with an evidence that contains place=church).
this is different. a probabilistic logic puzzle like this, as free form as you want, is hard to express. you can look for "probabilistic prolog" on google for something that has a limited form of expression that looks like this, with probabilities
so... how would you express those testimonies as something that can be true or false?
"the testimony of this npc B is accurate" "this npc B is trustworthy" etc. etc.
quick question
I have a type
and I want to create an empty array from it
but I don't know how to do that
it's up to you how many falsehoods and in what scope affect whether or not an "npc is trustworthy" - all we're doing is exposing a latent variable that happens to fit very neatly into a "if the npc is trustworthy, it has a very very strong impact on the probabilities of its descendents"
so I have a generic Type, and I want to make a new array of that Type
you just gotta be creative with how you express these things
a bayesian net is actually really well suited for something like a common predecessor of many nodes that works like "this source of information is trustworthy"
you're just getting caught up int he meanings of the numbers rather than the nodes
@half marten but like wha'ts the gameplay?
The testimony of this npc B contributes to the belief in the specific statement they're expressing, eg. "Tim congratulated Tom". And NPC c says "Tim congratulated Tom on Monday" but NPC d says "Tim congratulated Tom on Saturday."
i don't thin this stuff necessarily makes sense
there isn't any complexity here. a player will assume that a soon as an npc tells 1 lie, the npc isn't trustworthy
which is the most natural model
is the game logic puzzles?
is that hte idea?
That doesn't work for what I'm doing
what is the gameplay
No, not a logic problem
I'm working on an experimental dialogue game. Not even really a game, just an idea
contributes to the belief
i understand that you want to model it this way
these have to be bools*
i don'; tknow, it's pretty clear how to model what you are giving as an example
as a bayesian network
if you want to query "is npc C trustworthy?"
I'm trying to model belief of past events, based only on testimonies from sources
which is latent, it is unknown
okay well i think you'll figure this out
the thing you need is a bayesian network
Are you thinking of something like this? https://i.imgur.com/tCpev5J.png
the nodes are things like "the congratulation happened on a monday (true) or a saturday (false)"
@half marten but it should be obvious that, as soon as you observe that ANY ONE of the descendent facts from an NPC is a lie, then the NPC isn't trustworthy
and sure, yes, that would cause all the other "testimony" to be in doubt
but you don't need bayesian reasoning for that
there isn't going to be a situation where the precedent nodes "npc A is trustworthy" is 50% AND one of the descendent facts is observed
it's going to be 0% or 100% as soon as any descendent fact is observed
But not for my model. I want NPCs to be able to assert statements that might not be true (gossip) and still have their statements lend some credence even if they've lied in the past
you can use prolog if you want to solve and express that kind of logic puzzle more simply
you mean you want to show the player this number it calculates
for a probability that their statement is true? and that sometimes that probability is high even though the npc has lied in the past?
no probabilistic framework is going to give you this elegantly because it's a bad idea π
Not the player, other agents
they might as well play randomly then
if you seed it with garbage data it will act garbage
you'd have to add 100 facts that the npc has told the truth about
then 1 fact it lied about
and then yes, it will give you a nonzero probiblity the next statement is true
but that's so counterintuitive, and also, the agents will behave poorly if they did that
surely you see why - because you're contriving a bad situation for the agent to reason about
essentially with garbage data
anyway you should think about this more
you can do this very very easily
without any probabilistic framework
I think you've misinterpreted the system, and what I'm trying to do
You can forget about computing NPC trust, imagine that's a known number
i think you can just program it to do exactly what you want
because a probabilistic reasoning framework, a scientific tool, will not meet your gameplay needs
i think you're imagining that there's some fuzziness to the behavior in the real world. there isn't, so the scientific thing is going to do an excellent job with finding the real answer, which isn't your intended gameplay
because right now i'm hearing
"i want the npc's dialogue to sometimes express doubt about what the player says, based on whom the player heard that from"
What if 2 somewhat trustworthy NPCs both share identical statements about an event? Those two testimonies should combine to give you a higher belief that the statement is true than if only one of the npcs said it, right?
somewhat trustworthy is a Rhubarbist gameplay concept
Forget about the player for now
do you see what i mean
Those two testimonies should combine to give you a higher belief that the statement is true than if only one of the npcs said it, right?
in a scientific sense? no
somewhat trustworthy? does that mean you don't know yet whether "NPC A is trustworthy" is true or false yet?
It's not a binary thing
the facts aren't 0 to 1. the facts are true or false. the probability of those facts are 0-1
well there you go
i think that's where you're confused
anyway like i said
just think about it
Bayesian networks do use 0 to 1 probabilities though?
in a bayesian network, the nodes are booleans
the directed arrows between nodes are expressing a relationship that the bool affects another bool
With a certain weight?
in the sense that instead of say, a XOR gate, it's a probabistic logic gate.
maybe look carefully at what it is
wikipedia has a good example
A Bayesian network (also known as a Bayes network, Bayes net, belief network, or decision network) is a probabilistic graphical model that represents a set of variables and their conditional dependencies via a directed acyclic graph (DAG). Bayesian networks are ideal for taking an event that occurred and predicting the likelihood that any one of...
That example confirms what I was saying? The belief that it rained isn't 0 or 1, it's 0.2
no
that's not what it's saying
it either rained or didn't rain. it can tell you the probability rain=true given you observed wet grass and that the sprinkler was off.
that's a query you can ask it
it doesn't mean it's 0.35 rained
or wahtever
that would be misinterpreting what it's trying to say
"What is the probability that it is raining, given the grass is wet"
so it would be incorrect that it rained 0.35 inches instead of 1 inch
do you see what i mean
i wouldn't interpret the probability as "how trustworthy is the npc" if you had a node "npc is trustworthy"
in the same way that i wouldn't interpret "how heads is a coin" as "0.5"
you certainly could interpret it that way but it would be counterintuitive and weird
the agent would behave poorly
a simple criteria would be, if the probability is greater than 50%, then the npc is trustworthy... but what you'll see is that most of the time, because of the way this is structured and if you use a learned value for the truth tables
that it will bel ike, 1% as soon as the npc tells one lie
as soon as that one lie is known
and it will be very close to 50% as long as it's an incomplete picture of their facts they've said
it will bounce around 50%
...essentially RANDOMLY
which is why i'm saying they might as well act randomly
or don't use the scientific criteria!
i don't think it's suitable for the gameplay you're trying to make
which is fictional world dialogue system
In my example, the observations are that certain people told you they believe a certain event happened. We also have the probability that each source will tell the truth about any event.
The source trust variable is essentially describing to what level should you take something that source says seriously. A trust of 0 means that the source's descriptions are completely random. It's possible they might sometimes say something that actually happened, but it shouldn't affect your belief at all.
anyway i think it's pretty interesting
If two sources share identical descriptions of an event, our belief of that specific description should take in both of those observations.
you can use a bayesian network to model this
and use "NPC A is trustworthy" as a precedent / parent node to everything the NPC A says
How do I predict where the bullet will hit so i can make the ai aim at the player
i know the Velocity and traveltime
you can query "what is the probability npc a is trustworthy" and it iwll give you a probability, and a good agent will probably treat 90% or better as true.
but who knows! maybe with a big network, >50% is true would make the agent better performing. that's an empirical question
you can model this in a bayesian network as "npc A and npc B agree on on a description"
it would be a precedent of "the description happened this way"
or wahtever
as lon gas you express your things as bools, it works.
"probabilistic prolog" can help you express these things more succinctly the way they sound
but then you have to learn a programming language π
I think the answer you're looking for is really that it can be however you like, you're trying to establish some probability to an unknown from unknowns and without data, and the only thing you have to base anything off is the human and borderline philosophical point that if multiple people are saying the same thing it's probably more likely to be true, or that if they told a lie it puts doubt on their other statements - exactly how you quantify that social phenomenon really is up to you though
some models attempt to simulate it, some make assumptions, there's an entire field of ML devoted to taking data and building model weights out of it, you can make a very simple scoring system or try to incorporate some statistical theory, you can structure the data in a certain way, but there isn't a magic function of absolute truth to it
agent better performing
in the sense that, if you had a game where the npc that gets the most facts right with the least amount of information.
But there are so many different ways that descriptions can overlap. Wouldn't you have to have a node for every single possible combination of agreements?
i think maybe try something simple you can wrap your midn around
because "probabilistic prolog" is a million times more confusing lol
i don't know yet
i'd have to try making this thing to find out
wait until you discover Pyro
your head is going to explode
I'm not really trying to implement ML, at least not for now
I get the feeling that Bayesian Networks can't solve this though, When you combine incomplete descriptions from different sources you quickly run into combinatorial explosion
as a really simple idea as I'm a sucker for just trying ideas out without theory - how about you take the full set of statements from NPCs and build a set of events that have received predictions, then for each event you score it either positively or negatively based on a simple heuristic like:
1.0 trustworthy person said it's true -> +10 points
0.8 trustworthy person said it's false -> -8 points
this likely wont work exactly how you want, but you can iterate on additional factors as you go
Trustworthiness is the level that any given statement from a source correlates with the truth
So 1.0 trustworthiness = +infinity points
0.0 trustworthiness = no effect whatsoever
sounds like you've already started on the iteration π
But I already know how I would implement this if all the sources have identical descriptions
It would use this formula: https://i.imgur.com/IhrMyfL.png
nah
i think if you just did it it would be fine
your game is going to have 5 npcs in it...
you know what i mean?
i would start with something that has a pre-existing osftware library
that you can start building the game around
The issue is when descriptions overlap with each other
What kind of software library?
Prolog?
i would search "github c# bayesian network"
See this graph for example
reminds me of a philosophical question I was asked once: is finding a blue shoe evidence that all elephants are grey?
I understand what you're saying - I'm deliberately not trying to calculate the exact weights for you because it's really up to you, there is no right answer here other than figuring out which factors you want to include and what model you'd like to build
Two sources in total agreement, one has trust 0.6, and the other has x. If x is 0.5, belief of the event is 0.6, because x isn't taken into account at all. If x is 0.6, total belief is 0.69
I think doctorpangloss has given you a good high level approach to take and if you don't like that or think it doesn't fit maybe trying something simple and just getting to grips with the problem could help
π€·ββοΈ
So 2 sources with trust=0.6 agreeing on the same statement gives the statement a belief of 0.69. Higher than if only one of the sources had said it.
It's not a question of weights, I have that figured out. But I don't think a Bayesian network can be built because the number of possible combinations of statements that could be referring to the same event is too high
from the original question it doesn't seem obvious to me that that would be the case
especially if each attribute is independent
Take this example:
3 sources all have trustworthiness 0.6.
Source A says "Someone (null) congratulated Tom"
Source B says "Tim congratulated Tom on Monday"
Source C says "Mike congratulated Tom on Saturday"
B and C give completely different events, but they both agree with A.
If A, B, and C all agreed with each other, the belief of the event they're asserting would just be = (0.6 * 0.6 * 0.6) /( (0.6 * 0.6 * 0.6) + (0.4 * 0.4* 0.4 ) = 0.77142857142
So 3 sources with 0.6 belief agreeing would give 0.77 belief for the statement they agree on.
But here, B and C can't be referring to the same event. It's possible that both events happened, or just one, or neither.
surely source C could be forgetting that it was Tim rather than Mike who congratulated Tom on Saturday, and source B could be forgetting that it was actually on Saturday rather than Monday, and it is indeed the same event?
For the time being, I'm ignoring that possibility.
And even if that was the case, it's still somewhat unlikely that they're referring to the same true event, and more likely that they're referring to different events altogether. Either way it just complicates things too much
but you're just basing this off what feels right, trying to ignore very real possibilities as being too complicated, while seemingly wanting to account for other possibilities with scientific & mathematical rigour (which doesn't really exist, because the problem is so ill-defined to begin with) - it's all a bit strange to me
It just needs to feel right, but it needs to feel right in every given situation.
is there anyway to stop an event from registering without having to unsubscribe it, like a function I can call to make it so it will not run any of the handlers, because the issue I am having currently is if the script or the object the script is on is destroyed, then the even somehow still runs the code from that script without it being in the scene (which would cause issues with it not being able to find its own gameobject and stuff). I could possibly just make it unsubscribe them during on destroy but since I'm using it in the new input system, the input system is destroyed first meaning I cant get a reference to it or something to unsubscribe them or something, I'm honestly confused. Anyway thanks for any help or guidance.
i'm not sure why and how you would need to unregister during InputSystem destroy
event registering/unregister is usually done in OnEnable/OnDisable, the only thing you need when your "inputsystem is destroyed" is to disable every listeners i guess
ok turns out you are right
apparently destroy does something different if I try to unregister in that, it throws the error, even if I am destroying the object OnDisable runs and unregistering it in there stops the issue.
Well, Thanks for your help, knew it had to be something simple
Would anyone happen to know why this isn't changing the color of the tiles despite getting the correct information for each tile in the loop?
don't hesitate to share more on the chat as you make progress π
it's a cool idea
could it be that the tileFlags are prohibiting you to set the color ?
https://docs.unity3d.com/ScriptReference/Tilemaps.TileFlags.LockColor.html
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.SetTileFlags.html
i have not messed with these settings at all so they shouldn't be
Greetings! Not sure where i need to post my problem as it is not directly a code specific issue, so ill post it here for now.
Over the past couple of days, Unity has been crashing over and over. The behaviour in question has been happening whenever i was dragging an element to another sub window (like the Inspector), resulting in this screen:
This happens with every element of unity, from prefab editing to straight up variable assignment in the editor
For the past 20 minutes for instance, i had that crash error happen 10 times.
I can not work with a program that constantly crashes the second i move something in the editor
So i came here for help.
I want to add a custom animation to a GameObject that contains an animation controller through .dll modding (BepInEx w Harmony) I made an asset bundle containing an updated animation controller (Animator) (so it can handle my new animation in a separate layer), an AvatarMask and the actual animation clip (animation) containing the keyframes, Im not that versed with unity modding so It quickly becomes a headache trying to tackle this problem
This is what I came up to load the assets, however Im not sure if what im doing even could work, because the array of Objects I loaded Are just Unity.Object And I havent figured out what im I supposed to do with these Objects to convert them in the types I want (Animator, Animation, AvatarMask)
// Variables that I want to hold the data from the bundle
public Animator kickController = new();
public Animation kickAnimation = new();
public AvatarMask kickMask = new();
private void Awake()
{
var kickAnimationBundleStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RavenM.assets.kickanim");
var kickAnimationBundle = AssetBundle.LoadFromStream(kickAnimationBundleStream);
var animationBundleObjects = kickAnimationBundle.LoadAllAssets(); //This is the array of GameObjects Im talking about
foreach (Object obj in animationBundleObjects)
{
Plugin.logger.LogInfo($"{obj.name} type: '{obj.GetType()}' detected in the kick animation bundle");
}
}
@unborn bramble: Start with the obvious stuff - do you have any weird/unconventional packages/DLLs/editor scripts? Then handle the middle-tier stuff - reinstall unity, make sure it's completely clean (no leftover DLLs, directories, etc) - check for files that can't be deleted (hard drive issues) or dangling configuration files. Registry directories, etc. Kill it all with fire. Then install clean. If that doesn't work, dig into the crash logs if you're so inclined, and at a minimum, report the bug to Unity. I know it's a fair pain in the ass but.. Life is Pain
Btw, here is the manifest of the bundle in case you need it
correct, it was the rendertexture didnt have the same texture type than the destination texture
Hello !
I have a question
i'm using Unity Netcode for Gameobject and i'm trying to disconnect my client.
Basically; it's giving me this error :
NullReferenceException: Before using the library you should call Init() and do not forget to call Shutdown() afterwards
I searched on google, and it's telling me to use this :
Networktransport.Init();
Now the problem, is, as you can see in the screen : I do not have this function.
I'm heritating from NetworkBehaviour in my script, not Monobehaviour.
Would someone know how to fix that please ?
not an advanced issue. but you have to call Init on the instance, it isn't a static method
that's NetworkManager, not the NetworkTransport
How do you do an instance of the network transport ?
how did you get an instance of the object to attempt to disconnect?
okay well at this point you should redirect your issue to #archived-networking or to the netcode for gameobjects discord server which is also pinned in networking
maybe consider going through some of the docs/tutorials from unity for how to use it
Okay thank you :)
hi guys, i was wondering if anyone knows of a way to take some previously allocated memory (such as array of chars) and create a string that uses that exact memory, rather than allocating new memory? For example the string constructor can take a char* to an array of chars, but it will always copy the values to a new location in memory, thus requiring an allocation.
I know it's not technically allowed as strings are meant to be immutable, but you could argue that its already possible to mutate strings, by getting a pointer to it using the fixed statement etc.
im doing some low level string stuff and want to avoid allocations. I don't mind if its super smelly as long as it works!
Proly what you want is Span<T> tho the behaviors aren't what you described above
it is possible to change the string but requires unsafe... keep in mind, YOU SHOULDN't!
unsafe
{
char* str = (char*) gcHandle.AddrOfPinnedObject();
for (int i = 0; i < someStr.Length; i++)
{
str[i] = someStr[i];
}
}
untested, and I'm assuming you're used to this, so you should get the idea
to look for this sort of sorceries, your best bet is to c# discord... you won't find this sort of answer here unfortunately
also, Unity supports fastSpan now, you should go that route instead
Does anybody know why stream.Close() took 16ms when i looked on the profiler? is there something wrong the way im using it? :
await stream.WriteAsync(bytes, 0, bytes.Length);
stream.Close();
Disposables should be enclosed in a using statement, to avoid forgetting from closing the stream and/or disposing of it
Other than that, looks good
but should that affect the performance so much?
It depends where the stream points to
disk
Memory, it should be pretty much instant, file, a bit longer
The actual contents aren't written to the disk until you call Flush, or close the stream which calls Flush internally
yeah it pooints to Application.persistentDataPath
just by adding using in the declaration is enough?
like...
using var stream = new FileStream(path, FileMode.OpenOrCreate);````
?
using (var stream = new FileStream(...))
{
// consume resource
}
// disposed here
ah ok i remember this now
as you said is closed and disposed automatically if we do it like that
if you are using a unity version that supports this syntax, yes that would be enough. it's just sugar for the syntax spr2 provided in the following message
Yep, and even if you return; early, or if an exception is thrown!
(the using block compiles to a try/finally block in the background...)
just one question more, is there any way i can shorten the time the stream closes/is disposed?
maybe using something different than a stream? i used it because it allowed me to use WriteAsync
do I have an alternative?
You can tell it that the IO is really async in the stream's constructor:
The IsAsync property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the FileStream class using a constructor that has an isAsync, useAsync, or options parameter. When the property is true, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the IsAsync property does not have to be true to call the ReadAsync, WriteAsync, or CopyToAsync method. When the IsAsync property is false and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously.
Source MSDocs
π thanks a lot
Oh, and it seems it also implements IAsyncDisposable, so you can do
await using FileStream stream = ...
The disposal will be awaited
@novel plinth thanks for the feedback.
I'm already using mostly span/readonlyspan on the implementation side, its just that unity and textmeshpro API's all require strings which is sad.
Ill check out fast span - is that something added in newer unity versions?
oh, and I feel like if I ask this sort of question on the C# discord I'll get burned at the stake for blasphemy or something ha
oh, fast span is an implementation detail of spans? I guess that means I'm already using fast spans for most of the implementation. I just need to somehow stuff it into a string at the end so I can hand it over to some other API lol.
If I were you, I'd just copy the implementation of Zstring π
also, fyi, String.Copy does exactly what you're looking for, for the muttable parts I mean... it still allocates for the creation of a new string of successful copy
here https://docs.microsoft.com/en-us/dotnet/api/system.string.copy?view=net-6.0
mind you, it's deprecated for a reason...
where did you see it implements IAsyncDisposable?
On MSDocs, it isn't explicitly told, but I scrolled down to the methods section and saw DisposeAsync being there
intelligense shows FlushASync but not disposeAsync
Alright, then keep the standard, non-async using
but youre right, its here
Yeah, even on the .NET versions Unity uses, by switching to them using the dropdown at the top-left of the page
Oh well
Here's why
2021.2 has full C# 8 support and partial C# 9 support.
It's so unintuitive that destroyed GameObjects stick around a frame, why can't the API at least unparent them?
tho on the editor side, you can do so, but at the end of the frame... https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html
You could make your own function that destroys and unparents if that's what you want, and use that instead
Yeah I'll do that and add it along side ExpectedUnparent π
this is good new syntax
the performance issues with textmesh pro / ugui aren't from copying even large strings
anyway what is your objective? networking stuff? you can't marshal a char* to a managed string, full stop, without copying. you are expected to create ReadOnlySpans to achieve zero-copy buffers
Hello folks!
I got CORS issue from one of my two APIs. the other API works without flaw
but either way I could not handle the issue! Where is this fc bug coming from?
In the same application one API requires CORS the other one works fine.
and there is no difference!
you might wanna ask people who are more familiar with web development
ah. this is your issue. yes, do this on a unitask thread pool thread
you can also use await stream.FlushAsync with a main thread task
io to disk is always really slow. it just pretends to not be slow
hi dudes, i'm working on prototype for how MMO save the data and i need some help/information.
Any know any webpage, site or anything about how we can deal with store the player position, items, etc etc, during runtime?
I didnt know FlushAsync did the same than Close or Dispose
thanks again doctor!
see if there is a photon sample that is close to the gameplay you want, or search "unity mmo backend". there's also an asset store asset that is good for prototyping, and in my opinion very reasonable for 40-60 concurrent players with a typical intro skillset
any link? i cant find
rpg maker might be more helpful to you - https://assetstore.unity.com/packages/tools/game-toolkits/rpg-builder-177657
you should only destroy gameobjects that are used exclusively for rendering
why is that ?
SetActive(false) in contrast will immediately call OnDisable.
hmm
partly because of this problem - @crimson ruin is wrong that they stick around for a frame
it's that they stick around until a certain time that is counterintuitive
every game object that is Destroy ed will be in a phase where its code will have one last chance to execute before being removed from the scene... people will want it to be destoryed immediately but then... how would OnDestroy work?
for non-rendering scenarios, where you might have 1 game object for all your little controller and manager components
yeah, too little to matter
yeah that makes sense
should the scene have ever been permitted to also process game logic? it's impossible to build an editor environment without that assumption.
hence DOTS not really changing things for the better*
do i need to call .Close or Dispose after calling FlushAsync?
dispose and close both call flush
dispose will always try to flush. if you've already flushed and there's no new data, it depends on the stream, but the most obvious implementation is it will see there's no unwritten data and dispose "instantly" - meaning without any io
so
UniTask.Void(async () => {
using var fileStream = File.Open ( ... );
await fileStream.FlushAsync();
});
@stuck onyx this is fine
the complete example:
this is what i did, already inside a UniTask:
// simplest: use a threadpool
UniTask.Void(async () => {
await UniTask.SwitchToThreadPool();
using var fileStream = new FileStream(...);
fileStream.Write(...);
});
// on the main thread.
// must carefully never do blocking io
UniTask.Void(async () => {
// await UniTask.SwitchToMainThread() is redundant here
// file.open can still block indefinitely...
var fileStream = new FileStream(...);
try {
await fileStream.WriteAsync(...);
} finally {
await fileStream.DisposeAsync();
}
});
the best thing to do is use the thread pool
the reason of using... 'using' is to dispose automatically of the stream no? if we are doing it manually whats the point?
you can see in my main thread example i don't use using
because i'm not sure if your unity supports async disposables
if you are on the threadpool
you can use using var ...
no it doesnt, it doesnt support them
it's dangerous to create file streams on the main thread anyway
they can block indefinitely
meaning the constructor
i never write files using streams
i try to one-shot it in an async method
i suggest https://docs.microsoft.com/en-us/dotnet/api/system.io.file.writeallbytesasync?view=net-6.0
imo this is the only method for writing files that is safe enough to use on the main thread
because you don't actually care what the result is.
i want to wait until the UnitaskVoid has finished, shall i launch it like
await UniTask.WhenAll(myTask);
can you give me a little more context?
im saving 16 textures on a loop
so i have to wait till 1 is finished to save the next one
- render 1/16 part of the screen
- move that portion from renderview to a native array
3 Save that array in disc
loop
the step 2 i did it as you told me using the GPUAsyncRequest
now when saving that into disc i saw there was a little delay when closing the stream thats why im back π
use await File.WriteAllBytesAsync
and don't create a file stream, etc. etc.
just that one method
and save the files 1 at a time on the main thread, which is where async gpu readback gives you the frame bytes anyway
you need to be on the main thread
thanks gonna try
hmmm
cant do mate
writeAllBytesAsync not available
i guess thats why i chose the stream
cant I writeAllBytes on a different thread and wait for it?
on a thread pool thread yes
await UniTask.SwitchToThreadPool()
inside your task
this is thei mplemetation but it's not easy to port
why does this shit matter? on mobile devices, the operating system isn't reliable with files
they don't maintain a contract
stat can take forever. you have to wrap anything that touches files with CancelAfterSlim
otherwise you can torch thread pool threads
if you do File.WriteAllBytes instead of File.WriteAllBytesAsync
do you see what i am saying
im putting all my effort but nott completely, just that WriteAllBytes on a thread might f** ** me hard
i'm not sure even WriteAllBytesAsync helps you much.
it will throw an exception if you have a problem with the file path
well the filepath is starndard for all it shouldnt give a problem no? its the ApplicationDataPath/subfolder/
only thing is if they have no space
i'm saying ios might decide, in an afternoon
"apps only get 1MB to write to, if we feel like it"
yeah, wouldnt be surprising
do you see what i mean
no contracts
you can ask for temporary files, that has worked the best in my experience
what does this mean? π
oh, i didnt even know that existed
oh but its readonly
anyway, leaving aside the location of the files... ill try to make use of the script you sent me
the property is read only
in order to use this method in https://github.com/dotnet/runtime/blob/96b4b53d4a13dfdf644343beeb67b57367559d18/src/libraries/System.Private.CoreLib/src/System/IO/File.cs#L1012
do I need the whole library?
Hello. Is there a way to capture each frame produced by the rendered as int32 color arrays? Ideally a callback where I could script whatever I need to with that array.
onRenderImage cannot work in that case because it doesn't get called on HDRP pipelines.
There's ScreenCapture.CaptureScreenshotAsTexture that gives out a Texture2D you can manipulate further. No idea about the performance of that method though
take a look at this
@regal olive
first you set up a renderTexture, asign it to the cam you want
Thanks that's very helpful.
call AsyncGPUReadback.RequestIntoNativeArray
(ref _buffer, _rt.flip, 0, OnCompleteReadback);
and you have it
wow that's slow
one second per call
is that expected?
oh nvm
there's a one second timer lol
when using async and await in unity for things like api calls do I have to worry about thread lock?
Anyone know why you can't have prefabs with items that are reordered? It's not a problem for me but I'm curious behind the reasoning:
(like when trying to add a child gameobject in the middle of an instance of a prefabs heirarchy)
by default async methods in Unity all run on the main thread
it's just not one of the features they chose to support. They have support for changed fields and for added components. But not for rearranged or removed components. Probably because it's just a lot easier to implement those in the scene/prefab file format than deletions/rearranges
tasks (async await) are not threads
you can read a lot more about it here - https://stackoverflow.com/questions/4130194/what-is-the-difference-between-task-and-thread
neat
no i think it's not worth it
too hard to just grab
i mean, that particular piece of code and its dependencies
i think we're overthinking this π just write the files in a task on the thread pool
Hey while you're here
What are cases where synchronously writing files would block indefinitely?
Oh I thought I read in a forum it wasn't safe and thats why unity people don't use it
@undone coral
lol
you can use Tasks, it's easier to use UniTask
UniTask helps you deal with unity + Task idiosyncracies
i use tasks a lot now
they're more robust in my opinion that coroutines, and they are useful with unirx
I agree so the only reason why unity developres don't use it then is because of lack of knowledge?
well i use it and i'm a unity developer π
they do have some drawbacks, people may choose coroutines intentionally
depending on the situation through right? coroutines have their place but with async/await we can use those with apis and such
sure, tasks are very convenient, especially for async APIs
for me, coroutines may be better suited for driving lots of monobehaviors, tasks are kinda heavy to launch and track lots of them continuously
totally and completely agree. I was just under the impression asyn/await and tasks where a NONO in unity for whatever reason
well, Unity documentation used to have a "Avoid async/await" in bold letters not that long ago π
might be why
Tasks are also problematic on WebGL platform due to use of System.Threading, which UniTask addresses.
i just came across https://www.drdobbs.com/forward-difference-calculation-of-bezier/184403417?pgno=5 this solution for approximating points of a bezier curve. I'm not good at math and was wondering if there was a way to modify it to instead work on the first derivative of a bezier curve to approximate the tangents instead of the points?
what is the best solution for having a websocket server in an unity game as of now?
Tasks become problem if you're using threadPool, if you're not doing context switching you'll be fine... UniTasks won't work in webGl too if it uses threadpool UniTask.RunOnThreadPool
tbf, it's WebGl issue not Unity or tasks... webgl supports for multi threading is just non-existent
Sure, but UniTask won't break with simple things like delaying tasks
It's not obvious when the async API uses unsupported System.Threading features
it is due to jasvascript ... https://www.tutorialspoint.com/why-doesn-t-javascript-support-multithreading
Why doesn't JavaScript support multithreading? - JavaScript used to be single-threaded. It runs using what is called an event loop.The Event Loop has one s ...
webGpu tackled this issue
You can multithread on the web as the link you posted says, it's just not quite that simple with all the mechanics combined with webassembly and potential complexities of Unity's runtime.
Not aware of WebGPU changing this
it's a feature that later added, not natively built from the start or thought when they 1st built it.. *I dont know how to say this in english, not my 1st language
it will, it has privilege to lower level api, basically what desktop can do, webgpu can too
Yes, at least on a GPU
same approach on cpu side, lower level api than webgl... if you're interested, take a time to read the implementation in the link above
even the old Unity docs stated the reason why the webgl won't work with threading https://docs.unity3d.com/2019.3/Documentation/Manual/webgl-gettingstarted.html
they later removed the notes, but the issue still there
proly they though it was bad for marketing purposes
It's likely just a bit poorly worded and doesn't necessarily mean what you think it does. Again, I don't think WebGPU will implement new multithreading paths. WebGPU is most likely not a magical lower access granter like the old school browser plugins were, but very specific graphics related features implemented in the browser sandbox.
Unity's engine for a brief moment was multithreaded on browsers, but there were a lot of issues.
either way, it's a fresh technology, only known high-tech companies adapted the technology and I honestly think Unity wouldn't adapt it soon π
..I don't think WebGPU will implement new multithreading paths they do have a brand new implementation of it called WebWorkers
it is also mentioned in the linked doc
You sure web workers is new? Web workers were mentioned in your first link and the spec was published in 2009.
The WebGPU spec says that it can be used from web workers.
Adopting WebGPU for the browser platform today would do nothing since none of the browsers have it enabled yet. https://caniuse.com/?search=webgpu
it a common term for background workers for web browsers.. Mozilla did the same thing with it's firefox
give me a sec
as for the implementation, they are different from one to another
Zstring looks pretty good I'll admit, we have our reasons for needing to roll our own - we are mainly targetting playstation consoles and there are some really annoying memory related behaviours that occur when dynamically allocating memory - mainly large amounts of memory fragmentation and wasted blocks that we absolutely have to avoid, as memory is never truly released on these platforms.
We have two systems currently - one which allocates a fixed buffer during startup that we use to store string data, with a custom type that acts largely like a string for all of our internal logic - the problem being that we sometimes need to stringify this. The other one is simply a library for performing non-allocation string analysis and manipulation - again for similar reasons.
String.Copy looks promising but as you say its deprecated so I wouldn't want to use it.
Either way thanks again for your feedback - I'll have a look into Zstring to see if it would work with a fixed buffer (doesn't look like it would be too far a leap).
Where does the WebGPU spec talk about new web workers implementation?
you can read around the GPUBuffer or GPUQueue sections
You sure they aren't just talking about how you can use WebGPU APIs from existing web workers
yes, what I suggested is for you to copy the implementation of it and ofcourse adapt it to your needs
nope, pretty sure
the source code is on github and you do exact the same
and with some adjustment obviously, to your needs
I'm referring to memory related problems on playstation consoles - stringifying isn't a slow operation, but it causes dynamic allocations which we need to avoid at all costs (see my above message).
I really only have one objective here - avoiding dynamic allocations of strings during runtime. Ultimately I may end up having to write some native code that can allocate strings using a fixed buffer or some memory that I can actively release.
as for String.Copy yeah, they deprecated it for a very obvious reason, which that obvious reason is to muttate internal string, which I supposed is what you want .. lol,, my english is funny
yeah I wont deny that what I'm trying to do is pretty stinky
unfortunately this sort of thing is common when optimizing for console
at least we can create native plugins.
that's the correct way to say it when one asking how to mutate a string.. lol
There's another option if you're looking for a cheap way of allocating strings, StringBuilder has ValueStringBUilder.. but sadly this is internal
internal ref struct ValueStringBuilder
{
private char[]? pools;
private Span<char> chars;
}
and i doubt if it will perform better than zstring
looks like it uses ArrayPool as well, unless you pass it a stackalloced buffer - so its probably similar in performance to Zstring?
I'm actually already using stackalloc'd buffers as scratchpads for the non-alloc string manipulations/analysis that I am doing - so I don't think it would change much in terms of performance for me.
And of course I have to stringify it at some point.
it will allocate more once you do tmpTxt.SetText(); while zstring literally won't... never personally tried it, just raw guesses
for a trivia, there's a proposal to expose ValueStringBuilder... but I don't think they would do that lol
fair enough. and yeah it doesn't seem like they would expose it any time soon.
here just incase you want to track the progress https://github.com/dotnet/runtime/issues/25587
the proposal was there since 2018 lol...
thanks
Hello, what library should I use to have a websocket server in my unity game?
you can use the .NET builtin HttpListener. If thatβs the best thing to do depends on your actual requirements.
when importing stuff from a dll is there any way to get error handling and stop unity from crashing entirely if something isn't right?
it appears that using try and catch doesn't work sadly
Only if the dll is written without unsafe code
is there anyway of telling? I'm using a closed source nvidia api
Certainly using unsafe code if itβs written in C or C++
ah, welp that is unfortunate
so i guess trial and error is my only hope, and there is no way of stopping unity from crashing entirely?
If you get segmentation faults and stack overflow from them, then no
i dont get anything, no response,
it just crashes unity on hitting play
Sounds like segmentation fault
accessing memory that the OS has not assigned to the process
aha that is unfortunate, all im tryna do is run a function currently, is there anyway i can get it to not do that then?
No, but if you get it while calling a native βexternβ method, your address for the method is likely wrong
oh ok then, how i can i make the address for the method correct then?
You need to know the correct signature . You can find a guide and examples on MSDN
thankyou! That would make sense, as i do not know if i have the type correct yet!
Anybody here working with netcode for gameobjects?
oh thanks
btw if in the dll something is private, but when i recreate it in c sharp i make it public, will the dll not like this?
Something?
?
If something is private in dll you won't be able to access it, and thus make it public.
unfortunately im talking about structs, which cannot be grabbed from dll's as far as im aware, but from the nvidia docs i reckon they are private structs, so when im recreating them in c# i'm uncertain about whether to match the dll or make them public
Well, then they're not the same structs anymore.
oh, that is annoying, ill have to figure out how to create private structs, something ive never succeeded in doing before lol, oh well im sure ill find some way to make it work with being private then!
Just mark them with a private accessor.π€·ββοΈ
aha, unfortunately i have another private struct, that takes that struct as part of its constructor
Then don't make them private.π€·ββοΈ
but they are private in the dll? Do you think it would be ok?
I don't see the issue.
They're not the same struct, so it's totally fine.
im just scared that if i dont set things up in c# the way it is set up in the dll that it won't accept the structs as being the same
Yours defined in your assembly(potentially namespace). Theirs in their.
im afraid i dont know what that means?
It's like you can have 2 classes with the same name and layout in different namespaces. Doesn't make them the same class.
C# will still treat them as 2 different objects.
oh ok that makes sense, so if my dll is expecting the private dll struct, but i pass it my public c# struct, it wont raise an error?
It will. Because it expects something else.
oh, well how can i get it to be happy then?
Use their struct.
how, it is a private struct in the dll? How do i pull it out?
Then you can't.π€·ββοΈ
how would i pull out a public struct in a dll then, let us start with that
Unless you get the source code, make it public and recompile the dll
Same as anything else I guess.
unfortunately it is not
dll import doesn't work for structs
there are functions in the api to create the private structs that save as public structs (hope that makes sense), so assuming i can find some way to get/create the public struct then perhaps i can just deal with not having access to the private struct, although trying to get/create any struct from the dll is a pain lol
maybe something like this?
https://www.codeproject.com/Questions/1352299/Reading-a-complex-struct-from-Cplusplus-DLL-to-Csh
That doesn't make sense.
Is it returned as a pointer? Hard to say anything without seeing the code in question.
sorry for late reply, (i shall continue late replying sorry lol), i am unfortunately eating dinner, but all those links you have sent do look fascinating, so ill check them out after dinner, thanks!
unfortunately no one here knows anything about optimizing for playstation, i'm sorry
it is substantially, vastly easier to use an arena allocator for strings if this is essential to you. then you are welcome to manually memory manage strings.
zstring looks like it has some arena allocation features. @scenic helm without more context, it is hard to say what you should do. if you have to manipulate strings for routine gameplay, isn't it for things like dialogue? you will not have framerate issues in that situation, and besides, tough cookie, it's a text based game!
I want to make a vr combat system with swords but I dont know how to detect swing length and force. Can anybody help?
short question about cancelation tokens....
In this function...
async UniTask MyUnitask(CancellationToken ctoken)
{
// my stuff 1
UniTask.NextFrame(ctoken);
//my stuff 2
}````
when the cancellation token is triggered, does myStuff 2 executes?
or i need to do....
you need to await that next frame
yeah but... the Unitask.NextFrame(ctoken) is enough for the rest of the script NOT continue executing or do i have to do... if(ctoken.HasBeenCanceled)return ?
if you need to make sure it doesn't run you need to guard it with ct.IsCancellationRequested or ct.ThrowIfCancelationResuested()
async UniTask MyUnitask(CancellationToken ctoken)
{
// my stuff 1
UniTask.NextFrame(ctoken);
if(ctoken.IsCancellationRequested) return;
//my stuff 2
//my stuff 3
UniTask.NextFrame(ctoken);
if(ctoken.IsCancellationRequested) return;
//my stuff4
//mystuff 5
}````
so i'd need to explicitly ask if it has been requested to avoid the task to continue, like that
because in this case i want the task to execute complete, i dont want to stop at certain point and continue
if it is interrupted, i want it to start again
would be that the corrrect way ?
iirc you'd use ct.ThrowIfCancellationRequested(); to actually cancel all subsequent execution immediately
check out the cancel exception workflow
i prefer it more because of the finally block, very convenient to reset / dispose decencies and stuff like that
if you just check the token, nothing is actually cancelled but what you manually skip
hmmm okay lests see...
i think ThrowIfCancellationRequested is enabled on UniTask by default
so...
that NextFrame will not throw if you cancel it
it just returns a completed task
ohh, okay
if i use the AttacheExternalCancellation, the task will stop the flow then ?
like...
async UniTask MyUnitask(CancellationToken ctoken)
{
// my stuff 1
UniTask.NextFrame();
//my stuff 2
//my stuff 3
UniTask.NextFrame(ctoken);
//my stuff4
//mystuff 5
}````
idk, never used that
okay ill do some tests
its a discouraged API
you're not supposed to use it
but its there if you run into situations where you have to
UniTask does this a lot, the longer the method name the more "discouraged" its use is
hmm, thanks a lot Anikki!!!
btw , aniki comes from the japanese or some sort of alien stuff
but its only discouraged based on the opinion of its author ofc
its jap. for "big brother" but misspelled
its also a regular norwegian/finnish name
ohh, youre from norway?
nope
cool, because it sucks
no dissing of other cultures!
lol i dont diss the culture, i just dont like the country XD
yeah, this is not the place for discussing that kind of opinion π
true
btw the one thing to remember about async is that its not magic and if you have a fundamental understanding how threads work, you can guess most of its behaviour, but if you are talking to people the discussion often revolves around implicit and quirky parts of it that are very easy to misunderstand and often people have opinions about what they mean.
yeah i understand till certain point how threads work, thats why im not multithreading, just using async/await
if you want to master async in C# you need to understand synchronization contexts
and when in doubt, you can always do your own async with primitives (and a lot of bugs), or in unity (and other single threaded systems) by tracking state variables
my own async with primitives? what do you mean ?
try
{
...
}
catch (OperationCanceledException) when (tokenSource.Token.IsCancellationRequested)
{
...
}
finally
{
...
}```
what I use in my code to cancel tasks
they're regular c# Tasks, but UniTask is very similar afaik
and I don't have any checks in the awaited task
locks, semaphores, monitors, and most fundamentally Interlocked.CompareExchange
oh, okay, I got it
there is a lot of nuance to it, but its all there, no secret sauce needed
okay so cancellation tokens are confusing
because it's just copying java
and i happen to know a lot about how it works in java π
so consider the following categories of methods:
- i do a lot of cpu work on the thread i am called on and
a. i expect to finish and be done, OR
b. i can be gracefully interrupted and cleanup my work - i do something that either succeeds or fails, and i do no CPU work but it takes a long time, and
a. i have no way of knowing if i succeeded or failed until the long time is over
b. i can query and potentially interrupt the execution of the thing i'm waiting on - i do a mix of the categories 1 and 2
if you are 1, the implementation should check if a passed token has is cancellation requested "often enough" to give the cpu time back to the canceller. if you are 1a, you should throw operation cancelled exception because you didn't finish and it would be a programming error to cancel. if you are 1b, you should not throw anything.
if you are 2, which is typical of making a web request, you should 2a throw an operation cancelled exception or 2b do not throw the exception. in 2a, cancellation is always implemented as something similar to a timeout. because for example, you can't actually cancel a web request. do you see what i mean? it will still happen even if you decide to cancel an await UnityWebRequest.Post - the thing you are waiting on in 1a is just time.
if you are 3, you should use a return type that properly communicates what happens or method overloading to let the user decide. this is common because you will compose things that cannot really be cancelled (web requests) with things that can (creating an image in unity from a web request).
@stuck onyx WHY this isn't documented anywhere i don' tknow
OperationCanceledException will always be thrown by category 2a, which is by and far the most common category people interact with. it makes sense why!
you cannot actually cancel a web request. so in my opinion you should actually not pass the cancellation token to a web request, and instead after the request check if cancellation is requested and gracefully exit without throwing (i.e., category 3 method, you are a method that composes things that can and can't be cancelled)
some methods, like UniTask.Delay, they can be cancelled gracefully but unitask throws an operation cancelled exception anyway. that's because category 2b is too confusing of an API distinction, so nobody deals with it
for this there is the don't throw if cancellation requested extension method in UniTask, so that you can handle methods you know are category 2b
i can know if they have been finished or not but saving cpu is more important so i rather 1b
you can't actually cancel a file writing operation
so stop everything and start again when possible
you can design a file writing operation that can be cancelled
yes
so for example, writing buffer-by-buffer you would check if cancellation is requested in your while loop
this is fine
hmmmm, no i dont think I want to cancel an operation like that.... as you suggested... I must pass the CancellationToken
and check if it has been triggered, correct?
so this...
if it's indeed on a different thread. if it's on the main thread and you want to cancel from the main thread, you would have to await UniTask.Yield() (which is correct anyway)
so for example
im confused about this:
``` await TakeSnapShotAsync(i, false).AttachExternalCancellation(cancelAsyncSnaps);````
is this supposed to attach a cancellation token that cancels the task on any stage?
it can't do that no
you have to make it a method argument in order to pass it down
and check
yes
aha okay thats what im doing wrong
and then on the key parts of the process ask if it has been triggered and stop it myself
while (bytesLeft && !cancellationToken.IsCancellationRequested) {
// observe the file stream methods don't accept cancellation tokens
// because they cannot actually be cancelled
bytesLeft -= await WriteSmallChunk(someBytes);
// this ensures you can cancel "a task executing
// on the main thread" from the main thread
await UniTask.Yield();
}
yeah
thats how i saw one guy did it with normal tasks
but i saw this in Unitask and thought... this must be some advanced shit
yuou would then check how many bytes are left
if it's greater than zero and yo're outside the while loop... i guess delete the file
the screenshot
however... consider that if you quit the app which gracefully cancels this stuff
you won't have a chance to delete the file
remember: you can't actually cancel a file writing operation
hmmm no is not my case... if i cancel the process its because i want the cpu to be free for heavier operations, but its not like i want to cancel INMEDIATLY
i think all you need then is UniTask.Yield
you know, like when player moves, i set the FPS to 60
and when player is idle i set to 30
if you want to yield more time
so thats when i do this operations
yeah
that makes sense
it's a little tricky to detect when you are idle
you can estimate how much time you have
if player moves i cancel, but its not like im gonna stop in the middle of writting the snap into disk
this is why in practice, you pick a fixed amount of work and spread it out
nah it doesnt have to be exact, right now the script is damn quick
you don't try to measure when you're idle
ill fix the cancel thing
cancellation makes the most sense for tasks that compose a bunch of steps
im pretty proud of what the script does and since you helped me id like to share it with you
well im sure there must be stuff that can be inmensely improved though π
we can look at the source code of WithExternalCancellation
@stuck onyx i think all it does is turn any method into a 2a - which can be cancelled in the sense that you can stop waiting for it
so it will correctly throw an operation cancelled exception and nothing else
hmmm
why this does not work ?
i throw the OperationCanceled
and im catching it here
when i launch it
but seems it's not catching it
you're throwing the exception in the callback
oh shit
the way to do this is
async UniTask TakeSnapshot(CancellationToken token=default) {
var readback = new UniTaskCompletionSource<byte[]>();
AsyncGPUReadback.Request(cb => {
readback.TrySetResult(cb.GetData<byte>());
});
// cannot actually be cancelled!!!
// we cannot pass a token to cancel a async gpu readback request
var data = await readback;
if (token.IsCancellationRequested) {
return;
}
File.WriteAllBytes(data);
}
@stuck onyx do you see?
you converted the callback into a task
yeah, i wanted to do something like that for so many parts of my code
well
now you know π
that's because instead of TaskCompletionSource it should have been called Future or Promise but microsoft didn't want to use any words that could get them in copyright jeopardy or some completely irrelevant legalistic horseshit that would impact exactly 0 people
you can blame microsoft's preposterously bad lawyers
Promise is from js correct?
I see, Its a bit new to me but i get the grip of it
great @undone coral now the tasks are launched and cancelled exactly how i want and the order i want and the cpu is optimized π
only thing is i couldnt convert the callback
i think you can figure it out from the example
i don't remember what the task completion source is called
yep, googling the error
okay
iut's jsut the types
i don't know if async gpu readback gives you the result on the main thread
thanks a lot again once is finished ill send you the script
i assume it does
I need to pick a resolution for images in our game - they're "important" (they're character portraits), so high res seems better, but it's for mobile so to some extent, low res is fine. I know the ratio I want (1:2) and the designer is doing the work in vector so they can generate any size images just fine. How can I evaluate and pick an ideal size for these images that I'm going to put in the game? The only thing I'm aware of is that they should be a multiple of 4 so they can be compressed to DXT5 but.. I'm not sure how to see the imported texture sizes after unity does a build for a specific image.
ie - something like this https://github.com/aschearer/unitysizeexplorer but geared specifically for images - I also don't know if this repo/project is still functional, last commit over 4 years ago
you can use different compression settings and check file size and quality in the editor. If you switch to that platform, Unity will apply compression in the editor
https://docs.unity3d.com/Manual/class-TextureImporterOverride.html
I get pretty good results with ASTC 4x4 block on android and iOS
those don't need POT textures by the way
In most cases crunch compression can dramatically reduce memory footprint without being noticeable
Where could you see the size in the editor? I am obviously able to change the resolution of the PNG but ... I can't really see the effect on the crunched file size after the build
even on debug mode
or is that it? complete image size?
8.3mb? jesus
(granted I haven't sized this image as a multiple of 4, or downsized the resolution but that seems stupidly large?)
drag out the preview window
on the texture, not the sprite
uncompressed NPOT texture of that size can easily be 8mb
for DXT5 that matters a lot yeah, but if it's impractical to make the texture POT, you can use different compression techniques
how do you enable that preview window? Dumb question I know but I can't seem to locate it.
should just be at the bottom of the inspector (not in debug mode)
I don't even think it has to be perfect POT - tooltip says any multiple of 4
Mine doesn't have that panel.. digging, though.. i'll find it
looks like this if it's folded in; just click it or drag up
oh it only shows up if you have the "popup" window thing
like the inspector when it's embedded in a layout doesn't show it
Got it - the debug mode "Complete Image Size" is the same value it appears, so .. I'll just look there (i usually am working in debug mode in my inspector anyway)
I just have my inspector embedded like normal
preview window/widget of the inspector.. there's gotta be a way to enable it for the .. uh.. embedded view
oh
hahaha i found it
alllllllllll the way hiding at the bottom
i would have assumed it would appear "after" the other components
derp.
yeah it's just the general preview window; it also shows materials, prefabs, etc