#archived-code-advanced

1 messages Β· Page 84 of 1

strong harbor
#

let me test something

sly grove
#

it's part of it surely

#

you're creating a new list in every iteration of your while loop

strong harbor
#

that is very fair

sly grove
#

also not sure where movementTiles is getting populated from

strong harbor
#

from this section

#
GridTile start = MapManager.instance.map[gridPosition];

        movementTiles = new List<GridTile>();

        int step = 0;

        List<GridTile> tilesToCheck = new List<GridTile>();
        tilesToCheck.Add(start);

        while (step < movementRange)
        {
            var surroundingTiles = new List<GridTile>();

            foreach (var tile in tilesToCheck)
            {
                surroundingTiles.AddRange(pathFinder.getNeighbourTiles(tile));
            }

            foreach (var tile in surroundingTiles)
            {
                if (!tile.status.Equals("Occupied") && pathFinder.findPath(start, tile).Sum(t => t.movementPenalty) <= movementRange)
                {
                    movementTiles.Add(tile);
                    tilesToCheck.Add(tile);
                }
            }
            step++;
        }

        movementTiles = movementTiles.Distinct().ToList();

        foreach (var tile in movementTiles)
        {
            movementTilemap.SetTile(tile.gridPosition, moveTile);
        }```
#

this is in a different menthod

#

and is storred in the character script

#

the character then invokes the switch statement to display what ever the selected action is

novel plinth
#

.net MAUI can do mobiles and desktops. If you already familiar with UIToolkit in Unity, the concept is similar and you can do flex-box layout in maui like you would in Unity's UIToolkit.

strong harbor
#

which i guess could be a memory thing, but there is no other stat that like sky rockets that would indicate an issue

#

so this is becoming a head scratcher still

sly grove
strong harbor
untold moth
strong harbor
untold moth
#

I asked like 30 min ago to show the last frame that has the cpu time spike.

strong harbor
#

gothca i can send that

untold moth
#

Profiler in hierarchy mode btw.

#

Sort the hierarchy by CPU time and expand to the deepest item that takes most of the time.

strong harbor
#

i think i am doing this correctly

#

this is of the last frame where there is a massive spike

untold moth
#

If you look at the item that has the biggest time value, it's the Editor Loop. To see what exactly in the editor loop is taking that time, switch the profiler to editor mode(where it says play mode now)

#

That being said, you should probably try profiling a build as well and see if the issue is present there.

strong harbor
untold moth
#

You could try breaking on your button press and then step through the frames untill you get the spike.πŸ€”

#

Use Debug.Break to break from code.

strong harbor
#

that isnt the worst idea, my main curiosity is it has to be something special since its not like an explosion on the first one, its once i press it a couple times

#

hold on i can take a video and youll see the slow down

#

but yeah that has been the problem im trying to solve, the mechanic of switching between different actions to see ranges doesn't really work if when you go back to click on your third or fourth 1 the game colapses

untold moth
#

Well, can't really help you much without the profiler data.

strong harbor
#

I am trying to figure out how to get you a snapshot of the editor mode

untold moth
#

It would be enough to see the spikes on the first or second click to be able to guess as to what's going wrong

strong harbor
#

Notably, there was also a huge jump on the rendering section for triangles and verticies for some reason

untold moth
#

It shouldn't be too difficult to capture the frames of the second/third click.

strong harbor
#

so do you want me to run the game

#

have the profiler open

#

and trying to press the button and then stop?

untold moth
#

No need to stop

#

You can pause the profiler recording in the profiler window to stop it from scrolling on.

strong harbor
#

oh isee

#

i was going to ask i didnt see anywhere how to like

#

scroll across past what is shown on the base window

#

cause the window is stuck in like

#

a ~300 frame window

#

i dont see a timeline to truly scroll across

#

nevermind im dumb

untold moth
strong harbor
#

gotcha so i need to be fast then

untold moth
#

You need to stop the recording before your frame goes out of range.

strong harbor
#

ok i can try

untold moth
#

300 frames is like 5 seconds. Should be more than enough time to just click one button.

strong harbor
#

i see the jump but it like shoots by instantly

#

i think i caught a button press though

#

i think this was me being fast enough

untold moth
strong harbor
#

yeah basically

#

but i think i caught it

untold moth
#

If you press the stop recording button during the stutter, it should pause on the next frame.

strong harbor
#

did you just want to see a heirarchy again?

untold moth
#

Yes

strong harbor
untold moth
#

Not again through. You should be in the editor mode now with different info in the hierarchy.

#

You're allocating a 290 mb in a frame here

strong harbor
#

yeah im noticing that as well as the number of calls

#

a good clean 5.7 million calls

untold moth
#

Event system updateπŸ€”

strong harbor
#

yeah not entirely sure what that is

untold moth
#

Can you repeat that with deep profiling enabled?

strong harbor
#

where do i enable that

#

cause im happy to

untold moth
#

In the profiler window. On top.

strong harbor
#

ah i see

#

it seems to be something with the showWeaponRange() function

#

specifically with my pathfinding

#

unless im reading this wrong

untold moth
strong harbor
#

hmmm

#

see i figured my pathfinding was very optimized and decent

#

i feel like my pathfinding code is some of the oldest in this project

untold moth
#

Are you sure about that?😁

strong harbor
#
public List<GridTile> findPath(GridTile start, GridTile end)
    {
        List<GridTile> openList = new List<GridTile>();
        List<GridTile> closedList = new List<GridTile>();

        openList.Add(start);
        while(openList.Count > 0)
        {
            GridTile currentTile = openList.OrderBy(x => x.F).First();

            openList.Remove(currentTile);
            closedList.Add(currentTile);

            if (currentTile.Equals(end))
            {
                //finalize path
                return getFinishedList(start, end);
            }

            foreach (var tile in getNeighbourTiles(currentTile))
            {
                if (closedList.Contains(tile))
                {
                    continue;
                }
                
                tile.G = GetManhattenDistance(start, tile);
                tile.H = GetManhattenDistance(end, tile);

                tile.previous = currentTile;


                if (!openList.Contains(tile))
                {
                    openList.Add(tile);
                }
            }
        }

        return new List<GridTile>();
    }```
untold moth
#

Not with all the list allocations, it's definitely not optimized at all.

strong harbor
#

this is the code, welcome to see where i am just wrong and doing something super dupe

regal lava
#

should really learn to hook the debugger up too and let your code go through it all

untold moth
#

It's the opposite of optimized. But that's not the issue

#

The issue is that you call pathfinding from your weapon or whatever 5k times.

strong harbor
#

yeah that findPath call is in a for loop

strong harbor
strong harbor
untold moth
strong harbor
#

it shouldnt be though

#

which is the confusing part

#

doing some digging

untold moth
#

Then there's a bug.πŸ€·β€β™‚οΈ

strong harbor
#

the old classic

untold moth
#

Step through the code and see where the loop iteration count goes wrong.

strong harbor
#

yeah im doing that now

#

ok the pathfinder was only called 57 times which is semi ok

#

i think i could shorten that

#

ok there is the jump

#

that is so bizzare

#

clicking the button twice goes from 57 calls to 5k

#

yeah it just keeps increasing

untold moth
#

Where do you decide on that loop count?

#

Share the code?

strong harbor
#

what loop count?

#

like where am i getting that number?

#

its just the number being produced from the code

#

i put some print statements in the loop at the base level then further in

#

collapsing the console lets me count

#

i could see the the showWeaponRange is called once

#

but the pathfinder function is called 57 times on the first button press

untold moth
#

The whole script preferably.

strong harbor
#

sure i can

#

hmm

untold moth
strong harbor
#

hold on gotta test if something happened for a reason or if i was dumb

#

well that is interesitng

#

oh wait nevermind that makes total sense

#

this is the code, i realize it has the cs at the front

#

this is the loop in question causing problem

#

or 1 version of the loop

#

since this is the ranged weapon version vs the melee weapon version

#

they are very similar

#

the only real difference is in the if(path.Sum...) comparrison where some of the condition logic is a tiny bit different

untold moth
#

Please share it properly.
!code

thorn flintBOT
strong harbor
untold moth
#

I don't see you clearing the surroundingTiles anywhere. So each time you call that function, more and more tiles are being added to it.

strong harbor
#

that was exactly what i was thinking

#

although i do clear it at the start of the while loop

untold moth
#

Oh, didn't notice that.

strong harbor
#

i was still thinking i want to do a surroundingTiles.Distinct

untold moth
#

In which case the only explanation is either the range value goes up every time, or the movementTiles are not cleared, or there's an issue with the pathfinder returning more neighboring tiles than expected.

#

It should be pretty easy to debug if you just step through the code on the second click.

strong harbor
#

well that range isn't possible since its set as a value on the class itself

#

the movementTiles are technically not really cleared, but they are passed in as a method call so I don't see why that would happen but im happy to test if for some reason they are getting bigger

#

but ima try this distict call and see if that just cuts it right down

#

regardless, this has been a ton of help

#

i have 0 clue how long it wouldve taken me to find where the problem was on my own

untold moth
#

You can set a breakpoint on line 26 and check the size of the surroundingTiles, since that's what's deciding the count of pathfinding calls ultimately.
That times range to be precise.

strong harbor
#

true

#

ok already 57 -> 28 lol

#

314 -> 67 on second button press

#

its still going up but the cut is still cutting

#

so there is still something to figure out

#

556 -> 94

untold moth
#

What does the error imply? And the numbers before and after it?

strong harbor
#

the before is number of entires in the surroundingTiles array

#

the after number is how many are in the array after only having distinct entries

#

there is the still the question of why number go up

untold moth
#

Well, look at where you add the elements to that array.

#

I bet that attackTilesToCheck size goes up as well

strong harbor
#

yeah im checking that as well

#

putting in a lot of checks right now cause something is likely not being cleared when it should

#

and its causing exponential increase

untold moth
#

In which case, the movementTiles size is going up as well and is the culprit.

strong harbor
#

well it isn't going up lol

#

its going down

#

wait its also going up

#

why in the world

#

ok that is totally what it is

#

why would it go up though it shouldn't change

untold moth
#

Well, where do you set it..?

strong harbor
#

in a completely differnet function

untold moth
#

Then look at that function lol

strong harbor
#

i just checked the function isn't like, being called again

untold moth
#

Then it's modified somewhere else.

#

Make it into a property and break in the setter.

strong harbor
#

but i just dont understand how that is possible, the movementTiles are never modified besides that one point

untold moth
#

Then they are either modified or they're set to an unexpected value that one time.

#

If it's changing, then something changes it.

strong harbor
#

but i dont know how

#

it is changing

untold moth
#

There's no magic in code. It's just what you wrote.

strong harbor
#

i checked the length of the array and its increasing

#

but i dont know why or where

untold moth
strong harbor
#

perhaps

untold moth
#

You can also just set the breakpoint on the variable for when it's modified.

#

Break in scope of the variable access so that you can see it in the locals. Right click -> break when value changes. Then continue.

strong harbor
#

ok im going to lose my mind but i pinned it down

#

i ahve a section of code where the change someone has to occur

untold moth
#

Someone has to occur?

strong harbor
#

well its more so

#

i put a print statement

#

at the end of the showWeapon range

#

and its apparently changed by the end of it

#

so im going to slowly narrow down where in the world the change happens

untold moth
#

What change?

strong harbor
#

when the movementTiles amount changes

#

well i somehow got it slightly narrowed down

#

its somewhere

#
Debug.Log("probe 1 " + movementTiles.Count);

            foreach (var tile in surroundingTiles)
            {
                if (tile.status.Equals("Friendly") || tile.status.Equals("Enemy"))
                {
                    attackTiles.Add(tile);
                }
                else
                {
                    attackTilesToCheck.Add(tile);
                }

                Debug.Log("PATHFINDER CALL");

                var path = pathFinder.findPath(start, tile);
                if ((path.Sum(t => t.movementPenalty) <= range + movementRange && path.Sum(t => t.movementPenalty) > movementRange) || path.Count == range + movementRange)
                {
                    attackTiles.Add(tile);
                }

            }

            Debug.Log("probe 2 " + movementTiles.Count);
