#archived-code-advanced

1 messages Β· Page 2 of 1

undone coral
#

you're stil rendering the previous frame when you start the next frame, in unity

haughty niche
#

"the type or namespace 'mirror' could not be found"

undone coral
#

so once you stopped ReadPixels you stopped waiting for the render thread to finish

haughty niche
#

why cant it find mirror anymore?

undone coral
#

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

stuck onyx
#

that would be awesome

#

but dont hurry

#

ill be here

undone coral
#

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

stuck onyx
undone coral
#

but

stuck onyx
#

ah sorry

undone coral
#

what it really is is

#

"all the work here, there is no gameplay (meaning main thread) dependencies on it"

#

when you do readpixels

stuck onyx
#

aha

undone coral
#

as far as unity is concerned, you are using the texture for gameplay

#

main thread == gameplay

stuck onyx
#

got it

undone coral
#

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

stuck onyx
#

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

undone coral
#

yes

#

it assumed that it was

stuck onyx
#

shit but... yeah got it but, damn,

#

they tell you, " do this inside the lateupdate bla blΓ±a bla"

#

but dont tell you that

undone coral
#

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

stuck onyx
#

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?

undone coral
#

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

rugged radish
#

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

undone coral
undone coral
#

you're adding a command to a big queue

undone coral
#

yeah i meant no, it's not an anti-pattern

#

it's gucci

rugged radish
sly grove
#

I was agreeing with you doc πŸ˜‰

sly grove
rugged radish
#

right now they are static, but I do want to add animation down the line

tough knoll
#

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

rugged radish
#

still not sure if gpu instancing will fit my case, but it's definitely good information to learn and keep in mind πŸ‘

tough knoll
#

Definitely test

#

I recently discovered that on older hardware my game is about 10fps slower with GPU instancing enabled : S

rugged radish
#

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

undone coral
tough knoll
#

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

rugged radish
tough knoll
#

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

strong harbor
#

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.

  1. Is there any way to know on a tilemap what tiles have something placed in them?
  2. Is there any way to place tile grouping on the same tilemap
rugged radish
strong harbor
#

I can elaborate far better for my exact situation

undone coral
prime thorn
#

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

undone coral
undone coral
prime thorn
#

yeah i just have no clue how to pin point the issue

undone coral
#

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

undone coral
#

change nothing

strong harbor
strong harbor
undone coral
#

you can search for an asset store asset that might help you

strong harbor
#

I see I see. Thank you for the help

gritty nacelle
#

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

undone coral
#

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?

somber tendon
#

πŸ€” 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
undone coral
#

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

crimson ruin
#

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?

novel plinth
#

as you said, you already have a list of gos... then instantiate those? πŸ™‚

#

I see zero correlation between serialization and instantiation

somber tendon
crimson ruin
somber tendon
crimson ruin
unkempt nova
#

You are. They're doing something different I think, using prefabs

rugged radish
#

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

hushed fable
rugged radish
# undone coral i think if you're at 144 fps you're fine

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

crimson ruin
crimson ruin
unkempt nova
#

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

hushed fable
#

Yea my advice was made with the assumption that you would need this in build

#

Editor should have more options and IDs available

novel plinth
# crimson ruin The problem is that those GOs are created during gameplay, when the scene is loa...

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

placid shell
#

is there anyway to grab an enumerator out of a dll file or should i just manually recreate them in c#?

novel plinth
#

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

unkempt nova
#

Speaking of which, any chance I could get a link to that? I figure there are many

novel plinth
#

Marshalling?

unkempt nova
#

The C# discord, sorry

novel plinth
#

Sorry on my phone, dont know how to send invite

placid shell
unkempt nova
#

Someone else got me, thanks @novel plinth

novel plinth
#

See.. the bot wont allow me to post c# discord link. Lol

unkempt nova
#

Ah yeah forgot it'll eat them

novel plinth
#

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

unkempt nova
#

Sounds useful, thanks

thin mesa
stuck onyx
#

is someone familiar with this?

#

the first 2 captures got that weird texture

#

for them im trying to use this

unkempt nova
#

I wanna say I've seen this before and the solution was clearing the GPU's buffer before changing the data in it

valid ore
#

Collider[] hitColliders = Physics.OverlapSphere(center, (float)0.1);
how to use it in a thread that is not the main thread?

mint kraken
valid ore
#

And there is no way to trick it?

