#archived-code-advanced
1 messages · Page 22 of 1
So you don't really have to worry about having them on memory
What you can worry about is GC if you let them unreferenced
It probably matters a lot less than my mind assumed it would be
But aside from the character and stage that were selected by the player, I imagine it'd be a good idea to get these instances cleanly gotten rid of
At the very least tbh
You probably need them later in game, don't worry about it.
You can unload the unused assets, but the game data is fine.
Fair enough, least I got some advice on the matter. Much appreciated.
Okay I reduced it to tolerable level 😌
this is fine
if you feel more comfortable describing this stuff in code than in the editor - i would have done it in the editor - well this is #archived-code-advanced , you are capable, you can do that
Well, good to know it's fine!
I have, and im using windows 10. the dll works fine is visual studio. im just trying to use it with unity. the available assets for kinect are rare and very old.
do u have one that uses unity? (sry for the late answer)
Hi anyone
I'm making a clean up game
but line 147-150 makes the game slow
How can I enhance that line of code
Do one getpixels call instead of so many individual ones
But the real winner is using a shader and graphics.blit
this is a tough one, sorry.
you can't just copy and paste that one DLL
i think you'll get a little more experienced with this stuff and it will be easier
well its for a school project, internet says its as easy as copy pasting the dll but we got decieved once again xdd
you can try to copy the right SDK content into unity
it's not going to be that one DLL
the DLL itself has references to other DLLs, and the runtime tries to find those via a variety of strategies
it's telling you it can't find something
i think if you configured the error messages correctly, it would tell you what that is
it may already be telling you in the editor
that said, there is an official, modern Azure Kinect device, and a modern nuget package, which may be easier for you to use
thats what i was thinking, could there be a way where i can check which other dlls its connected to and then paste them in the editor aswell
this is the error im getting
i might try this as well tonight
there are tools that can tell you what managed and native DLLs something references
it might be easier to copy the entire SDK directory into your Assets/ folder for now though
that might Just Work
you should also use .net framework 4 as your ... whatever it's called
i hardly remember anymore, but you will change it from .net standard 2 in your player settings
thanks a lot, ill try it out when i got time !
Trying to use Newtonsoft Json in my project. Any idea what's causing this? ```cs
class Control
{
[JsonProperty("look_x")]
public float look_x { get; set; }
[JsonProperty("look_y")]
public float look_y { get; set; }
[JsonProperty("jump")]
public bool jump { get; set; }
[JsonProperty("arm_left")]
public bool arm_left { get; set; }
[JsonProperty("arm_right")]
public bool arm_right { get; set; }
[JsonProperty("forward")]
public bool forward { get; set; }
[JsonProperty("backward")]
public bool backward { get; set; }
[JsonProperty("left")]
public bool left { get; set; }
[JsonProperty("right")]
public bool right { get; set; }
[JsonProperty("dead")]
public bool dead { get; set; }
[JsonProperty("reload")]
public bool reload { get; set; }
}
class HFFInput
{
public static Control hffControl;
public static void init()
{
hffControl = new Control();
}
public static void unpackJson(string json)
{
hffControl = JsonConvert.DeserializeObject<Control>(json);
}
}```
provide all of the other context
Working with the BepInEx plugin injector to inject code into a game at runtime (modding). To the best of my knowledge, the game uses Unity 2017. I've included the Newtonsoft Json and System.Numerics dlls in the plugins folder to be injected along with my code.
And in case you're wondering, the mod is really only applicable in a singleplayer setting, and a lot of the community is supportive of the development of this mod. (The only reason I say this is because the last time I asked for modding help here, people asked to make sure I wasn't doing so for nefarious reasons before they provided help)
i'm trying to figure out multi-threading, especially using Parallel.For from System.Threading.Tasks. i just wanted to ask since it's running way worse than a normal for loop, and before I waste 20 hours reading, is this the way to do it in Unity, or does Unity prefer some other method for running a Parallel.For loop? I'm seeing some stuff about ParallelFor jobs but not sure that's what I should be looking at.
How is it way worse? In unity you can use the Job System to schedule parallel workloads with full engine optimization, but parallel tasks work too. Generally running parallel code introduces some overhead, so it will always be slower than single threaded code but it can do more work in the same amount of real time.
i'm trying to learn it so i'm not sure i'm doing it right, and the for loops i'm attempting it on are long and complicated, but it simply runs way worse when i run it so probably something is not done right.
Can you specify what ‘way worse’ means? How do you profile the performance?
simply checking the frame rate in both the editor and in a build, it drops from 120-300 fps to 80-120 fps
so you run those tasks every frame?
yes
well that’s not going to be performant indeed
you should run worker tasks independent of the update loop
why is it so bad to run a Parallel in the update? wouldn't you do something similar for multi-threading pathfinding for example?
let them finish whenever they do and use the result when they are done, launching new tasks every frame is wasteful
Unity prefers the job system where possible
what exactly are you trying to multi-thread?
oh boy. well, i've created a 3D tile system where each tile is represented by a 3D array of Tiles, and each frame where the camera moves I run a for loop to iterate through the visible tiles and create a "slice" of the world represented by values in a Color32 array that I then send to a shader via a Texture3D
i say 3D but this is still very much 2D
That’s really a longer discussion about how multitasking works on multicore CPUs
so i have a 3 for loop deep nested loop (x, y, z) that does some checks to look for walls, doors, etc to determine render states
it runs fine even on old CPUs but it's still by far my heaviest process so I wanted to attempt to multi-thread it if possible
This will be quite a challenge to multithread effectively
the job system will guide you a bit more
but you might end up figuring out that true performance improvement would require very specific data structure that drives the computation and parallelization, which ultimately leads to data oriented programming/ dots
yea just gotta figure out what that is first 😂 sorry multi-threading is completely new to me
It remains that way for most people
been reading all day but still very confusing
not something anyone can master in a few days
just need to find some good resources that isn't MS docs
How theoretical/generic do you want it to be?
i don't mind as long as it's not MS docs. MS docs only works for people who already know most of it, it's like reading math on wikipedia.
any resources are good resources, can always learn bits and pieces here and there
if you have any recommendations i am all ears
I’d work through a mooc on the subject, there is a quite nice and often used method of incrementally teaching it
in textbooks that are written to accompany such a course this same explain would also occur
The keywords to look for are concurrent and parallel programming
i don't really like going through courses but i'll consider it, thanks for the tip
☝️
they are extremely hard to navigate unless you already know where everything is
Have you profiled this right now, why do you think multithreading is the way to go? Is it even possible to multithread
@tribal pivot i did profile it and the function takes like 5-6ms, and it's iterating through 3 axes of tiles in a matrix so it might be like 80*60*50 entries. like i said it runs ok at the moment but i wanted to look into multithreading it, it just felt like it made sense to offload some of the 240 000 loops to other cores
because i am also going to add more on top later
i say "matrix" but it's a 3D array
all the iterations of the for loop are independent really so i don't need them to return in any specific order, i just don't know why it runs badly yet 
maybe they're fighting over access or something, or the parallel overhead is actually simply heavier than the loop
that's what im trying to find out
not to mention thread safety
hey, when using the xr rig, is there a way of getting possibly position (vec3) and rotation (qt) for each eye? i know that when using ovr, the eyes were already there named as left and right camera anchor. here with xri i get just the center camera and for my project i kinda need both right and left ones.. help pls
Could anyone help me converting a counting sort algorithm to be in place?
why not just look up an in-place algorithm
iirc that’s not really possible, best you can do is fake in-place where you get the results in the input array but you aren’t saving space since you definitely need 2 arrays
What two arrays are you referring to? The count array is 1 and the elements to be sorted is another. I am just trying to work together to understand.
Those two
But if it is not in place you would need 3 arrays. The input array, the count array, and the temp output array.
in-place means that you don’t need extra space besides the input array
correct this is not "true" in place but my count array is very small and doesn't really impact.
sure, but you asked for in-place and it sounded like a theoretical question which generally has little to do with what matters in practice
this is not Unity related
the problem with calling one getpixels is that it will not count all the cleaned amount
you can't make an in-place counting sort unless you want to do something hacky (like using upper word/lower word if your value range is small enough)
I can't tell if this goes in advanced or beginner but I'm struggling to find a way to find the difference in the way an object is facing to an object
like a number of how far off the rotation is to facing the object
the difference in what unit
degrees
Vector3.Angle should work
compare your transform.Forward with a vector you create by subtracting position from the target object position
wow
if the angle should only be around the Y axis you can use Vector3.SignedAngle the exact same way too
jut pass it Vector3.up for its 3rd arg
this will also let you know which direction the angle differs in as well
Thanks
Hi can someone help me https://stackoverflow.com/questions/74069108/getpixel-makes-the-game-slow?noredirect=1#comment130777290_74069108
you are uploading a new texture to the GPU each frame, this is very inefficient
actually the getpixels are the problem
When I try to remove the code Color pixelDirtMask = _templateDirtMask.GetPixel(pixelXOffset + x, pixelYOffset + y);
How can I know the remaining dirt to be cleaned if I don't get individual pixels?
you'd load the whole texture into a buffer, and process the changes in that buffer, or use the raw data to do the same
I've managed to get pixel getting and setting running pretty well every frame, but it depends on the size of the texture. The best method I have found so far is using get and setpixels32 and then adjusting the color32 array
^this (multi pixel methods) also works
but editing textures like that is very inefficient regardless
what would be 100x better is doing all this with a render texture
or a compute shader
can render texture compute the remaining dirt to be cleaned?
can it compute the remaining dirt to be cleaned?
do you need pixel accurate info on what is dirt and what is not?
typically you'd have one datastructure that holds the info on what has been cleaned (a low resolution texture or plain array) and another one that handles the display of the progress in a nice way
yes I need to know the remaining dirt
--> screen pixel accurate <-- is the keyword here
ok i'll try to research about dat
Is this 2d or 3d
2d
Then even if you have a 1080p resolution a 2d array should be fine to determine what's on the screen. You can make the game logic alter the array contents and only draw it every frame with no get calls.
Alternatively store the status of the dirt in a color32 array only and alter that
Then you can just do setpixels32 directly
Thank you for ur inputs I love u all
Since the screen has 2 axis and the color32 array is 1d you have to do something like "x + (y * xSize)" to access it right in a nested for loop if that makes sense
On phone
ok i'll study about color32 array
Hello! idk if this is a code-advanced question but i didn't find anything useful in google so yeah. Anyway, the question is: How can i create custom properties on the inspector using fieldInfo?
foreach (FieldInfo fieldInfo in myCustomType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
EditorGUILayout.PropertyField(fieldInfo/*do magic with fieldInfo?*/) ;
}
Use SerializedProperties instead of fieldinfo
but how? idk how to, all i can get is fieldInfo or propertyInfo
in fact, that's the main problem
i can't, i don't have an instance of the object i want to get the fields of
and please tag me so i can respond faster
Show more context then, what are you actually doing
probably nobody right?
i have a custom class that contains information an entity should have: property. Let's say Shield. A shield property should have : maxShield, shieldSprite, ShieldColor etc. I want to tweak the values of the shield property for each prefab; i also want to do that in one place: the entityBuilder AND i want to make it generic so i don't have to change the code each time i add a different property. That's why i'm searching for all types that inherit from the abstract Property class. For each iteration, i want to get the property fields and draw them in my entityBuilder so i can edit and store the data
maybe i'm doing it wrong, but at this point i just wan't to know if my solution is even possible
bellow should be a SaveProperty Button
Is there a way to force an update of a transform's position and rotation so it is reflected in the hierarchy immediately?
whats the xSize? is it the brush width?
How do you know it's not reflected in the hierarchy?
Since the screen is both x and y but you are using a 2d color array you need to multiply the y value by the maximum size of the x axis, so 1920 for a 1080p resolution
So when y goes up to 1 we add a full loop of x to the index
@winter yacht I use an active ragdoll and when I enable the gameobject I play an animation, the animation rig's transform are immediatly set to the right positions, but the active ragdoll's rig takes an extra frame to set itself even though I go through all the transforms to set them to match the animation rig's position and rotations.
This is within a nested for loop
Just a thought... maybe have the meshrenderer disabled and only enable after setting the positions?
Basically hide the first frame somehow.
@winter yacht If I Debug.Break right after enabling the object, starting the animation and setting the transforms, I see the transforms of the ragdoll are not at the positions I set them. The renderer is enabled.
Yes I do this already but it causes other issues. Those ragdolls replace entities rendered with DrawMeshInstancedIndirect when I need them to interact with physics. I was hoping to find a way to get them ready to receive a beat up on the same frame I enabled them.
I was hoping to find something like Animator.Update() for transforms to force an update
Does anyone know when changes to a transform is updated in the hierarchy? Is it during FixedUpdate ?
what exactly are you trying to assert? changes happen immediately, effects of a change may appear only during the next update/fixed update depending on what you are looking for
@compact ingot This shows the problem well, In this image the green rig are the transforms used by my active ragdoll, the red one represents the animator's rig. This screenshot is taken just after I enable the gameobject, play an animation with animator.Play() and run through all the transforms of the green rig and set their position and rotation to match the animation rig (red). Then I did Debug.Break to take a shot.
Somehow the animator manages to set the transform of it's rig on the same frame the animation starts playing but the changes to the green rig are not reflected untill the next frame
Anyone have any idea how this audio mixer group selection UI is made? I want to make UI like it to be able to nest items inside each other
You are taking into account that setting some transforms in the green rig will affect their children?
@winter yacht yes. The position of the green rig at that moment is the position it was at when the gameobject was previously disabled.
as in the animation that was playing at that time
Since I'm replacing entities with the dolls, I need it to be ready on the frame it's enabled. Thats why im trying to figure out how to force the transform update
somehow the animator manages to force that update
hey I didnt read your whole convo but theres this setting
https://docs.unity3d.com/ScriptReference/Physics-autoSyncTransforms.html
might help/be related
I will check it out ty
actually that doc kinda says that it shouldn't be used... maybe this method is more relevant
https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html
That's worth a try!
@lament salmon unfortunatly that doesnt work 😦
Anyone familiar with CIL, can I use call instruction but pass a lambda instead of a static method and if yes how?
by looking at the IL it looks like call is used for methods
and lambdas are used with callvirt
You could generate a display class and call that if u really want calls but that might be counter to what you'd want if you're looking at CIL
If you're generating IL yourself then iirc you can but I doubt you can coerce the compiler to generate it for you
Hey so, I'm wondering if something like this is possible. I have a Height Map and a Texture Map for a Sphere that are mapped Cylindrically
Is there any way to project the heightmap onto a sphere and then apply the texture so that I can create a planet type object?
Sure it's just math
Yeah, I meant more with Unity's built in stuff.
Hi, quick question; can you save json in a custom file type? Some games have save games called 'Savegame.data' or some other custom extension. I would like to know if it's as easy as changing the file extension
Yes, you can name the file whatever you want. The file extension isn't the same as file type.
Extensions don't really mean anything, it just helps the OS to decide what application to open
Saving raw json is just changing file extension. However other game's custom format probably have more obfuscation and encryption than raw json.
Thanks folks!
What would be a good way to go about making a "terrain smoothing" brush? I'm making an in-game level editor. I want to make something that has the same basic behavior as the Unity Editor terrain smoothing brush (I already have all the other editor brushes implemented).
anyway, I guess one good way is to make a loop that starts on the outside of the selection circle and goes in a spiral. For each vertex, it raises or lowers the loop iterated vertex in whatever direction the average height of those 5 vertices is. That's probably the best way but to make it go in a circular spiral pattern, that would involve some complicated trig that might introduce rounding bugs
If there was a way to use the editor's actual smooth height function, that would be great but I haven't found it, if its possible
the smoothing brush measures the average height within the brush's borders, then raises or lowers terrain to that measurement within the brush
oh is that all it does? Wow ok I was trying to make it more complicated than it needs to be
Hello,
What do I do when I have big list of positions and I want to draw instanced meshes on these points?
Can I just send a Vector3 list for positions to the gpu?
I am currently sending transform matrices and using Graphics.DrawMeshInstanced
positions are part of the Matrix4x4s
DrawMeshInstanced only takes matrices iirc
Yes, thats the case
I know what transform matrices do
DrawMeshInstanced didnt let me have more than 1024 matrices
And I was thinking that it is not efficient sending any more information other than positions to the gpu
Because rotations and scale dont change in my case
If you want to get more efficient you'll want to look into DrawMeshInstancedIndirect
In which case the position data will come from a compute buffer
Will I be able to have more than 1024 with a standard shader?
Now that I think, I'll hit the materials input buffer limit
If you use DrawMeshInstancedIndirect you'll need your own shader which reads position data from your compute buffer
If that 1024 is because of the materials input buffer size limit
This is a really good guide on it:
https://toqoz.fyi/thousands-of-meshes.html
GPU instancing is a graphics technique available in Unity to draw lots of the same mesh and material quickly. In the right circumstances, GPU instancing can allow you to feasibly draw even millions of meshes. Unity tries to make this work automatically for you if it can. If all your meshes use the same material, ‘GPU Instancing’ is ticked, your ...
@sly grove allright thanks
I want to create a custom attribute [RadiusGizmo] that I can slap on any float field and as a result I want it to draw a circle with the given radius as a gizmo in the scene view around the selected game object. Where do I start?
I cannot wrap my head around how to implement this. I'm trying to implement movement so that when the player is on a slope that is "too steep", the input direction should be translated so that it does not move up it. As if you set the movement direction into the slope (even with 0 at Y axis), the physics system will still push it up (unless it is a 90 degree wall). Any ideas how to implement it so that the movement on a steep slope is the same as if it were a 90 degree wall? I made a very artistic visual representation in case I can't explain it well enough in words
Here is the current logic for sloped movement, but because I want my air acceleration high, it just shoots up on steep slopes
private void SlopeMovement()
{
// Calculate desired velocity based on direction
Vector3 desiredVelocity = m_desiredDirection * m_airSettings.MaxSpeed;
desiredVelocity = Vector3.ProjectOnPlane(desiredVelocity, Vector3.up);
// Determine if we should accelerate or decelerate
float speedChange = (m_desiredDirection == Vector3.zero) ? m_airSettings.Deceleration : m_airSettings.Acceleration;
// Find new velocity and apply it
Vector3 newVelocity = Vector3.MoveTowards(Motor.Velocity, desiredVelocity, speedChange);
newVelocity.y = Motor.VerticalSpeed;
Motor.SetVelocity(newVelocity);
}
sorry if this doesn't go under "advanced" code, but no one seems to have the answer elsewhere 😅
How about adding an invisible 90° wall? It's kinda dumb but it could be an easy solution.
And collide with the air every time there is a steep slope... ?
I am asking here because there has to be some way to calculate it, not ruin the game experience
Hello everybody. Does anyone know how I can convert a value from a linear range [1, 0] to a value in a logarithmic range [1, 0]? thank you
Seems you are working against the physics engine. If you want to do this manually, perhaps when the player collides with the slope, check the slope contact.normal. If Vector3.Dot(normal, player.up) > 0.8f , limit y movement. https://docs.unity3d.com/ScriptReference/ContactPoint-normal.html
This really does not solve anything though. As for limiting velocity added to y, I am already doing this. And you cannot limit the y movement either, as any time you come into contact with a steep slope, it will stop your y velocity instantly, which feels very bad.
Math.log10(value) + 20 i think
Check this video
Unity Audio Mixers, adjustable with sliders and saving its values to persist! EVERYTHING YOU NEED TO KNOW comprehensive guide
How to add audio to your game (the basics of audio): https://youtu.be/eNi67i5my84
How to play a specific clip instead of a random one:
[SerializeField] AudioClip clip; //Just use a clip instead of a list
audioSource.P...
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131 with this asset being now free I can not recomend it enough. Look at the code even for learning purposes.
Oh, I see what you meant now. Your rigidbody drag is so high, the player won't fall down easily? Seems like this would be solved by playing with the physics parameters. Maybe instead of limiting the y movement / velocity, just increase the rigidbody gravity then, when it's in contact with a slope. It kind of depends on how you actually are moving the player and the physics setup
Thank you.
Dont know exact minute but look for slider part in code also might need to modify it
Yes, I got it. I never used audio mixer, so I simulated the exact behavior of this component by hand. By watching this video first, I would have saved a lot of time.
Yes, instead of using a slider value, I am using the player distance with the audio source to create spatial audio.
Thank you for this resource @livid kraken. Managed to find this line when looking through the code which is exactly what I needed. Thank you
Vector3 perpenticularObstructionNormal = Vector3.Cross(Vector3.Cross(Motor.CharacterUp, Motor.GroundingStatus.GroundNormal), Motor.CharacterUp).normalized;
Any of you guys know how to import a .GIF file as texture assets in runtime? I want a way to play them in-game, but I want to be able to load them from a file that's already on the user's device. I found one method that seems to only be set up for downloading GIFs from a URL, and another that requires System.Drawing.Imaging which seems to be incompatible with my project.
if you want to write your own you can use an imagemagick wrapper and get the raw pixel data for each gif frame and call LoadRawTextureData
else just google one
how to export to android?
nvm I figured out how to refactor that URL-based method to work from a file (although I haven't tested it), thanks though
go to build settings and set the target to Android. Make sure you've downloaded the necessary NDK and JDK, and that you've enabled USB debugging on your device.
I have a client-server game that is a unity client along with a C# console app (containerized and deployed in Azure so I can eventually scale it). I've been a little bit lazy with some of the networking messages, opting to occasionally send the entire player model back and forth instead of cherry picking data and merging it on both ends.
As development has progressed, I'm finding that the model is getting larger - it's about 1kb - and many normal game operations send the model back and forth.
How should I plan for load here? Where do I spend my efforts? It's pretty time consuming to pick out only the data I need and re-assemble it on both ends, but I'm starting to worry that I won't be able to scale unless I cut down on the bandwidth. Should I base my efforts on some sort of "normal" kb/sec average and use that to guide my efforts?
Thanks for your thoughts. Screenshot is of console app running locally while I click around the app.
It's probably on the order of like 5kb/minute for normal gameplay..? But I was hoping that my server would be able to scale to several thousand concurrents or more - 5MB/minute seems low, yeah?
I was just about to reference the asset Uri did. you should be using it
5MB/minute is low
In terms of total server throughput - what kind of numbers do you think I should start thinking about it? I'm planning to add quite a few more features and I find just sending the entire player model back and forth is convenient
If I were able to get 10k concurrent users (I mean, first of all, hooray, right?) that'd be around 50MB/min - I feel like that'd be pretty dangerous
Spikes could easily be 10MB/sec
usually the thing that falls over in managed runtimes is memory usage
I'll keep an eye on that. I hadn't really thought that'd be a bottleneck. I was always assuming it would be bandwidth - which feels harder to solve than cpu/ram/disk issues
on public clouds, bandwidth is always bad. you'll have to contact them directly with your support account to get advice on specifically which instance where has good bandwidth
for example the outbound bandwidth of a M6 instance on AWS is about 25MB/s
last i measured
which is quite low.
10MB/s is fine
I don't speak AWS instance sizing 🙂 But my azure container instances are tiny, but I have no idea what kind of networking costs/throughput I get with them
hmm
well it's going to be the RAM that stops you from getting to even 100 concurrents
although, 100 concurrents is like a 150,000 DAU game
I think I have to pay for all these metrics
maybe not
Anyway, I'm probably just wasting time.. I should get back to the game dev. (btw, beta launch in tier 3 markets scheduled for nov 15 woohoo)
for spellsource i have a benchmarking system with a dummy client
to measure how much RAM each user takes
yeah
I spent the whole weekend ripping out the networking library and replacing it with a different/(better?) one
that's good
lol
no that stuff is a little low yield
I was showstopped by not having nat punchthrough support on the older one
you ever work on something really gnarly for like 72 hours and then magically it works and it's done and you're kind of in a daze after? that's me
(including a 2+ hour support call with ms azure support.. which was awful, they literally couldn't figure out Zoom so they all had the wrong audio devices and were playing my voice through their speakers with horrible feedback/echo)
lol
"dude trust me you aren't using your headset I can hear myself clearly"
memory usage seems....... really low
In broad terms - what's going to soak a lot of memory? Is it the overhead on connections? My game is pretty lightweight - I think an active user is gonna use something like 2-4kb
those are my container sizes - tiny
really depends what you simulate on the server
nothing? is it just a relay essentially?
virtually nothing.. there's no "world" per se, it's mostly just .. hm.. how do i describe it.. it's an idle game, so i track occasional things like currencies, speed, distance, but most of the calculation is done on the client
i think it's probably fine then
sometimes there is a per-thread memory cost that is high on managed runtimes
ie, we trust the client to calculate distance and taps and stuff, and then the client just says "ok i reached level 2, here's my player model" and I do some light validation on it and persist it, that's mostly it
if you do not do thread-per-connection/thread-per-user you are fine
Yeah, I don't ever send anything to all connected clients (aside from shutting down gracefully, which honestly doesn't count) 🙂
the bandwidth willb e fine i think
(battles are turn based battles so even the ProcessBattles() call is virtually empty - it just checks to see if it's any computers' turns and if so, takes those turns)
does the bot create copies of the game state?
Yeah, but it's small
maybe a few hundred bytes
All of those dicts and lists contain objects with only a couple of fields, and the collections themselves will only have <10 items
etc
I still have to figure out how I'm going to load test this application.. I suppose I'm going to have to write some app that can fake a player for each module of the game and .. click around and stuff
i have a client that plays randomly authored in the server tests
this is with 400 concurrents playing as quickly as possible
it's a way more complex game
Do you have your tests in your CI/CD pipeline?
yes everything is tested
I probably ought to do that. That's one of my biggest gaps I think but... you know, indie things. (don't hate me)
it makes more sense for me because randos were contributing
and can break things in surprising ways
Yeah. I suspect I have a huge ass pile of unfun work once I start friends and family beta testing
hi there wanted to ask how can i make controls like these? i want my players to scatter inside that area like in this video
I've tried using navmesh and assigning random destinations but it isn't giving a scattering feel like in this video
first of all this is something to ask in #🤖┃ai-navigation not advanced coding.
It looks to me like they're just moving towards it, look how the first few are running into the wall.. does not look like proper pathfinding to me.. could even be a simple character controller
the scattering is just them bumping into eachother
but maybe there is more to it than that have no idea where this is from.
it shows errors tho
Does anyone know how I can get the IntPtr of an IEnumerator
think you would need to go through GCHandle for that
var handle = GCHandle.Alloc(items);
then cast the handle to a IntPtr, and be sure to free the handle when you are done with it
think it has a ToIntPtr method on it as well
now i would question why, IEnumerator is not a regular collection of stuff in continuous memory you can easily pass off to something else or memory map
why...
What is the best common name for storage classes and persistent data? (save/load persistent data)
Also what about mapper/converter to map object to persistent data
For example there is a world object (voxel game) and I want to convert it to WorldPersistentData
WorldObjectToPersistentConverter?
public class WorldObjectToPersistentConverter
{
public WorldPersistentData Convert(World world)
{
}
}
public class WorldPersistentToObjectConverter
{
public World Convert(WorldPersistentData worldData)
{
}
}
A world consists of chunks and each chunk has voxels.
Also, copying data is time consuming. Is it better to have one data structure for logic and persistent data?
To me it also looks like a bunch of low friction rigidbodies just naturally squishing in there, physics driven
when you dispatch a compute shader, does it immediately start execution ?
"copying" data?
shouldn't you be streaming in data
and streaming out data
assuming its works on same basis as any other 3d chunk loader
i have a somewhat general question, but i could post code if necessary: i'm running a tilemap game that has a separate tilemap for the water tiles, which are running a kind of cellular automata process to simulate fluidity. the code works well enough, and if there's not a lot else going on there's no issue. however, after a time, i start getting major cpu hits when other things happen during runtime like instantiation and destroying of gameobjects. my question is mainly if doing the water tilemap running calculations on where to move next update is the type of thing that would be worth trying to run on a separate thread, or if i should be looking at other optimizations first?
always analyze your performance with the profiler before you start optimizing further
i've done that and it seems like the major fps spikes are from "animation", which presumably is from the tilemap because it drops when i disable the automata script. also the stack use seems to just rise and rise, as well as memory use. i changed my tile data from classes to structs and that helped with memory but the cpu usage and memory usage is still bad
i think what is happening is that the water calculation process is hogging the main thread so when other things want to happen they have to wait. but i guess my other question would be is if this "animation" cpu usage looking like a spike would necessarily translate into that same spike occurring even if the calculations were magically done with zero cpu usage (just theoretically). if that were the case, i would need to look at reducing the animation, but if it weren't the case, then i could look into reducing the main thread load from that calculation process.
you need to determine if it's animation or calculation that is causing your performance problem. How you optimize will go from there. If it's animation, a separate thread won't help because you can't interact with the tilemap outside the main thread
that's what i was thinking. and i understood that second statement somewhat lol (just watched a good video on the subject). do you have any suggestions as to how i might start diagnosing which is which? i guess this might require getting into specifics but are there any general techniques for helping to parse this? i only first opened the performance monitor thing yesterday so there's a lot about it i don't understand...
profiler, augmented with some https://docs.unity3d.com/ScriptReference/Profiling.Profiler.BeginSample.html/EndSample pairs where needed to identify exactly which fragments are slow
so if i'm understanding i want to use this for a part of code that i suspect is a cpu hog?
that seems to be the case. okay thanks a lot for the info.
I mean I don't really think telling someone that they "should be using" an asset instead of learning is a good idea imo. Sure it is a great controller and is free, but definitely not "should be using" and instead a good way to learn
I mean when I want to convert a voxel (struct) to voxel persistent data, I have to copy it. Using ref assignment?
I'm making a game for a gamejam, and I've run into an implementation problem involving audio...
So there are two scenes, one scene is a 2D game where the camera renders to a render texture, and a scene where the game is being played (render texture on a TV model.)
The problem I'm facing is getting the audio to route from the 2D game to the "real life" scene in a way that audio from the 2D game seems like it's coming from the TV.
The obvious hack is to fade volume of the 2D game master mixer based on distance, but is there a more elegant way to achieve this?
The idea is that you can leave the 2D game on the TV playing if you want, and walking away from the TV changes the audio (volume, doppler, etc.)
Wnat to ask is there new feature other than asset bundle to help with dynamic content ?
addressables
its built ontop of asset bundles but makes them a lot easier to use
also the scriptable build pipeline if you just need to make existing asset bundles more flexible
I get this error when using message pack csharp serialization
FormatterNotRegisteredException: Bitzooma.MiniCity.Core.WorldPersistentData is not registered in resolver: MessagePack.Unity.UnityResolver
I have used Key() attribute and MessagePackObject for classes
private static readonly MessagePackSerializerOptions MessagePackSerializerOptions = new(UnityResolver.Instance);
Unity 2021.3.6 .NetFramework + Mono
and if I use MessagePackSerializerOptions.Standard I get the error below
MessagePackDynamicObjectResolverException: can't find matched constructor. type:Bitzooma.MiniCity.Voxel
What does it mean? I should have ctor in data structures?!
IIRC you need a compound resolver that registers your own classes and you should have a ctor that has the same order of parameters as the properties defined in the model
I don't have reference code anymore so can't give you concrete details
I see some examples without any ctor in its github
Could be but that's how I did it
Thanks
and why the errors are different when I change the options
It worked
[SerializationConstructor]
public Voxel(byte id, byte rotationType)
{
Id = id;
RotationType = rotationType;
_flags = 0;
}
So there are two scenes
do you mean two scenes or two Scenes? it sounds like you have one Scene
audio to route from the 2D game to the "real life" scene in a way that audio from the 2D game seems like it's coming from the TV.
unfortunately you can only have 1 audio listener. my suggestion is to place the 2d game content right where the TV is, and hide it from the main camera using rendering layers. then it will all work idiomatically
Why the particulates on capitalization? One scene (the file type) is loaded, then on request a second scene (also the file type) is loaded. You can have multiple scenes loaded at once. Anyway, if I did that, I'm sure I would need to scale down the 2D content which might have unintended implications on rendering, not to mention it would make it annoying to debug in the scene view.
i suggest using only one Scene
i say that because it wasn't clear from your language
if you meant scenes metaphorically, or a literal unity scene
i don't think the scaling will matter. as long you use a game object to achieve scaling and positioning whose local space is still "normal" coordinates for the 2d metaphorical scene
it should work well
Why? it works perfectly the way I have it now
hmm
anyway that is my advice, i think your game sounds great
all the other solutions are more complicated. you could try duplicate the audio sources into the tv, at the right positions, which is a lot harder than moving the metaphorical 2d game scene
you can also ignore audio
which i think is what you are probably going to do
that's actually not a bad idea, I'll try that
really depends what the goals are. immersion? is it meant to be played in a browser? etc. etc.
it's usually a bad sign when someone takes the suggestion i say is the worse one lol
but i've been striking out lately with trying to get people to do good stuff
I could extend the AudioSource class and create logic to move the audio source to the TV on start
BUT, changing volume in the mixer based on distance would be more performant, just not as immersive. but it's a gamejam game so that's okay
i just think this is a really, really bad idea
when it would take you all of 5 minutes to move the 2d game scene into the tv, and set up the camera render layers correctly
it's a game jam
you're talking about performance...
it's a built in render pipeline game right?
Yeah
thank you
I have a source generator project specific to the Unity project, I only want to source control the SG source but not the built SG dll. Is there a way to make Unity execute a command when opening the project so I can use it to build the SG project and copy the dll over (it has to happen early enough in the opening process otherwise I'm under the impression that SG wouldn't work) rather than having to tell people that clone the repo to "please build the SG project, copy the dll over, before opening the Unity project"?
imo you should check in the built dll
normally you could achieve this using an asset preprocessor, but it will always be glitchy to generate code which then modifies the player assemblies on launch
I do not have any advice but am in a very similar situation so i'm happy to see that you have posted this! Additionally, do you happen to have found a good way to specify AdditionalFiles in Unity (since you can't edit the csproj directly)?
i have never gained anything from generating sources at launch, and have gained a lot from checking it in, and i've been using source generators for years
that said, you probably mean a msbuild feature called Source Generators
and not something like protobufs
you should check in the DLL
I was wondering about additional files too. There's a hook to modify generated csproj but I'm under the impression that csproj isn't actually used for building, only for IDE (so your SG will work in IDE properly but not when you are building the game)
I'm (obvs) not Burrito, and this may be the best solution but working on a large team, PR noise can be a bummer -_-
I don't think it's ideal to check in the SG dll, it's really just artifact of the SG project and that should serve as the single source of truth
yes but it might provide zero ROI
InitializeOnLoadAttrib?
If someone makes changes to the SG project but forgets to rebuild and commit the new dll, that's a mistake that will be pretty hard to spot.
They can get out of sync due to human error basically.
in my experience with protobuffers, the kind of person who has the knowledge to make modifications to them can handle checking in the updated generated artifacts
that's what i'm saying. nobody who has that level of knowledge will make such a mistake
i completely disagree with this take 😅
and someone who lacks that knowledge, who can't modify e.g. protobuf files, will never need to think about source generation in either scenario
i don't know. unity is a build tool, it's not a Build Tool
i use gradle as my build tool, and i do have a single command for all source generation
it really comes down to what the project is
you can write a piece of C# code, as this user suggested, that runs in an editor script
and executes the generation step
i guarantee you that it will be really buggy
it will be running all the time
it will be hard to engineer it to detect changes, etc.
because you will be reinventing a build tool
you can try to use an asset importer class, but that is going to be
then FileSystemWatcher and rebuild on change
Ideally Unity would just support project reference so you can just reference the SG project like you normally do.
this is correct, the .csproj files are only for IDEs
i have a separate solution that, via a build tool, generates assembles that i check in
i do that because when an artist does need my repo, they will not comprehend any steps beyond "download a zip" and "open the project"
they're not going to understand git anyway
they're not going to be using this thing. they don't reall yhave a reason to be in unity, honestly.
so it's tricky
really comes down to what the project is
Yeah, I think that's correct. But is there a hook or something to know when the csproj has been regenerated (or a reliable plugin or something to make sure edits stick around?)
You can just modify the csproj straight in that hook, don't need to edit manually
i was thinking about this too. is it custom or do you have a link to something?
you shouldn't make any edits to the csproj files
But the bigger problem remains that those changes won't affect actual building so it's pointless.
Yeah, not directly, but I guess how else can one (for SG) specify something like AdditionalFiles
i don't know how meaningful this will be to you
is SG referring to Source Generators, an MSBuild feature?
you do not use them directly from unity
Source Generators.
you create a separate solution that is an ordinary dotnet solution
and use dotnet publish
and cp your build artifacts into unity
the consumer is who has to specify the files for the generator.
That's exactly the problem we are trying to solve, to make that process automatic instead of manual for every time SG is changed.
unity isn't a Build Tool, it cannot know.
yeah, i'm not trying to make it one
yeah
you definitely cannot modify Unity player code
using a source generator
is that what you are trying to do?
for code weaving?
getting the source generator imported works fine, but the source generator needs ot know where files live (and this is usually specified as AdditionalFiles in the CSProj)
nah
okay
we are generating an enum for localization keys
honestly i would ismply avoid using the feature
which works
well
that is honestly kind of low ROI
this is a very very burdensome, buggy feature to use
for that
@scenic forge hasn't said what the projec tis
so i don't know
sorry i can't give better advice
cool
you can just go and make the enum
the mistake would be obvious
nobody really fucks that up
and when they do it takes seconds to fix and is obvious
so i don't know
I mean it doesn't matter what the feature is, it's already determined SG is a good way to solve our problem, simply to make SG nicer to use than having to do all these manual labor of copying and syncing.
besides, there are approaches to localization that obviate the need for that
pretty cool to hear that you work with devs that don't make mistakes.
i don't know, almost* every person who has ever said that has been wrong
i make mistakes and have caused bugs
I have something busted in my build, and I'm not sure how to fix it.
I recently refactored a script to rename it from ISGSceneManager to IsgSceneManager. Works fine, but now only on Android, I get these error messages in my build:
How 2 haz fix
did you try the rename trick
(I've deleted the DDOL object, readded a new one, readded it)
where you change it so that it doens't differ only in casing?
What's the rename trick? To force unity to generate a new guid for it?
try changing it back to ISGSceneManager
then rename to ISGSceneManager2
then rename it to IsgSceneManager
refactor rename*
yes but case sensitivity is fucky
Yeah, no problem.. I was thinking of mucking with the meta files and making sure they're correct
yeah
Actually...... I can probably at least verify the problem is there by looking at the guids and making sure they line up
i suggest using gradle then
gradle or bazel
they are good build tools to solve problems like these
otherwise you can share what you are using the source generator feature for, maybe we can brainstorm an alternative
I do have something similar as well (unrelated to the current SG discussion), we have 1 i18n json as single source of truth so we can pass that to localization platforms, and need to generate code to handle stuffs. Due to the lack of additional files support we did it with a regular editor script and it just reruns whenever it detects changes, it works alright but every time you change anything in i18n your commit includes like 4 other files 🙁
handle stuffs
hmm... well i have bad news for you
you're trying to Microsoft Visual Studio & Windows your way into a multi-platform, not microsoft visual studio world
it will not work
this will not be the first nor last problem
if you want to make Microsoft Visual Studio applications, do not use Unity
those skills are not really translatable
the fewer editor scripts the better
I don't see what this has to do with VS or Windows, the game needs localization.
it is hard to come from a place where you are comfortable, Microsoft Visual Studio, to a place you are not
actually kinda the same. We are using Smartling and have had to do (Unity yaml <=> csv <=> smartling) which we quarantined to a separate (orphan) branch. Smartling reads/writes to CSV branch, and we have a job that turns the CSV back into unity assets when it sees changes from smartling
that is a really bonkers workflow
Yeah which is exactly why we have 1 i18n json only as the single source of truth, to prevent workflow getting out of sync due to some human error.
Yeah, if the rest of the company was not already using Smartling it would probably not have been our choice because it does not play nice with Unity
I don't see your point, I don't even use VS.
do you use Rider?
i'm not sure then where you would have gotten introduced to source generators
maybe you are a rare C# backend developer... using Rider...
No I use VS Code, and I fail to see how localization has anything to do with what my IDE is.
okay i see
OK, the files are completely cursed. Let this be a lesson, don't refactor file/classes in windows/unity to just change the casing. 😐
anyway i use the unity localization package, and i always do localization at the end, when it makes the most sense to
yeah
if you can roll back in source control
Renamed it and git kept the original casing 😐
okay
Nah it was months ago
that's unfortunate
I'm just renaming it to something else
okay
yeah that's tough, it doesn't really make sense to integrate with smartling, the best time to do localization is at the end
then it doesn't matter
how it is integrated
and you can work with unity localization throughout 99% of your product lifecycle harmlessly
it doesn't really make sense to iteratively translate
i can see how someone can think it does, but it doesn't
this is getting continued updates
if you are in that kind of jeopardy
so that really is no end
well you know what i mean
right before a release
not during development
like literally the last thing before you release something
we release weekly 😄
well it's not like this can't be done in unity localization
safely
it certainly can
it's a very good package
that apes all the best stuff from everyone else
okay well, i don't know, i agree it's tough
it's tough to know. i don't know what these games are
i find out bits and pieces
Is Unity localization type safe? Eg prevent referencing strings that don't exist, or knowing a string takes exactly 2 interpolation arguments.
you can't use source generators in unity code really, end of story
You very well can, the integration is just not seamless.
i think if your game is making money and you've got at hing working, you know, go for it
you got something
i don't really know
i've offered my perspective
you probably have a support contract, go ahead and use it
once i heard "stuffs" and "csv branch", it signaled to me a certain set of processes that require support contracts and paid advice, which i cannot give, i am sorry
well they wrote a fluent api-esque system on top of ugui, so... right
what i meant to say was he does some pretty wild stuff
who does?
burrito
i see
i mean this stuff is really interesting
it is sort of subjective what the yield is on doing weird source code features
making things intellectually stimulating there means more game code is written, even if the intellectually stimulating stuff is low yield
so i do not mean to begrudge experiments in this approach at all - go ahead, use source generators and figure it out for the rest of us 🙂
SG is very powerful even not for something specific to Unity
(And they are also a pain to debug so its usage isn't widespread even in the wider C# community)
There are tons of uses for SG, practically anytime you have boilerplatey/repetitive code it may be a good SG use case.
yeah i agree
i use source generation just not Source Generators
listen i mean to be supportive
i guess i am not familiar enough with the feature
i got the highest yield from embracing real build tools like Gradle
to solve problems
You can think of source generators as source generation but always up to date with the input (doesn't need to be run manually and invisible)
Source generators don't have the issue of "I have to manually run any time changes occur so they are reflected in the generated code", "I must either gitignore generated code but give instruction to how to generate that code so my project even runs", or "I must commit the generated code and keep it in sync all the time"
yeah but macros are always a little radioactive
it makes sense to me to use them as an IDL, but then the reality is it's a network artifact, like protobufs, it's going to be out of date somewhere always
and in my unity streaming service, it is really high ROI to have done everything using grpc / protobufs, because it really did ensure backwards compatibility across my API
Source generators are invisible to the consumer, as long as you have it set up, you do not need to manually handle them ever and the generated code will always be in sync with input.
it just sounds like they would have, in the general sense, the same problems Macros do
unreal engine uses a lot of macros
out of necessity
You mean C++ templates?
ue c++ has a lot of macros for all i know
I don't know much about Unreal or C++ templates, but they are very different from C# SG
they use proper macros yes
hmm
when i looked at the source generator docs just now
it looked like macros by another name
C++ templates directly modify and transforms your source code, SG does not.
source generators can achieve "code weaving" aka bytecode instrumentation
which i have also seen from the java end, and takes a lot of expertise to do correctly
It cannot.
hmm
It can only append, not modify.
Which makes it a lot less powerful, but a lot more sane to work with.
The only thing C# SG can ever do is "here's a new file I generated, include it in the project"
It cannot modify anything.
il weaving on the other hand
they kind of achieve the same thing except one generates and one changes the source dll
IL weaving or any sort of modification can do a lot more than SG but yeah.
but you'll need a weaving library since source generators wont do it
Yep, and it's very easy to blow things up completely and descend into madness, so it's very niche.
I REALLY need help with Local Multiplayer, anyone that have done a Local Multiplayer game that can help me or give me a link to a working Youtube Tutorial? Please!
do not spam/crosspost. keep it in #💻┃code-beginner
Hey guys, hopefully this belongs in the advanced category. I'm building a small space colonizer game where you can build on planets. While I like how it's shaping up I was considering switching my current building system (place anywhere) to a tile based one to have more precise control on how buildings are placed and whatnot. The problem is the following:
All gameplay happens on actual spherical planets! I have no idea on how to begin to map a tilemap of squares onto a sphere.
Does anyone have any tips OR know any online resource on the topic? Anything is appreciated!
I can point you towards one of my favorite resources on such matters:
https://www.redblobgames.com/x/1938-square-tiling-of-sphere/
I'm going to say right out that Unity's build in Grid/Tilemap etc are probably not going to be of use to you, and if you haven't already, you'll probably need to make your own solution.
This is amazing thanks. I just gave it a quick peek, but I'll read it properly once i've got a bit of time!
From the interactive things I've seen tho it's seems like I should be generating a second sphere around the planet with uniform quads and use those for my tiles?
Probably missed a few things but nothing that reading it properly wont fix.
you probably don't need actual meshes for each tile. What you want is a mathematical formula for converting back and forth between a point on the sphere and tile coordinates
Which one lead to more compression?
Storing the entire byte array or only filled values + indices.
I think the first one because the consecutive values can be repeated and it can be compressed more
it depends on the nature of the data.
If the data has high entropy, storing the entire array will be smaller than values + indices.
On the other extreme, If the entire array is all zeroes or all ones, then it's very highly compressible via this technique
DataStruct1[] // byte rotation, byte id --> Entire Array
DataStruct2[] // byte rotation, byte id, index --> Only Filled values
Yes, it depends
but suppose it is a world with many empty spaces close together probably
I use LZ4 compression as well
Also, I do not know LZ4 can handle repeated patterns in bytes or not
23,2,23,2,23,2
data(id,rotation),data(id,rotation),...
Why is Unity so poorly implementing Native stuff from iOS... anyone has some trick how to get the lastError for ReplayKit without constantly recieving the same error? ReplayKit.lastError will stay forever... no matter if you restart recording...
Compressing algorithm does the something similar for you, so I don't think filtering will help making result smaller..
Can LZ4 compress data structures efficiently if they are the same?
public struct S{
public byte Id;
public byte Rot;
}
They should
So, adding indices can ruin that compression :/
Yeah it could be just adding more things to compress
how do i get the width and height of 2d camera??
orthographicHeight gives you half the height of the camera
the width is based on that height and the aspect ratio
float height = cam.orthographicHeight * 2;
float width = height * cam.aspect;```
always helps to check the docs
you're right
like I said - always check the docs
I just typed that code above off the top of my head
I want to make a GameMode system in unity for a multiplayer game where I can override base functions to create new modes easily. Would it better design practice to have an event based system where I subscribe and unsubscribe from game events(eg player dies, player joins late) and invoke them when they occur or have a base GameModeClass and override functions that are called when the events are invoked? Also what would be the best way to manage different player prefabs for each gamemode?
The best way is the way that uses least of resources the computer has
I'm asking more from a software design standpoint of view
Oh could have said that at the start 🙉 
Would it be better design practice...
Second sentence
And why not? Event based is extremely versatile as it's loosely coupled, your game mode "drivers" could subscribe to the events they need from a game manager object
Watch out for subscription spaghetti though, try not to link events back and forth too much
Hello what happens when object is destroyed using destroy
. Does it free the space it used quick
It is flagged to be garbage collected if there is stuff inside it filling up memory and will be removed on next GC if not done manually
If its collected by GC, it is removed.
To fully collect the managed side of the objects you need to also set references to them to null. Same as any C# object.
want to ask about that. if i'm instantiating 50 'collectible' objects because the player did X thing, then i soon after destroy them because the player picked them up, is this the type of thing that probably would have leftover references? or do you mean explicit references by variable declaration and things along those lines? i'm just now peeking my head into garbage collection and memory so sorry if this question isn't the best phrased...
It depends on what is in the obejct. Its not just gameobject are being handled equally all over the game runtime. If you load textures for example and create texture2Ds, all of those things can affect if GC is kicking in or things never get disposed
in this case it's a prefab to represent a dirt tile after it's destroyed (very similar to terraria or minecraft)
If you Destroy something the native C++ representation is freed. As with any other C# object, references to it keep it in memory. Destroy cannot set references to null.
The references just evaluate to null via Unity's overridden equals comparison.
To have the managed C# memory ready to be garbage collected all references to those objects must be null.
You're likely to come along and set those references to null later by just operating on the same lists, overwriting the variables, etc. So usually you don't have to think about it
ok, that actually was in the vein of my next question. i'm making a game that includes a tilemap running a cellular automata process and both the memory use, heap use, and cpu use seem to rise over time so i'm trying to diagnose. the cellular automata script uses extended use of lists and dicts so i was wondering if that was part of the issue. the code isn't cleaned up for review but if you have a moment to look to see if there's any obvious memory collection or leak issues or whatever i'd appreciate it a lot.... http://pastie.org/p/3MDJEtV9NL5wFvX7Bp5ya1 - not the shortest script but a lot is repeating logic or commented out...
and please don't make fun of my ifs lol
https://docs.unity3d.com/Packages/com.unity.memoryprofiler@1.0/index.html
Use the memory profiler to diagnose the issue
i'm trying to learn but i think the issue is that there's several things going on at once. anyway i just though i'd ask but i get it's a big ask, nbd...
thanks for the answers though i appreciate it
If several things are going on, take apart your system and profile single mechanics, loadings, instantiations, whatever is going on. And dig into it to find out
gonna ask here but anyone know how to fix this?
its all from unity default scripts
all of them being com.unity.ugui
while this comes from a game decompile, i first deleted the decompiled versions, then reinstalled them in package manager
version is 2019.2.13f1
I have some frame stuttering when my client starts. In profiling it, though, I have this spike - a single frame that takes 201ms to process, but there's no single obvious low hanging fruit. Any ideas on this?
Is this useful? What's all this GC alloc going on?
In the editor, in builds, or in both
both
I'm not an expert with the profiler, but I can't seem to identify what's actually taking up all the time in this frame
JIT is compiling a whole bunch of stuff
hm... I still get stuttering on Android, which my understanding is that I'm not using any JIT at all there
Just curious, I saw something like that once (EventSystem to taking a while) with complex UI size fitters and with best fit text. But that was mobile only.
I mean, I have some fitters, but nothing here is doing any layout/UI work.. It's likely the parsing of the settings json I'm getting from the server, but ... I can't seem to prove that
There's a bunch of logging mentioned. Turning off stack traces for anything but errors is always a good first step
OK, lemme see, brb.
Remind me where that setting is? That's a console setting? I haven't played with that setting in months
This stuff?
This mayyy help
https://answers.unity.com/questions/1264528/insane-eventsystemupdate-lag-spike-no-graphic-rayc.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
i'll try with deep profiling.. not sure my problem is what this guy is mentioning..
AHA, deep profiling uncovered it
and ... I'm stupid.
(I don't even want to share the culprit)
I forgot that I added some geolocation service thingy and meant to make it non-blocking but.... just forgot about it. Yes, that's a blocking HTTP request right in my game. 😐
That certainly seems more relevant
and yes, what you had above sadly does affect both the stack traces in builds and in the editor.
I wish they were separate things. I've had to make custom build steps that set those sort of things just for builds and then reset them
Yeah. I mean, it's one thing to have a clue and chase it down (and still have the hiccup), it's another to know and realize that you are, in fact, dumb today. 🙂
All good - I just wrote it that way because I was debugging some other thing (as a completely related aside, fuck microsoft azure container instances) and just.... forgot to do it properly with async or a coroutine
I've also added a little bit of pseudo-profiling and .. my MessagePack object takes 93ms to deserialize, and my initialization in unity (once it's deserialized and I set up my game world) is another 140ms, so there's still some other low hanging fruit
ISG: <color=#6666FFFF>Debug: LNL: Connected. Connection took 110.5901 ms</color>
ISG: <color=#6666FFFF>Debug: Deserialization took 93.0114 ms.</color>
ISG: <color=#ccccccff>Verbose: Finished initalizing. It took 144.6879 ms.</color>
(all of those steps are sync atm)
Anyway, I'm rambling. Thanks for the help.
Hi, Im looking for a high-performance way to find a closest point to another point, right now Im using this https://gdl.space/feqegiyidu.cpp
but Im worried that this wont perform well enough without sacrificing accuracy
there has to be a better way to do this, right?
So can you explain your code a bit? What is pathCreator.path.GetPointAtDistance
sure thing, pathCreator is an asset for creating bezier curves in unity, this function returns the position of a point on a predefined curve
it takes floats from 0 to 1
Alright, and the ontriggerstay is on one object or on multiple? what is ClosestPoitnFound doing
the idea is that the player is supposed to "drag" an object along the curve, this script is on the object they are supposed to drag, when their finger is in its collider, the ontrigger stay is looking for the closest point from the finger on the curve, ClosestPointFound then moves this gameObject to the point that has been found
well one thing to do is certainly not call GetPointAtDistance three times
save the result in a variable and reuse it.
Same with other.transform.position
Actually this whole thing:
dist.x = pathCreator.path.GetPointAtDistance(f).x - other.transform.position.x;
dist.y = pathCreator.path.GetPointAtDistance(f).y - other.transform.position.y;
dist.z = pathCreator.path.GetPointAtDistance(f).z - other.transform.position.z;```
Could just be ```cs
Vector3 dist = pathCreator.path.GetPointAtDistance(f) - other.transform.position;```No?
I have read that calculating the x,y and z separately was faster than using the vectors as a whole
but I havent tested it yet
maybe, but not the way you're doing it it where you're recalculating the whole vec3 on either end 3 times 😱
needless to say, calling the method 3 times is a mistake nonetheless
aye, now I realize it, thats certainly a thing to fix
is there a way to do the entire logic better tho? I dont really have a good feeling about the way it is now
but I wasnt able to come up with anything better myself yet
Doesn't the bezier library you're using have a ClosestPointOnCurve?
Might want to look into Unity's first party splines library. They have such a method:
https://docs.unity3d.com/Packages/com.unity.splines@2.0/api/UnityEngine.Splines.SplineUtility.html#UnityEngine_Splines_SplineUtility_GetNearestPoint__1___0_Unity_Mathematics_float3_Unity_Mathematics_float3__System_Single__System_Int32_System_Int32_
looks like it might do some kind of binary search under the hood too
which is promising for performance
it actually does, I just missed it the first time
I dont really understand how it works, but it probably does
https://gdl.space/picarevoxu.cpp if anybody would be willing to help me understand Id be glad, but it isnt really needed for what I need to do
thanks for pointing out that there should be a function for that! I thought of it, but I looks like I wasnt thorough enough
How come HttpMethod.Patch exists and works for some people but not others
if you look at https://github.com/Unity-Technologies/mono/blob/unity-main/mcs/class/System.Net.Http/System.Net.Http/HttpMethod.cs#L136
it just throws on access
and yet - it works for me
and my colleague
what is the best practice for creating a currency system in my game? I see a lot about playerprefs but I was thinking more saving to a file? especially as a long term goal would to get this on aws for multiplayer
Saving to file makes it easy to modify and is not secure. Here is good tutorial https://www.sitepoint.com/saving-and-loading-player-game-data-in-unity/
Zdravko shows you how easy it is to save and load player data in Unity - persisting to hard drive and reading from it. Start making awesome games today!
I see so this will work and eventually I just move this over to aws?
anybody debugging on device on a mac? can't attach visual studio to the unity process of the phone
Are you think about serve side!
no sure never done multiplayer saving before tbh
I have no idea how that works lol
but the thought of an api call everytime gold updates does seem extreme
For serve side saving use PHP and MySQL
how does saving work though? is it really a server call for every input?
It depends on how you approach things
You could save data on when they exist game
If you want the minimum amount of cheating possible then you need to validate everything on the server
that would not guarante the data seve
save*
E.g. user buys something? Server validates and executes everything and only tells the client to update the inventory with x items and x gold change
Yeah or he could save it on som secure file first and move it to the server
I dont know about your project, but for the moment i recommend you to ignore possible cheating
if people cheats on your game means you have become succesful
if you have become succesful a few cheaters will be the least of your problems, believe me
dont waste your time on that
i tell you by experience
Yeah they come when the game gets population
Also fighting cheaters is pain in the ass
leave the anticheating for when you become succesful, if youdo
there will be ALWAYS cheaters, thats unavoidable
so im making just a simple multiplayer td
although nothing multiplayer is simple lol
so think just get gold build towers
but wasting your time creating a super safe anti cheating game its stupid.
i mean wasting it now
just trying to think through the currency system for the time being
and how that can be done
what are you using as database?
Just send it to your database
You should probbaly just do peer 2 peer networking instead of some centralized system for some simple TD game
I have nothing set up 😄
I just have normcore atm
and got people to join database and the rest is still all in the works
learnign about this thank you all!
going to hook it up to a firebase db?
does that sound correct?
a SO wouldn't work right
Playable API question. How to set an existing AnimationClipPlayable's clip to null (without recreate the playable)?
there's only a GetAnimationClip() function, but when I inspect the Animator's Graph via PlayableGraphVisualizer, the playable can set clip to null without recreate itself
i think there's a photon sample for multiplayer tower defense
on phones?
I see thank you! I did some research and came to azure playfab. Im curious to try it out
im sure the learning curve will be fast hahaha
is this for a phone?
I have some weird and difficult to diagnose problems with UGS in app advertising.. Randomly and without any discernable error messages or logging, the sound devices don't resume when coming back from an interstitial. The sound plays before, the sound plays from the interstitial ad, but coming back to the client .. no sound. Any ideas? Edit: On Android devices
why are you using PATCH?
is this for an http server you control, or something else?
in unity, you use unitywebrequest, not system.net.httpclient
that sounds like a red herring. serialization does not take 93ms. if unity objects are creating during deserialization maybe
if your deserialization involves huge, huge huge strings
this is strictly my messagepack deserialization.. not sure ..
maybe
that's fine
but i mean
inside the json
is it 18.999kB of strings
isn't msgpack a binary format..
hmm
it's 19kb packed
it doesn't really take 93ms to deserialize 19kB of data
it might take 0.2ms, or 1ms in the worst case
or less
d("Received configuration info from game. Unpacking settings and initializing systems.");
_startedConfiguration = DateTime.Now;
ServerSendConfiguration ssc = UnityNetworkingUtils.Deserialize<ServerSendConfiguration>(msg.Message);
TimeSpan ts = DateTime.Now - _startedConfiguration;
d($"Deserialization took {ts.TotalMilliseconds} ms.");
public static T Deserialize<T>(byte[] value)
{
return MessagePackSerializer.Deserialize<T>(value);
}
can you ask msgpack for a dictionary instead of your object?
that's the 93ms call
it's pretty much only MessagePackSerializer.Deserialize
i wouldn't use datetime.now
a call to datetime.now can take a long time lol
on a device
believe it or not
Yeah, I mean, that's fair, I was just looking for magnitude of order issues
because it needs to load timezone data
really? lol, didn't know
yeah
I use UtcNow almost everywhere, fwiw - does that avoid that timezone overhead?
in webgl, at some point, calling datetime.now in a mobile browser took 2.7s
you shouldn't use datetime ever
if you can avoid it
or does that still need to .. "unconvert" my perfect time (pacific time best time) to utc
that's crazy, TIL
I use it extensively on my server.. 😐
ah
i don't totally comprehend why unity's implementation of datetime is so bad
it is the Built In Render Pipeline of time functionality
so, the object that msgpack is de/serializing here is .... quite large, i don't think 93mb ms is out of bounds
ok lemme try, standby a sec
wait profiler is a unity thing? should i use stopwatch or profiler? i just want to see the ms delay in console output, not have to fire up the profiler to dig into it
you should use profiler
because it will give you valuable context
Profiler.BeginSample is conditionally compiled away using ConditionalAttribute. Thus it will have zero overhead, when it is deployed in non-Development Build.
Oh, actually, yeah, this is nice
yes
it will be absolutely correct in editor for small stuff
it will be relatively correct for big picture performance
so you can use it to optimize in editor, but if you need absolute performance, you should measure big stuff like total render time in standalone builds
It is working well for us so far. Patch is the right verb for the action performed
Is there any way to get a profiler frame data out to the console? or do I have to enable the profiler to view this info
i would enable the profiler view at this stage
I'm mostly just interested in this chunk of init code
you will be able to find it easily
Is this first call or are all calls the same speed?
like, i did that just to get roughly what's failing
yeah
This only happens once in the game lifetime
unfortunately that will give you wrong answers because of the imprecision of DateTime
"ssc" in the snippet above is rather large
Chances are then that msgpack is generating more optimized systems to deserialize in the first call
i don't think msgpack in unity emits
and reflection is slow but it's not that slow
i don't know if it caches the results of attributes. i don't use attribute annotation based stuff
https://pastebin.com/DSfxDEaU if you wanna see the size/nesting of the data
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.
you can also try marking classes as sealed if it is properly caching the reflection results
all of the object classes are sealed and .. pretty plain, but I don't think that makes a difference, since messagepack is generating its own code for deserializing.. but i can't read that particular code since it's a source-generated-mess
7700 lines
i see
if it's generated sources* (not a .net source generator)
yeah, required for android
hm.. ok, doing the profiler thing
it's going to be immeasurable
standby 🙂
it will probably create a lot of GARBAGE which almost all deserialization does
but that will not show up in the time it takes to deserialize
being stubborn about stuff like this is a guaranteed way to ship a game very very late
it really depends on your objectives
that's fine, I don't mind garbage since.. theoretically that can be cleaned up later (and is hopefully optimized a bit not to lock up rendering threads)
what do I do with this profiler frame? do I just look for it in the profiler? it'll have it's own line item?
(sorry, trying to read and digest the API for Profiler. really quickly)
that's it?
you should try to find which frame it was called on. the simplest way to do that is to type in the name of the sample in the search
then scrub the timeline
around when it is called
oh i can get it in the profiler no problem since it happens on demand (when I click "login" in the client and run the server locally)
okay great
it'll be a spike i'm pretty sure
standby
hm... where do i find it..? i think i have the frame but I don't see the profile sample I made
you should see the list of methods at the bottom
that are being called
one view is the hierarchy, another is the timeline
you can also see it shows you only Main Thread
you can change which thread if it's not being called on the main thread at all
but the best way to od it is to type SSC into the search box
k
then scrub gently around when you clicked login
and look carefully at the hierarchy view, it should appear
crap "SSC" is found in "IsScene"
"Deserializer" is probably the unique search
sure
and gently scrub
hmm, just to confirm you do not have Deep Profiling turned on correct?
it should be turned off
oh, i have it on
turn it off and run it again
i couldn't find the call anywhere
We already have a workaround, I am just asking how it could be explained that we need the workaround for sind people but not others
k - i'm going to name the key "pangloss" because you deserve the credit 😉
is it not being called on the main thread? turning off deep profiling will reduce the noise significantly
because httpclient isn't supported in unity
lol
it's being called on the main thread, yes (it's on my TODO to offload this but.. for now it's on the main thread)
do you mean in some essential sense? because httpclient isn't fully implemented in unity
and unitywebrequest, on most platforms, is using libcurl or the platform http client
you shouldn't ever use httpclient
it's a major sticking point for people
Says who
listen i'm not a content creator and i don't aspire to be one
relying on content creators for programming knowledge is a guaranteed way to ship a game very very late
so the sooner you start using unitywebrequest the better your game will perform and the fewer bugs you'll experience, on all devices
Again, it is understandable that mono is not implementing everything, this is also not my question. The question is why it is working for some people, possibly hinting at a bigger problem of framework version mismatch between people
lol
i think at this stage you can now enable deep profiling and see what exactly is taking so long
I don't know what you're on about about content creators
Yeah, I mean.. I could but.. I'm a bit frazzled with launch timeline - I think I'm just going to offload the MP deserialization to another thread or coroutine it or something
it works just fine and literally it's one little burp during startup.. I feel like people are mostly ok with a little jankiness during load screens
because the big difference between self and time is looking not great
the music plays smoothly during the loading anyway, it's just a little bit of framerate stuttering
you asked me "says who" and what do you want me to link to? a youtube video? a blog post?
unity certainly says use unitywebrequest
anyway
this isn't going anywhere
Well you appealed to authority without backing up your claim
there isn't more of a story than that
I didn't ask for facts about UWR vs .net
yeah i think that's fine
lol
the stars
you can easily offload it... with unitask 🙂
I asked about how some people have different .net implementations
they don't
unity standalone player doesn't fully implement httpclient
so you cannot rely on it 100%
But they do. It works for me and doesn't for others
it's okay
you are welcome to bust your head against this bug
you can ship your game late
it's your game
this is #archived-code-advanced
Are you saying it stops working once you go from editor to a build
if you want to die on the hill of "muh visual studio" go fo rit
i am saying it isn't fully implemented
I'm not even using VS
Dr.P when we start our next game I'm going to have a big long chat with you about UniRX because .. I'm too far in to refactor it (remember when we talked about it like a year ago and I said "this looks cool but I'm going to stay the course" - I wish I hadn't!). Next project is going to be rx based for sure.
lol
The Faith of UniRx
I occasionally see you promoting it in answers and I always have a little giggle and sad head shake that I didn't listen earlier 😛
i am just teasing
We're doing animation bugs and stuff and ... gosh, what a headache. It would have been so nice to just drop animation events into a stream
i am trying to emphasize i don't know why you feel so strongly about using an API that is not supported in Unity versus one that is
it would take you an hour to rewrite everything to use the working API. depending on what the game is it might even be 5 minutes
Well the one that is supported by unity is not implemented in the same why as mono
I can't recall if I told you my non-rx solution.. I literally copy a data structure on the server and client, then copy it again on the client, one for the "true" data and another for the "animated" data, and then merge them all up at the end. It works, but man, so fiddly..
UnityWebRequest has a simple enough API
yeah
that's reinventing UniRx
cursed comment
yeah it took me a while to figure out how to "Delay out" animation events
like at an intellectual level
I mean, it's only now that I realize that this fundamentally IS rx
what is the game?
and so all the work I did... doing this... was just wasted effort because my implementation is not as good as UniRX (probably is)