#archived-code-advanced
1 messages Β· Page 84 of 1
it's part of it surely
you're creating a new list in every iteration of your while loop
that is very fair
also not sure where movementTiles is getting populated from
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
.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.
read up on the profiler, I actually dont think its a memory issue. Scanning through a version where unity basically crashed, and the objects stats never push somewhere where I'd think the game is going to crumble, though notably the GC allocated in the frame skyrockets
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
lots of GC could be coming from all the lists you are allocating
sure but its the last frame in the profiler
What is there to head scratch lol? Can you finally provide proper profiler data for us to look at?
i mean the problem is a head scrather, im trying to think of what the problem is, And I would be happy to provide what ever you want for the profiler
I asked like 30 min ago to show the last frame that has the cpu time spike.
gothca i can send that
Profiler in hierarchy mode btw.
Sort the hierarchy by CPU time and expand to the deepest item that takes most of the time.
i think i am doing this correctly
this is of the last frame where there is a massive spike
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.
i see what you mean but because its in editor i dont know if i can stop it on that frame from a while ago
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.
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
honestly shocked unity didnt crash at the end, seemed to save itself
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
Well, can't really help you much without the profiler data.
I am trying to figure out how to get you a snapshot of the editor mode
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
Notably, there was also a huge jump on the rendering section for triangles and verticies for some reason
It shouldn't be too difficult to capture the frames of the second/third click.
so do you want me to run the game
have the profiler open
and trying to press the button and then stop?
No need to stop
You can pause the profiler recording in the profiler window to stop it from scrolling on.
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
You can't each frame takes a hell lot of memory, so there's a limit.
gotcha so i need to be fast then
You need to stop the recording before your frame goes out of range.
ok i can try
300 frames is like 5 seconds. Should be more than enough time to just click one button.
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
Does it stutter on the spike and then jumps several frames or something?
If you press the stop recording button during the stutter, it should pause on the next frame.
did you just want to see a heirarchy again?
Yes
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
yeah im noticing that as well as the number of calls
a good clean 5.7 million calls
Event system updateπ€
yeah not entirely sure what that is
Can you repeat that with deep profiling enabled?
In the profiler window. On top.
ah i see
it seems to be something with the showWeaponRange() function
specifically with my pathfinding
unless im reading this wrong
Yeah, it seems like you're calling findPath 5k times in one frame.
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
Are you sure about that?π
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>();
}```
Not with all the list allocations, it's definitely not optimized at all.
this is the code, welcome to see where i am just wrong and doing something super dupe
should really learn to hook the debugger up too and let your code go through it all
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.
yeah that findPath call is in a for loop
Creating new lists.
after all this definietly considering doing some reading
yeah im noticing that lol
Then it's being looped 5k times. Which doesn't sound reasonable.
Then there's a bug.π€·ββοΈ
the old classic
Step through the code and see where the loop iteration count goes wrong.
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
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
Share the loop code...
The whole script preferably.
We've seen the count of the calls in the profiler. What we want to know is what causes it.
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
Please share it properly.
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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.
that was exactly what i was thinking
although i do clear it at the start of the while loop
Oh, didn't notice that.
i was still thinking i want to do a surroundingTiles.Distinct
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.
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
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.
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
What does the error imply? And the numbers before and after it?
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
Well, look at where you add the elements to that array.
I bet that attackTilesToCheck size goes up as well
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
In which case, the movementTiles size is going up as well and is the culprit.
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
Well, where do you set it..?
in a completely differnet function
Then look at that function lol
i just checked the function isn't like, being called again
but i just dont understand how that is possible, the movementTiles are never modified besides that one point
Then they are either modified or they're set to an unexpected value that one time.
If it's changing, then something changes it.
There's no magic in code. It's just what you wrote.
And that's why I suggested this:
#archived-code-advanced message
perhaps
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.
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
Someone has to occur?
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
What change?
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
Just do this:
#archived-code-advanced message
It's 10 seconds and you'll know where it's changed...
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
What type are they?
they are just List Objects
Oh, they're not just an int?
no they are full list objects
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.
how has this never caused me a problem before
i feel like i have done this so many times
and never had an issue
Donno. It's a pretty basic thing to know.π
no i agree
Well, it wouldn't cause issues if there are no changes to the reference on the right.
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
You can create a new list.
But that would be one more pointless allocation added to the whole thing.
Which is a separate problem.
Or just pass the list you want to copy into the constructor of a new list.
true but that would mean i have to recreate the list every method call
which might be fine might not be
The orthodox way, but I guess ToList is gonna work too, although it's not intended for this use case specifically.
fair enough
You do it anyways. ToList just does it for you.
Hopefully, you've learned how to profile and debug more efficiently.
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
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?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
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)
Disabling domain reload after compile would be pretty pointless as the compiled code would not be being used
But isn't the whole point of assemblies that it should only reload the assembly you're working in?
no, I suggest you read up on domain reload
assemblies help with compiling not with domain reload
Is there a way to reduce domain reload time?
disable it entirely
I found a setting to disable it in playmode, is there a way to disable it entirely?
yes, get a better computer, write smaller programs, don't have so many concurrent running processes
Thats when you enter playmode, isn't it?
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
Write smaller programs? It's a multi-year project, that's simply not an option
shouldn't take > 15 seconds in 2022+ on a mid sized project
you asked for ways, that's a way, doesn't mean it's achievable
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
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
That's much more likely to be threads being slow to stop and restart
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
is there a way i could attach a gif file into an image UI canvas?
if you create a new project and try to set this platform checkmark with this DLL, does it work?
are you sure it's compiled for linux?
is this a native DLL for windows?
ultimately it's possible that epic would have accidentally copied the windows dll into the spot where the linux.so file is supposed to be. it's unusual you called it a DLL
it works if i manually copy it into a linux build
so i simply made it part of my build script lol
annoying to have to work around it
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
do you have a screenshot of your game?
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.
lol i can't show it here
you'll hear about it soon π
try
Yeah already tried
Maybe it's related to this? https://forum.unity.com/threads/audio-latency-on-android.1462328/
Audio latency on Android seems to be a well known issue (see: https://forum.unity.com/threads/need-a-fix-for-audio-lag-android.267620/,...
I am using v2023.1.17f1
so how was the stadia development experience?
Do you use 2023 ?
Yep...
Then, you know your issue is probably wht is written there
Is the time the audio supposed to be played known (eg you know it's going to need to play it 3 seconds from now)? Or does it play conditionally (eg it's only played when player touches the screen)?
It plays when you click the object that spawns
Look at the forum thread linked by @dusty wigeon above.
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
Can't downgrade?
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?
A mix of trial and error, google and documentation read.
I've been trying to get a system setup for like 3 days..... I have had half working implimetations looked at the references and examples online with little sucess for what I need
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?
Hello, is there a way to determine at Unity Gaming Services whether a player is an admin or a normal user?
what does that mean
where do you recognize me from? lol
honestly it's super vague... don't really remember
something something voxel asset
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?
Just a note, WebGL can't do threadPool. Make sure you're not doing that in your code
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
Man WebGL - The bane of my existence haha
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
You can enable it in Unity, but only work on some browsers https://docs.unity3d.com/ScriptReference/PlayerSettings.WebGL-threadsSupport.html
Interesting!
Thank you for sharing that @novel plinth !
If this doesn't work, looks like I'm building a JSLIB π
Hey guys. Does anybody here know how to call a function from a script from another script without using tags?
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)*
- Get a reference to the other script
- Call the function on the reference
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.
do you have a screenshot of your game / experience?
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?
@red flax Don't cross-post, please
I managed to overcome that π€
I'm building an SDK (https://docs.eidolon.dirtroad.dev)
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.
Sorry can't remove embeds on my phone π
looks cool
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?
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; }
okay... what is a weightChanges and a persistentWeightChanges? what is this type?
A first optimization would be to use TryGetValue on the collection, so it only accesses the collection once instead of twice.
what is the native parallel hash map you are using?
Its the same collection, just different names in different jobs
what is the type
The key is a vector3int and the value is a custom struct
π¦
do you mean NativeParallelHashMap<Vector3Int, T>?
I mean NativeParallelHashMap<Vector3Int, PersistentWeightChange>
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?
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
Okay looked at the docs and the method exists, so
if (persistentWeightChanges.TryGetValue(hash, out var value))
{
// use 'value'
}
One collection access here, instead of two like you have now (contains key + indexing)
Thank you, didn't realize it was accessing twice
I'm not parallel writing
can you show the line where you construct the hash map?
this is like, what fixing these problems looks like
answering a bunch of questions as quickly as possible
persistentWeightChanges = new NativeParallelHashMap<Vector3Int, PersistentWeightChange>(1000, Allocator.Persistent);
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?
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
you have to set that to 500,000
I don't think I do?
you very much have to
go ahead and try that first
this is how hashmaps work
especially concurrent hashmaps, which are complex
I have to set the inital capacity specifically to 500,000, even though it could be higher than that?
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
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
do you mean multi-key?
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?
Using a tuple might mitigate the hash collision issues
So you're saying that the Unity hashcode for vector3int is the culprit?
now it's MORE LIKELY that you are not observing the correct thing
i am saying in the condition that what you are observing is correct, then that's an important factor, BUT i do not get to see the distribution of your vector3ints
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
`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
okay well
I figured nativehashmap and nativeparallelhashmap are identical, since nativehashmap is deprecated
i'm not sure what this is doing
what is the idea here?
why are you doing this?
In mathematics, a pairing function is a process to uniquely encode two natural numbers into a single natural number.Any pairing function can be used in set theory to prove that integers and rational numbers have the same cardinality as natural numbers.
Combining the chunk coordinate and index inside that chunk
i don't think this does what you think it does
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
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
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
Yes, but I figured that would be slower
you shouldn't use a hashmap at all
simply use a 3d array
it is hard to tell. is this sparse?
it's complicated. 3*4 is less than 3*2+2 of memory, so in a micro-optimization sense it's faster, but i don't know how much space you need for voxel coordinates. i'm not sure what role the x and z indices play
so try to define your struct first
what your key should actually be
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
i think you can define a struct of the form
Vector3Int chunkOrigin;
VoxelType[,,] voxels = new VoxelType[CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z];
and these are your terrain chunks that get generated
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
okay, thanks for the help
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Wdym by "Data objects" is it just a plain old C# class or something else?
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?
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.
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
The player.Data is null sorry if I didn't explain that.
How do you know that
Referencing it in anyway returns the error.
Use the debugger or debug.log and prove it first. Maybe player itself is null for example
Its not because player.Id returns the id as a string.
Debug.Log(player.Data["playerName"].Value + " " + player.Id);
Ok so you'd have to show how these player objects get into that list in the first place
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
{
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.
Make a struct
ok, that was my first thought. i've admittedly ignored structs in my journey thus far
do you know if there's a performance difference between the tuples method I used and using a struct?
ValueTuples are literally structs
You're already using them, you just didn't name any of the fields basically
Got it, so structs would simply add more readability. Thank you
Yes
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??
Unity Hub has nothing to do with the editor, nor does this question with advanced code.
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?
@humble leaf Apologies. Which room do you think I should ask in? It's not code but it seemed like an advanced problem!
#π»βunity-talk if it's about the editor
Cool thanks
Sounds like your reference to the different class is null, or the list itself is null
structs are passed by value. Just in case you're expecting them to be passed by reference
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?
Does it have anything to do with code, and is it an advanced problem?
Perhaps you want #πβanimation
Oh mb I didnt see that
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 β€οΈ
What's weird is that it should be an async method, so it should not block the main thread.
async doesn't neccessarily mean it runs on another thread
Any way to stop it from blocking the main thread? I tried to call this method from another thread, but it can't be called outside the main thread π¦
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?
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?
Most likely because you destroy the object. A coroutine lives on an object
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.
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();
}
}```
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Apologies.
SO what about it "isn't working"?
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?)
Ok so where is this script located and where exactly did you put the discord plugin?
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
The plugin folder is named DiscordRpc, and it is located in Assets\Plugins\DiscordRpc (the script is located in the same folder as DiscordRpc)
Is it this? I don't think that's the proper way to install it
It's a UPM package it shouldn't be dragged into Assets
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
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.
are you saying you have an editor script that is buggy
Its a CustomEditor that's running this yes.
the screenshot of the editor script isn't that informative
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
sorry i don't know anything about editor scripts
Looks like you are creating new asset rather than updating existing asset
Is there a way to just update the asset then?
Load asset and modify it, mark dirty and save
Thanks that solved it!
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
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);
}
I'm late, but the better way of controlling code via animation is to use Animation Events instead. Create an event in the Animation you need, then select a public method you'd like to call when the animation reaches the marked frame. Then manipulate your canvas there
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 whichMicrosoft.CodeAnalysis.CSharpversion 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"?
only by trying
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?
In general yes, scheduling a job is expensive.
Cool then, thanks!
I don't think there's enough information here to make a determination. We don't know how expensive operation x and y are and how much benefit there might be to parallelize them.
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
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.
wanting your own editor, or just to change the envirement the prefab editing happens in
for the first thing, you can define scenes in your editor settings for the prefab editing envirements for the 2nd thing woudl look into https://docs.unity3d.com/ScriptReference/SceneManagement.PrefabStage.html
Turning the outer foreach loop into a parallel job achieves the same parallelization as scheduling each X and Y as individual jobs, except without eating the job scheduling cost for all of them.
Thanks I'll have a look π
Also I duno if I forgot to turn mention off, sorry if I didn't ^^
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?
is this iJobParallelFor?
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);```
Yeah, i know that, that's what I have
Im asking if I can do it the other way, the pseudocode i wrote
you shouldn't call job.Execute() manually, no
nor would you want to schedule a new job for each iteration of some previous job if these are IParallelFor jobs
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
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?
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.
}
}
}```
Not really sure it's an advanced issue.
Hard to say without seeing your setup, but it's probably either a matter of using triggers or compound colliders being involved.
Check this troubleshooting guide first:
https://unity.huh.how/physics-messages
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".
Go through the guide that I linked. If it still doesn't work afterwards, share screenshots of your setup.
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.
There are interactive links to lead you through troubleshooting:
https://unity.huh.how/physics-messages/3d-physics-messages
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! π
100% custom would imply that you have your own physics engine and not using unity rbs, colliders or physics queries like raycasts.
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.
Well, then you're relying on unity physics. And unity physics have certain conditions for working properly(like having rbs). So you're basically fighting the actual system you're basing your implementation on.
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.
How are you trying to get collision callbacks without a rigidbody?
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 
I would guess it does.
The CullingGroup will calculate visibility based on frustum culling and static occlusion culling
only. It will not take dynamic objects into account as potential occluders.
Looks like I cant read. Thank you π
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.
What would you want to use that for?
im already using it for signaling server for my webrtc connections
it works perfectly in editor
cant get them to work on android
I mean why use it for unity stuff
what do you mean?
Itβs a library for web apps, no reason to use it if you arenβt forced to use a JS stack.
i need websockets
there is a proper port to csharp and unity, and everything is working as intended
just not on android
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?
what's SoundManager.GetHandle?
Is that one of yours?
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
Search your IDE for SoundManager? Is that part of DOTween?
did, didn't find
weird
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?
not sure but I found this https://forum.unity.com/threads/soundmanager-loadfmodsound-causes-a-critical-spike.1182781/
intristink
No solutions there but... at least some precedent
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
I think there's some checkbox for it but... yes I think they do
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..
π€·ββοΈ
Well that actually might make sense
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
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)
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!
what error are you getting?
GetWindow seems like the canonical way to do it:
https://docs.unity3d.com/ScriptReference/EditorWindow.html
GetWindow seems to say this:
If there is none, creates and shows new window and returns the instance of it.
here is the error when the window is not already open:
That looks like they couldn't instantiate your class
probably because you defined a constructor for it that requires parameters or something
Because it's abstract, as per the error message
ah yeah that makes sense, nice catch
Yeah you'd have to do GetWindow<SomeConcreteClass> not an abstract class @craggy bronze
I think i tried calling just "EditorWindow.GetWindow<TimelineEditorWindow>(title: "Timeline", focus: true);" to the same effect.
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
Honestly the easiest way can sometimes be https://docs.unity3d.com/ScriptReference/EditorApplication.ExecuteMenuItem.html
But do note that the menu items change between versions
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
Perfect, thanks @austere jewel ! π
Probably impossible to say anything without seeing your code and profiling data.
Ill take some time tomorrow for writing a benchmark on NativeParallelHashSet!
Then ill report here
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.
Just don't do tests is the answer clearly
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
There may be hidden costs in the O(1) contains of a parallel hash set that youβre overlooking. For example the hash function might have to acquire a lock each time.
You'd have to look at the source code but probably to do with your equality comparison?
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
What I do is just DestroyImmediate each sub asset
(Or Undo.DestroyObjectImmediate)
Haven't worked much with assed database, but don't you need to mark stuff as dirty, or apply changes or something.
AssetDatabase.SaveAssets maybe? They use it in the example:
https://docs.unity3d.com/ScriptReference/AssetDatabase.RemoveObjectFromAsset.html
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β¦
- Move everything at the bottom (highest parent in hierarchy). Queue up all their children.
- 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
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.
Makes sense. They(native collections) are not supposed to be faster. They're supposed to be thread-safe.
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;
}
That being said, in a shipping build, a lot of their checks are probably stripped, reducing the gap even further.
This one makes sense, but from what i understand that's not true for everything. For example, adding elements to a NativeList doesn't look thread safe (i tried parallel writer, still has race conditions). So i resorted to NativeQueue, and it apparently makes use of AtomicAdd, removing race conditions
(heres an extra demo video)
looks like my c++ collision algorythm
It depends how you define a race condition. Atomic end would just guarantee that you don't write to the same memory from 2 threads.
How are you moving the ball?
Why the complicated raycast logic, when you can use unity physics?
Im not allowed, i have to do everything myself
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;
}```
I mean, how are you actually moving the ball?
Here is the full code, please ignore the mess
There's so many problems I don't know where to start.
Maybe by sending you to #π»βcode-beginner
alright, apologies
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
I am allowed to use Raycasts and Colliders! I can try and implement that system and ill get back to you. Thank you =]!
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.
yes, this is good idea, and for circle collision that's what you need
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?
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
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.
So is it laggy at first and the lag stops when you unfocus and refocus the playmode window? Because thats what happens to me
Or are you talking about something else?
sir in the build... when user install the build and play the game, first time it lag, when we quit the game, and play again then it works fine
Ok, start by attaching a profiler to the build and see what is causing it
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
you would use the profiler to determine what is causing performance issues. otherwise it would just be guessing
Does anyone know if it's possible to access and use Airdrop features on iOS through unity?
doing raycasts for collision detection really isn't how "creating physics" is done.
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.
what is your goal? you can use something like https://assetstore.unity.com/packages/tools/integration/ios-screen-gallery-save-and-native-share-109860#content https://assetstore.unity.com/packages/tools/integration/native-share-for-android-and-ios-127249#content
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
i'm not sure if you can airdrop a folder and have it received into... what exactly?
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
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?
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
Do you think sumulation survival games like oxygen not included has used behaviour trees to handle tasks, etc.?
BTs are for execution of behavior. They arenβt great for decisions, planning or scheduling of tasks. So ONI/others might use them for parts of their AI but certainly not exclusively.
when we create submeshes will it maintain the order of the combined instances
for CombineMeshes function
im so confused
About what
the errors
not advanced question, and please configurate the !ide first
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
my bad
The class should be the same as the name of the script
So it should say public class UI or whatever
oh alr cheers
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
Doesn't sound like a #archived-code-advanced question to me, or a code question at all
physics involves in it.
that's why i am pasted here sir and major technicalities in it
try to see the "line" in screen view from different angle, to see if the rect (or line) generated is "misaligned"
Doesn't sound like a physics problem and even it was that's what #βοΈβphysics is for. This is a rendering issue
you didn't actually even say what you are trying to accomplish
UnityWebRequest confuses me. This is a working curl PUT statement:
curl -X 'PUT' \ 'https://my-nice-server.me/api/users/9c02b89c-0409-4f77-a04d-fc30ec503dfb/blabla?queryParameter=https%3A%2F%2Fmy.escaped.parameter%2F6543c6b5354f74c8de2d9210.bla'
How do I properly translate this to UnityWebRequest.Put?
You might want to adjust your alignment settings, how does LineAlignment.View look?
This doesn't work.
What sort of errors are you getting when you make the call?
result: ProtocolError, responseCode: 404
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
Does that matter? I have a feeling I am using UnityWebRequest.Put the wrong way. How do I put the format "parameterName=escapedParameter" properly into the Put method?
The curl statement works, always.
Debug.Log(query) and check that it's identical to the one used with curl
It is identical.
Then it's not an issue with the query parameters
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?
it's telling you what the error is. you are trying to access something and it's not found
there's nothing wrong with your put
are you trying to do this in webgl?
because PUT requests cannot be made in web browsers.
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
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.
did you try .text = $"{existingStr}{appendThisStr}"
I did
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
and what is _chatContent exactly?
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
so youre saying "message" and "sender" in SendChatMessage debug.log exactly as you want them but they are repeated in the .text?
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
well, have you actually tried what i suggested, not append to .text but to a separate variable outside .text
Can you elaborate more?
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
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
well, do you know 100% for sure at what line and on which method call the error happens?
There is no error
then what are we talking about?
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
how are your newlines encoded?
Would anyone know how to change a gameobject position between two positions based on a Blendshape value in the Start Function?
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);
}
that doesn't do anything to your newline encoding
what do you mean newline encoding?
\r\n vs. \r vs. \n
\r is just a carriage return that would not produce a newline for example
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
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
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);
yes, try that
I did
So the result is it only prints Current text:
It does not log sender and message
you need to click the log message and look at the full version
console only shows you the first line
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)```
alright, so this means that the text in .text gets truncated at the newline once you assign it
I made this log after _chatContent.text, let me log it before
So the first line worked, but not the second etc
can you show your tmp component with settings expanded?
Sure
including the rect transform
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
This thing is making me crazy, I am so desperate
why does this API actually give you bytes?
yes, but do you know why that is?
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
thats just a γ character could be an emoji
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
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
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 the log
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.
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
it seems to be reaching the flask server app, because it just keeps spamming post requests (probably reconnecting), but the sockets are not established
Meaning your web server is printing logs?
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
Just trying to clarify what you mean by "it just keep spamming post requests"
android logcat shows 0 errors or other messages related, just nothing happens.
Do you have logging around when you are trying to establish the connection?
Are there Error callbacks you can subscribe to?
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 -
I don't know how SocketIO works
there are, im subscribed they dont give errors
is it possible you are trying to access a Unity object inside those callbacks or something? That can lead to your thread dying (multithreaded Unity object access)
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"));
};```
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
alright looks like your editor is trusting your TLS cert and your Android device is not
this is pretty well trod ground!
after 4 days of nothing i consider this a huge win
holy shit it works. I'm gonna go get wasted
thank you
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.
In what form are you expecting an answer? It's about as costly as running Update
it depends how costly the check is too
a basic if check on a basic boolean field is very cheap
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)
thanks, mobile might be a consideration so I'll keep that in mind
you're still at the beginning of a long journey. you will have to recreate session management on top of socketio, which is very painful.
Dude stop with the long journey stuff π im doing it and im enjoying it. Im almost done
it gives you negative value. it adds three state machines on top of the two you have to manage to determine mobile session liveness.
for example, what do you think happens to a socketIO connection if the android user receives a text message and taps on it to reply?
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
so if we aim your turbo energy canon on a good design, maybe it will be really good
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.
that's good
i've also built a thing on top of someone else's session representation
i personally like grpc the most
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
What's the difference between **Debug.Assert **and Assertions.Assert?
When the assertion condition fails, the former will log an error message in the console, while the latter will throw an AssertionException
Assertions is intended for unit testing
That makes sense, thanks!
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?
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?
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.
yeah I'm just not familiar with what unity supports
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
Is there a way for me to force a complete burst jobs recompilation manually?
Is netcode for gameobjects a good starting point? Or is that not recommended for a project like mine?
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?
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.
I don't think this is possible. Another alternative I can think of is to trick the safety system by creating a "new" NativeArray with the same pointer as the original. I don't know for certain if that will bypass the check, but I think it could. You can get the pointer and create an array from the pointer using NativeArrayUnsafeUtility.
There are also some interesting methods in AtomicSafetyHandle which I haven't used before, but look potentially useful for this.
PUT cannot be made in browsers? Why?
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.
Maybe i'm wrong, but you could try having those arrays as attributes marked with NativeDisableContainerSafetyRestriction.
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...
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 :)
Elasticity can easily be simulated with acceleration and some sort of damping (which would stand for the lost of energy).
how would i impliment that and what sort of method would i use to rotate the hands? something like Quaternion.Slerp?
Yes, Quaternion.Slerp would be the function to use.
Here an example of elasticity: https://dotnetfiddle.net/u8SsKK
im struggling to re-format that code snippet to be used for quaternions any suggestions?
Try again :P. Coding is a complex subject that needs to be done by yourself if you want to learn. Sometimes, it can takes days before understanding correctly how things work. Take it as a challenge.
Whatever you are going to figure out here, will help you a lot in the future.
sorry about that, i was reading an old post about webgl limitations
it's hard to say what's going on because you have given too little context
it is unlikely that he's on a browser old enough to not support PUT in xmlhttprequest, but apparently they existed in mainstream devices as recently as 3 years ago
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
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
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.
Itβs a bit late right now where I am so
you can enumerate the assemblies and exclude the editor ones, then it becomes AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !IsEditorAssembly(assembly)).assembles.SelectMany(assembly => assembly.GetTypes())
i don't know why you would want to do this though
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
Where is the IsEditorAssembly function defined?
i'm sorry. you would have to author it
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
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
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)
and you may need this as well for the board https://docs.unity3d.com/Manual/Tilemap.html
I believe that you could achieve that by using IProcessSceneWithReport and AssetBundle/Resources/Addressables.
- In the IProcessSceneWithReport, you edit the scene such as there is no unwanted component.
- 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.
- 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).
i don't know. i mean it's just a ton of work. you'd have to deal with ordinary .net assemblies too. why not simply use the namespace? why not just name the things? what is your goal?
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.
what is the goal
like what is this for
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
EF, as in .net EntityFramework?
Initializing event buses for now, but I intend to use it for other things as well
what does that mean though initializing event busses? like for what part of your game?
Yeah, like in EF when you pull from the database you need to have .Include() at the end of a linq query to include embedded objects like lists of struct etc.
but I thought we didnt need it in unity for just accessing a object
I am pulling memoryState from a ES3 (plugin) file
If the AOT you're talking about is IL2CPP, then you can use most of the Reflection API. It's mostly just Reflection.Emit and methods that use it that are off limits. What Reflection APIs do you need that you think won't be available to you?
it's so I can pass events through the buses. At the start of the game I need to run a bit of code to create all the buses, then I can trigger & receive events through them later on. That way I can have things like a PlayerDamageEvent in a way that is globally accessible
@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
code generation
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.
This is perfect, thanks!
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?
using vertial/horizontal layout components
Thanks for the help everyone, I figured it out. I was dumb, I had an object embedded that wasnt set as a IEnumerable<T>
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is really a beginner concern. Read on Unity UI/Anchor and you are going to see exactly why.
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIBasicLayout.html
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Rush Hour Generation
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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)
!code
And maybe #archived-code-general instead
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Alright thank you! :)
unity deep linking doesn't work ???
i'm trying Application.deepLinkActivated but the url is none, nothing shows up
any fix ?
Works for me
i did exactly like the unity documentation but nothing
π€·
here is what i did
ios -> configuration -> added url scema
then in the code :
Application.deepLinkActivated += onDeepLinkActivated;
What type of ios build are you making?