sly grove
valid ore
#

I don't understand how to change this Collider[] hitColliders = Physics.OverlapSphere(center, (float)0.1); to a SpherecastCommand

sly grove
#

start by looking at the example in the docs

valid ore
#

How to fix it?

#

@sly grove

rugged radish
#

it tells you in the error message

#

try TempJob

valid ore
#

And how to do it?

sly grove
#

yeah the error tells you exactly what to do

valid ore
#

What to do?

hoary pendant
#

It says right there

sly grove
#

you should be starting your job from the main thread basically

hoary pendant
#

Main thread and dispose the NativeArray

sly grove
# valid ore 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

wind gyro
#

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?

stuck onyx
#

how to set the device so it pauses when we are looking at the profiler ?

granite viper
#

You can stop recording on the profiler

stuck onyx
#

yeah but i've seen its possible to set it so the device stops

granite viper
#

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

stuck onyx
#

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

granite viper
#

Hmm, I don't recall that option

stuck onyx
#

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

hallow cove
#

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

stuck onyx
#

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

somber swift
half marten
#

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.

fickle inlet
#

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

sly grove
# fickle inlet Could you recommend what to use?

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

fickle inlet
#

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

sly grove
#

if there's no physics then what is causing a curvature

#

it's just a line right?

undone coral
fickle inlet
#

raycast finds end position

#

and start position is camera

#

and camera is always above the raycast hit position

sly grove
fickle inlet
#

But I need it to be curved

sly grove
undone coral
fickle inlet
#

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?

sly grove
#

I'm saying you want to draw some curvature

#

presumably this is in advance of you actually throwing some object in your game right?

fickle inlet
#

Yes

sly grove
#

Is this curvature also what you will use to prescribe the path of that object?

fickle inlet
#

I need a trajectory where it will fall

#

yes

sly grove
#

Or does that object already have a way of moving a curved path from a to b?

fickle inlet
#

grenade will follow the line

sly grove
#

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

fickle inlet
#

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

half marten
bold slate
undone coral
real mortar
#

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?

half marten
undone coral
#

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"

half marten
#

But the likelihood that the npc is telling the truth is also dependent on the testimonies from other sources

undone coral
#

(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

undone coral
#

"the testimony of this npc B is accurate" "this npc B is trustworthy" etc. etc.

hallow cove
#

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

undone coral
#

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"

hallow cove
#

so I have a generic Type, and I want to make a new array of that Type

undone coral
#

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?

half marten
undone coral
#

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?

half marten
undone coral
#

what is the gameplay

half marten
#

No, not a logic problem

#

I'm working on an experimental dialogue game. Not even really a game, just an idea

undone coral
#

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

half marten
#

I'm trying to model belief of past events, based only on testimonies from sources

undone coral
#

which is latent, it is unknown

#

okay well i think you'll figure this out

#

the thing you need is a bayesian network

half marten
undone coral
#

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

half marten
#

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

undone coral
#

you can use prolog if you want to solve and express that kind of logic puzzle more simply

undone coral
#

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 πŸ™‚

half marten
undone coral
#

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

half marten
#

I think you've misinterpreted the system, and what I'm trying to do

undone coral
#

"if the npc has told more than N lies, not trustworthy."

#

that's it

half marten
#

You can forget about computing NPC trust, imagine that's a known number

undone coral
#

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"

half marten
#

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?

undone coral
#

somewhat trustworthy is a Rhubarbist gameplay concept

half marten
#

Forget about the player for now

undone coral
#

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?

half marten
#

It's not a binary thing

undone coral
#

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

half marten
#

Bayesian networks do use 0 to 1 probabilities though?

undone coral
#

in a bayesian network, the nodes are booleans

#

the directed arrows between nodes are expressing a relationship that the bool affects another bool

half marten
#

With a certain weight?

undone coral
#

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

half marten
#

That example confirms what I was saying? The belief that it rained isn't 0 or 1, it's 0.2

undone coral
#

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

half marten
#

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.

undone coral
#

anyway i think it's pretty interesting

half marten
#

If two sources share identical descriptions of an event, our belief of that specific description should take in both of those observations.

undone coral
#

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

regal olive
#

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

undone coral
#

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

undone coral
#

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 πŸ™‚

obsidian glade
#

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

undone coral
#

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.

half marten
#

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?

undone coral
#

i think maybe try something simple you can wrap your midn around

#

because "probabilistic prolog" is a million times more confusing lol

undone coral
#

i'd have to try making this thing to find out

#

wait until you discover Pyro

#

your head is going to explode

half marten
#

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

obsidian glade
#

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

half marten
#

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

obsidian glade
#

sounds like you've already started on the iteration πŸ‘

half marten
undone coral
#

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

half marten
half marten
#

Prolog?

undone coral
#

i would search "github c# bayesian network"

obsidian glade
obsidian glade
# half marten See this graph for example

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

half marten
obsidian glade
#

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

#

πŸ€·β€β™‚οΈ

half marten
half marten
obsidian glade
#

from the original question it doesn't seem obvious to me that that would be the case

#

especially if each attribute is independent

half marten
#

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.

half marten
obsidian glade
half marten
half marten
obsidian glade
#

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

half marten
#

It just needs to feel right, but it needs to feel right in every given situation.

wooden bronze
#

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.

fast pagoda
#

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

wooden bronze
#

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

strong harbor
#

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?

undone coral
#

it's a cool idea

strong harbor
unborn bramble
#

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.

tawny kraken
#

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");
      }     
  }