#

in here

untold moth
strong harbor
#

ok well, i know where its changing

#

for some reason

#

each iteration of that foreach loop

#

increases the movemenTiles by 1

#

omfg wait

#

does this line for some reason like, link these two objects together

#

so that is attackTilesToCheck changes

#

movemenTiles changes

#

that has the be the only possible option

#

but in my 8+ years of programming I dont think I have ever seen this happen

strong harbor
#

they are just List Objects

untold moth
#

Oh, they're not just an int?

strong harbor
#

no they are full list objects

untold moth
#

Lists are reference type, so when you use the assign operator, you get a reference to the right side object.

#

So any changes to the object on the right would obviously be reflect to the object on the left and vice versa.

strong harbor
#

how has this never caused me a problem before

#

i feel like i have done this so many times

#

and never had an issue

untold moth
#

Donno. It's a pretty basic thing to know.πŸ˜…

strong harbor
#

no i agree

untold moth
#

Well, it wouldn't cause issues if there are no changes to the reference on the right.

strong harbor
#

well there aren't changes to movemenTiles

#

but it seems that when attackTilesToCheck is changed

#

movementTiles gets changed too

#

so I need to recall now how to instead take a snap shot of movementTiles instead

#

which might be a choppy toArray

#

maybe toList would work

untold moth
#

You can create a new list.

#

But that would be one more pointless allocation added to the whole thing.

#

Which is a separate problem.

strong harbor
#

yeah toList worked

#

omg what a random bug

untold moth
#

Or just pass the list you want to copy into the constructor of a new list.

strong harbor
#

true but that would mean i have to recreate the list every method call

#

which might be fine might not be

untold moth
#

The orthodox way, but I guess ToList is gonna work too, although it's not intended for this use case specifically.

strong harbor
#

fair enough

untold moth
strong harbor
#

gotcha

#

well that was an adventure

untold moth
#

Hopefully, you've learned how to profile and debug more efficiently.

strong harbor
#

i have, which will be so much more helpful down the line now

#

this has been a confusing but very helpful experience

#

i really appreciate you willing to help a random person on the internet

green crane
#

I am back with my problem again. So far I've gotten the system working, but the problem is that it plays on Update (I intended it to do that). I don't know what's a good way to let my system detect when the correct button has been pressed, and change the scene.
SceneChanger script: https://pastebin.com/qbjKMS8X
DialogChange Script: https://pastebin.com/YN7cxLWV
DialogOptions Script: https://pastebin.com/WLKnfRfU

Here's what I got. I've managed to get it working but it triggers when the game starts (I know, I'm using Update to make sure it does), is it possible to make an event that calls out to the DialogChange script and Invokes both methods once I click on the correct dialog option?

wraith snow
#

Hey all, I have a PID controller that's controlling a space ship translating between to points. The PID caluclates force to add to the rigidbody and moves from A to B using apply force. I want to do something similar using add torque to turn but all my attempts thus far have been very cursed.

has anyone ever attempted something like this? In my head I see it as comparing the angles between two vector3's in space and making the PID approach 0, but caluclating the angles always becomes spagetti, especially when my rigidbody is child of a transform that is not orientated at 0,0,0

Has anyone tackled this before?

Edit: I also tried using lerp'd lookAt quats and rigidbody.rotate but the angualr velocity always read out 0, so I'm worried that if the rigidbody has a collision it will end up spinning forever. This approach pretty much gave me exactly what I wanted but it didnt work using forces the way I was hoping

hearty shoal
#

Not sure if this is the right place for it, but I'm a little confused about why domain reloading is taking so damn long.

I have an assembly. The assembly doesn't reference many other assemblies, and is not referenced by many other assemblies. It's not auto-referenced. Yet, when I save something in it, I have to domain reload for 20+ seconds. I know you can remove domain reloads for play mode, but can you disable it for re-compiles?

#

My current version is 2022.3.4f1 (LTS, not latest tho)

upbeat path
hearty shoal
#

But isn't the whole point of assemblies that it should only reload the assembly you're working in?

upbeat path
#

no, I suggest you read up on domain reload

compact ingot
hearty shoal
#

Is there a way to reduce domain reload time?

compact ingot
#

disable it entirely

hearty shoal
#

I found a setting to disable it in playmode, is there a way to disable it entirely?

upbeat path
hearty shoal
compact ingot
#

you obviously cant avoid loading the domain before playing it

#

so after compiling you have to reload it

#

usually long domain reload times are a sign of a memory leak

hearty shoal
compact ingot
#

shouldn't take > 15 seconds in 2022+ on a mid sized project

upbeat path
compact ingot
#

if you use a lot of editor scripting, validators and such, you could eliminate/optimize those

#

avoiding absurd generic APIs that generate variants for 1000s of types could help (reduces the amount of code to reload)

#

if you use a lot of SOs, check what they do OnEnable, maybe there is something wild going on there

hearty shoal
#

A couple do, but nothing too wild

#

I'll continue my search

#

There does seem to be a leak somewhere, as you suggested, as a restart did help

upbeat path
jagged stone
#

i'm trying to include a DLL in my builds for linux dedicated servers. when i check this box and hit apply, unity unchecks it automatically. no errors in console. anyone have any idea wtf is going on here? thanks

#

also - can i can manually place it in my build's plugins folder, and it will load properly

cerulean wasp
#

whenever Unity gets too slow, I just restart it

#

usually once every few days

mellow sail
#

is there a way i could attach a gif file into an image UI canvas?

undone coral
#

are you sure it's compiled for linux?

#

is this a native DLL for windows?

undone coral
jagged stone
#

so i simply made it part of my build script lol

#

annoying to have to work around it

undone coral
# jagged stone it works if i manually copy it into a linux build

well there are a bunch of wacky scenarios that could be causing this:

  • you have an asset post processor that is "unchecking" this
  • there is something messed up about the file or metadata, so while you may be able to copy this, it will not work when you actually deploy it
  • there is an error, but it is being suppressed for some reason
#

i think odds are highest that something is messed up about the file

#

ignore it at your own peril

undone coral
indigo citrus
#

Hey I am freaking out, I don't know what is wrong! But my audio on Android is delaying almost a second. When in editor this does not happen, it just plays instantly.

#

It is in WAV format

#

The sound is added to a audiosource in different objects that are spawning through the screen, when you click them the sound plays and they get destroyed. The sound must play pretty fast as the game is quite fast paced so it doesn't make sense that you get a delay of 1 second each time you click a object.

#

When you stop clicking the objects you even hear more one sound that comes from the delays.

jagged stone
#

you'll hear about it soon πŸ˜‰

dusty wigeon
indigo citrus
#

Yeah already tried

#

I am using v2023.1.17f1

undone coral
indigo citrus
dusty wigeon
#

Then, you know your issue is probably wht is written there

scenic forge
dusty wigeon
indigo citrus
scenic forge
#

Look at the forum thread linked by @dusty wigeon above.

indigo citrus
#

I linked it ;-;

#

But yeah I only found that out after posted here

#

I just kept to know if there was any update on that

scenic forge
#

Can't downgrade?

left timber
#

I'm trying to implement scrolling functionality for a controller/keyboard input using the new input system. My content, which is dynamically generated, is placed within a scroll rect content. While mouse/slider input allows for scrolling, I want the scroll to move up or down based on the direction when near the top or bottom. I also need to support left and right movement. How can I achieve this?

dusty wigeon
left timber
undone coral
#

has anyone developed a dummy AR plugin? I am struggling to wrap my mind around the sheer complexity of the XR namespace, and why it doesn't even use InputSystem

#

if i have a remote stream of camera pose data aka a Matrix4x4 for the camera, why is it so challenging to pipe that in? why are there so many moving parts?

sinful hamlet
#

Hello, is there a way to determine at Unity Gaming Services whether a player is an admin or a normal user?

undone coral
#

what does that mean

jagged stone
undone coral
#

something something voxel asset

regal jasper
#

Hey Team!

Bit of a wild shot, but do you guys know about a libc.dll in Unity?

It seems like System.threading.tasks relies on it, and it fails to run with WebGL.

Has anyone seen / overcome this?

novel plinth
#

Just a note, WebGL can't do threadPool. Make sure you're not doing that in your code

regal jasper
#

Thanks for the heads up @novel plinth !

I'm working with Nethereum and mainly rely on tasks. I don't think WebGL likes tasks lol

flint sage
#

Webgl is single threaded

#

So it's easy to get into deadlocks

regal jasper
#

Man WebGL - The bane of my existence haha

novel plinth
#

In the case of multithreading in WebGl, the SharedArrayBuffer compatibility across browsers is the issue and is the source of most security concerns in webgl.

Some browsers simply aren't supporting it due to security reasons

novel plinth
regal jasper
#

Interesting!

Thank you for sharing that @novel plinth !

If this doesn't work, looks like I'm building a JSLIB πŸ˜‚

raven sleet
#

Hey guys. Does anybody here know how to call a function from a script from another script without using tags?

novel plinth
#

I mean if it's a web request, you can always do it asynchronously which I assume that's what you're doing with the Netherium*(I don't know what that is tbh, proly crypto stuff)*

sly grove
opal minnow
# raven sleet Hey guys. Does anybody here know how to call a function from a script from anoth...

