#archived-code-advanced
1 messages ยท Page 139 of 1
This sounds like a question, that has hundreds of right answers
so what is one of them ?, i was thinking to get a mesh and build it from small cubes
if you're making a game like teardown, Unity is not the engine for it.
no, voxel destruction
something like plaint the town red
soo, how can i do that i need to do it for a school project
Tbh it's more of a watch-a-tutorial kind of thing, don't you think?
i watched a tutorial, and when i tryed to do it a small cube spawned instead of filling the mesh \
What?
I'm a little late, but I finally made the voxel destruction tutorial I promised. In the video I'll show you how to destroy some stuff in real-time with voxels in Unity! :D
This video took a long time to make mostly because I had some major technical issues (my entire project became corrupted). Despite the delay, I hope someone still finds this ...
in this video,
he makes a cube out of smaller cubes
but when i try it the script dosen't work
Theres an asset you can pay for to do it for you
But making voxels isnt an easy thing
check out magicavoxel. it is a voxel 3D modelling software
Then you 100% didn't follow it correctly.
That said, you don't want to use a rigidbody implementation anyway, so the video isn't one you want to follow.
I've been down this rabbit hole. Voxel games in unity is impossible, unless you're using ECS
Or at least, if you do, you're going to want to build it with DOTs.
and ECS is... complicated
dose downloading git hub script counts like not doing it corecctly
?
Yes
As clever as you think you're being, there's still in-editor setup that has to happen.
you're also asking these questions in the wrong channel
you're not learning how to code by ripping off scripts
you're learning how to rip off scripts
Ask in #๐ฑ๏ธโinput-system
Sure
Might be some discussion in the history there
I'll check
How to make a 2D sprite copy transform of a UIImage? Basically just copy the look of a UIIMage
This is not an advanced code question. But you can assign the sprite from you UI.Image to a SpriteRenderer component.
Is there any way to pause the play mode right after pressing the play button.
yep, pause first
damn
Why are you asking this in #archived-code-advanced? It's not even a code question.
couldn't find a suitable one
right
this isn't really an advanced code question, but you can only use the google play leaderboard for google play installed / associated apps
Im using Transform.Translate to move an object on its own local axies. The problem is that my script is using OnBecameVisible/OnBecameInvisible and the translation desyncs when the object gets out of the camera view.
Is there an alternative to the Translate method? My idea was to convert the Translate coordinates to world but I cant seem to make it work
what is your objective
you shouldn't really use OnBecameVisible for game rules, might be more effective to do #archived-code-general #๐ปโcode-beginner
I just spent 15 minutes trying to figure out why an audio clip was playing twice.. including stepping through code, writing debug statements when the audio clip played and ended, and so on... Only to realize just now it was playing twice because I have two clients running (it's a multiplayer game). Sigh.
@undone coral : I found the bug, btw (in the dictionary thing we were talking about yesterday). Turns out it was completely unrelated to the data structure - that was just a downwind effect of the bug. I had a divide by zero exception that was... not crashing the app (and instead corrupting a lot of stuff going on).
I have to spend some time to wrap my head around exception handling at the application level in Unity, I think..
You guys my last hope, I'm making an extension to a VTubing software and i need a loader that allows me to Import VRM Models at runtime so that people can load their VTuber models, is there any documentation that can show me how to do this? VSeeFace does it, but theres no documentation on how.
You're better off asking the vrchat discord
Does unity serialise generic C# classes?
In newer versions of Unity it can serialized specified generic classes without issue
if it doesn't work for you you may be on an earlier version that requires it be manually specified with an additional class to serialize properly
https://help.vertx.xyz/?page=programming/variables/serialization/serialization-4/serializing-generic-types for more information on that
(also oh no I have to update my code highlighter to fix it aggressively highlighting things with comments)
It was giving me errors when I used with [SerializeReference]. For some reason I thought that was necessary. It worked right of the bat when I removed it. Thanks
how to apply these settings in my fbx file from code? this code runs - i can see it with breakpoint, but settings in inspector remain unchanged
Did you try setting the whole array? As many things in unity, modelImporter.clipAnimations might be a copy of the original array.
Ok, maybe not. At least not according to docs.
No you're right! It works when copying and then setting the whole array. No way you solved it like that ;D
@true cosmos do the rigs match?
Really?
yeah
actually
yeah, thanks a lot. theres property underneath with some applying settings code probably
Is it possible to bind a function call to FixedUpdate() in script?
like for example something like this:
onFixedUpdate += doSomeCallback;
Avoid cross-posting.
Just call the method in FixedUpdate.
The more complex way would be to create an event and Invoke it in FixedUpdate.
seems I can also just add my own delegate ๐ค
Events "encapsulate" a delegate, so yes you could. A simple Action (that maps to methods without parameters and with no return value) would be the easiest one.
@fresh salmon thanks ๐
Is there a way to stop this kind of behaviour? One of my players can push the other player
What do you want to happen instead?
Ignore collision between the same layer, in this case it might be player in physics settings
I would my player 2 to be unpushable AND unpassable by the player 1
That would stop the pushing thing, but I would prefer my player being unpassable as well
Oh, so you want him to be super heavy so he wont get moved. Well, I would then fix him to his position as long as there is no input for example. Depends on your game tho
Then it's probably best to use kinematic rbs.๐ค
But with kinematic rbs I don't get stopped by Static rigidbodies
Yeah, you'll need to write a custom controller.
Alternatively, set velocity to 0 on collision if it's with the other player. That's kind of a junky solution though.
Is your player going to be altered by any other physics, if not, just fix him on position while not getting player input.
@midnight violet but this is gonna be weird when the two players are both moving and run into each other
The problem is, you are using physics system, so thats how it works. You can still try to add some weight to the rigidbody, so it wont get moved that easily.
@midnight violet but players (since they derive from the same Prefab) are both gonna have the same weight :/
But if the force is not strong enough, it wont move. You could also add no bouncieness physics mateiral to try out
In the end, I would write a custom script that gets the collision of the players and prevent them from going towards the other player with a circular radius or something like that. Just overwrite the velocity on the hitpoint normal for example to stop them from moving in that direction.
is there any way to get the touched line segment from a polygoncollider?
i want to place gameobjects along the perimeter of this collider
OnCollision your collision.point?
@midnight violet that gets me the world space location yeah, but im looking for something different
i want to place gameobjects along the perimeter of this collider, so my plan was to look at the collider.Points array
and for each pair of points that make up the collider, figure out the direction
and then place objects on that line by following the direction
once it hits a corner, id look at the next pair of points
and repeat
i know how to do that, but my problem is knowing where to start
you can still get the normal of the point too
do a raycast against that from wherever you want and use that point and its normals
i know but that still doesn't tell me whether i'm touching the line between point[0] and point[1] or point[5] and point[6]
if you understand what i mean
Why exactly do you need to know that?
i need to know where i need to start my gameobject placing algorithm
i cant just start it at point[0] and run till point[point.Count-1]
anywhere I can find a good example for this?
because the objects should start being placed in L/R rdirections
@midnight violet i wanna do something like this but without the raycasts:
I mean, you have the bounds of your object, right? Bounds.min.x is the first available point wher you could shoot a ray down to the collider
Oh, worms incoming ๐
Okay, got you, so where is that gif from ๐ as it is doing what you want
thats from my current code
but the raycasts are causing too many edge case bugs
so i want to do it in a more consistent way
the polygon literally contains all of the data you need to calculate the perimeter of the polygon
and i want to plac ethe objects around the perimeter
I think so
Just google unity top down 2d character controller and look up one that fits your needs.
actually that wouldnt work either
and you got the points in https://docs.unity3d.com/ScriptReference/PolygonCollider2D-points.html . so you can basically compare those points and their position to your spawned one and go from there.
let me draw something out for u
@midnight violet i would basically need to know that the collision happened on the line segment between points 3-4 here
if you get the two closest points, it would return points 2 and 3
Yeah, get your worldpos in vector2, get closest point of pointsArray, go from there
but you hit line 3-4 not 2-3
yeah, the closest point to your collision is still 3, right. and you want to go from left to right, so integer +1 is the next point, right
If you set it up like this, otherwise you would have to like check on the normal.right direction for the next point, might work too, not sure about performance.
would it always be integer+1 though
yeah, if you start from right to left generating the collider, it would be messed up, thats why I would check for the direction then too, or just reorder the points by their x and y values. many approached, depending on your final setup tho
here i wrote it up in more detail https://stackoverflow.com/questions/69451000/calculating-which-of-the-collider-line-segments-was-hit-in-unity-placing-gameo
like this? ```csharp
private void FixedUpdate()
{
Vector2 motion = direction * Time.deltaTime * currentSpeed;
hit = Physics2D.CapsuleCast(transform.position, capsuleCollider.size, capsuleCollider.direction, 0, new Vector2(0, direction.y), Mathf.Abs(motion.y));
if (hit.collider != null)
{
motion.y = 0;
}
hit = Physics2D.CapsuleCast(transform.position, capsuleCollider.size, capsuleCollider.direction, 0, new Vector2(direction.x, 0), Mathf.Abs(motion.x));
if (hit.collider != null)
{
motion.x = 0;
}
body.MovePosition(body.position + new Vector2(motion.x, motion.y));
}
If that works for you, then yes. 1 capsule cast might be enough imho.
I'm having this weird thing though where my capsuleCast is colliding with my capsuleCollider and I don't get how/why
I think it has to do with the pivot offset of my spriteRenderer (?)
If I offset my capsuleCollider2D with the same offset as my sprite then everything is fine
really weird
This collides with itself:
this doesnt:
The collision cast colliders
I think I'm getting this wrong, the second one doesnt collide because the capsule is too far away
Could use a collision layer mask to ignore the layer that the collider is on. Although then every character will need to be on a separate layer...
Could use CapsuleCastAll or CapsuleCastNonAlloc. Get all colliders and check if there are any beside itself.
ye, I'm trying that now :/
so it works
but if a player spawns inside of an object, he can never get out :/
Don't spawn it inside an object
๐คท well no way to check that though
@untold moth I disabled "Queries Start in Colliders" in ProjectSettings and that seems to solve it ๐ค
idk but i like your art
@bleak edge thanks, I'm currently in the process of porting it from Godot to Unity ๐
here's my steam page (https://store.steampowered.com/app/1724900/Midwintar/) :p
Midwintรคr catches you at Khazar's Pass.You shelter in a cave as the days and nights grow long and cold,as the snow seals you in and as the world darkens.Midwintรคr is a narrative-driven stealth action game inspired by medieval horror folklore that combines careful tactical planning with fast-paced arcade execution and innovative gossip mechanics....
Coming soon
Cool game
thanks โค๏ธ
Is there an easy way to check the ScriptingBackend in either compile-time or run-time?
(I know I can do it in the Editor, and I think I would be able to set a Scripting Define Symbol from there)
I've got an error message (I've had for a while, actually) that doesn't seem harmful but I want to explore it and make sure. It says that I'm referencing System.Windows.Forms.dll in the codebase (which is obviously .. false?). Any thoughts on how I might find out which plugin assembly is the culprit?
System.Windows.Forms.dll assembly is referenced by user code, but is not supported on StandaloneWindows64 platform. Various failures might follow.
(There's a very big stack trace but it appears unhelpful)
(I also did comb through the references in my project and my shared DLL to ensure there's no references or code looking for System.Windows.Forms)
These are my project references, ISG-Shared is my own DLL (and there's no references to winforms there)
Can you take a look at the contents of the various .csproj files? Especially the Assembly-Csharp* ones
Yah, standby
I did poke through all those assemblies, but I didn't look at the csproj files
No references to "forms" or.. anything that seems out of place
Let me check in the shared project too
Yeah, it looks clean. The packages.config and app.config are both clear as well
I mean, clear from any references to System.Windows.*
oof discord antispam ๐
(I hate when I type out a big message and it deletes it)
https://forum.unity.com/threads/system-windows-forms-dll-assembly-is-referenced-by-user-code-warning-cant-find-src.206036/ Seems like the latest posts in this 10 year old thread indicate it's Unity Collaborate
Wow. removed collaborate and the error goes away. ๐คฏ
github 4 lyfe throws up gang signs
I didn't know where to ask about jobs, but maybe advanced code is the correct channel. I'm just wondering of a good way to deal with "results".
I currently have a job that'll check which positions are within a certain radius, but I'm not sure how I would write back the results.
Looks like this
struct IsWithinCircleJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<Vector2> positions;
[ReadOnly]
public Vector2 center;
[ReadOnly]
public float radius;
public void Execute(int index)
{
Vector2 pos = positions[index];
//Check if the point is within the circle
if(((pos.x - center.x) * (pos.x - center.x)) + ((pos.y - center.y) * (pos.y - center.y)) < (radius * radius))
{
//Match found, now what?
}
}
}```
Any tips would be appreciated!
#archived-dots Is most likely the channel you are looking for. (It has been too long since I used jobs to answer my self otherwise I would)
I would raise an event that you subscribe to with whatever needs to know about it
struct ... {
public static Action OnExecuteFinished;
public void Execute(...)
{
if (...) OnExecuteFinished?.Invoke();
}
}
... elsewhere ...
IsWithinCircleJob.OnExecuteFinished += MyHandlerMethod;
public void MyHandlerMethod() { .. do your thing ..}
That should work fine with the Jobs system?
should? I'm not familiar with the jobs system that much but the above code is just c#
Yeah the jobs will be running on different threads
basically you're just signalling "to the world" with ?.Invoke() and anything that subscribes to that event will then execute its own code
and I'm not sure the behaviour events have between threads
totally fine to have separate threads
the handler will get executed (synchronously) when your side-thread finishes processing
Events handlers are executed on the thread that invoked the event, IIRC
That would be something to check using the debugger to make sure it's right, especially with that Jobs system
I see
Yeah, you could, but I'm 99% sure that it'll just get executed immediately.. it's not unity specific functionality (raising and consuming an Action) - it's basically the same as:
public void Execute(...)
{
if (...)
{
yourOtherClass.MyHandlerMethod();
}
}
except now your IsWithinCircleJob doesn't need to know all the external listeners - there's no dependency created
I really โค๏ธ C# Actions and subscribing to them - I use them liberally in my code
Maybe the Jobs system has a special event delegate that allows it to invoke on another thread, like the DispatcherTimer does in WPF - the events are invoked on the UI thread to avoid exceptions.
it's like a poor man's separation of concerns, if you don't want to use full fledged DI
The thing that the Jobs system usually does is writing changes to a NativeArray which can be accessed on the main thread
If I invoke an event while executing my jobs, the event will be executed on the same thread right?, aka the worker thread
Which might cause complications
Yeah, then you'll need to put a lock in your data structure
(lock the structure when your job is finished and you update it, and lock it on your main thread when you're reading from it)
Yep that's correct. Usually when doing multithreading, and like the Jobs system does, is writing "messages" into a thread-safe object (like a ConcurrentQueue) so you can push and try to retrieve elements to make the threads communicate
(and to be clear, you don't lock the actual data structure - lock a boolean that's specifically for access to the structure)
easiest way would be to allocate another NativeArray of the max size of the results, and then another job dependent on the first which inserts results into a NativeList (to keep all work off main thread).
But overall, this is multithreading a brute-force search. You'd get an optimum runtime by using some spatial subdivision data structure instead
Yeah I just saw from job system examples that a similar thing was done (test intersections between bounds), but it never displayed how it dealt with the results
https://github.com/stella3d/job-system-cookbook/blob/master/Assets/Scripts/CheckBoundsParallelFor.cs
But thanks for the advice, I'll look into that then
just imagine BoundsContainsPointJob has another (writable) NativeArray<bool> which is true if the ith bounds in boundsArray contains the point. I'm pretty sure NativeList isn't parallel writable, or you could use it directly
And you mean that the NativeArray<bool> would be the same size as the position array then?
And assign true / false to the index it found / didn't found a match at?
But that would mean I'd still have to loop through an array of the same amount of elements as in the first place after the check, except booleans?
or am I interpreting that wrong
yes you would
I assume the performance gained in that isn't gonna be that great right
well obviously depending on the amount of elements
i think you just set the property on the job with your result
that's why I suggested a second job, so you can do that step on a worker thread too. How many points are you dealing with and how often do they move?
it sounds like you're overcomplicating things
The points are statically located, while the bounds are moving with the player. I'm not sure how many points as of yet, as I haven't gotten around to create all of them yet
then you read the field when it's done
I'm pretty sure NativeList isn't parallel writable, or you could use it directly
well arrays are parallel writable in every programming language
NativeList isn't an array
they just don't have rules about conflict resolution
I'm aware of that, but I was trying to look for a way I can only get the results which passes the check, instead of needing the same amount of space for the results
well I mean it technically is, but it isn't parallel writable like NativeArray is
if you just want an easy to use list that works with jobs, use https://www.jacksondunstan.com/articles/4865
JacksonDunstan.com covers game programming
this is "parallel writable"
I see
hope that helps ๐
I'll try it out
queue since like a reasonable alternative too yeah
i'm not sure if nativequeue is unbounded or if it's a linkedlist underneath
but i don't think it matters
you can probably just use an array and an integer
and if it "gets too big" just resize it
i don' tknow, don't overthink this ๐
//Check if the point is within the circle
if(((pos.x - center.x) * (pos.x - center.x)) + ((pos.y - center.y) * (pos.y - center.y)) < (radius * radius))
{
//Match found, now what?
}
is pretty dubious
Hahaha why is that
it's fine
i just think it's so simple you might be overengineering it with the jobs
like how many points are there
a million?
Yeah that's why I was about to ask what you think is the reasonable amount of points for it to even be worth it
every frame?
Yeah
probably not
you can barely visualize a million distinct points on a screen
I know I can do it in other ways to decrease the amount of searching too, honestly I just wanted to try out the job system
got it
yeah then this is fine
i would just allocate a huge buffer
and not bother with queues or whatever
because a million bools is... <1MB
so who cares
Fair enough
all points are static in the world, and the player moves around with a circle collider, so once they're within the collider I want to display them. I wanted to test the Job system on all the points in the world. But I'm aware I can easily divide the map "grid style" and just look for the points within a specific cell
But all performance gains I can get are good, because it is a server build
the more I can milk Microsoft Azure's resources the better ๐
yeah i think there are existing packages that give you spatial queries for static geometry in 2d and 3d
Oh I see
Yeah the reason I thought the Job system could be useful is that the server will be "searching" for each player in the world
and I plan to have around 64 players, so there can be quite a bit of searching
A dynamic, loose octree implementation for Unity written in C# - GitHub - Nition/UnityOctree: A dynamic, loose octree implementation for Unity written in C#
Supergrid sounds like it is what I'm looking for
I actually also considered placing a circle collider and have each point be represented in the world as well, to let the Physics determine if I've overlapped a position
Not sure which method would be the best tbh, as I'm already using collision for other parts of the game
maybe adding more components to the same simulation is also a decent alternative
won't know unless I try I guess ๐
as I can't imagine that 2d collisions should be that expensive
@uncut thorn read #๐โcode-of-conduct for where to post jobs
Oops! Sorry about that
Anybody encountered a similar error?
Your possible culprit.
I'm assuming it was an unwanted single quote ( ' ) escape character bug in some older versions of Unity.
Mine was 2019.4 tho.
The quote issue is one Unity's code as far as I understand.
So I guess I'll have to upgrade
RESOLUTION NOTE (FIX VERSION 2020.1):
The workaround is to add \ before every '
Was the resolution Unity applied.
Your version isn't a fixed version or verified issue version:
Fixed in 2020.1.X
Fixed in 2018.4.X, 2019.2.X, 2019.3.X
Is this fix only applicable for 2020.1?
So it's present in your version but never fixed because not discovered; who really knows unless someone reports it.
You aren't likely going to recompile Unity so best just use a different version.
Yeah. Thanks for finding the issue so quickly.
Fortunately I do have 2020.1 installed
Hey there, i have a Code design Question and the Scenario is the following:
My game currencies that you can, for example, buy in a shop. When you buy it, it should fly up from the position of the Button, where you bougbt it to the pannel at Top. So far so good. I want to have i strict seperation between animation state and model state, so when buying the currency, it should instantly be on the storage of the player (ok easy) but for the player it should look like the currency is flying to the pannel and when the pannel is reached, the number should count up. How do i implement this in the cleanest way? Any architect here who can help me with this? ๐
Make the animation/counter subscribe to a model event. I.e. observer pattern.
Yes sure, this is easy
but i also want coins flying up and after flying up it should count up
so observer pattern doenst realy work
i think
cause i also need the information at witch psosition the currency was bought
so they can fly up from there
Hey guys i am interested to learn about vehicle physicw in unity where can i learn about that in depth i want to understand how a advance car controller works lights / car damage and drifting i did make sone controllers before but they were incomplete i could add lights to them or even breaks at a point so i need help:(
Anyone got an idea how the lifetime of an unbound (not bound to a file) scriptable object works in the Editor?
I have a scriptable object that I create using ScriptabelObject.CreateInstance() it works well, tho whenever the scripts are reloaded in the project I of course lose reference to the scriptable object, but it's OnEnable, method still fires, suggesting that it's still there some where in memory, can I still retrieve that ScriptableObject in memory, if so, how's I get rid of it?
It should actually be gone on assembly reload.๐ค
Is that the UE4 position gizmo I see?
You can pass a Space enum value to transform.Rotate, which rotates either on the world or local space.
you can pack all that info into eventArguments, i.e. a contextObject you pass along with the event. If you need to merge multiple events, have the subscriber generate the animation procedurally... which you probably have to do anyway because of variable source locations.
That's what I thought, I even tried to DestroyImmediate the asset in the destructor, but it still doesn't get destroyed and I end up with tens of them in memory after every assembly reload
How do you know that?
I have Debug.Log code and it gets called linearly one more time after every refresh
Can you share the script?
Debug.Log code in OnEnable on the scriptable object
Oh, my PC kind of crapped on me ATM, which is why I came to ask here, but I can send the source later
Matrix? Is this a Unity question, because you can do that using transform.Rotate or by using the quaternions directly.
Then it's not a Unity question
I'm afraid you're in the wrong channel, or server
We should have something like a #math channel for discussing maths applied to game dev contexts
Anyone who has experience with loading and playing OBJ sequences with EF EVE:tm: Unity package ?
how can i find a weapon in a list of weapons where GUID is "5" ?
loop through, check the GUID?
It's the less expensive way of doing that in a List.
what's a more expensive way?
LINQ
If you don't need to serialize it there is always Dictionaries.
Best solution for fast access
i want to check them in the inspector
LINQ looks like this, right?
if you need it, you gotta use it, if you dont, do not use it ๐
There are some serialized dictionary implementations. I think it depends how often you will be getting the weapon details to determine if it is worth it.
not frequently
so will just use the foreach function
dont think will be a problem
How do you save all IDs?
string ๐
In a json?
Eh
but honestly i will run that function 10 per game so not gonna impact
Yeah x3
I need a way to store like 200 skins for my game, I'm still working on it
I wouldnt do it that way but if it work then that's awesome
i think it works without a problem
@regal olive do you have any idea about this?
Not sure, just take it step by step and do debugs
So, I went on to further develop the ScriptableObject system and it works well now thanks to the
AssemblyReloadEvents.beforeAssemblyReload
event, I DestroyImmediate the asset whenever it's called.
This is the final code if you are interested in seeing this monstrosity for yourself:
https://pastebin.com/dK5ytb9r
Basically it's a singleton ScriptableObject that get's saved and recalled from the ProjectSettings folder instead of the Assets folder and can be modified from the Project Settings window in the editor (Project Settings -> My Settings), in editor the asset is created at runtime, and when building an executable the asset is created as a file temporarily before build and then deleted after build.
Unity should really provide an API for doing something like this, I jumped through so many hoops that I don't even know if I want to use this code now.
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.
what was the objective?
have you considered
public class Settings {
public static readonly string applicationUrl = "http://mydomain.com";
public const int numberOfDaysInWeek = 7;
}
@pale pier
because that behaves the same as what you made, although you have to use a text editor to set the values. which makes more sense to me anyway.
i think you should just google how to change the basis of transforms
z is up to y is up is pretty common
there is going to already be source code on github to do this
The ScriptableObject system is much more powerful, it allows you - among many things - to:
-Edit values right from inside the Unity Editor.
-Assign any Unity serializable type as a property (Color, Prefab, Texture, ... etc).
-Edit those settings right from the Projects Window
...
It's just more useful
yes but why would your settings file have a texture
do you see what i am saying
that's only useful to a scene in a running game
you might as well just have an object in your scene with a reference to the asset
you never need a color before you have a running unity scene
you can make an asset that contains that data, and just reference it normally
reference it normally meaning drag and drop it into a slot in the scene. perhaps there is only one slot it goes into, and that component with that slot has an public static SceneSettings instance {get; private set;} in it
and it's a singleton
but you don't need to interact with runtimeinitializationonload
unity already has an asset type, with all the most sensible constraints, that "exists" "before" everything else, it's a C# code file
anyway just think about it
a dozen different packages and assets have settings assets that work fine, there is an API for this
i just don't remember off the top of my head what it is
Consider something like TextMeshPro, it's an asset that gets used by many other people, and comes as a Unity package so you can't reliably modify it's source, yet it still needs to expose settings to all the developers using it, those settings could be a registry of Sprite atlas' for emojis, could be font assets, could be anything, it would be very cumbersome to do all those modifications in a script file somewhere.
This project settingss entry is basically for those sorts of situations
textmeshpro's project-wide settings are toxic and i'm sure if you ask them they'd want to get rid of them
they of course create assets like the font asset
same with hdrp, the community reviles its project wide settings
it's super toxic
I haven't really had trouble with them, what issues do you have with them?
the volumes make sense, they belong inside scenes
why would you ever have to change them?
"i don't"
well that's why it doesn't make sense to have them as settings
do you see what i am saying?
and you're about to be lost in
well what project wide settings am i talking about?
you're not even sure
You think they are toxic because you rarely have to change them?
there's a panel that is the textmeshpro project settings
yes, exactly. because they should just decide for me
a setting i never change is pretty pointless
same with hdrp, lots of settings nobody ever wants to change
people just want Looks like Unreal
Unreal, you open it up, it's got defaults and no meaningful way to change them
and that's what people want
I don't want that
this is all over the forums
you haven't made enough HDRP content yet
to appreciate how pointless the HDRP scriptable pipeline options are
well it's just an example
i think just consider carefully how toxic of a piece of code you wanna drop into people's projects, if you're authoring a package meant to be used by other people
a createassetmenu settings that makes a plain scriptable objet, that you then have to drag and drop into a slot of a game object component, it's not bad
people are used to that
maybe a runtimeinitializeonload aftersceneload that instantiates that game object and Resources.Loads the asset is the maximum toxic waste you should dump in
but stuff that interacts this much with the editor assets api
it's going to have bugs
I still don't really see how it's toxic, a setting I rarely change means that the setting has a sensible default value
it's upt o you, i have no idea what you're concretely making
Well, I already recognize that, which is why I don't really want to use this method, but I still don't find any issue with global settings
I just wish Unity would provide this sort of API for developers, instead of everyone scrounging up something of their own
The Projects Settings windows already exists, and means to add to it exist too, just not the means to really fit into the usual Unity object way
But nonetheless, thank you for the insight, I will continue to check this toxic global settings concern
yeah i just want you to thrive dude not make horrible code you know is horrible ๐
finally I was able to read the SplatMap and derive the pixel based on the position from the real world.
but now I've another issue... 'cause the color are blended together so I need to filter in some way, the "Blue" that I need.
{
float r = color.r; // 0.0 to 1.0
float g = color.g;
float b = color.b;
int val = 0;
if (color.a > .15f)
val = 0;
else if (r <= .1f && g <= .1f && b <= .1f)
val = 0;
else if (r > g && r > b)
val = 1;
else if (g > r && g > b)
val = 2;
else if (b > r && b > g)
val = 3;
// Debug.Log("Color:" + color + ": " );
return val;
}```
I wrote this stupid method but I guess I need something more complex
for example I need to avoid Cyan ... which have a lot of blue, but also use a bunch of green
I've googled a lot but no lucky, 'cause he pops out a bunch of shareders which it's not my case.... ๐ please any advice would be very very welcome ๐
setting a bunch of else if is a terrible way to do things.
what do you want to do exactly?
I would like to get a range of blue... for example
this is my splat, I need to stay on Blue...
ok, but that is just checking the blue component... what do you want to do with with the "blending"?
my method isn't working 'cause that blue-greenish color is blended but the method will pass as blue anyway
so you want blue and excluding all green?
yes...
๐ค maybe I could expose a value that will be substracted to other color?
as you can see here... it will read for blue also cyan
this area is the black big dot on the splat
@compact ingot yes... something like that ๐
how do you feel about a selective color filter like in photoshop?
anything that will read more "pure" blue would be fine.
it will run in runtime and it's a procedural map
so I have to stick with math... and I'm a ๐
well, i'd say in special cases its quite trivial... i just wonder what an ideal generic function would do for you
you could for example compare with a HSV representation of the color
so I could convert the RBG in HSV and then make a second check ๐ค
you could do a comparison with a reference color
yes! I will play a bit with photoshop to see what I can get ๐
so I can figure out what is going on xD
Thank you ๐ป
with a similarity comparison you can encode more layers into one splat-map but you can only mix neighbouring layers together
you could add value/saturation to encode more layers with fewer steps
that's exactly what I need, a sort of "contrast" filter... increasing or decreasing the saturation
that should return more / less pure blue and cyan should become more greenish
i'd just be worried that its overcomplicating things
it will be fun ๐
consider that I even can't access to the splat via TerrainData
so all is coded in a "blind" way
'cause MapMagic ๐คฆโโ๏ธ
what about height blending?
nope.. the area to avoid, often is about 100% flat
height/displacement of the texture/material
but the various spots are at different height
didn't know that
I just can access to the splatMap 'cause MM to works with MicroSplat have to assign a component and put the splat on it.
if you have microsplat anway you can do height blending easily
then some green under your blue will add nice flavour instead of making it appear toally wrong
so I have coded a method to convert the texture and calculate the real world position into a pixel on the texture
indeed I've made it.. if you see the texture it have a nice contrast but for the 2 types of grass I would like to have a more blended ... mix
Thanks anyway for the tips, it's always useful to chat ๐
keep it simple ๐
for some reason "people" use either 1-bit splats or 8-bit splats without any fancy tricks and stuff inbetween... at least i haven't seen any
That's the first rule! ๐ ๐ป
the second is to avoid hardcoded value as if it is black plague
but also avoid excessive configurability
I'll keep it in mind ๐
Is it possible to read unity data using a windows service? I'm talking about in game data not log files or whatever
you mean the compiled asset files or the runtime state in memory? Neither is really meant to be read "from the outside" unless you design it to be exposed.
if you want to access in-memory data on while the game is running, I would point you towards c# interoparability
you can use unity's navmesh / navmeshagent for easy pathfinding
it's mostly just adding components, baking the values for runtime and then setting a position for where the agent should go
pathfinding on normal-sized graphs is not hard to code
For top down, is A* pathfinding the best option?
hi there
is there a reason why my Play() function in a script wouldnt be playing from the editor?
can you elaborate?
unity's pathfinding is built upon a*
For a top down grid system, will I need to implement A* myself, or can I piggyback off unity somehow?
turn-based*
it's rather simple
I have a script on a freshly instantiated object/character which spawns a prefab as a subobject, but the void Play() function suddenly wont run after I fiddled with the debug settings
I was trying to get the debugger running
you should probably check the script where you are calling Play() from then
why would I call play? Isnt that part of Unity that gets called automatically?
oh nvm, sorry, I meant void Start()
if you want motions that snap to the grid, you should probably do a custom solution, if you want smooth transitions, you can probably use unity's version
yeah i was thinking that
nvm I figured it out, had a nullpointer access at Awake
you can use aron granberg's a* asset
navmesh doesn't navigate along a grid
Oh dang, there's an asset for it? You might have just saved me a lot of work ๐
think of your color space as vectors
for example, let vector3 be the HSV of the color, and let Blue be (blue hue, 0, 0). then the blueness of something will be Vector3.Dot(blue, queryColor)
-blue ought to be orange
there are many ways to express colors in a way that makes sense for vector math. typically, the most robust one is the Lab colorspace
but that's probably not appropriate for your splat map
use the dot product instead of subtraction
it's more expressive
We have an active ragdoll system that follows these steps:
- Call animator.Update
- apply physics on a second rig to move body parts to the animated position
- after physics sets the rotation and position of the animated joints to the same position as the physics rig
We encountered a problem where 4 of the joints didn't reset their position correctly when we called animator.Update, and to fix it we turned off resample curves on the imported animation.
Now with resample curves turned off, those same limbs do a 360 at a random point during the animation.
Does anyone know how we can fix either of those problems?
On the original problem: we found if we made literally any change to the animator in the inspector it fixed it
Hey, im currently trying to learn Marching Cubes. Im finding it a bit difficult to find videos on what im looking for. Id like to have a asteroid that i can laser into. All the resources ive come across are mainly for terrains. Any insight much appreciated!
can you be more specific what you want to understand?
i havent implemented marching cubes myself, but i have a feeling you would be able to use the code from a "terrain" marching cubes tutorial, change the input function so that it generates a sphere shape instead of a terrain, and bam you have an asteroid
https://www.youtube.com/watch?v=vTMEdHcKgM4 this isnt a tutorial, but it shows what i think youre trying to do
I got a bit tired of my simple heightmap-based planets and decided to experiment with generating them using the Marching Cubes algorithm instead, so that I could add a 'terraforming' ability for shaping the world with caves and tunnels and so on. I hope you enjoy!
Project files are available here:
https://github.com/SebLague/Terraforming
If yo...
the #archived-code-advanced answer is first, start with stuff you read not stuff you watch ๐
there are lots of good assets for this
which at the very least should introduce you to some concrete concepts
marching cubes are actually a technique to fill an abstract description of geometry that doesn't resemble vertices, like a heightmap
or in the case of a general shape, something called a signed distance field
Using marching cubes to form a sphere with some noise to make it look more like a asteroid.
you can see it in action in the clayxels / mudbun unity assets
Thx! Ill check this one out.
which is what i'd recommend you'd start with
that's SDF geometry, which is clayxels and mudbun
they are both pretty expensive, so im prolly gonna avoid that route
expensive in the sense that the asset is expensive?
mudbun is like, one of the most underrated assets
@bcjordan 4D GAMES FTW! ๐ been playing around with some modifiers in mudbun/clayxels, there's one that is sort of melting which is cool?? https://t.co/6nQcNH39JL
it does exactly what you are expressing in words
Im not sure if yall thought i was looking for a asset to buy, but would really prefer a article that could point me in the right direction. (was looking to do it myself)
it's like, what if the article cost $75
it's better than any article you could just learn from it
it's just really, really complicated
clayxels is $58
anyway
just think about it
marching cubes or really any meshing strategy is easy, the hard part is 3D SDFs
Thx for all the help homie!
this is nice - https://github.com/Javier-Garzo/Marching-cubes-on-Unity-3D
Hi all. Need some opinion on how i implement modular dynamic data. Say for items that summons pet(the item gotta keep track of the pet's level, hp etc), or equipments/weapons with enchantments/upgrades, equips with dye customizations, etc
I have the static side of the item data (all clients have this info). I also have the dynamic side which is a polymorphic class depending on the type of item it is, called them DynamicPetItem, DynamicWeaponItem and so on
The de/serialization is done in 2 steps:
- Stored in base64 string in the database, converted to byte array. This byte array is what is being sync'd around clients
- Byte array to the DynamicPetItem stuff objects, each client builds this themselves based on the byte array they have. Server too. This DynamicAbcItem is what's being modified, and on "sync time" (like pet get killed, levelled up, weapon get upgrades), this object gets written to byte array and then sync'd to all
So de/serialization from/to string to/from byte array is only done when saving/loading to the database. It's not what's being done most of the time at runtime
So all this works nice, but i learned recently that an empty byte array is already around 12 bytes
Now i wonder if i should keep the string version and sync that around, instead of the byte array one
This means the de/serialization step is now 2 steps for runtime all the time (from only 1), database save/load is 0 step instead of 1, and.. yeah
So just wondering if this is a good decision. I just started this yesterday and wanna polish the foundation before moving forward
Cheers
Hi, i've got a sort of Race condition problem in my project
i have a state machine behaviour that instanciate fire balls on the StateUpdate
it works fine, but when the Enemy that fire the balls and have that SMB on it gets quick collision with an arrow the SMB stop working completely
once i trigger a collision with another weapon, the balls goes back firing
once it collide back with an arrow quickly, the SMB stop working once more
if you're using sockets to send data ultimately it does get converted to byte array before being sent if your using some library.
Real question is how are you checking the size of the byte array and how do you get the byte array?
Logically speaking you should never check size of byte array but check string if that is empty or not . If not convert to byte and send
The byte array is just an intermediary deserialize process from base64 string, on which is the form it gets stored in DB
From byte array it can be deserialized to the corresponding object type (based on item type) and they'll handle the array size
I'm using Mirror, but this part really doesn't matter. Just mentioning bcoz i'm using their Writer/Reader which is pretty standard and supports byte array too
How do i get the byte array? Hmm, from the base64 string from DB when deserialize, and from the runtime version object "DynamicAbcItem" when wanna serialize and send packet
Any directions for loading an mtl+png file on ** runtime ** and applying it to an already loaded and instantiated unity mesh in the scene ?
Have you looked at this? https://docs.unity3d.com/Manual/UnityWebRequest-RetrievingTexture.html
You can swap the materials on the mesh in the scene
this can work with local files too ?
like files on my assets, resources/streaming etc
also what about mtl files ?
Oh I suppose I use the url llike path with "file://C:" etc
file:// should work. Dunno about .mtl , but I guess it might just work as is :P
If you have the texture in resources, you can just use Resources.Load
Hello, i'm kinda lost so i'm asking here because it's been i've searched with no results.
My main problem is that my project works perfectly fine in editor, but when i build it, it mess with the GUI and even the code since my game is different
Here is the example :
this is in editor
this is what is shown in build, as you can see the GUI is off
i have absolutely no error in the console, how can i debug that ? i tried a lot of options but without success
(i'm in Unity 2020.3.5f1 on a Windows 10 64 bit system)
what mode is your canvas scaler set to?
it's scale with screen size apparently
does this weird scaling happen if you resize your game window in editor?
nope i just tried after you asked the question
where do you have your anchor points set for the objects at the centre
well the thing is they don't have anchor points i guess
at least i didn't touched that
i'm not sure what the issue is
scale with screen size should keep all objects correct relative to each other
this could probably go in #๐ฒโui-ux or #๐ปโunity-talk
this is driving me crazy no one have an idea what's going on
i'll do that, thanks a lot for taking the time searching with me ๐
how can i enum classes
i want to choose between classes on enum
i need a variable to choose weapontype so can give details, for example axe does not need bullet name
dont think enums work that way
They don't.
The best you can do is associate an enum value with a certain class via a custom inspector, but that's gonna be super bad in terms of extendibility.
You should be using Scriptable Objects for this ideally
thats what i'd do anyway
hi there, how u're doing?
I've been working in a project and I faced myself with animation problems. I just started to study about Playables and I'm having some problems understanding how to set everything up and call clean and nice. The problem I'm facing right now I think I know what is. I play the animation clip correctly, but when I call the animation again doesn't do anything. I think this could be beacuse I call the animation in the same spot it was when ended before, in the end '-' so, basically I'm calling the animation in the end of it, I think. Does anyone know how to reset the animation before calling it again? And how to setup the option "Has exit time"?
I'm having issues serializing a large array with the BinaryFormatter, when the array is super small it generates a 1kb file but as soon as i increase the array side the files become ridiculously large
MapGeneration.cs
MapSave.cs
[System.Serializable]
public class MapSave
{
public string name { get; set; }
public Block[,][,] chunks {get; set; }
public MapSave(string name, Block[,][,]chunks) {
this.name = name;
this.chunks = chunks;
}
}
Block.cs
[System.Serializable]
public class Block {
public int type { get; set; }
public Block(int type) {
this.type = type;
}
}
}
anyone got a clue what's going on?
for reference these values make a huge 4mb file
private int blockSize = 100;
private int mapWidth = 5;
private int mapHeight = 5;
while these make a 1kb file
private int blockSize = 10;
private int mapWidth = 10;
private int mapHeight = 10;
Well you're not showing the code where the array itself is initialized but...
Block[,][,] is a ridiculously crazy data type. It's a 2D array, each element of which contains an entire 2D array inside it
you're looking at some exponential growth of the size of that thing, depending on how you're initializing it
Well obviously. You are creating 250,000 cells.
5x5 creates 25 cells, and each one of those is a 100x100 2D array which is 10,000 cells.
Which as I said is then 10,000 x 25 = 250,000.
line 31 and 41 in the hastebin
So for this:
void GenEmptyBlockHoldersForChunks() {
chunks = new Block[mapWidth, mapHeight][,];
for (int x = 0; x < chunks.GetLength(0); x++) {
for (int y = 0; y < chunks.GetLength(1); y++) {
chunks[x, y] = new Block[blockSize, blockSize];
}
}
}```
You've got:
5x5 = 25 chunks.
Each chunk contains 100 * 100 blocks which is 10,000
so 250,000 blocks
easily could be 4MBs
well it's exactly the same amount as blocks, it's just sectioned off into chunks
So Block[,][,] is to store chunks?
yes
vs if you did:
10x10 = 100
10 * 10 = 100
100 * 100 = 10,000 total
Why not have each chunk manage it's own block map, then you just serialise an array of chunks?
Same size sure, but much less convoluted
it is not the same amount, it's 10,000 vs 250,000
what, not true at all
100 * 5 * 100 * 5
Is my math wrong somehow?
exactly 250.000
Yes it is, I just did the math too.
Look at GenEmptyBlockHoldersForChunks
not the other method
that's your issue
The math is (mapWidth * mapHeight) * (blockSize * blockSize)
yes - notice how blockSize is squared
huh? but those are two different scenarios, why would they give the same number?
they don't
who said they do
YOu said: 100, 5, 5 gives you 4MB while 10, 10, 10 gives you 1kb
we're comparing those two
i thought you meant that for the same numbers more blocks are generating in chunks than blocks
I'm comparing 100, 5, 5 to 10, 10, 10
okay anyway, not the point, any suggestions how to store and reduce the size, serializing and deserializing takes forever
Well, 250,00 cells is always going to be 250,000 cells. There is not much to be done about that. To make it easier to read I would create a separate class that represents a chunk.
You could try emitting the binary yourself it might make it more faster and have a bit smaller file size. But it is also more work for sure.
At the very least you could move the saving to a separate thread it looks like so it wouldn't cause freezing.
hmm, how does terraria do it then, my mid size world file is 6mb and afaik they store a lot of information inside each block
and a midsize world has millions of blocks
11.520.000 blocks
and the file gets read instantly
Might save the delta of the blocks that have changed from the original world seed?
I am not sure personally how to save things like this. As I said my best guess would be saving only the things that have changed from the original. However you can try looking up how to save voxel terrain, or how Minecraft saves terrain. And don't just look up Unity specific stuff since there could be some good info out there.
Sorry I can't give more help.
yeah i'll look around, thanks for the help
I doubt terraria stores more than perhaps 4 bytes per block
probably even less than that
trying to pass a type through to this static method. What am I doing incorrectly? I don't really understand the error.
the T is a placeholder where you're supposed to put the relevant class when you use the function
for example, Resources.Load<T>(string path) doesn't mean you put the T there when you type it out, you are supposed to put the type of the object you're loading from resources.
Yeah but I want to pass that T in from another function
ah i see
as I'm trying to make it generic as possible
does it give you any quick fix options when you click on the error
i'm not sure how to ensure that T is of type BasePlugin
i just changed to 1 byte per block and a medium map is 168mb..., they have to be doing something different
since it says it needs to be BasePlugin can't you just use BasePlugin instead of T
why do you want to use T if it can't be anything else
That's 176 million isn't it?
blocks?
Yes
You said 1 byte per block, at 168 megabytes
ahh
Ignoring Google, because they are idiots, it's 168 * 1024 * 1024
Ah I wasn't aware of this syntax. Thanks for your help.
oh nice i didn't know that either thanks for teaching me
weird sql lookin syntax
okay, so the size is correct then, they must be avoiding storing all block information somehow
Minecraft breaks up the world into 16x16 block "chunks".
Only chunks that you have visited are actually stored on your hard drive.
To a first approximation, each block takes two bytes to store or so.
A 16x16x256 chunk takes 16 * 16 * 256 * 2 bytes, or about 128kilobytes.
128kilobytes is about the size of a small and/or grainy photo.
In practice, chunks are significantly smaller since some blocks only need 1 byte, etc.
minecraft stores only visited chunks
but surely it's possible to visit all chunks in a terraria map
ergo making it 200mb
What's the max size of a Terraria map?
you could store your map with rle ๐
with what?
run length encoding, it's a simple form of compression that combines long runs of the same value into one
with something like a terraria-style map, that could drastically reduce the size
but it was kind of a joke
yeah but you still gotta generate the initial file to compress it
which takes ridiculous amounts of time
oh i didn't think that was the issue
i thought you were trying to reduce the size of it in storage
nvm then
well loading it is also an issue, you don't wanna wait 2 min for your map to decompress ๐
If your generator is deterministic you would have to only store changes.
it's not like zip compression
to be fair, terraria and minecraft both take insane amounts of time to generate, so it's not like yours would be any worse
hmm yeah maybe, generate only the spawned chunks and then apply changes to those
it would generate from seed
but still, terraria has corruption which literally changes the entire map over time
yeah, true, my issue is just when loading an already generated map
corruption also can be deterministic.
but it's influenced by player placed blocks ๐ค
You can store corruption mask separately
Also the entire thing is in chunks, so you would never need to have huge amount of data loaded all the time.
well, this really complicates, everything ๐ฅ
The reason you can't pass the generic type to the NewSkeletonMecanim is I assume because it constrains the type that is required where yours does not.
Yes I think so.
nobody said it wouldn't be complex ๐
i wouldn't worry about the memory unless it doesn't work
because if the first 100 blocks of your world aren't interesting, no one's going to bother exploring the next 10.9999 million
good edit lmao gotta get those technicalities
168MB is nothing
oh, you can't use binaryformatter
just don't use it
BTW it's possible that terraria also compresses their save files
there are many approaches to reading and writing large arrays
the simplest is to just read it ๐
you can also use MemoryMappedFile
i wouldn't overthink it
you can use the IO Streams to get compression for free
it's fine to use a container data format that has all the fields you need. it's true that axe does not need bullet name... so just don't fill it in
don't overthink it
To just read it, what do you mean?
loop through the array and do what you want with each value
Not sure how that helps me serialize and deserealize to disk ๐ค
idk i'm just saying that's what he meant, like don't do anything fancy to read it, just loop through it
serializing an deserializing is a separate matter i think
i'm saying read it using File.Read
i punched into google reading and writing a large array to disk C#
you're not going to serialize/deserialize it, you're just going to read it
does that make sense?
you're not going to delegate to something else the decision for how to interpret the bytes at a given index, you will
Hmm, so let's say i have a list of 10 bytes, do i just loop through the list and append bytes to the file one by one and then when i read the file i just loop through the bytes on the file and manually put them back in my list?
just store it on disk using memory mapped file
and author Block GetBlock(Position position) and SetBlock(Position position, Block block) methods
Yeah, i saw this too, I'm just a bit unclear how they get the data back into the array
you don't need it in an array
you can do
class BlockData : IList<Block> {
// todo: implement me
}
you don't even need to implement most of it, don't overthink it
just the this[int index] getter and setter if you'd like
Not sure what you mean
you're saying array, which means System.Array, like Block[, ]
okay, i get it, you want to access stuff with indices or whatever
so just write the methods to access stuff with indices
you don't need System.Array specifically to do that
just like i can do
class BullshitList : IList<string> {
public this[int index] {
get => throw new UnsupportedOperationException("You can't access a bullshit list");
set => whatever
}
}
do you see what i'm saying?
then i can do
var blah = new BullshitList();
blah[10];
look it behaves like an array
lol
No, I'm very confused ๐
okay well this is more of a #archived-code-general question
then
if you've never done an interface
or is it the part where you just write bytes to a file
I have in java lol, not sure how they work in c#
like the Block at location x y
okay
well that's #๐ปโcode-beginner i think you'll figure it out
they are exactly the same thing
IList<> is just java.lang.List<>
6ou don't HAVE to do any of this
So put my bytes into a list?
just author set and get
no
you're not using a list
your'e using a memorymappedfile
look at the class
alright that's all the help i can give because we're in #๐ปโcode-beginner territory
I think this may be more of a #archived-code-general question, but I don't want to disrupt the conversation in general code and honestly I'm not sure where this falls.
Let's say I have some abstract class A. In order for any class to inherit from A, that class should satisfy the "is a" relationship. So if B is A, every property, member and method on A should be make sense to use on B. Let's say I have a class ContainerA (abstract too is fine) that A contains an instance of. Now, ContainerA works with both B and A because of inheritance, but there is some extra functionality in ContainerB I'd like to implement only for class B. A better example to make this more clear is probably with generics. If A is actually A<T> and Container is Container<T>, then B inherits from A<int> and ContainerB inherits from ContainerB<int>. So for example, I may want to do something special with some T Value (defined in ContainerA) in class B, now that I know Value is of type int.
Well, there's two things I've thought of doing. I can hide MyProperty and access it through a property marked with the new keyword, which casts the base property to type ContainerB. Or I can override the setter for MyProperty and perform dynamic type-checking to ensure B or a class accessing MyProperty through B does not perform an invalid assignment, and then store the actual value in a field of type ContainerB. (I guess I could do dynamic type checking hiding and the new keyword too, but this just feels less intuitive for some reason).
I guess the thing that bothers me is that there's nothing stopping someone from calling the base setter and assigning an invalid type to ContainerA. Of course, using this method above means that MyProperty should probably not be public and A should only deal with ContainerA as the base type ContainerA... which it probably will do in the first place if A is abstract. But this doesn't prevent a line in B from doing
base.MyProperty = new ContainerC();
and causing an exception later down the line. I guess I'm just worried I may be doing the balance between inheritance and composition incorrectly.
You can use a generic pattern, where you have a subtype of A that has a generic type parameter that represents a concrete subclass of ContainerA
Then you provide another (generic) property of the type parameter's type - and return/set that in the generic subtype's imlementation of the MyProperty property (with casts)
then finall;y you have B be a concrete subclass of the generic subclass described above
with a signature like public class B : GenericA<ContainerB>
This is the pattern Unity uses for things like https://docs.unity3d.com/Packages/com.unity.addressables@0.6/api/UnityEngine.AddressableAssets.AssetReferenceT-1.html
I have to run to class rn, but I appreciate the answer and will be looking at this asap
Still in class and only got to play around with it during the break, but it looks like I might owe you a coffee. It looks kind of ugly since in my real example, both A and ContainerA are already generic of type T, but it looks like hiding the base member in GenericA with the design you described statically enforces the type like how I want it
At this point in time, who doesn't owe PB a coffee
Say I have a c# savedata class serialized into binary in a file. If I add a new field, does the old save still work?
It might actually fail but not sure
This is one reason why I prefer to write my own serialization
Depends how you serialize it I think.
I've heard that it causes problems with Binary formatter. But it's working so far after adding a few fields for me.
wrong room... Try #archived-code-general or #๐ปโcode-beginner
okay
Eventually a certain person here will tell you "don't use binary formatter, it is toxic". Binary Formatter generally only works when used in the exact same build/version of the app. And it its use is strongly discouraged for security reasons. It is probably best to serialise into something custom or pre-made that allows you to do such things explicitly (rather than accidentally), like JSON or MessagePack.
It's even warned against in the docs: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-5.0#remarks
also BinaryFormatter isn't exactly space efficient
Nor secure
how do i change value of a variable of a scriptable object. I tried using dot operator and vlaue doesnt seem to change??
Context?
{
public Sprite CurrentHat;
public Sprite[] Hats;
public void ChangeHat(Sprite hat)
{
CurrentHat = hat;
}
}
public Image HatImage;
public int Cost;
bool bought = false;
public GlobalClass Hatdata;
public void HatButton()
{
Hatdata.CurrentHat = HatImage.sprite;
Hatdata.ChangeHat(HatImage.sprite);
Debug.Log("Hat Equipped");
} ```
what am i doing wrong??
You should avoid modifying SOs at runtime
i am trying to use SO as a global variable that i can access anywhere
I can see that.
so why cant i change variable hat??
You likely can?
Anyone got a recommendation for a persistent data path where I can save a file for user settings that will be shared by all projects? preferably something that Unity already exposes like Application.persistentDataPath ?
On Windows, your roaming folder %userprofile%\AppData\Roaming would be a nice place to store these. It's local to the user, and roams with your profile if you're in a network of multiple users (Active Directory)
Seems like a good option, thanks
Gonna have to look up some paths for MacOS & Linux too
Let's say I got a collection Unity Meshes in my scene. Their mtl+png files exist in the disk but I haven't applied them yet. How can I apply them on runtime, having in mind I know which mtl+png combo maps to each Unity Mesh.
Addendum: I had a series of obj+mtl+png files. I compressed the objs with the draco encoder to make the size smaller. Now when I import these draco encoded files in Unity, the mtls+pngs are not mapped. And I'm stuck. I think I can map them manuall directly to the Unity Meshes but I'm stuck on how to do this.
If you have any pointers on the things I can try please let me know.
hello there ๐
I'm still working on that damned splat trying to reading the colors....
Now I've got why I can't find the colors as expected... it's cause of Alpha.
If i save the splat (via script) and encode it as TGA looks fine, but if I save it as PNG it's barely 100% transparent (which I suppose it is what my code reads.)
so... there's another solution instead of saving a new texture and read it? (which takes a bunch of times, 'cause I have 4x4 terrain tiles)
I mean something like take my texture and read it as RGB8
@pulsar isle the materials have the links to the textures, you can just change the material at runtime. Compressing an obj before importing into unity probably isn't going to do anything as unity will convert it to its own format
there's no material, indeed to be sure what is going on I have to save the texture on the HD, 'cause it's runtime generated
that's why it is so difficult ๐คฆโโ๏ธ
It's because I will download said objs at some point, so reducing their filesize would help.
oh.. sorry ๐
Do you mean the meshes will be unknown at runtime?
No, like I want to download the compressed(draco format) models at run time, instantiate them using the draco unity decoder and then apply the materials etc
but draco encoder doesnt support mapping the mtl files like the objloader plugins do
maybe I need to look into gltf/glb which apparently seems to support draco compression too
I'm sure I have approached the problem from a wrong perspective
why encoding to TGA a 1024 2Dtexture takes so long?
I mean, I have an I7 with 16gigs and a 3080 but it took over a minute
also this takes loooong time
splat = new Texture2D(tempSplat.width, tempSplat.height,TextureFormat.ARGB32, false);
splat.SetPixels(tempSplat.GetPixels());```
nice, thanks ๐
Anyway it wasn't slow, it was me that maybe I'm working on it too much ๐
I was updating the splat for each tree so the file get overwrited about 3000 times xD
You should avoid using GetPixels if you can because it allocates an unnecessary array
Ok, I'll keep it in mind.
it sounds like you're looking for a workaround for this plugin. i think look at how the objloader plugin works with reading materials, and add it to the draco unity decoder ๐

When would boxing and unboxing be appropriate in Unity development?
I'm trying to think of a situation where you would want to box values as reference types to store on the heap rather than the stack
Whenever required is where it's appropriate. If you need to store a struct to be used later, it probably needs to be boxed. If you need to serialize something, it will likely need to be boxed. There are many circumstances where it's also a part of convenience methods, and unless GC is impacting framerate, it can be totally okay to just do the easy thing.
Avoid boxing in hot paths, other than that it's generally okay to do so.
Thanks, this is exactly what I was hoping for, and then some
I was with you until the hot paths, I'll have to look into that concept
I found this to be helpful: Compiler hot paths are code execution paths in the compiler in which most of the execution time is spent, and which are potentially executed very often.
The reason for avoiding (heap) allocations in these code paths is that allocations may trigger a garbage collection, which may cause sudden, extreme performance deteriorations. These should obviously be avoided in very commonly executed code paths.
Linq and foreach are singled out because these will implicitly allocate memory โ unless your GetEnumerator returns a struct, which will not cause heap allocations.
Would Update() be a prime example of a hot path?
Yeah, definitely, a perfect example
Great thanks
Is foreach still allocating, or the update saying it doesnt anymore is just in my head? This is from the docs, right
https://www.jacksondunstan.com/articles/3805
Moving on..
JacksonDunstan.com covers game programming
shrug
for List and Array it does not
i'm sure you can find a linkeddictionary that does not
Does anyone know a better way to find the closest collision point that isn't this?
while (Physics2D.CircleCast(newPos, (dist)* scale, Vector2.up, 0, layer_mask) && dist > 0) //While circle collider hitting
{
playerBoarderHit = Physics2D.CircleCast(newPos, (dist)* scale, Vector2.up, 0, layer_mask); //Remember collision
dist -= 0.01f; //Constantly reduce checking distance until no more collisions
}
it's a circle that shrinks until it stops colliding
CircleCast takes a direction that cast the circle along that vector you can use that. read the docs on it
"A CircleCast is conceptually like dragging a circle through the Scene in a particular direction. Any object making contact with the circle can be detected and reported."
Yeah I read, I couldn't find anything that checks for the closest point
also I noticed circle cast starts from the right then drags clockwise
What can I use to find the closest point apart from CircleCast?
not closest object but closest collision point
collider.ClosestPoint ?
will that work if there are other objects in radius too that I am checking?
RaycastHit2d has a point field
that would be the world space coords of the collision point
where's the documentation for 2d closest point?
does it have a 2D version?
you can find that out yourself, can't you?
I remember that being a stop for me when I first tried this one
I mean I have tried this one before but couldnt find the 2D one
Thank you though
Does anyone know how to efficiently make Pink Noise, without using Low Pass filtering?
Or brown noise.
I'm guessing the most efficient way is to use a sine wave to modulate the range of a random function through a sample length (of time) sufficient to roll off over the full extent of an audible period (let's say 20KHz to 50Hz), but I've not found anything remotely efficient at creating this.
navmesh agent moving too slow regardless of speed
and it only happens when sometimes
forsome reason
Is there a good way to take data from a shader? Say I want to export a texture and use it to populate terrain data. Can I do that?
@sly schooner search for creating height maps from texture readings of colour and/or brightness.
getRawTexture (from memory) is the way to get at the data of a texture
how could I write unit tests for my project?
using Mirror;
using Mirror.Examples.Pong;
using Steamworks;
using UnityEngine;
public class CharacterSelect : NetworkBehaviour
{
#region Singleton
public static CharacterSelect instance;
void Awake()
{
if (instance != null) Destroy(gameObject);
else instance = this;
}
#endregion
[SerializeField] GameObject characterCardPrefab = default;
public List<Character> remainingCharacters = new List<Character>();
List<GameObject> characterCards = new List<GameObject>();
[SerializeField] Transform canvas;
Character selectedCharacter;
public override void OnStartClient()
{
foreach (var character in remainingCharacters)
{
CharacterCard card = Instantiate(characterCardPrefab).GetComponent<CharacterCard>();
card.SetCharacterCard(character);
characterCards.Add(card.gameObject);
card.transform.SetParent(canvas);
}
}
void DestroyAllCards()
{
Debug.Log("Ara");
for (int i = 0; i < characterCards.Count; i++)
{
Destroy(characterCards[i]);
}
Debug.Log("Ara");
}
public void SelectCharacter(Character character)
{
selectedCharacter = character;
CmdSelectCharacter();
}
[Command(requiresAuthority = false)]
public void CmdSelectCharacter(NetworkConnectionToClient conn = null)
{
MyNetworkManager.instance.CreatePlayer(selectedCharacter, conn);
Debug.Log("Ara");
/*characterCards.RemoveAt(remainingCharacters.IndexOf(character));
remainingCharacters.Remove(character);*/
DestroyAllCards();
}
}
when the client starts, I check from a list of all characters that have not yet been selected
and then send a server command
how could I unit test this to see if the player gets created or anything really
I just wanna learn how to write unit tests basically
and I also wanna learn how to write my code better architecture wise
Thank you! This is exactly what I need!
You may want to look into compute shaders
I have also gotten into unit testing in Unity not long ago and would like to get better at writing them
I try to use composition to test what I can without needing to instantiate a monobehavior. I don't have a gigantic amount of dependencies on startup, but I haven't written my game to be able to start itself just from adding a single component to the scene.
I don't use them heavily, but I usually put them on complicated logic that doesn't depend on MBs, usually static functions. The other thing I use them for is auditing assets. For example in the game I'm working on we have about 30 different character configs and I have a test that checks that they all have a portrait texture assigned to them.
I think the best way to start integrating tests is by automating stuff that is easy to break.
Or difficult to notice if it does.
Or simply difficult to test your logic, sometimes it's quicker to write a test than come up with some manual way.
I want the distance between two vectors, but relative to the forward of the first vector. So, how far ahead/behind is the other vector. Right now I'm just using the .z, but that's not going to work when rotated. So what's the best thing to do?
I'm not sure I understand the question completely, because you can literally just add/substract vectors:
Vector3 leader = ..
Vector3 follower = ..
Vector3 difference = leader - follower;
i am getting so mad that the code doesnt work
and it worked like 30 seconds ago
everything is going horrible
Yes but I want to know how far in front or behind a vector some other vector is.
if someone could go on a vc with me and help me fix this crap i would really apreciate it
its a problem with a goddamn transition
@regal olive : start with pasting code, vc's are pretty rare or just never happen here
c
ok
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Main : MonoBehaviour
{
public Animator transition;
public void Iniciar()
{
StartCoroutine(LoadLevel(SceneManager.GetActiveScene().buildIndex + 1));
}
public void Fechar()
{
Application.Quit();
}
IEnumerator LoadLevel(int levelIndex)
{
transition.SetTrigger("Start");
yield return new WaitForSeconds(2);
SceneManager.LoadScene("Level1");
}
}
that's what difference is above.. ?
the code
No, that just gives the vector towards the other vector, not the distance on the local Z
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Main : MonoBehaviour
{
public Animator transition;
public void Iniciar()
{
StartCoroutine(LoadLevel(SceneManager.GetActiveScene().buildIndex + 1));
}
public void Fechar()
{
Application.Quit();
}
IEnumerator LoadLevel(int levelIndex)
{
transition.SetTrigger("Start");
yield return new WaitForSeconds(2);
SceneManager.LoadScene("Level1");
}
}
Are you in 2d or 3d space? and what does it mean "how far" someone is behind someone? with vector math, the difference in vectors is the distance between, or rather the difference in locations
Unless you have some sort of track or something
when i click play its supposed to transition to level1
but it simply doesn't transition
and it says this
in your scene, your "Main" object has a component called transition which is null
3d space. How "far" on the z axis of a vector. Think of it as a straight race track. I want to know how far ahead one if of the other.
(also, "Main" is a terrible name for an object.. main what? mainscene? mainlevel?)
mainmenu
sorry but i dont understand
transition is the "Animator"
I'm still not understanding. So if one player is at (100,50,0) and the other is at (50,50,0) then they are (50,0,0) apart
Friendly reminder that this is #archived-code-advanced and that your issue is not fitted for this channel
None of this is advanced, why are we posting here?
Or do you want a single float that is the distance apart? if so, you want difference.magnitude
you're describing an integration test, if you want it to interact with a real server and such
They're not players. I used it as an example to help you understand me. If vector A is at 0, 0, 10 and vector B is at 0, 0, 20, then the difference is 0, 0, 10 and I can just use Vector3.Distance to get the distance. But what if vector A is rotated 45 degrees? Then the Z value no longer matters because the forward is a different. The distance also no longer matters because it only tells me how far apart they are, not how far ahead it is.
Yeah
if you wanted to unit test what you're showing, you'd have to "mock" CreatePlayer
I mean, you're not in vector math anymore, you're in something more complicated, I think? lemme mspaint something up for you
it's really challenging to integration test unity games. it's also usually a waste of time
you're never going to change anything inside mirror, so you don't need to validate that it works when it says it does
and once you use mirror correctly, you've used it correctly forever
project the second vector onto the first, then compare their magnitudes
like, the distance between those vectors is the purple line, but if your game cares about "forward" then figuring out the "distance" between them (along the track) is more complicated
Project them onto a vector or plane and then get the distance.
Or rotate the vectors onto the forward plane and then compare Z
There are no bends, if that helps. It's always a straight line.
otherwise, it is as simple as starting another copy of your game in the test, using Process.Start
what were you expecting?
I don't fully understand. But I'll see if I can figure out what it means :p
if they are transforms, the amount B is in the "forward" of transform A is transformA.InverseTransformPoint(transformB.position).z
is that helpful @tulip sonnet ?
do you see what this is doing?
it's finding transform B's position in the local space of transform A
Not until I open the docs. But based on your description it's exactly what I need. Now I just need to learn what it does.
Idk, like, advice?
lol
how much detail do you want
Like
it's hard to tell what's going on from your code, what you want to test
So could I also do transformB.TransformPoint(transformA.position).z?
the snippet isn't that relevant to an integration test
I wish I could test if the player gets created correctly and can pick up items correctly
no
transformpoint is local to world space
you may still be at #archived-code-general level
because you're being imprecise about what hte code says
maybe put it into separate variables with names
so you can wrap your head around what it's doing
I just asked because it has "inverse" in the name. I didn't actually check it out yet
Anyway thanks.
once you QA that the item gets picked up correctly, why would it stop being picked up correctly?
an integration test looks more like, "The player can start and end a match to completion"
and you make the players behave randomly inside the game
if it's something specific about items, yeah, that's a unit test, but then you'll find that you're making tests for nothing
like let's hypothesize what kind of mistake you'd make with item pickups. not attach the right script?
Because I suck at networking code and don't wanna waste a minute every time I need to test
this is some good shit and i'm glad you said it
Dhgegeev
lol
Wow
one thing to consider is
trust Mirror
once you get it working once you're not going to break it
When I came here I kind of wanted to learn how to write my code in order to be able to write unit tests later
okay, is there an example of something other than creating and picking up items?
like something that you wrote new?