misty glade
#

@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

tawny kraken
stuck onyx
unkempt moat
#

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 ?

thin mesa
#

not an advanced issue. but you have to call Init on the instance, it isn't a static method

unkempt moat
#

Like this ?

#

I think I did something wrong, I do not have any Instance I guess

thin mesa
#

that's NetworkManager, not the NetworkTransport

unkempt moat
thin mesa
#

how did you get an instance of the object to attempt to disconnect?

unkempt moat
#

With the client Id

thin mesa
#

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

unkempt moat
#

Okay thank you :)

scenic helm
#

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!

novel plinth
#

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

stuck onyx
#

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();
fresh salmon
#

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

stuck onyx
#

but should that affect the performance so much?

fresh salmon
#

It depends where the stream points to

stuck onyx
#

disk

fresh salmon
#

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

stuck onyx
#

yeah it pooints to Application.persistentDataPath

stuck onyx
#

like...

using var stream = new FileStream(path, FileMode.OpenOrCreate);````
#

?

fresh salmon
#
using (var stream = new FileStream(...))
{
  // consume resource
}
// disposed here
stuck onyx
#

ah ok i remember this now

#

as you said is closed and disposed automatically if we do it like that

thin mesa
fresh salmon
#

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

stuck onyx
#

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?

fresh salmon
#

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

fresh salmon
#

Oh, and it seems it also implements IAsyncDisposable, so you can do

await using FileStream stream = ...
#

The disposal will be awaited

scenic helm
#

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

novel plinth
#

If I were you, I'd just copy the implementation of Zstring πŸ‘€

#

mind you, it's deprecated for a reason...

stuck onyx
fresh salmon
#

On MSDocs, it isn't explicitly told, but I scrolled down to the methods section and saw DisposeAsync being there

stuck onyx
#

hmmm maybe my c# version does not implement it

#

i think that must be c# 8 ?

fresh salmon
#

It's there for .NET Framework 4.8

#

Also there for .NET Standard 2.0

stuck onyx
#

hmmm how am i getting this then?

stuck onyx
fresh salmon
#

Alright, then keep the standard, non-async using

stuck onyx
fresh salmon
#

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

stuck onyx
#

πŸ˜„

#

this is specific to unity?

#

any specific version or all of them?

fresh salmon
#

Yep, that's Unity docs

#

Any version that uses C# 8

stuck onyx
#

well.. thanks a lot

#

πŸ™

sage radish
#

2021.2 has full C# 8 support and partial C# 9 support.

crimson ruin
#

It's so unintuitive that destroyed GameObjects stick around a frame, why can't the API at least unparent them?

novel plinth
sly grove
crimson ruin
undone coral
undone coral
mint sleet
#

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!

undone coral
undone coral
#

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

frosty elm
#

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?

stuck onyx
#

thanks again doctor!

undone coral
undone coral
undone coral
undone coral
undone coral
#

SetActive(false) in contrast will immediately call OnDisable.

stuck onyx
#

hmm

undone coral
#

it's that they stick around until a certain time that is counterintuitive

stuck onyx
#

what about memory? they must use some no?

#

or is it too little that doesnt matter?

undone coral
#

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?

undone coral
#

yeah, too little to matter

undone coral
#

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*