Let's say you have 2 scripts User script and Another script. If those are mono behaviours in your scene it is pretty simple.
Inside your User script you add a field for Another script e.g.
[SerializeField] private Another another;
then you use the method inside of the User script like:

    another.SomeMagicMethod();
}```
in order for it to work, you need to set the reference in the inspector. You click on the object with the User script and drag and drop into the Another field the game object with Another script.
undone coral
#

previously you were trying to interact with the metamask wallet right? and then it sounds like you're trying to import a C# ethereum library? what is your goal?

frozen imp
#

@red flax Don't cross-post, please

regal jasper
#

But I do have my own multiplayer game => https://untitledplatformer.io that uses an existing SDK which got deprecated, so I'm rebuilding my own version of it.

Untitled - Adventure Into The Blockchain!

Real-Time Multiplayer. Free-To-Play and Entirely Gas Free, Untitled sets itself apart from other blockchain games!

#

Sorry can't remove embeds on my phone πŸ˜…

shell horizon
#

Anyone who has more experience with native collections and burst than I do: I'm trying to use a native parallel hash map with a pretty significant amount of entries (around 500,000), but when I use ContainsKey I get significantly worse performance than I'm expecting. I was under the impression the time complexity would be O(1), but it seems to scale with the number of entries in the map. Am I doing something wrong or is this intended?

undone coral
shell horizon
# undone coral can you show a snippet of code?

Populating in a regular IJob:
Vector3Int hash = TerrainManagerUtility.Hash(new Vector3Int(influenceIndex.index.x, index.y + y, influenceIndex.index.z), influenceIndex.coord); weightChanges.TryAdd(hash, new PersistentWeightChange(weightChange));

Retrieving in a parallel job:
Vector3Int hash = TerrainManagerUtility.Hash(coords, chunkCoords); if (persistentWeightChanges.ContainsKey(hash)) { weight += persistentWeightChanges[hash].weightChange; }

undone coral
fresh salmon
#

A first optimization would be to use TryGetValue on the collection, so it only accesses the collection once instead of twice.

undone coral
#

what is the native parallel hash map you are using?

shell horizon
undone coral
#

what is the type

shell horizon
#

The key is a vector3int and the value is a custom struct

undone coral
#

😦

fresh salmon
#

A Dictionary then

#

Use TryGetValue

undone coral
#

do you mean NativeParallelHashMap<Vector3Int, T>?

shell horizon
#

I mean NativeParallelHashMap<Vector3Int, PersistentWeightChange>

undone coral
#

what exactly is significantly worse performance?

#

can you be more precise?

#

like what is going on in this code

#

it looks like you are using a hash map to sparsely store... what?

#

parallel (concurrent) hash maps are complex

#

for starters, if you want to write in parallel, you have to access its .ParallelWriter object explicitly

#

can you show the line where you construct the hash map?

shell horizon
#

I'm storing changes to certain indices in different chunks by hashing the chunk coordinates + the index inside that chunk into a vector3int, and then checking each index inside each chunk for a value in the hashmap

fresh salmon
shell horizon
undone coral
#

this is like, what fixing these problems looks like

#

answering a bunch of questions as quickly as possible

shell horizon
#

persistentWeightChanges = new NativeParallelHashMap<Vector3Int, PersistentWeightChange>(1000, Allocator.Persistent);

undone coral
#

it's confusing to me, you're saying you're using jobs, and a NativeParallelHashMap, and you THINK you're not writing in parallel

#

okay

#

well why did you initialize it with a capacity of 1,000

#

if you know there will be 500,000 entries?

shell horizon
#

I don't know explicitly how many there will be

#

1000 is just a good starting point

#

the main problem Im trying to figure out

undone coral
#

you have to set that to 500,000

shell horizon
#

I don't think I do?

undone coral
#

you very much have to

#

go ahead and try that first

#

this is how hashmaps work

#

especially concurrent hashmaps, which are complex

shell horizon
#

I have to set the inital capacity specifically to 500,000, even though it could be higher than that?

undone coral
#

you should specify it to the highest capacity you expect, although i think there is a lot going on in your code

#

you're asking me to speculate about something only you have read

#

go ahead and make this change and see what the impact is

#

another big problem is you're using Vector3Ints as keys

#

Unity's hashcode for it is extremely poor for your use case*, so there would be a lot of collisions

    public override int GetHashCode()
    {
      int hashCode1 = this.y.GetHashCode();
      int hashCode2 = this.z.GetHashCode();
      return this.x.GetHashCode() ^ hashCode1 << 4 ^ hashCode1 >> 28 ^ hashCode2 >> 4 ^ hashCode2 << 28;
    }
#

this is a very bad hash code for your use case

#

they don't expect people to use Vector3Ints as keys, so i wouldn't give them a hard time about it

#

certainly not in the way you're using it

#

which it sounds like, if there are 500,000 elements or more, it's not really sparse, is it?

#

I'm storing changes to certain indices in different chunks by hashing the chunk coordinates + the index inside that chunk into a vector3int, and then checking each index inside each chunk for a value in the hashmap
maybe give me a bigger picture description of what you're doing, and post as much of the code as you think illustrates what this algorithm is doing

#

i think the biggest problem is that you are using a parallel hash map, but you say you are not doing work in parallel

#

there is a significant performance impact for that

shell horizon
#

Okay, so changing the initial capacity hasn't changed anything as far as I can tell, the performance still seems to worsen as the hashmap grows in size, which is contradictory to what I expected. The problem I'm trying to solve, is that I need to be able to map a value to both the chunk coordinates and the index inside that chunk, and since there's no multi-key native collection (as far as I can tell), I figured my best bet would be to hash those two numbers into a vector3int so I could store it in one large hashmap. The code I've shown you is pretty much everything there is, aside from the hash caclulation

undone coral
#

what are you trying to say?

#

there is a NativeHashMap in the collections package

#

supposing 100% of what you are saying is true, like let's say you have observed the correct thing - that ContainsKey takes longer with the number of elements - that is saying that the hashing function of your keys has many collisions

#

not the one that you authored, but the one that unity authored

#

and indeed, for 500,000 distinct vector3ints, if they were densely populated, we can even compute based on the GetHashCode function, what the collision rate is

#

that's just how hashmaps work

#

hashcodes do collide

#

each mapping is a hashcode to a list of key-values internally

#

when there's a hashcode collision, the key-values are scanned until your matching key is found

#

i said the capacity issue because that's just straight from the textbook

#

does this make sense?

fresh salmon
#

Using a tuple might mitigate the hash collision issues

shell horizon
#

So you're saying that the Unity hashcode for vector3int is the culprit?

undone coral
#

now it's MORE LIKELY that you are not observing the correct thing

undone coral
#

you appear to be doing some other "Hash" step

#

which you didn't want to show

#

it's not clear what this algorithm is doing

#

you didn't want to post the code

#

you can also try using the NativeHashMap collection instead of the NativeParallelHashMap

shell horizon
#

`private static int Hash(int a, int b)
{
int A = a >= 0 ? 2 * a : -2 * a - 1;
int B = b >= 0 ? 2 * b : -2 * b - 1;
return (A + B) * (A + B + 1) / 2 + A;
}

public static Vector3Int Hash(Vector3Int a, Vector2Int b)
{
return new Vector3Int(Hash(a.x, b.x), a.y, Hash(a.z, b.y));
}`
you never asked for the hash code, and I think I explained what the algorithm is doing as best as I possibly can

undone coral
#

okay well

shell horizon
undone coral
#

what is the idea here?

#

why are you doing this?

shell horizon
#

Combining the chunk coordinate and index inside that chunk

undone coral
#

i don't think this does what you think it does

shell horizon
#

I wasn't aware of how collisions worked with hashmaps, but not that you've explained it, I'm assuming I've made some mistake and this function I've created is causing a significant amount of collisions, in turn causing terrible performance as the hashmap grows

shell horizon
# undone coral i don't think this does what you think it does

https://stackoverflow.com/questions/919612/mapping-two-integers-to-one-in-a-unique-and-deterministic-way I read about it after finding this thread, and the code works perfectly so I'm not sure how it wouldn't

undone coral
#

i don't think you should be using vector3ints

#

or a cantor pairing function

#

what is your key supposed to actually be?

#

why not declare a struct that describes the key? it sounds like it's

short x;
short y;
short z;
byte xIndex;
byte zIndex;

right?

#

i can't really tell because i odn't know what this is doing

#

then you can declare a hashcode that makes sense for your usecase, however it doesn't sound like this is actually sparse

shell horizon
#

Yes, but I figured that would be slower

undone coral
#

you shouldn't use a hashmap at all

#

simply use a 3d array

#

it is hard to tell. is this sparse?

undone coral
#

so try to define your struct first

#

what your key should actually be

shell horizon
# undone coral simply use a 3d array

I was, but the problem is that when I'm producing the pairs the results could be in any of a number of chunks, and since this is for infinite terrain generation, I can't just create a massive 3d array

undone coral
#

using the native arrays. this is shorthand.

#

the size of the chunks should be tuned for locality.

#

really depends if any of this stuff matters

#

i gotta go

shell horizon
#

okay, thanks for the help

drifting plinth
#

I can't access anything in a PlayerDataObject without it returning a null reference error. With Unity Lobby.
My total code can be found here: https://pastebin.com/TTqQDbvR

I get a null reference error when ever I try to access the data in a PlayerDataObject.

{
    try
    {
        Debug.Log("Listing Players in " + joinedLobby.Name);
        //Debug.Log(joinedLobby.Players[0].Data.);
        foreach (Player player in joinedLobby.Players.ToArray())
        {
          Debug.Log(player.Data["playerName"].Value + " " + player.Id); <---
        }
    } catch (LobbyServiceException e)
    {
        Debug.LogError(e);
    }
}```
I put the data in the player object with the GetPlayer() method:

```private Player GetPlayer(string playerName)
{
    return new Player
    {
        Data = new Dictionary<string, PlayerDataObject>
        {
            { "playerName", new PlayerDataObject(PlayerDataObject.VisibilityOptions.Public, playerName) }
        }
    };
}```
I have no idea what to do because I have never used DataObjects before now.
Any help would be greatly appreciated.
sly grove
#

Is this not just a basic NRE?

#

How do we know the player from GetPlayer has anything to do with the one in that array?

drifting plinth
# sly grove How do we know the player from GetPlayer has anything to do with the one in that...

I don't full understand the question. But, I'm using Unity's Lobby service to sync player data and this is the provided way of holding strings under a "PlayerDataObject" and letting you pull it out on other clients with player.Data["playerName"].Value which returns the data stored under the string. I don't know if the problem lies with the lobby not syncing or me storing the data improperly but this is driving me crazy.

sly grove
#

The first step for ANY NullReferenceException is to figure out what is null

#

You're wasting your time guessing if you haven't figured that out yet

drifting plinth
#

The player.Data is null sorry if I didn't explain that.

sly grove
#

How do you know that

drifting plinth
#

Referencing it in anyway returns the error.

sly grove
#

Use the debugger or debug.log and prove it first. Maybe player itself is null for example

drifting plinth
#

Its not because player.Id returns the id as a string.

#

Debug.Log(player.Data["playerName"].Value + " " + player.Id);

sly grove
#

But you're accessing both there..?

#

If that line works then Data is not null

drifting plinth
#

I have done both separably.

#

Data is null Id is not.

sly grove
#

Ok so you'd have to show how these player objects get into that list in the first place

vale zenith
#

How would y'all recommend storing groups of 3 float pairs that need to be accessed frequently at runtime?

I'm doing List<((float, float), (float, float), (float, float))> but I feel like that may be crazytalk

drifting plinth
#
    {
        try
        {
            JoinLobbyByCodeOptions joinLobbyByCodeOptions = new JoinLobbyByCodeOptions
            {
                Player = GetPlayer(playerName)
            };
            Unity.Services.Lobbies.Models.Lobby lobby = await Lobbies.Instance.JoinLobbyByCodeAsync(lobbyCode, joinLobbyByCodeOptions);
            joinedLobby = lobby;
        } catch (LobbyServiceException e)
        {
            Debug.LogError(e);
        }
    }``` The Data is stored with the unity lobby.
vale zenith
#

do you know if there's a performance difference between the tuples method I used and using a struct?

sly grove
#

ValueTuples are literally structs

#

You're already using them, you just didn't name any of the fields basically

vale zenith
#

Got it, so structs would simply add more readability. Thank you

sly grove
#

Yes

twin parcel
#

Hello, I woke up this morning and my Unity editor is running SO SLOW!!

#

The only thing that's changed since last night (when it was fine, like always) is Unity Hub updated to 3.6.0

#

Could that have messed up my editor somehow??

humble leaf
#

Unity Hub has nothing to do with the editor, nor does this question with advanced code.

vale zenith
#

Anyone know why I'd get NullRefExceptions when referencing a list of structs from a different class, but it works fine if referenced in the class it's a part of?

twin parcel
#

@humble leaf Apologies. Which room do you think I should ask in? It's not code but it seemed like an advanced problem!

twin parcel
#

Cool thanks

sly grove
novel plinth
warm flume
#

So im having a problem with the animator

#

Whenever the state changes the camera looks in a different direction when it should be continouing from to play the animation its original pos

#

Is this the wrong place?

austere jewel
#

Does it have anything to do with code, and is it an advanced problem?

warm flume
#

Oh mb I didnt see that

lament briar
#

Hi! Any way to avoid WaitForJobGroupID lag? I'm not using any jobs but every time I build my navmesh it lags with WaitForJobGroupID. I have no clue why it's doing that since it should be async (I'm using the UpdateNavMeshDataAsync method). I've been stuck there for the past week, please if you have any advice, it would be really appreciated ❀️

lament briar
#

What's weird is that it should be an async method, so it should not block the main thread.

compact ingot
lament briar
compact ingot
#

maybe you just have a mistake in your code

#

it would make no sense to return a async operation when the process is blocking

#

how to you await the completion?

mellow sail
#
 public IEnumerator ShootArtillery(Vector3 currentTargetPosition)
 {
     airstrikeBulletSpawnPoints[1].parent.position = new Vector3(currentTargetPosition.x + OffsetSpawnPointParent.x, currentTargetPosition.y + OffsetSpawnPointParent.y, 0f);
     List<GameObject> airstrikeBulletInstance = new List<GameObject>();

     for (int i = 0; i < airstrikeBulletTargetHits1.Length; i++)
     {
         airstrikeBulletInstance.Add(Instantiate(airstrikeBullet, airstrikeBulletSpawnPoints[0].position, Quaternion.identity));
         airstrikeBulletInstance.Add(Instantiate(airstrikeBullet, airstrikeBulletSpawnPoints[1].position, Quaternion.identity));
         foreach (GameObject airstrikeInstance in airstrikeBulletInstance)
         {
             airstrikeInstance.SetActive(true);
         }
         airstrikeBulletInstance[0].transform.DOMove(new Vector3(airstrikeBulletTargetHits1[i].position.x, airstrikeBulletTargetHits1[i].position.y, 0f),
             Vector2.Distance(airstrikeBulletInstance[0].transform.position, airstrikeBulletTargetHits1[i].position) / 30f).SetEase(Ease.Linear).OnComplete(() =>
             {
                 StartCoroutine(DestroyAfterHit(airstrikeBulletInstance[0], airstrikeBulletTargetHits1[i]));

             });

         airstrikeBulletInstance[1].transform.DOMove(new Vector3(airstrikeBulletTargetHits2[i].position.x, airstrikeBulletTargetHits2[i].position.y, 0f),
             Vector2.Distance(airstrikeBulletInstance[1].transform.position, airstrikeBulletTargetHits2[i].position) / 30f).SetEase(Ease.Linear).OnComplete(() =>
             {
                 StartCoroutine(DestroyAfterHit(airstrikeBulletInstance[1], airstrikeBulletTargetHits1[i]));
             });

         yield return new WaitForSeconds(0.1f);
         airstrikeBulletInstance.Clear();
     }

     Destroy(gameObject);
 }

I need help, why does the startCoroutine on the OnComplet DOMove didnt get called? But if i move it outside, it will get called?

dusty wigeon
spare lance
#

Hey does anyone know how the force of the SpringJoint2D is calculated ? I know there is a built in method to get the force but I need to know the math behind it so that I can apply a constant force by changing the frequency depending on the objects mass and distance.

pliant kite
#

yoo

#

my discord rpc isnt working

#

i have a script and everything, and the rpc is named DiscordRpc in my Plugins folder

#
using UnityEngine;

public class DiscordRichPresence : MonoBehaviour
{
    private DiscordRpc.RichPresence presence;
    private string applicationId = "1167936905518796830"; 

    private void Start()
    {
        DiscordRpc.EventHandlers handlers = new DiscordRpc.EventHandlers();
        DiscordRpc.Initialize(applicationId, ref handlers);
    }

    private void Update()
    {
        presence.state = "Developing Game"; 
        presence.details = "Creating You're A Duck 3";
        presence.largeImageKey = "woah"; 
        presence.largeImageText = "YAD3S2"; 
        presence.smallImageKey = "woah"; 
        presence.smallImageText = "INDEV";

        DiscordRpc.UpdatePresence(ref presence);
    }

    private void OnDestroy()
    {
        DiscordRpc.Shutdown();
    }
}```
thorn flintBOT
pliant kite
#