stuck onyx
undone coral
#

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:

stuck onyx
#

this is what i did, already inside a UniTask:

undone coral
#
// 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

stuck onyx
#

the reason of using... 'using' is to dispose automatically of the stream no? if we are doing it manually whats the point?

undone coral
#

because i'm not sure if your unity supports async disposables

#

if you are on the threadpool

#

you can use using var ...

stuck onyx
#

no it doesnt, it doesnt support them

undone coral
#

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

#

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.

stuck onyx
#

i want to wait until the UnitaskVoid has finished, shall i launch it like

#

await UniTask.WhenAll(myTask);

undone coral
#

can you give me a little more context?

stuck onyx
#

im saving 16 textures on a loop

#

so i have to wait till 1 is finished to save the next one

#
  1. render 1/16 part of the screen
  2. 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 πŸ˜…

undone coral
#

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

stuck onyx
#

thanks gonna try

#

hmmm

#

cant do mate

#

writeAllBytesAsync not available

#

i guess thats why i chose the stream

undone coral
#

hmm

#

it should be

stuck onyx
#

cant I writeAllBytes on a different thread and wait for it?

undone coral
#

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

stuck onyx
#

im putting all my effort but nott completely, just that WriteAllBytes on a thread might f** ** me hard

undone coral
#

i'm not sure even WriteAllBytesAsync helps you much.

#

it will throw an exception if you have a problem with the file path

stuck onyx
#

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

undone coral
#

i'm saying ios might decide, in an afternoon

stuck onyx
#

ah

#

okay, yeah got it

undone coral
#

"apps only get 1MB to write to, if we feel like it"

stuck onyx
#

yeah, wouldnt be surprising

undone coral
#

do you see what i mean

#

no contracts

#

you can ask for temporary files, that has worked the best in my experience

stuck onyx
stuck onyx
#

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

undone coral
stuck onyx
#

do I need the whole library?

regal olive
#

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.

fresh salmon
#

There's ScreenCapture.CaptureScreenshotAsTexture that gives out a Texture2D you can manipulate further. No idea about the performance of that method though

stuck onyx
#

take a look at this

#

@regal olive

#

first you set up a renderTexture, asign it to the cam you want

regal olive
#

Thanks that's very helpful.

stuck onyx
#

call AsyncGPUReadback.RequestIntoNativeArray
(ref _buffer, _rt.flip, 0, OnCompleteReadback);

#

and you have it

regal olive
#

wow that's slow

#

one second per call

#

is that expected?

#

oh nvm

#

there's a one second timer lol

alpine adder
#

when using async and await in unity for things like api calls do I have to worry about thread lock?

misty glade
#

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)

sly grove
sly grove
undone coral
undone coral
#

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

tough knoll
#

Hey while you're here

#

What are cases where synchronously writing files would block indefinitely?

alpine adder
tough knoll
#

@undone coral

undone coral
#

lol

undone coral
#

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

alpine adder
undone coral
rugged radish
#

they do have some drawbacks, people may choose coroutines intentionally

alpine adder
rugged radish
alpine adder
rugged radish
#

well, Unity documentation used to have a "Avoid async/await" in bold letters not that long ago πŸ™‚

#

might be why

undone coral
#

unity is going to integrate unitask and unirx

#

coroutines were created before Tasks

hushed fable
#

Tasks are also problematic on WebGL platform due to use of System.Threading, which UniTask addresses.

sharp moon
regal olive
#

what is the best solution for having a websocket server in an unity game as of now?

novel plinth
#

tbf, it's WebGl issue not Unity or tasks... webgl supports for multi threading is just non-existent

hushed fable
#

It's not obvious when the async API uses unsupported System.Threading features

novel plinth
#

webGpu tackled this issue

hushed fable
#

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

novel plinth
#

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

novel plinth
hushed fable
#

Yes, at least on a GPU

novel plinth
#

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

novel plinth
#

they later removed the notes, but the issue still there

#

proly they though it was bad for marketing purposes

hushed fable
#

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.

novel plinth
#

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

hushed fable
#

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.

novel plinth
#

give me a sec

#

as for the implementation, they are different from one to another

scenic helm
# novel plinth If I were you, I'd just copy the implementation of `Zstring` πŸ‘€

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

hushed fable
#

Where does the WebGPU spec talk about new web workers implementation?

novel plinth
hushed fable
#

You sure they aren't just talking about how you can use WebGPU APIs from existing web workers

novel plinth
novel plinth
#

and with some adjustment obviously, to your needs

scenic helm
# undone coral the performance issues with textmesh pro / ugui aren't from copying even large s...

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.

novel plinth
#

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

scenic helm
#

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.

novel plinth
novel plinth
#

and i doubt if it will perform better than zstring

scenic helm
novel plinth
#

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

scenic helm
#

fair enough. and yeah it doesn't seem like they would expose it any time soon.

novel plinth
#

the proposal was there since 2018 lol...

scenic helm
#

thanks

regal olive
#

Hello, what library should I use to have a websocket server in my unity game?

compact ingot
placid shell
#

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?

placid shell
compact ingot
placid shell
compact ingot
placid shell
#

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?

compact ingot
placid shell
#

it just crashes unity on hitting play

compact ingot
#

Sounds like segmentation fault

placid shell
#

unfortunate

#

what usually causes them?

compact ingot
#

accessing memory that the OS has not assigned to the process

placid shell
#

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?

compact ingot
placid shell
compact ingot
placid shell
#

thankyou! That would make sense, as i do not know if i have the type correct yet!

thick rain
#

Anybody here working with netcode for gameobjects?

thick rain
#

oh thanks

placid shell
untold moth
#

Something?

placid shell
untold moth
placid shell
untold moth
placid shell
untold moth
#

Just mark them with a private accessor.πŸ€·β€β™‚οΈ

placid shell
untold moth
#

Then don't make them private.πŸ€·β€β™‚οΈ

placid shell
#

but they are private in the dll? Do you think it would be ok?

untold moth
#

I don't see the issue.

untold moth
placid shell
#

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

untold moth
#

Yours defined in your assembly(potentially namespace). Theirs in their.

placid shell
#

im afraid i dont know what that means?

untold moth
#

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.

placid shell
#

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?

untold moth
#

It will. Because it expects something else.

placid shell
#

oh, well how can i get it to be happy then?

untold moth
#

Use their struct.

placid shell
#

how, it is a private struct in the dll? How do i pull it out?

untold moth
#

Then you can't.πŸ€·β€β™‚οΈ

placid shell
#

how would i pull out a public struct in a dll then, let us start with that

untold moth
#

Unless you get the source code, make it public and recompile the dll

untold moth
placid shell
#

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

untold moth
untold moth
#

Is it returned as a pointer? Hard to say anything without seeing the code in question.

placid shell
undone coral
undone coral
#

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!

final heath
#

I want to make a vr combat system with swords but I dont know how to detect swing length and force. Can anybody help?

stuck onyx
#

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

compact ingot
stuck onyx
#

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 ?

compact ingot
stuck onyx
#

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 ?

compact ingot
rugged radish
#

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

compact ingot
#

if you just check the token, nothing is actually cancelled but what you manually skip

stuck onyx
#

hmmm okay lests see...

#

i think ThrowIfCancellationRequested is enabled on UniTask by default

#

so...

compact ingot
#

it just returns a completed task

stuck onyx
#

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
    }````
compact ingot
#

idk, never used that

stuck onyx
#

okay ill do some tests

compact ingot
#

its a discouraged API

stuck onyx
#

discouraged?

#

what do you mean?

compact ingot
#

you're not supposed to use it

#

but its there if you run into situations where you have to

stuck onyx
#

i've heard doctorpangloss say unity is going to include it

#

unitask and UniRx

compact ingot
#

UniTask does this a lot, the longer the method name the more "discouraged" its use is

stuck onyx
#

hmm, thanks a lot Anikki!!!

#

btw , aniki comes from the japanese or some sort of alien stuff

compact ingot
#

but its only discouraged based on the opinion of its author ofc

compact ingot
stuck onyx
#

yeah, callme oyabun

#

XD

compact ingot
#

its also a regular norwegian/finnish name

stuck onyx
#

ohh, youre from norway?

compact ingot
#

nope

stuck onyx
#

cool, because it sucks

compact ingot
#

no dissing of other cultures!

stuck onyx
#

lol i dont diss the culture, i just dont like the country XD

compact ingot
#

yeah, this is not the place for discussing that kind of opinion πŸ˜„

stuck onyx
#

true

compact ingot
#

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.

stuck onyx
#

yeah i understand till certain point how threads work, thats why im not multithreading, just using async/await

compact ingot
#

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