Apologies.

sly grove
#

SO what about it "isn't working"?

pliant kite
#

Oh yeah, here's the error: Assets\Plugins\DiscordRichPresence.cs(6,13): error CS0246: The type or namespace name 'DiscordRpc' could not be found (are you missing a using directive or an assembly reference?)

Assets\Plugins\DiscordRichPresence.cs(1,7): error CS0246: The type or namespace name 'DiscordRpc' could not be found (are you missing a using directive or an assembly reference?)

sly grove
vital fossil
#

Respected, I want to achieve this type of movement.
1- The rotate around rotation you see in the attached video is achieved by animation or code, and how?
2- I want the turning effect which you can at the end of the video, where force applied in the direction of face and then rotate until the gameobject will not straight.
Please guide.
thank you

pliant kite
#

The plugin folder is named DiscordRpc, and it is located in Assets\Plugins\DiscordRpc (the script is located in the same folder as DiscordRpc)

sly grove
#

It's a UPM package it shouldn't be dragged into Assets

pliant kite
#

I'm using a similar script, thats one that was reccomended to me recently. I'll look into the way they installed it, thanks!

#

Ah, I may have it still in folders, I need to individually unpack the SDK. thanks for the help

tranquil spear
#

I'm having a strange issue with Asset Saving where I'm overwriting an AnimatorController, but doing so loses its reference in my Animator components. I can get around this by storing the reference beforehand in the script and re-assigning it, but that doesn't help when the AnimatorController is assigned to other objects in the scene.

undone coral
tranquil spear
#

Its a CustomEditor that's running this yes.

undone coral
#

the screenshot of the editor script isn't that informative

tranquil spear
#

What other parts of it would you like to see? Most of the funciton is just assining what parts for the animation script

#

Heres the whole thing

undone coral
#

sorry i don't know anything about editor scripts

jolly token
tranquil spear
jolly token
tranquil spear
#

Thanks that solved it!

cunning citrus
#

Hi everyone, i have a problem on detecting the animation length by code... This code is supposted to do that... But it shows me 1 on the log, but the anim is quite shorter than that. This is the code and the animation length: ```cs
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public class LoadingScreen : MonoBehaviour
{
private float loadingCanvasTime = 2.4f;

[Header("Drag")]
[SerializeField] private GameObject loadingCanvas;
[SerializeField] private Animator loadingCanvasAnimator;
[SerializeField] private Animator loadingTextAnimator;

void Start()
{
    loadingCanvas.SetActive(true);
    StartCoroutine(CanvasTextFade());
}

private float time;
private IEnumerator CanvasTextFade()
{
    loadingTextAnimator.SetTrigger("ActiveLoadingFadeText");

    yield return new WaitForSeconds(loadingCanvasTime);       
    loadingCanvasAnimator.SetTrigger("ActiveLoadingCanvasFade");

    time = loadingCanvasAnimator.GetCurrentAnimatorStateInfo(0).length;
    Debug.Log(time);

    yield return new WaitForSeconds(0.3f);
    loadingCanvas.SetActive(false);
}

}```
I have to say that all anims are on the deffault layer, i have not touched that. On the next image you can see the log and the anim duration

soft marlin
# cunning citrus Hi everyone, i have a problem on detecting the animation length by code... This ...

just to get this out of the way first, when you call "loadingCanvasAnimator.GetCurrentAnimatorStateInfo(0).length;" are you 100% sure that the animation in question is the active one / the one that is playing?

for a more general solution, in awake you could do something like:

float loadingWaitTime = 0;

public void Awake() {
  // get all the clips on the animator
  var clips =  loadingCanvasAnimator.runtimeAnimatorController.animationClips;
  
  //find the clip you need by name
  foreach(AnimationClip clip in clips) {
    if (clip.name == "NAME OF LOADING ANIMATION") {
      loadingWaitTime = clip.length; // cache the clip length
    }
  }
}


// other code stuff

private IEnumerator CanvasTextFade() {
        // other code

        yield return new WaitForSeconds(loadingWaitTime); // use the time we found here

        //other code

        loadingCanvas.SetActive(false);
}

fresh salmon
cunning citrus
#

Ohh

#

Thank you both

#

😁😁

slim tree
#

How does one verify that a Roslyn Analyzer NuGet package is compatible with a given version of Unity?
NUnit Analyzer's readme states:

You should use an analyzer built with the same version of Microsoft.CodeAnalysis.CSharp as the one embedded in the Unity Editor.
Docs on analyzers does say:
Your source generator must use Microsoft.CodeAnalysis 3.8 to work with Unity.
but that only says source generators, so no explicit mention of pairing an analyzer with a specific version.
Is there a known documentation page that tells me which Microsoft.CodeAnalysis.CSharp version is "embedded into Unity" then?
I've seen other packages describe their compatibility using Roslyn compiler versions, though The docs only state a C# version, a seemingly separate variable than C# version. (Roslyn versions seemingly only applicable when not as a part of an IDE.)
Furthermore, I can't tell if Roslyn Analyzer package compatibility differs based on the active API Compatibility Level. Certain packages list out their requirements via Visual Studio versions or some .NET Version, which gets more complicated given this MS doc compatibility table.
Is there a simple answer to "what makes an analyzer compatible with this version of unity"?

tired fog
#

Hi!

#

If I have a task that is for example
for each
do X
do Y
add X and Y

can I assume that with jobs and Burst compiler, it will be faster to do:
schedule a job that does
does X
does Y
adds X and Y
than instead doing
foreach
schedule a job that does X
schedule a job that does Y
shedule a job that adds x and Y
??

#

would the first (single job) be faster than the second (task splitted into multiple jobs) or I can't make that assumption?

scenic forge
#

In general yes, scheduling a job is expensive.

tired fog
#

Cool then, thanks!

sly grove
brisk pasture
#

it would depend on how long running x and y are

#

if its not very complex would do it all in 1 job

#

but if they are operations that take a long time yeah would do it concurrently

#

or if its IO heavy work

regal olive
#

You know how when you double click a prefab, it opens up in that prefab editing scene? Is it possible to create my own custom prefab editor like that?

#

If it is, I guess any help in pointing me in the right direction would be appreciated.

brisk pasture
#

wanting your own editor, or just to change the envirement the prefab editing happens in

scenic forge
regal olive
#

Also I duno if I forgot to turn mention off, sorry if I didn't ^^

tired fog
#

If I have
Schedule Job X
Schedule Job Y
Schedule Job that adds X+Y

How could I write a job that does the three steps, without rewriting X, Y and X+Y? Like, what would be the way to reference and use the execute of X, the execute of Y while still filling it's parameters in a job?
Should i pass all parameters into a job, and then create and call the new jobs at each execute iteration?

#

Like execute (i)
{
JobX = new JobX(parameters)
JobX. Execute(i)

Job Y = new JobY(parameterd)
JobY. Execute(i)

.
.
.
}

#

Or is there a way to cache those job creations?

tiny pewter
#

is this iJobParallelFor?

tired fog
#

Yup

sly grove
# tired fog Yup

then you'd just do something like:

JobX jobX = new JobX(params);
JobY jobY = new JobY(params);
JobXY jobXY = new JobXY(params);
JobHandle xHandle = jobX.Schedule(length, batchCount);
JobHandle yHandle = jobY.Schedule(length, batchCount);
JobHandle combined = JobHandle.CombineDependencies(xHandle, yHandle);
JobHandle xyHandle = jobXY.Schedule(length, batchCount, combined);```
tired fog
#

Yeah, i know that, that's what I have

#

Im asking if I can do it the other way, the pseudocode i wrote

sly grove
#

nor would you want to schedule a new job for each iteration of some previous job if these are IParallelFor jobs

tired fog
#

Yeah, I wouldn't want to schedule a new job at each iteration. Could you explain why it's a bad idea to call job.Execute()?. Would it be better then to copy the code on first job and paste it into the job containing more code? @sly grove

open rapids
#

Does anyone know how to get an error from a DownloadHandler ?
I have this code:
var audioClip = ((DownloadHandlerAudioClip)www.downloadHandler).audioClip;
And it throws this error to the console:
Unable to determine the audio type from the URL
but it doesn't throw an exception and also the www.error property is empty. How do I get this error info?

regal olive
#

Would anyone know why my OnCollisionEnter callback won't fire? I'm setting up hitboxes for my Smash fangame. Hitboxes are standard CapsuleColliders, which should interact/overlap with one of 3 boxcolliders on the opponent's Mario? "HurtboxLw" (legs), "HurtboxN" (midsection) and "HurtboxHi" (head). Attack colliders are tagged "Hitbox", and the aforementioned hurtboxes all labeled "Hurtbox(type)", which is looked for in the hitbox's OncollisionEnter. But the callback won't trigger at all. Even the Debug.Log I put in the very beginning.

#

Code :

{
    Debug.Log("TEST 1");
    if (collision.transform.tag.StartsWith("Hurtbox"))
    {
        // TODO: hitbox.HitEffectEmit();
        SSBFHurtbox otherCode = collision.transform.GetComponent<SSBFHurtbox>();
        // Hitbox component: get data and apply it here.
        if (otherCode._State == HurtboxState.Damageable)
        {
            Debug.Log(collision.transform.root.name + " hit " + transform.root.name);
            PlaySoundEffect();
            int colliderType;
            collision.transform.root.GetComponent<SSBFAnimCMDUser>().TakeDamage(_HitData._Damage);
            if (collision.transform.CompareTag("HurtboxLw"))
            {
                colliderType = 2;
            }
            if (collision.transform.CompareTag("HurtboxN"))
            {
                colliderType = 0;
            }
            if (collision.transform.CompareTag("HurtboxHi"))
            {
                colliderType = 1;
            }
            else
            {
                colliderType = -1;
            }
            _User.TakeKnockback(colliderType, _HitData._Angle, _HitData._BaseKnockback, _HitData._KnockbackGrowth, 
                _User.parametersFile._Weight, _User.parametersFile._Gravity, _HitData._HitlagMultiplier);
        
        }
        if (otherCode._State == HurtboxState.Invincible)
        {
            // Collide with opponent, but take no damage or knockback.
        }
    }
}```
untold moth
regal olive
#