stuck onyx
#

my own async with primitives? what do you mean ?

rugged radish
#
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

compact ingot
stuck onyx
#

oh, okay, I got it

compact ingot
#

there is a lot of nuance to it, but its all there, no secret sauce needed

undone coral
#

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:

  1. 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
  2. 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
  3. 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

stuck onyx
#

i can know if they have been finished or not but saving cpu is more important so i rather 1b

undone coral
#

you can't actually cancel a file writing operation

stuck onyx
#

so stop everything and start again when possible

undone coral
#

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

stuck onyx
#

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

undone coral
#

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

stuck onyx
#

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?

stuck onyx
#

or this is sh**t

#

and i must pass the cancellation token by parameter

undone coral
#

you have to make it a method argument in order to pass it down

stuck onyx
#

and check

stuck onyx
#

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

undone coral
#
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(); 
}
stuck onyx
#

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

undone coral
#

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

stuck onyx
#

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

undone coral
stuck onyx
#

you know, like when player moves, i set the FPS to 60

#

and when player is idle i set to 30

undone coral
#

if you want to yield more time

stuck onyx
#

so thats when i do this operations

undone coral
#

yeah

#

that makes sense

#

it's a little tricky to detect when you are idle

#

you can estimate how much time you have

stuck onyx
#

if player moves i cancel, but its not like im gonna stop in the middle of writting the snap into disk

undone coral
#

this is why in practice, you pick a fixed amount of work and spread it out

stuck onyx
#

nah it doesnt have to be exact, right now the script is damn quick

undone coral
#

you don't try to measure when you're idle

stuck onyx
#

ill fix the cancel thing

undone coral
#

cancellation makes the most sense for tasks that compose a bunch of steps

stuck onyx
#

im pretty proud of what the script does and since you helped me id like to share it with you

undone coral
#

cool

#

yeah i'm glad to spread the joy of tasks

stuck onyx
#

well im sure there must be stuff that can be inmensely improved though πŸ˜…

undone coral
#

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

stuck onyx
#

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

undone coral
stuck onyx
#

oh shit

undone coral
#

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?

stuck onyx
#

you converted the callback into a task

undone coral
#

yeah, in a way

#

i made a way to wait for the callback

#

that is ergonomic

stuck onyx
#

yeah, i wanted to do something like that for so many parts of my code

undone coral
#

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

stuck onyx
#

Promise is from js correct?

undone coral
#

yes

#

it's older than that i'm sure

#

but you see what i'm saying

stuck onyx
#

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

undone coral
#

i don't remember what the task completion source is called

stuck onyx
#

yep, googling the error

undone coral
#

okay

#

iut's jsut the types

#

i don't know if async gpu readback gives you the result on the main thread

stuck onyx
#

thanks a lot again once is finished ill send you the script

undone coral
#

i assume it does

misty glade
#

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.

pale zinc
#

those don't need POT textures by the way

#

In most cases crunch compression can dramatically reduce memory footprint without being noticeable

misty glade
#

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

pale zinc
#

drag out the preview window

#

on the texture, not the sprite

#

uncompressed NPOT texture of that size can easily be 8mb

misty glade
#

yeah lol, i made that exact same texture 2 pixels wider:

#

1/4 the size

pale zinc
#

for DXT5 that matters a lot yeah, but if it's impractical to make the texture POT, you can use different compression techniques

misty glade
#

how do you enable that preview window? Dumb question I know but I can't seem to locate it.

pale zinc
#

should just be at the bottom of the inspector (not in debug mode)

misty glade
#

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

pale zinc
#

looks like this if it's folded in; just click it or drag up

misty glade
#

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

pale zinc
#

oh yeah

#

wait, what

#

lol

misty glade
#

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)

pale zinc
#

I just have my inspector embedded like normal

misty glade
#

preview window/widget of the inspector.. there's gotta be a way to enable it for the .. uh.. embedded view

pale zinc
#

can you take a screenshot of your entire window

#

it's weird if it's not there

misty glade
#

oh

#

hahaha i found it

#

alllllllllll the way hiding at the bottom

#

i would have assumed it would appear "after" the other components

#

derp.

pale zinc
#

yeah it's just the general preview window; it also shows materials, prefabs, etc

misty glade
#

What do I look like, an artist? Gimme code or gimme death. πŸ˜‰

#

(As an aside the preview window for scripts is .. terrible)