Well the colliders are children of the fighter gameobject.

I couldn't find much on Google, which is why I came here, no offence

#

I tried triggers and it didn't work, so I turned off "Is Trigger".

untold moth
#

Go through the guide that I linked. If it still doesn't work afterwards, share screenshots of your setup.

regal olive
#

Your guide talks about Rigibodies and Kinematic Rigidbodies. I put those in already as a safeguard. I'll just have to continue on.

#

Wait, I see something here about not using "transform.position". In a way I use that, I set the hitbox's position via "transform.position" to the body part it's supposed to be attached to.

untold moth
regal olive
#

I didn't expect this to be easy, I don't like working with rigibodies and this kind of collision detection :/ I will have to figure something out custom, as my environment and terrain collision detection is 100% custom. Oh well. Thanks anyway! πŸ‘

untold moth
#

100% custom would imply that you have your own physics engine and not using unity rbs, colliders or physics queries like raycasts.

regal olive
#

Oh what I meant was it's a custom system with colliders and Raycasts, yes. My bad. But no rigidbodies at all. I just plain don't like those personally.

untold moth
#

I also don't understand what does it mean to "not like rigidbodies personally"? I kinda feel like you just don't understand how they work and thus avoid them.

tall ferry
livid kraken
#

Anyone here used the CullingGroup API before? Does it take the baked occlusion culling into consideration when calculating visibility? I cant find evidence of this in the docs expect the particle example right at the beginning. Sadly I am afk and cant just tryitandsee

dusty wigeon
livid kraken
#

Looks like I cant read. Thank you πŸ˜„

fresh basalt
#

anyone used socketio? and maybe ran into an issue that it works great on editor, but on android device it just wont work. No errors, no warning, nothing.

compact ingot
fresh basalt
#

im already using it for signaling server for my webrtc connections

#

it works perfectly in editor

#

cant get them to work on android

compact ingot
#

I mean why use it for unity stuff

fresh basalt
#

what do you mean?

compact ingot
#

It’s a library for web apps, no reason to use it if you aren’t forced to use a JS stack.

fresh basalt
#

i need websockets

#

there is a proper port to csharp and unity, and everything is working as intended

#

just not on android

misty glade
#

I'm getting a frame stutter during gameplay that seems to be .. in DOTween calling LoadFMODSound? I don't have any tween-related code that's doing anything with sound. Anyone know what that might be?

sly grove
#

Is that one of yours?

misty glade
#

No

#

I'm not an expert in reading the profiler but I don't see any references to any sort of sound manager in the DOTween decompiled DOTweenComponent.Update() method

#

(and I double checked my own audio service and ensured that I'm not doing any DOtween audio tweening

#

i can pretty consistently repro this stutter but.. have no idea what it is

sly grove
#

Search your IDE for SoundManager? Is that part of DOTween?

misty glade
#

did, didn't find

sly grove
#

weird

misty glade
#

Couldn't locate inside DOTween but .. yeah.. I'm sorta stumped

#

i'm assuming SoundManager is an FMOD thing? like, I don't have FMOD but maybe dotween is using it?

sly grove
misty glade
#

intristink

sly grove
#

No solutions there but... at least some precedent

misty glade
#

there's a small solution buried in the thread it seems

#

something about loading in background

#

adding that to all my audio, we'll see what happens

#

well i still got a spike but at least it's something different now! prroooooogress 🎡

#

and probably not worth worrying about, some sort of editor GC or something

#

does unity use FMOD internally? I was looking for an FMOD dep in DOTween but it didn't occur to me that maybe it's built into unity

sly grove
#

I think there's some checkbox for it but... yes I think they do

misty glade
#

what's interesting is that A) this thread is 10 years old and still relevant (unity 2022) and b) that the .. profiler stack was .. wrong? that it showed a call to this soundmanager.load inside of an unrelated DOTween stack..

#

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

sly grove
#

if it's loading a scene

#

the scene may be loading an audio clip

#

oh sorry I misread

#

thought you wrote scenemanager

#

but... if dotween is somehow loading an asset in the tween, then that asset may be loading an audio clip

misty glade
#

hm... I don't think I have the tweens loading any assets that have sounds attached to them.. but ... I might be playing a sound inside of a some other sequence (not tweening the sound, but rather just doing some callback on my own audio manager to play a given sound)

craggy bronze
#

Hey all, does anyone know how to open an editor window through c#? Specifically the Timeline editor window?

"EditorWindow timelineWindow = EditorWindow.GetWindow<TimelineEditorWindow>(title: "Timeline", focus: true);"

Will focus it if its already open, but returns errors if it's not.

Thanks!

sly grove
#

GetWindow seems to say this:

If there is none, creates and shows new window and returns the instance of it.

craggy bronze
sly grove
#

probably because you defined a constructor for it that requires parameters or something

fresh salmon
#

Because it's abstract, as per the error message

sly grove
#

ah yeah that makes sense, nice catch

#

Yeah you'd have to do GetWindow<SomeConcreteClass> not an abstract class @craggy bronze

craggy bronze
fresh salmon
#

TimelineEditorWindow is abstract, thus it cannot be instantiated. Try to find a class that inherits from it, and pass that to the method

#

Looking at the docs, it seems that nothing (exposed at least) inherits from that abstract class. You might need to roll your own implementation or do some reverse-engineering to see what concrete type is behind the editor window when you open it manually

austere jewel
jade coral
#

Guys i'm making a dynamic culling system because i need to have a lot of objects instantiated in the scene, with a near camera fade. So what i did initially is using NativeParallelHashSet and its ExceptWith operations to get the difference of previous culled cells and current culled cells, and only activate and deactivate the differences. Unfortunately, the operation takes too much time (order of 300 ms for a ~4000 elements hashset). I haven't been able to fix it. Then basically i implemented my stupid hashset iterating two bool arrays every frame, and somehow that takes 1ms. Does anybody have any informations on why this might be the case? I have never had any performance problems with native collections before. Any insight is appreciated

craggy bronze
untold moth
jade coral
#

Ill take some time tomorrow for writing a benchmark on NativeParallelHashSet!

#

Then ill report here

warm fulcrum
#

Anyone have a clue why Test Framework 1.3.9 always gets stuck on Generate Context, as in the image? It happens regardless of test result, and doesn't seem to ever resolve.

It also fails to cleanup the scene it made, or unload the test scene sometimes, though I don't know what triggers that additional failure behaviour.

#

Jesus christ this thing is so utterly broken.

clever urchin
#

Just don't do tests is the answer clearly

warm fulcrum
#

It sure seems to be what Unity is telling me, yes.

#

I figured out what triggers it to not cleanup or run the tests though - it happens on every run except the first

#

Or... not? apparently now it happens randomly

compact ingot
clever urchin
steel snow
#

any one know why this wont delete the assets:

public static int DeleteAllSubAssets(this TankAsset asset)
{
    int i = 0;
    var objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GetAssetPath(asset));
    foreach (var obj in objs)
    {
        if (obj != null)
        {
            AssetDatabase.RemoveObjectFromAsset(obj);
            i++;
         }
    }
        return i;
}
``` i get 0 and the files are still showing up in the asset folder
#

objs.length==2 so that makes even less sense for why it wont remove

#

if i remove the null check i get an error saying cannot delete null aswell

lament salmon
#

(Or Undo.DestroyObjectImmediate)

untold moth
cerulean wasp
#

I want to run an algorithm for a physics simulation by someone. The goal here is to move things in reference frames (ie like they are parented in hierarchy). So block A rides block B rides block C…

  1. Move everything at the bottom (highest parent in hierarchy). Queue up all their children.
  2. At each child: Cast it to try to move it by the displacement of its parent.
    β€”If we hit something that has an unresolved upcoming displacement in the same direction (dot product > 0), then cancel and send us back to the end of the queue.
    β€”If not, then move, and queue all our direct children.
#

Assuming every movement uses Cast to check if cost is clear to move

jade coral
# compact ingot There may be hidden costs in the O(1) contains of a parallel hash set that you’r...

ok, i wrote this simple benchmark. From what it seems, the C# HashSet is 2x faster than its parallel native unity variant for big sets, like 10000+. At the same time, it's not nearly as slow as it seemed yesterday. Probably the slowdown was caused by doing operations directly on the job output, like this:
cullingJob.outCulled.ExceptWith(prevCulledCells);
This simple operation took 300ms for sets of 4000 elements.

untold moth
late lodge
#

Im doing a 2D assignment in unity where I have to code all physics myself -- Im doing pinball and working with raycasts. Currently Im working on an issue where the ball keeps getting stuck inside walls if there are more than one. Ive solved the issue where the ball will no longer get stuck in a wall if its the only thing it can hit, but if there are a collection of walls (like shown in the picture) it can still get stuck in any other wall.

I know in ProcessMovements i should do a CircleCastAll, but im not sure how to process that.
(Please ping if you respond, im in class)

{
    return Physics2D.CircleCastAll(transform.GetPosition2D(), radius, transform.forward ,0,  _filter.layerMask);
}

protected override void ProcessRaycasts()
{
    RaycastHit2D[] raycastHit2Ds = RaycastEdges();

    // Stop infinite bouncing
    if (velocity.magnitude < 0.09f) velocity = Vector3.zero;

    // Reflect the ball in the opposite direction.
    Vector2 normal = Vector2.zero;
    foreach (var rayHit in raycastHit2Ds)
    {
        normal = rayHit.normal;
        velocity = Reflect(velocity, normal);

        // Add extra velocity if the collision has a push
        var component = rayHit.collider.GetComponent<Pusher>();
        if (component != null)
        {
            velocity *= component.PushStrength;
        }
    }
}
// Done before applying ANY movement
protected override Vector3 ProcessMovement(Vector3 movement)
{
    Vector3 move = transform.position + movement;

    // Make sure the ball wont be inside of a wall next frame
    var r = Physics2D.CircleCast(transform.GetPosition2D(), radius, movement.normalized, movement.magnitude, _filter.layerMask);
    if (r)
    {
        Debug.Log(r.collider.ClosestPoint(move));

        pt = r.point; // Debug
        // Find a safe spot outside of the collider
        ct = r.collider.ClosestPoint(move);

        return ct;
    }

    return move;
}

private Vector2 Reflect(Vector2 enter, Vector2 normal)
{
    return enter - 2 * (Vector2.Dot(enter, normal)) * normal;
}
untold moth
jade coral
jade coral
untold moth
untold moth
#

Why the complicated raycast logic, when you can use unity physics?

late lodge
late lodge
# untold moth How are you moving the ball?

First ProcessRaycasts is run, then gravity is applied, and then ProcessMovement is run, then its applied to the transform ```void Update()
{
ProcessRaycasts();
ApplyGravity();

Vector3 move = ProcessMovement(velocity * Time.deltaTime);
// move the bullet
transform.position = move;

}```

untold moth
#

I mean, how are you actually moving the ball?

late lodge
untold moth
late lodge
#

alright, apologies

jade coral
# late lodge Here is the full code, please ignore the mess

void ghost, i wanna ask you a question. if using unity physics isn't allowed, are you allowed to use colliders and raycasts? You might want to implement some kind of separating axis algorithm for checking collisions, and some kind of spatial indexing (for example, for a finite world like the one you have, you can simply use one HashSet<int2> and a Dictionary<int2, Tranform[]> for holding the objects) to avoid checking the permutation of all objects

late lodge
untold moth
#

This shouldn't be that difficult. You just need to circle cast in the velocity direction the amount your ball is gonna move in the next frame. and clamp the movement if it hits anything.

jade coral
#

i encountered a strange bug with spherecasting mesh colliders: sometimes, i haven't been able to exactly reproduce when, the valid RaycastHit returned from 3d spherecast has the Point property set to vec3(0,0,0). Did anybody else encounter this strange behavior?

fresh salmon
#

How did you check that the hit was "valid"? Because the zero vector is the default value of that type, set when the raycast did not hit anything

vital fossil
#

Respected, my game is laggy only for the first time, when I remove it from the background, next time it works fine. In 2nd scene, many coroutines and updates are at the start.. I haven't experienced too much about the profiler. What should i do, 3-5 colliders are triggered... 10-15 updates almost.. And the 2nd scene is loading with "loadingsceneAsync" method.. Please guide.

lament salmon
#

Or are you talking about something else?

vital fossil
lament salmon
vital fossil
#

today is the deadline.. that's why i am asking here for fast response, becuase for now i haven't idea of the profiler, but if only this solution can work then I will learn it first

thin mesa
#

you would use the profiler to determine what is causing performance issues. otherwise it would just be guessing

slim fulcrum
#

Does anyone know if it's possible to access and use Airdrop features on iOS through unity?

plush hare
#

generally you'd calculate the overlap yourself, and solve for depenetration yourself. then create your new velocity from that.

#

it looks like your ball is moving too fast for the cast to see the wall infront of it until it's too late. Or maybe not. I didn't look too deeply at your code.

#

you should probably also stop moving your physics entities in the frame update. create your own fixed update loop.

undone coral
# slim fulcrum Does anyone know if it's possible to access and use Airdrop features on iOS thro...

Use the Native Share For Android And iOS from Smile Soft on your next project. Find this integration tool & more on the Unity Asset Store.

Use the iOS Screen Gallery Save and Native Share from No More Game Studio on your next project. Find this integration tool & more on the Unity Asset Store.

slim fulcrum
#

I've used one fo those before. My goal is that I want people with iphones to be able to airdrop custom folders that are created inside my app to toher users locally as they may not always have a wifi / data connection

#

so if one user has a set of files they can share it in person with another use.

#

simple as that.

#

Essentially the way airdrop works is what I need, but I don't know if I can use airdrop, doesn't seem to be a lot of information on the web

#

Says in there you can airdrop, I will check that out, thanks

undone coral
slim fulcrum
#

That's what im wondering also, just had that thought

#

I think you can provide it with a reciever

#

this could be fine for me, as im creating my own custom data structure for my apps data

#

Anyways something to look into thanks for the info

green roost
#

The official example here, for loading a scene Asynchronously https://docs.unity3d.com/ScriptReference/AsyncOperation-allowSceneActivation.html

It seems to me, that if I want code to run after asyncOperation.isDone, then naturally I should put it after the while loop while (!asyncOperation.isDone)

Yet it seems the example is encouraging you to put anything you want after the scene has loaded inside the while loop in the if (asyncOperation.progress >= 0.9f) block.

And indeed, if I put any code after the while loop, it never gets run, even after the while loop should be false and skipping over it. Can someone explain what's going on?

long ivy
#

if allowSceneActivation is false, loading will reach 0.9f and then stop until you allow activation. They just use that check to wait until you press spacebar before the scene becomes active

timber flame
#

Do you think sumulation survival games like oxygen not included has used behaviour trees to handle tasks, etc.?

compact ingot
steel snow
#

when we create submeshes will it maintain the order of the combined instances

#

for CombineMeshes function

spare anvil
#

im so confused

worldly imp
spare anvil
#

the errors

tiny pewter
#

not advanced question, and please configurate the !ide first

thorn flintBOT
spare anvil
#

my bad

worldly imp
#

So it should say public class UI or whatever

spare anvil
#

oh alr cheers

vital fossil
#

Respected, I am using line rendering of two points between two gameobjects. The staring point is stationary and ending point is continuing moving in any direction.
But the problem is if object is near to the camera then line renderer seen thick, if goes away it looks like ------
I try with different values but didn't achieved the right result.
My line rendering is the thin wire...
and the material i using on it standard->opaque. I have also tried unlit material.
Please guide.
Thank you

sly grove
vital fossil
#

physics involves in it.
that's why i am pasted here sir and major technicalities in it

tiny pewter
#

try to see the "line" in screen view from different angle, to see if the rect (or line) generated is "misaligned"

sly grove
#

you didn't actually even say what you are trying to accomplish

sly palm
shut surge
shut surge
sly palm
#

result: ProtocolError, responseCode: 404

shut surge
#

Where is your server being hosted? Are you testing locally, or are you using a service like AWS/Firebase?

#

Given that it's a 404 error, it might just be that the URI that you're making the request to could be incorrect

sly palm
#

The curl statement works, always.

devout hare
#

Debug.Log(query) and check that it's identical to the one used with curl

devout hare
#

Then it's not an issue with the query parameters

shut surge
#

What happens when you try to make a call using only the URI, do you end up getting a different error or do you still get a 404?

undone coral
#

there's nothing wrong with your put

#

are you trying to do this in webgl?

#

because PUT requests cannot be made in web browsers.

sly grove
#

Yes if you are using the wrong HTTP Method (e.g. PUT vs POST vs GET) you can get a 404 as well

#

even if the URL is correct

fickle inlet
#

Hey guys I have an issue that is making me desperate and it is difficult to elaborate

#

I have this method that writes user messages to chat. When new message is added, it appends it to the text component in UI. This is the code ```cs public void SendChatMessage(string sender, string message)
{
_chatContent.text += $"[{sender}] {message}\n";
UpdateContentHeight();
StartCoroutine(ScrollToBottom());
}

#

It works fine if I do it locally.

#

But I have a callback function from steam that can return message to all clients, here is the code ``` private void OnLobbyChatMsg(LobbyChatMsg_t callback)
{
CSteamID steamUserID;
byte[] data = new byte[4096];
EChatEntryType chatEntryType;

        int messageLength = SteamMatchmaking.GetLobbyChatEntry((CSteamID)callback.m_ulSteamIDLobby, (int)callback.m_iChatID, out steamUserID, data, data.Length, out chatEntryType);

        string message = System.Text.Encoding.UTF8.GetString(data);

        string sender = SteamFriends.GetFriendPersonaName(steamUserID);

        _chat.SendChatMessage(sender, message);
    }```
#

The issue is that messages can't be appended when I get the string from string message = System.Text.Encoding.UTF8.GetString(data);. When I do logs for both sender and messege it is fine, it does print correct info. But it can't be appended. There must be something with C# that I am not aware.

#

I am not looking for an answer, but just to point me where I could look. I am desperate to solve this.

compact ingot
compact ingot
#

then i'd just try logging and checking if the values that i assume to get from the API are actually the ones i get

fickle inlet
#

Yes they are, even on clients

#

It shows them in logs exactly how I want them

compact ingot
#

and what is _chatContent exactly?

fickle inlet
#

But I can't append them in UI. It only adds the first message and just repeats the first message over and oever

#

it's a text component tmpro

#

It works perfectly if I do local messages. But if I try to append string message = System.Text.Encoding.UTF8.GetString(data);
then it doesn't work. But I do log correct message from "string message", I just can't append it

compact ingot
#

so youre saying "message" and "sender" in SendChatMessage debug.log exactly as you want them but they are repeated in the .text?

fickle inlet
#

Yes. Exactly the first message that is sent is overwriten over and over. It is suppose to add new messages.

#

It acts as if I cacched the first message

compact ingot
#

well, have you actually tried what i suggested, not append to .text but to a separate variable outside .text

fickle inlet
#

Can you elaborate more?

compact ingot
#

c# strings are immutable, there is no appending, you can only compose new string out of existing ones, maybe something weird is going on, to figure out what, use the most explicit way to construct new strings available.

#

this eliminates all possibilities for weird caching, property return sideeffects etc

#

if you log that composed new string immediately before you assign it to .text (or use a debugger) and it is correct, then you know that something outside your code is going wrong

fickle inlet
#

If I hard code message string, it works fine

#

It will append hardcoded string to a new line

#

and it doesn't have to be hardcoded string, I can just use chat without steamworks where I can eneter whatever and it will still append

compact ingot
#

well, do you know 100% for sure at what line and on which method call the error happens?

fickle inlet
#

There is no error

compact ingot
#

then what are we talking about?

fickle inlet
#

I can't write a new message to a new line

#

It will only show the first message

#

So here are my theories, there is something with Encoding class and maybe it prints my value after .text is called, like an Async method or whatever. In logs it is printed before .text

compact ingot
#

how are your newlines encoded?

gritty delta
#

Would anyone know how to change a gameobject position between two positions based on a Blendshape value in the Start Function?

fickle inlet
#
private void SendChatMessage(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            byte[] messageData = System.Text.Encoding.UTF8.GetBytes(message);
            CSteamID lobbyID = new CSteamID(ulong.Parse(_lobbyData.LobbyID));

            SteamMatchmaking.SendLobbyChatMsg(lobbyID, messageData, messageData.Length);
        }
compact ingot
#

that doesn't do anything to your newline encoding

fickle inlet
#

what do you mean newline encoding?

compact ingot
#

\r\n vs. \r vs. \n

#

\r is just a carriage return that would not produce a newline for example

fickle inlet
#

aham

#

it is \n

#

_chatContent.text += $"[{sender}] {message}\n";

#

you can see \n at the nd

#

end

#

I don't encode \n btw. I do it after I get the string

compact ingot
#

well, i can only repeat myself, if you don't show a log of $"{existingText}[{sender}] {message}\n" and how that is correct, i cannot help you

fickle inlet
#

Ok I am sending it to you

#

Is this what you want ```cs
string log = $"Current text: {_chatContent.text}, sender:{sender} message: {message}";
Debug.Log(log);

compact ingot
#

yes, try that

fickle inlet
#

I did

#

So the result is it only prints Current text:

#

It does not log sender and message

compact ingot
#

you need to click the log message and look at the full version

#

console only shows you the first line

fickle inlet
#
UnityEngine.Debug:Log (object)
Birdmoot.UI.Messenger.Chat:SendChatMessage (string,string) (at Assets/Scripts/Runtime/UI/Messenger/Chat.cs:33)
Birdmoot.Steam.SteamChatController:OnLobbyChatMsg (Steamworks.LobbyChatMsg_t) (at Assets/Scripts/Runtime/Steam/SteamChatController.cs:60)
Steamworks.Callback`1<Steamworks.LobbyChatMsg_t>:OnRunCallback (intptr) (at ./Library/PackageCache/com.rlabrecque.steamworks.net@a3fe8091f7/Runtime/CallbackDispatcher.cs:291)
Steamworks.CallbackDispatcher:RunFrame (bool) (at ./Library/PackageCache/com.rlabrecque.steamworks.net@a3fe8091f7/Runtime/CallbackDispatcher.cs:191)
Steamworks.SteamAPI:RunCallbacks () (at ./Library/PackageCache/com.rlabrecque.steamworks.net@a3fe8091f7/Runtime/Steam.cs:112)
SteamManager:Update () (at Assets/Scripts/Runtime/Steam/SteamManager.cs:195)```
compact ingot
#

alright, so this means that the text in .text gets truncated at the newline once you assign it

fickle inlet
#

I made this log after _chatContent.text, let me log it before

#

So the first line worked, but not the second etc

compact ingot
#

can you show your tmp component with settings expanded?

fickle inlet
#

Sure

compact ingot
#

including the rect transform

fickle inlet
#

If I manually break line in editor, then I can write to a new line, which is weird

compact ingot
#

weird indeed, maybe you actually have some characters in your message that are causing this

#

maybe look at the actual bytes you convert to a string

fickle inlet
#

This thing is making me crazy, I am so desperate

compact ingot
#

why does this API actually give you bytes?

fickle inlet
#

Because I have to pass it

#

throught Steam API

compact ingot
#

yes, but do you know why that is?

fickle inlet
#

Because it is written in C++ and I am using a C# wrapper

#

They don't support Unity, it's just some dude made it for unity

#

Do you want me to log bytes?

#

Also my other theory is that my fonts are not supported or something

#

I tried with another font without success, maybe I should try another one?

#

Btw I have this warrning, it does not occur when I write to chat, it occurs when I start the project. Maybe this tells something ```The character with Unicode value \u30C4 was not found in the [LiberationSans SDF] font asset or any potential fallbacks. It was replaced by Unicode character \u25A1 in text object [UITextPlayerName].
UnityEngine.Debug:LogWarning (object,UnityEngine.Object)
TMPro.TextMeshProUGUI:SetArraySizes (TMPro.TMP_Text/UnicodeChar[]) (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMPro_UGUI_Private.cs:1274)
TMPro.TMP_Text:ParseInputText () (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_Text.cs:1902)
TMPro.TextMeshProUGUI:OnPreRenderCanvas () (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMPro_UGUI_Private.cs:1644)
TMPro.TextMeshProUGUI:Rebuild (UnityEngine.UI.CanvasUpdate) (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TextMeshProUGUI.cs:216)
UnityEngine.UI.ScrollRect:set_verticalNormalizedPosition (single)
EnhancedUI.EnhancedScroller.EnhancedScroller:ReloadData (single) (at Assets/Plugins/EnhancedScroller v2/Plugins/EnhancedScroller.cs:738)
Birdmoot.UI.Misc.FriendsScrollerController:Enable () (at Assets/Scripts/Runtime/UI/Misc/FriendsScrollerController.cs:29)
Birdmoot.UI.Networking.UIViewLobbiesController:Start () (at Assets/Scripts/Runtime/UI/Networking/UIViewLobbiesController.cs:44)

#

It happens when I return strings from steam api (my username), but doesn't break anything. But could be related

compact ingot
#

thats just a ツ character could be an emoji

fickle inlet
#

Indeed. It gets steam friend names, and on steam they can name their accounts however they like, so that is probably why. But maybe there is some unicode that breaks my chat

compact ingot
#

you could try converting whatever you get from steam to alphanumerics, stripping everything else, just to make sure no weird characters are decoded

#

unicode has a lot of control characters that can mess things up

#

but its still weird to debug remotely, i'd probably look at the actual bytes next

fickle inlet
#

Okay I did log data[] (byte[])

#

So on the first line it prints a number

#

and on all other lines it prints 0

#

byte size is 4096

#

I am not familiar with bytes, so I am not sure what it is telling me

#

This is some black magic sourcery, I do not know where to even look at anymore

#

So I found something. When I try to log current message, sender and message in one line, it will not print them all. But if I print them induvidually then it will show all of them. I assume there is a network operation going on and it doesn't sync with cpu cycle.

#

I tried to use IEnumerator and wait for sender and message, but it still didn't work. Maybe you guys have some other suggestions

#

SOLVED IT

#

The issue was that my message was too long. message.Length showed me that my string is actually 4096 long, but it is suppose to be long as my string character length

#

So TEXT UI couln't show that big string

#

what confused me is that unity debugger didn't show me empty spaces, it showed the string as it is + empty spaces that I couln't see

#

So I had to include messageLength when encoding byte data ```cs
string message = System.Text.Encoding.UTF8.GetString(data, 0, messageLength);

#

In my case Steam API provides me with messageLength, so I just had to use it ```cs
int messageLength = SteamMatchmaking.GetLobbyChatEntry((CSteamID)callback.m_ulSteamIDLobby, (int)callback.m_iChatID, out steamUserID, data, data.Length, out chatEntryType);

#

I hope this will help someone in the future.

fresh basalt
#

im not sure if this is the place to ask this, but here goes nothing
On clientside im using unity 2022.3.10f1 and SocketIOUnity. For server side : ubuntu server running flask socketio : flask version 2.3.3, flasksocketio version 5.0.2.

When testing using socketio testing websites or when in editor in unity, the sockets are established correctly, but when doing it on android build they are not. Nothing happens, android logcat shows 0 errors or other messages related, just nothing happens.
most important thing : it seems to be reaching the flask server app, because it just keeps spamming post requests (probably reconnecting), but the sockets are not established

it's driving me insane for 4 days, im on the verge of just going to work for mcdonalds and forgetting all this bullshit

sly grove
fresh basalt
#

yeah, i launch the flask app through ssh and i see what is happening. With editor it establishes connection, so i see it correctly in game and in the ssh, but with android all it does is spam post requests

sly grove
#

Just trying to clarify what you mean by "it just keep spamming post requests"

sly grove
#

Are there Error callbacks you can subscribe to?

fresh basalt
#

78.xxxxxx - - [03/Nov/2023 15:47:00] "POST / HTTP/1.1" 200 -
78.xxxxxx - - [03/Nov/2023 15:47:17] "POST / HTTP/1.1" 200 -
78.xxxxxx - - [03/Nov/2023 15:47:39] "POST / HTTP/1.1" 200 -
78.xxxxxx - - [03/Nov/2023 15:47:45] "POST / HTTP/1.1" 200 -
78.xxxxxx - - [03/Nov/2023 15:47:50] "POST / HTTP/1.1" 200 -
78.xxxxxx - - [03/Nov/2023 15:47:55] "POST / HTTP/1.1" 200 -

sly grove
#

I don't know how SocketIO works

fresh basalt
sly grove
fresh basalt
#
socket.OnError += (sender, e) => {
    Debug.LogError("Failed to connect socket : " + e);
    conn.connectionStateChange?.Invoke(ConnectState.FailToServer);
    Connections.Remove(conn);
    socket.Disconnect();
};```
#

the thing is, im doing a similar thing on OnConnected and in editor when it connects, the thread isnt dying or anything it properly does everything it is supposed to

#
socket.OnConnected += (sender, e) => {
    Debug.Log("Connected");
    conn.connectionStateChange?.Invoke(ConnectState.SuccessToServer);
    passedLobby.alreadyEstablished = true;
    socket.EmitAsync("MakeRoom", Config.ApplicationID + "/" + passedLobby.uniqueID + "/" + (Hosted ? "1" : "0"));
};```
fresh basalt
#

got some progress
System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> Mono.Security.Interface.TlsException: Handshake failed - error code: UNITYTLS_INTERNAL_ERROR, verify result: UNITYTLS_X509VERIFY_FLAG_NOT_TRUSTED

sly grove
#

alright looks like your editor is trusting your TLS cert and your Android device is not

#

this is pretty well trod ground!

fresh basalt
#

after 4 days of nothing i consider this a huge win

#

holy shit it works. I'm gonna go get wasted

#

thank you

raw lily
#

How costly is it to have an update method that checks for a condition, when the condition is false and the logic does not happen?

#

Let's say there are multiple in a scene/project.

flint sage
#

Depends on teh condition

#

Probably close to free though

sly grove
#

it depends how costly the check is too

#

a basic if check on a basic boolean field is very cheap

dusty wigeon
# raw lily How costly is it to have an update method that checks for a condition, when the ...

Ideally, you should disable object instead of checking for a condition. On most console, it won't make a lot of difference, but for mobile this can add up quickly if you have a lot of object that does that. (Performance/Battery consumption).

Note that an Update function is more costly than a simple function call because of the context switch you need to have between the C++ and C# (And diverse check)

https://blog.unity.com/engine-platform/10000-update-calls

raw lily
undone coral
fresh basalt
#

Dude stop with the long journey stuff πŸ˜„ im doing it and im enjoying it. Im almost done

undone coral
#

it gives you negative value. it adds three state machines on top of the two you have to manage to determine mobile session liveness.

undone coral
#

from the clients' POV and the server's POV?

#

what happens when the user loses cell connectivity? or when the user changes from wifi to cell, whether because the OS decides to or because they lose wifi connectivity?

#

so the lifetime of a game session isn't exactly mapping 1-to-1 to the lifetime of a socket.io connection, however based on your two snippets of code you assume that they are

#

anyway it's your game

#

you've already rewritten this once it looks like, and it's important journey, but you gotta think about these things

undone coral
fresh basalt
#

I know, and im dealing with this stuff

#

I understand its not a few hours job, ive been on this for weeks and im grasping it quite good.

#

The socketio connections dont need to be live always. Im doing it a bit differently

#

Same as with lobby timeouts and etc.

undone coral
#

that's good

#

i've also built a thing on top of someone else's session representation

#

i personally like grpc the most

fresh basalt
#

Just stop with the long journey thing, because its kinda discouraging, blows my excitement away πŸ˜„ i understand you know a lot about this, so ill ask you if im stuck somewhere

little sluice
#

What's the difference between **Debug.Assert **and Assertions.Assert?

fresh salmon
#

When the assertion condition fails, the former will log an error message in the console, while the latter will throw an AssertionException

sly grove
shut surge
#

Hey all, is there any way that I'd be able to tell a Unity-made job such as BoxcastCommand.ScheduleBatch() to treat an array like it it's okay to be overwritten in parallel? Something like the [NativeDisableParallelForRestriction] attribute but assignable from outside of a job

NativeArray<RaycastHit> subBroadphaseHits =
    broadphaseHits.GetSubArray(
        scheduling.startHits, scheduling.hitsLength
    );
NativeArray<BoxcastCommand> subBoxcastCommands =
    boxcastCommands.GetSubArray(
        scheduling.startLookers, scheduling.lookersLength
    );
lastHandle = BoxcastCommand.ScheduleBatch(
    subBoxcastCommands, subBroadphaseHits,
    Mathf.Max(256 / scheduling.numberOfHits, 1),
    scheduling.numberOfHits, lastHandle
);

The code above is theoretically thread-safe, each scheduling will select partitions in the broadphaseHits + boxcastCommands arrays that don't overlap - so there aren't any race conditions. The trouble is, the job system doesn't like that the same underlying arrays are being written to by different BoxcastCommand.ScheduleBatch at the same time since it thinks that there might be conflicts

For now, I've been scheduling these jobs in sequence, but that's turned out to be a bottleneck and I want to find a way to address it. Any way that I could make this work?

autumn basalt
#

I'm making a game that will require some "multiplayer" functionality
The data is all very simple, I'd like to store it in an SQL database since I'm familiar with SQL at least a bit. (though I'm open to alternatives)
There's no multiplayer movement synchronization going on, so that makes it a lot easier.

I want to have a server running that saves all the player data, like their level and items.
When a player starts a task I want my server to track the start time and same for the end time. My server will then calculate the task result so there can be no cheating.
There will also be trading between players.

In the future I might want to display players on the same screen (there's no movement or anything) just damage.
It's an idle game so no complex movement synching. Just need to somewhat synch the dps & monsters health.

What would be the optimal solution to use for this?
I have a lot of experience in PHP, some in SQL, a decent amount in JavaScript and obviously I'm using a lot of C# now

The main problem I want to solve is that it will be a multiplayer trading game.
So I don't want people cheating in "single player" and then trading those cheated items with other players
For that I think the only real way to prevent this is running everything on a server?

scenic forge
#

Yeah, always assume clients are not trustworthy and any logic you run in the client is compromised.

#

Do things you don't want to be cheated on the server side.

#

The backend of what you described seems simple enough that you can do it with practically any language and any framework, even serverless.

autumn basalt
#

yeah I'm just not familiar with what unity supports

tiny pewter
#

backend can be written in any language, more generally since the data is sent and received as bit stream so you can parse it in different language

tired fog
#

Is there a way for me to force a complete burst jobs recompilation manually?

autumn basalt
#

Is netcode for gameobjects a good starting point? Or is that not recommended for a project like mine?

gilded wren
#

Hello, I encountered an issue with setting vibrations on a PS4 controller. It is connected to my laptop via Bluetooth (I tried also via USB though). I tried to use gamepad.SetMotorSpeeds as it is commonly said how to do that, but unfortunately it doesn't work - there is just no vibration.
Yet haptics do work well in some games, so it is not a hardware issue. Now I have no idea on how to deal with this problem, maybe there is a common issue regarding this which I dont know about?

dusty wigeon
# autumn basalt Is netcode for gameobjects a good starting point? Or is that not recommended for...

I would consider other alternative in this situation.

  • Netcode for GameObject required a Unity base server
  • Unity is kinda heavy and not really optimized to treat high volumes of request (Which you probably will have)

An other alternative would be any sort of REST API server. (ASP.NET, Nodejs, Spring, etc.) Those are made to maximize the amount of request answered. They also scales really well if you ever needs to scale up. (If you want to validate the integrety of a play session, you might want to look into other architecture than REST as REST API are not made for such things. The operation they support are more in the line of CRUD (Create, Read, Update, Delete))

That being said, if you intended to have things like dungeon or instance that regroup players, Netcode for GameObjects would actually be a better idea for this particular content.

sage radish
#

There are also some interesting methods in AtomicSafetyHandle which I haven't used before, but look potentially useful for this.

sly palm
scenic forge
#

You absolutely can. Open your browser console and type in:

await fetch('https://echo.zuplo.io/', { method: 'PUT' }).then(res => res.json())

https://echo.zuplo.io/ is something that will echo back your request (you can open the URL directly to see it echoes back the GET request), you can replace it with your own server instead.

wary vector
crystal oar
#

Hello, im trying to create procedural fps animations just using math and whatnot in unity, im using second order dynamics method that tessl8r made a youtube video about (here: https://www.youtube.com/watch?v=KPoeNZZ6H4s&t=319s) on the position of my hands and it works great, however im struggling to use it for the rotation of my hands. For example when i shoot my gun and apply my recoil rotation to the hand i want the rotation to have a bit of elasticity to it or some "overshoot". I cant seem to find anywhere on the internet something that talks about adding this elasticity behavior to rotations in unity. I have tried so many things but my understanding of complex math and quaternions isnt the best so its been a struggle. Any suggestion would be amazing!

It's been a while since the last video hasn't it? I've made quite a bit of progress since the last update, and since one of the things I worked on was some procedurally animated characters, I decided to make a video about the subject. In particular, this video highlights the entire process from initial motivation, to the technical design, techni...

β–Ά Play video
heady elm
#

hi! sorry to dig up an old mesage, but i was searching if anyone has solved this problem. I'm trying to add Max and Min distance constraints to my verlet integration physics system, and i'm wondering if you could give any input!

currently my system only allows for a static target length per Stick. solving for the distance each point needs to move to satisfy the length constraint, and multiplying that by some (0 to 1) stiffness value results in "soft" length constraints.

specifically what i'm after though is 0 stiffness, unless it's outside of it's min max range, in which case it's at full stiffness.
I've not seen any implementations of this specific constraint anywhere.

thanks :)

dusty wigeon
crystal oar
dusty wigeon
crystal oar
dusty wigeon
#

Whatever you are going to figure out here, will help you a lot in the future.

undone coral
#

it's hard to say what's going on because you have given too little context

undone coral
#

it would at least explain why he would receive a 404 on a URL he believes is correct. it's much more likely the URL is wrong

umbral geyser
#

It’s a bit late right now where I am so apologies if this doesn’t make much sense but I am always very happy to talk about verlet ropes should you need help. When I have more time I willl look at my old setup.
I tried for a while very hard to implement this and honestly? I’m not sure it’s possible in a verlet simulation to do.It’s a very weird thing to do, because it touches on the question of what does max distance mean in a finite point simulation? If two points are too far apart, we are already breaking the simulation in some way, since a real rope in that situation would break. length as a sun along each individual segment doesn’t really mean much because even if you do go over some max, you don’t have the information you need to correct back down somehow. So the question then becomes how do we stop rope segments from getting too far apart but that’s already what verlet rope is all about.
I tried for a long while to get the kind of thing with tension working, where if a rope is over it’s max length it will try to squeeze itself together harder. It didn’t really work together as it turned the rope into a kind of spring where it would become unstable. It did have some ability at low magnitudes to increase the ropes ability to stay within a max distance but it wasn’t a perfect fix.

#

@heady elm

regal olive
#

Does anyone know of a good way of getting all the runtime types in your unity project? Essentially any types in your assets folder, or included in a package that you're using, but excluding editor types.

heady elm
#

It’s a bit late right now where I am so

undone coral
#

i don't know why you would want to do this though

faint void
#

Anyone know if its possible to modify prefabs/assets temporarily just before build so that the build uses the modified versions of the prefabs.

The context is that we have many shared prefabs in our project that contain both server, client and shared monobehaviours on them.

Before building our client we want to modify all prefabs, to remove all server components from them, and vice versa when building our server

regal olive
undone coral
regal olive
#

ah ok, that's really the core of my question. What about the assembly can I check to see if it's an editor or non editor assembly. Right now I'm just doing the name, but I'm wondering if there is a better way

timid eagle
#

!code

thorn flintBOT
timid eagle
#

https://paste.ofcode.org/CVsxQ44xrnVAiyTzSG4zVd
having issue where the rectangle prefabs (with properly sized collision and rigidbodys) are spawning on top of each other. It is supposed to check during cell generation if the spaces are already occupied by colliders and if they are it is supposed to ignore that space. I am also try to get it to automatically align the smaller rectangle on a crease (Taking up two cell spaces) and a larger rectangle in the middle (taking up three cell spaces). Trying to make a generation algorithm for Rush Hour game (get the red car to the exit)

#

ill be back in 8 hours im going to bed just wanted to post this here in case anyone can help me by the time i wake up (its 2am)

#

6x6 grid I'm working with btw as main goal of achievement

tiny pewter
#

the generation is advance topic but not the placement

#

suppose you already have the generation algorithm and output initial layout eg
0 1 1
2 2 0
0 0 0
0 means empty, 1 means car in some color, 2 means another car with different color
then you can just iterate each cell of the 6x6 layout and see if the cell is car first, and explorer the neighbor cells to see how the length and direction of car hence the position and orientation of car prefabs

#

your IsCellOrGroupOccupied may fail because of the the bound size, you should use vector2Int

#

and there not exists mapping from world space to the bool 2d array
ie given a coordinate in world you cant tell which element of the array is mapped. (you implicitly assume each element is mapped from (x+offset,y+offset) to (x+1+offset,y+1+offset) but this is bad practice)
and the position is wrong, if you try to spawn a 2x1 car in (0,1) to (0,2) and the position is (0,1), then your car will overlap (0,0) (0,1) (0,2) three elements, since it is supposed to be the "middle" of the car not where you start to loop and check

#

you should not rely on collider size but instead separate the car prefabs to 2x1 and 3x1 car to make your life easier (i assume the cellprefabs is actually car prefabs, idk why you have cellPrefab and cellPrefabs)

dusty wigeon
# faint void Anyone know if its possible to modify prefabs/assets temporarily just before bui...

I believe that you could achieve that by using IProcessSceneWithReport and AssetBundle/Resources/Addressables.

  1. In the IProcessSceneWithReport, you edit the scene such as there is no unwanted component.
  2. When you build your asset, you make a copy from the original assets to either the folder of your asset bundle or Resources folder. When you do the copy, you remove the unwanted component.
  3. The tricky part would be the dependencies. For that, I would probably forces the build to have no dependencies on GameObject; forcing only weak reference such as Addressable.AssetReference or string (path of the resource in the AssetBundle/Resource folder).
undone coral
regal olive
# undone coral i don't know. i mean it's just a ton of work. you'd have to deal with ordinary ....

I'm using reflection to get all types that descend from a particular type, and generating a few functions that use them. The system needs to support AOT compiling so using reflection at runtime isn't an option as I understand it. I can always do some manual configuration to specify assemblies, but I'm hoping to find a way to avoid that and just have it be based on some property of the assembly. Right now I'm just checking for the word "editor" in the assembly's name, but I'm not sure how reliable that is going to be.

undone coral
#

like what is this for

icy owl
#

Hey, weird question for me here. I have a object that stores the current game state "memoryState", in it there is a "baseState" that holds stuff that's first initialized.
However, when I query this using linq, it isn't capturing the children items of that object. for instance in this code.

        Character aICharacter = memoryState.BaseMemoryState.CharactersList.FirstOrDefault(c => c.CharacterId == memoryState.AIConversationCharacterId);
        Relationship AIPlayerRelationship = aICharacter.Relationships.FirstOrDefault(r => r.OwningCharacter.CharacterId == memoryState.AIConversationCharacterId && r.PerceivedCharacter.CharacterId == memoryState.PlayerCharacter.CharacterId);

I get the error "cannot evaluate children" for relationship (which is a list held by the character)
Any idea why this is occuring, I thought I only need .include in EF

undone coral
regal olive
undone coral
icy owl
#

but I thought we didnt need it in unity for just accessing a object

#

I am pulling memoryState from a ES3 (plugin) file

sage radish
regal olive
icy owl
#

@undone coral
So I have tested it in the Unity Scene, also in VS. And i've attached the script to the unity debugger to line/line which is where I found this

undone coral
#

code generation

regal olive
sage radish
# regal olive In that case I might not need to do the code gen at all, thanks for the info!

I'm just guessing about your use-case here, but I'm using Reflection with my event bus, which heavily uses generic types. To be able to serialize event listeners and use the event bus non-generically, I'm using Reflection to make the generic types at runtime. That's not an issue with IL2CPP, unless the generic type is a value type. But even then, you can change a build setting to make IL2CPP use fully shared generic types, including value types, which lets you use MakeGenericType and MakeGenericMethod with value types.

fickle inlet
#

Hello everyone. I cannot figure out how to do this. I have a card with custom design and I need to display card name, card icon, description at specific spots on the card. But I cannot figoure out how to place UI text and image elements at specific spots on the card. When the card is scaled, text or image will offset itself and it will not look good. What is a good approach to this problem?

fickle mango
icy owl
#

Thanks for the help everyone, I figured it out. I was dumb, I had an object embedded that wasnt set as a IEnumerable<T>

magic scroll
#

Could someone look at this code and why it doesn't work on HDRP? The problem was that it didn't render at all. But now it started rendering but now the problem is that the color is always white for some reason. I'm trying to make another "generator" work with colors, but it doesn't work
Link: https://hastebin.com/share/ijafixebep.csharp

dusty wigeon
thorn flintBOT
timid eagle
#

Rush Hour Generation

magic scroll
sacred steeple
#

I'm trying to make it so that when falling my player does its falling animation, however I'm having troubel with the animation getting stuck on the jump animation, and not switching from jump to falling. Whats weird is the jump animation does not have this problem with switching between anything else. After a while of bug testing it seems like the issue is happening due to the IEnumerator JumpCooldown()
But for the life of me, I can not figure it out, if anyone has any ideas let me know. (If needed I can also post SS of the animator tab)

thorn flintBOT
sacred steeple
#

Alright thank you! :)

muted pilot
#

unity deep linking doesn't work ???

#

i'm trying Application.deepLinkActivated but the url is none, nothing shows up

#

any fix ?

flint sage
#

Works for me

muted pilot
flint sage
#

🀷

muted pilot
#

here is what i did

#

ios -> configuration -> added url scema

#

then in the code :

#

Application.deepLinkActivated += onDeepLinkActivated;

flint sage
#

What type of ios build are you making?

muted pilot
#

i'm building for movile

#

mobile