#archived-code-advanced

1 messages ยท Page 139 of 1

swift prism
#

hello i have a question, how can i make voxel destruction ?

shadow seal
swift prism
shadow seal
#

So you are making a Minecraft-esque world?

#

Voxels don't have to be cubes you see

zenith ginkgo
#

if you're making a game like teardown, Unity is not the engine for it.

swift prism
#

something like plaint the town red

#

soo, how can i do that i need to do it for a school project

shadow seal
#

Tbh it's more of a watch-a-tutorial kind of thing, don't you think?

swift prism
shadow seal
#

What?

swift prism
#

in this video,

#

he makes a cube out of smaller cubes

#

but when i try it the script dosen't work

zenith ginkgo
#

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

humble leaf
#

That said, you don't want to use a rigidbody implementation anyway, so the video isn't one you want to follow.

zenith ginkgo
#

I've been down this rabbit hole. Voxel games in unity is impossible, unless you're using ECS

humble leaf
#

Or at least, if you do, you're going to want to build it with DOTs.

zenith ginkgo
#

and ECS is... complicated

swift prism
#

?

humble leaf
#

Yes

#

As clever as you think you're being, there's still in-editor setup that has to happen.

zenith ginkgo
#

you're also asking these questions in the wrong channel

shadow seal
#

That is plagiarism

#

You just said this was for school

tropic lake
#

you're not learning how to code by ripping off scripts

#

you're learning how to rip off scripts

kindred tusk
regal olive
#

Sure

kindred tusk
#

Might be some discussion in the history there

regal olive
#

I'll check

ancient sparrow
#

How to make a 2D sprite copy transform of a UIImage? Basically just copy the look of a UIIMage

kindred tusk
fallen halo
#

Is there any way to pause the play mode right after pressing the play button.

fallen halo
#

damn

kindred tusk
fallen halo
#

couldn't find a suitable one

kindred tusk
fallen halo
undone coral
#

this isn't really an advanced code question, but you can only use the google play leaderboard for google play installed / associated apps

arctic valve
#

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

undone coral
misty glade
#

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

fast girder
#

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.

harsh grotto
runic tendon
#

Does unity serialise generic C# classes?

austere jewel
#

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

runic tendon
true cosmos
#

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

untold moth
#

Ok, maybe not. At least not according to docs.

true cosmos
untold moth
#

@true cosmos do the rigs match?

true cosmos
#

yeah

untold moth
#

actually

true cosmos
#

it works

untold moth
#

Could be because of the foreach.

#

But yeah, glad you got it solved.

true cosmos
#

yeah, thanks a lot. theres property underneath with some applying settings code probably

gusty monolith
#

Is it possible to bind a function call to FixedUpdate() in script?

#

like for example something like this:

#
onFixedUpdate += doSomeCallback;
fresh salmon
#

Avoid cross-posting.

#

Just call the method in FixedUpdate.

#

The more complex way would be to create an event and Invoke it in FixedUpdate.

gusty monolith
#

seems I can also just add my own delegate ๐Ÿค”

fresh salmon
#

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.

gusty monolith
#

@fresh salmon thanks ๐Ÿ˜„

#

Is there a way to stop this kind of behaviour? One of my players can push the other player

untold moth
midnight violet
gusty monolith
gusty monolith
midnight violet
untold moth
gusty monolith
untold moth
#

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.

midnight violet
#

Is your player going to be altered by any other physics, if not, just fix him on position while not getting player input.

gusty monolith
#

@midnight violet but this is gonna be weird when the two players are both moving and run into each other

midnight violet
gusty monolith
#

@midnight violet but players (since they derive from the same Prefab) are both gonna have the same weight :/

midnight violet
#

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.

bleak edge
#

is there any way to get the touched line segment from a polygoncollider?

#

i want to place gameobjects along the perimeter of this collider

midnight violet
bleak edge
#

@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

midnight violet
#

do a raycast against that from wherever you want and use that point and its normals

bleak edge
#

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

midnight violet
bleak edge
#

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]

gusty monolith
bleak edge
#

because the objects should start being placed in L/R rdirections

#

@midnight violet i wanna do something like this but without the raycasts:

midnight violet
midnight violet
#

Okay, got you, so where is that gif from ๐Ÿ˜„ as it is doing what you want

bleak edge
#

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

midnight violet
#

okay, so you need to get the closest point, right?

#

and then the next closest

bleak edge
#

I think so

untold moth
bleak edge
#

actually that wouldnt work either

midnight violet
bleak edge
#

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

midnight violet
#

Yeah, get your worldpos in vector2, get closest point of pointsArray, go from there

bleak edge
#

but you hit line 3-4 not 2-3

midnight violet
#

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.

bleak edge
#

would it always be integer+1 though

midnight violet
#

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

bleak edge
#

its a unity collider

#

they seem to be quite random

#

where they start

bleak edge
# midnight violet yeah, if you start from right to left generating the collider, it would be messe...
gusty monolith
# untold moth Just google `unity top down 2d character controller` and look up one that fits y...

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

}

untold moth
gusty monolith
#

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:

gusty monolith
#

I think I'm getting this wrong, the second one doesnt collide because the capsule is too far away

untold moth
#

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

gusty monolith
#

yeah, that's no good :/

#

can I add expections?

untold moth
#

Could use CapsuleCastAll or CapsuleCastNonAlloc. Get all colliders and check if there are any beside itself.

gusty monolith
#

ye, I'm trying that now :/

#

so it works

#

but if a player spawns inside of an object, he can never get out :/

untold moth
#

Don't spawn it inside an object

gusty monolith
#

๐Ÿคท well no way to check that though

#

@untold moth I disabled "Queries Start in Colliders" in ProjectSettings and that seems to solve it ๐Ÿค”

bleak edge
gusty monolith
#

@bleak edge thanks, I'm currently in the process of porting it from Godot to Unity ๐Ÿ˜„

#

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

Release Date

Coming soon

โ–ถ Play video
gusty monolith
timber saddle
#

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)

misty glade
#

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)

fresh salmon
#

Can you take a look at the contents of the various .csproj files? Especially the Assembly-Csharp* ones

misty glade
#

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)

#

Wow. removed collaborate and the error goes away. ๐Ÿคฏ

#

github 4 lyfe throws up gang signs

sturdy olive
#

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!
urban warren
misty glade
#

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 ..}
sturdy olive
misty glade
#

should? I'm not familiar with the jobs system that much but the above code is just c#

sturdy olive
#

Yeah the jobs will be running on different threads

misty glade
#

basically you're just signalling "to the world" with ?.Invoke() and anything that subscribes to that event will then execute its own code

sturdy olive
#

and I'm not sure the behaviour events have between threads

misty glade
#

totally fine to have separate threads

#

the handler will get executed (synchronously) when your side-thread finishes processing

fresh salmon
#

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

sturdy olive
#

I see

misty glade
#

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

fresh salmon
#

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.

misty glade
#

it's like a poor man's separation of concerns, if you don't want to use full fledged DI

sturdy olive
#

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

misty glade
#

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)

fresh salmon
#

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

misty glade
#

(and to be clear, you don't lock the actual data structure - lock a boolean that's specifically for access to the structure)

long ivy
sturdy olive
#

But thanks for the advice, I'll look into that then

long ivy
#

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

sturdy olive
#

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

long ivy
#

yes you would

sturdy olive
#

I assume the performance gained in that isn't gonna be that great right

#

well obviously depending on the amount of elements

undone coral
long ivy
#

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?

undone coral
#

it sounds like you're overcomplicating things

sturdy olive
undone coral
#

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

long ivy
#

NativeList isn't an array

undone coral
#

they just don't have rules about conflict resolution

sturdy olive
long ivy
#

well I mean it technically is, but it isn't parallel writable like NativeArray is

undone coral
#

this is "parallel writable"

sturdy olive
#

I see

undone coral
#

hope that helps ๐Ÿ™‚

sturdy olive
#

I'll try it out

undone coral
#

i think a native queue will also be fine

#

it's all the same

sturdy olive
#

queue since like a reasonable alternative too yeah

undone coral
#

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

sturdy olive
#

Hahaha why is that

undone coral
#

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?

sturdy olive
#

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

undone coral
#

every frame?

sturdy olive
#

Yeah

undone coral
#

that's dubious

#

do you really need to check a million points?

sturdy olive
#

probably not

undone coral
#

you can barely visualize a million distinct points on a screen

sturdy olive
#

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

undone coral
#

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

sturdy olive
#

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 ๐Ÿ˜‰

undone coral
sturdy olive
#

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

undone coral
#
GitHub

A dynamic, loose octree implementation for Unity written in C# - GitHub - Nition/UnityOctree: A dynamic, loose octree implementation for Unity written in C#

GitHub

A C# 2D Spatial Indexing library that utilizes a fixed grid to optimize queries in the euclidian plane - GitHub - bartofzo/SuperGrid2D: A C# 2D Spatial Indexing library that utilizes a fixed grid t...

sturdy olive
#

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

austere jewel
runic tendon
#

Anybody encountered a similar error?

orchid marsh
#

Your possible culprit.

#

I'm assuming it was an unwanted single quote ( ' ) escape character bug in some older versions of Unity.

runic tendon
#

Mine was 2019.4 tho.

runic tendon
#

So I guess I'll have to upgrade

orchid marsh
#

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

runic tendon
orchid marsh
#

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.

runic tendon
#

Fortunately I do have 2020.1 installed

regal olive
#

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? ๐Ÿ™‚

compact ingot
regal olive
#

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

quasi nest
#

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:(

pale pier
#

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?

untold moth
pale pier
#

Is that the UE4 position gizmo I see?

fresh salmon
#

You can pass a Space enum value to transform.Rotate, which rotates either on the world or local space.

compact ingot
# regal olive so they can fly up from there

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.

pale pier
pale pier
pale pier
#

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

fresh salmon
#

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

pulsar isle
#

Anyone who has experience with loading and playing OBJ sequences with EF EVE:tm: Unity package ?

pseudo gulch
#

Render based selection

#

^need help with render based selection for UI elements

whole viper
#

how can i find a weapon in a list of weapons where GUID is "5" ?

sturdy edge
whole viper
#

wouldnt it be too expensive?

#

list will contain 300 items

#

at least

fresh salmon
#

It's the less expensive way of doing that in a List.

whole viper
#

got it

#

thanks guys! โค๏ธ

sturdy edge
fresh salmon
#

LINQ

urban warren
fresh salmon
#

Best solution for fast access

whole viper
#

i want to check them in the inspector

sturdy edge
whole viper
#

any bad side of serialising?

#

just gonna use this

midnight violet
urban warren
whole viper
#

so will just use the foreach function

#

dont think will be a problem

regal olive
whole viper
#

string ๐Ÿ™‚

regal olive
#

In a json?

whole viper
#

in a class

#

like this

#

its a scriptable object

regal olive
#

Eh

whole viper
#

but honestly i will run that function 10 per game so not gonna impact

regal olive
#

Yeah x3

whole viper
#

also, this keeps referencing, i need to clone

#

do you know how?

regal olive
#

I need a way to store like 200 skins for my game, I'm still working on it

whole viper
regal olive
#

I wouldnt do it that way but if it work then that's awesome

whole viper
whole viper
regal olive
pale pier
# untold moth Can you share the script?

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.

undone coral
#

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

pale pier
undone coral
#

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

pale pier
#

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

undone coral
#

they of course create assets like the font asset

#

same with hdrp, the community reviles its project wide settings

#

it's super toxic

pale pier
undone coral
#

the volumes make sense, they belong inside scenes

undone coral
#

"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

pale pier
#

You think they are toxic because you rarely have to change them?

undone coral
#

there's a panel that is the textmeshpro project settings

undone coral
#

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

pale pier
#

I don't want that

undone coral
#

this is all over the forums

#

you haven't made enough HDRP content yet

#

to appreciate how pointless the HDRP scriptable pipeline options are

pale pier
#

I haven't made any HDRP content

#

I still use built-in

undone coral
#

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

pale pier
#

I still don't really see how it's toxic, a setting I rarely change means that the setting has a sensible default value

undone coral
#

it's upt o you, i have no idea what you're concretely making

pale pier
#

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

silent dagger
#

๐Ÿ‘‹ Hello world ๐Ÿ™‚

#

lol this one was fun ๐Ÿ˜‚

undone coral
silent dagger
#

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.

compact ingot
silent dagger
#

I would like to get a range of blue... for example

#

this is my splat, I need to stay on Blue...

compact ingot
#

ok, but that is just checking the blue component... what do you want to do with with the "blending"?

silent dagger
#

my method isn't working 'cause that blue-greenish color is blended but the method will pass as blue anyway

compact ingot
#

so you want blue and excluding all green?

silent dagger
#

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

compact ingot
#

how do you feel about a selective color filter like in photoshop?

silent dagger
#

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 ๐Ÿ‘

compact ingot
#

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

silent dagger
#

so I could convert the RBG in HSV and then make a second check ๐Ÿค”

compact ingot
#

you could do a comparison with a reference color

silent dagger
#

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 ๐Ÿป

compact ingot
#

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

silent dagger
#

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

compact ingot
#

i'd just be worried that its overcomplicating things

silent dagger
#

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 ๐Ÿคฆโ€โ™‚๏ธ

compact ingot
#

what about height blending?

silent dagger
#

nope.. the area to avoid, often is about 100% flat

compact ingot
#

height/displacement of the texture/material

silent dagger
#

but the various spots are at different height

silent dagger
#

I just can access to the splatMap 'cause MM to works with MicroSplat have to assign a component and put the splat on it.

compact ingot
#

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

silent dagger
#

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

compact ingot
#

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

silent dagger
#

the second is to avoid hardcoded value as if it is black plague

compact ingot
silent dagger
#

I'll keep it in mind ๐Ÿ˜„

regal olive
#

Is it possible to read unity data using a windows service? I'm talking about in game data not log files or whatever

compact ingot
drifting galleon
#

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

compact ingot
#

pathfinding on normal-sized graphs is not hard to code

stoic compass
#

For top down, is A* pathfinding the best option?

raw path
#

hi there
is there a reason why my Play() function in a script wouldnt be playing from the editor?

drifting galleon
stoic compass
#

For a top down grid system, will I need to implement A* myself, or can I piggyback off unity somehow?

#

turn-based*

raw path
# drifting galleon can you elaborate?

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

drifting galleon
raw path
#

why would I call play? Isnt that part of Unity that gets called automatically?

#

oh nvm, sorry, I meant void Start()

drifting galleon
drifting galleon
raw path
undone coral
#

navmesh doesn't navigate along a grid

stoic compass
#

Oh dang, there's an asset for it? You might have just saved me a lot of work ๐Ÿ˜ƒ

undone coral
#

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

leaden arch
#

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

green iris
#

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!

compact ingot
sleek marsh
#

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

โ–ถ Play video
undone coral
#

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

green iris
undone coral
#

you can see it in action in the clayxels / mudbun unity assets

undone coral
#

which is what i'd recommend you'd start with

green iris
undone coral
#

expensive in the sense that the asset is expensive?

#

mudbun is like, one of the most underrated assets

#

it does exactly what you are expressing in words

green iris
undone coral
#

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

green iris
#

Thx for all the help homie!

undone coral
smoky glade
#

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:

  1. Stored in base64 string in the database, converted to byte array. This byte array is what is being sync'd around clients
  2. 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

sturdy tartan
#

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

tough tulip
smoky glade
#

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

pulsar isle
#

Any directions for loading an mtl+png file on ** runtime ** and applying it to an already loaded and instantiated unity mesh in the scene ?

modest lintel
#

You can swap the materials on the mesh in the scene

pulsar isle
#

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

modest lintel
#

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

native finch
#

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)

tropic lake
native finch
tropic lake
native finch
#

nope i just tried after you asked the question

tropic lake
native finch
#

well the thing is they don't have anchor points i guess

#

at least i didn't touched that

tropic lake
#

i'm not sure what the issue is

native finch
#

this is the canvas the manage it

tropic lake
#

scale with screen size should keep all objects correct relative to each other

native finch
#

this is driving me crazy no one have an idea what's going on

native finch
whole viper
#

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

untold moth
#

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.

zenith ginkgo
#

thats what i'd do anyway

regal olive
#

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

frail dock
#

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;
sly grove
# frail dock anyone got a clue what's going on?

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

urban warren
#

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.

frail dock
sly grove
# frail dock 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

frail dock
shadow seal
#

So Block[,][,] is to store chunks?

frail dock
sly grove
#

vs if you did:
10x10 = 100
10 * 10 = 100
100 * 100 = 10,000 total

shadow seal
#

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

sly grove
frail dock
#

100 * 5 * 100 * 5

sly grove
frail dock
#

exactly 250.000

urban warren
sly grove
#

not the other method

#

that's your issue

urban warren
#

The math is (mapWidth * mapHeight) * (blockSize * blockSize)

sly grove
#

yes - notice how blockSize is squared

sly grove
#

so 250K vs 10K again

frail dock
#

huh? but those are two different scenarios, why would they give the same number?

sly grove
#

who said they do

#

YOu said: 100, 5, 5 gives you 4MB while 10, 10, 10 gives you 1kb

#

we're comparing those two

frail dock
#

i thought you meant that for the same numbers more blocks are generating in chunks than blocks

sly grove
#

I'm comparing 100, 5, 5 to 10, 10, 10

frail dock
#

okay anyway, not the point, any suggestions how to store and reduce the size, serializing and deserializing takes forever

urban warren
#

At the very least you could move the saving to a separate thread it looks like so it wouldn't cause freezing.

frail dock
#

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

urban warren
#

Might save the delta of the blocks that have changed from the original world seed?

urban warren
frail dock
#

yeah i'll look around, thanks for the help

sly grove
#

probably even less than that

pulsar owl
#

trying to pass a type through to this static method. What am I doing incorrectly? I don't really understand the error.

elfin tundra
#

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.

pulsar owl
elfin tundra
#

ah i see

pulsar owl
#

as I'm trying to make it generic as possible

elfin tundra
#

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

frail dock
elfin tundra
#

why do you want to use T if it can't be anything else

frail dock
shadow seal
#

Yes

frail dock
#

no, it's 11 million

#

6400 ร— 1800

shadow seal
#

You said 1 byte per block, at 168 megabytes

frail dock
#

ahh

shadow seal
#

Ignoring Google, because they are idiots, it's 168 * 1024 * 1024

pulsar owl
elfin tundra
#

weird sql lookin syntax

frail dock
#
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

shadow seal
#

What's the max size of a Terraria map?

frail dock
#

8400 ร— 2400

#

~ 20 mil blocks

#

that would make my map 300mb ๐Ÿ˜ฅ

elfin tundra
#

you could store your map with rle ๐Ÿ˜‚

frail dock
#

with what?

elfin tundra
#

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

frail dock
#

yeah but you still gotta generate the initial file to compress it

#

which takes ridiculous amounts of time

elfin tundra
#

oh i didn't think that was the issue

#

i thought you were trying to reduce the size of it in storage

#

nvm then

frail dock
#

well loading it is also an issue, you don't wanna wait 2 min for your map to decompress ๐Ÿ˜„

elfin tundra
#

yeah true lmao

#

but rle is pretty simple so it wouldn't take too long

frozen imp
#

If your generator is deterministic you would have to only store changes.

elfin tundra
#

it's not like zip compression

elfin tundra
frail dock
#

it would generate from seed

#

but still, terraria has corruption which literally changes the entire map over time

frail dock
frozen imp
#

corruption also can be deterministic.

frail dock
#

but it's influenced by player placed blocks ๐Ÿค”

frozen imp
#

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.

frail dock
#

well, this really complicates, everything ๐Ÿ˜ฅ

urban warren
sly grove
undone coral
#

because if the first 100 blocks of your world aren't interesting, no one's going to bother exploring the next 10.9999 million

elfin tundra
#

good edit lmao gotta get those technicalities

undone coral
#

168MB is nothing

undone coral
#

just don't use it

sly grove
undone coral
#

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

undone coral
#

don't overthink it

frail dock
elfin tundra
frail dock
#

Not sure how that helps me serialize and deserealize to disk ๐Ÿค”

elfin tundra
#

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

undone coral
#

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

frail dock
undone coral
#

just store it on disk using memory mapped file

#

and author Block GetBlock(Position position) and SetBlock(Position position, Block block) methods

frail dock
undone coral
#

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

frail dock
#

Not sure what you mean

undone coral
#

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

frail dock
undone coral
#

then

#

if you've never done an interface

#

or is it the part where you just write bytes to a file

frail dock
#

I have in java lol, not sure how they work in c#

undone coral
#

like the Block at location x y

#

okay

#

they are exactly the same thing

#

IList<> is just java.lang.List<>

#

6ou don't HAVE to do any of this

frail dock
#

So put my bytes into a list?

undone coral
#

just author set and get

#

no

#

you're not using a list

#

your'e using a memorymappedfile

#

look at the class

undone thorn
#

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.

sly grove
#

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>

undone thorn
#

I have to run to class rn, but I appreciate the answer and will be looking at this asap

undone thorn
# sly grove with a signature like `public class B : GenericA<ContainerB>`

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

misty glade
#

At this point in time, who doesn't owe PB a coffee

runic tendon
#

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?

olive totem
#

It might actually fail but not sure

#

This is one reason why I prefer to write my own serialization

kindred tusk
runic tendon
kindred tusk
waxen karma
#

okay

compact ingot
# runic tendon I've heard that it causes problems with Binary formatter. But it's working so fa...

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.

compact ingot
#

also BinaryFormatter isn't exactly space efficient

flint sage
#

Nor secure

violet bramble
#

how do i change value of a variable of a scriptable object. I tried using dot operator and vlaue doesnt seem to change??

flint sage
#

Context?

violet bramble
#
{
    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??

kindred tusk
violet bramble
#

i am trying to use SO as a global variable that i can access anywhere

kindred tusk
#

I can see that.

violet bramble
#

so why cant i change variable hat??

kindred tusk
#

You likely can?

flint sage
#

Yeah that works just fine

#

You probably don't have the same instance

pale pier
#

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 ?

fresh salmon
#

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)

pale pier
#

Seems like a good option, thanks

#

Gonna have to look up some paths for MacOS & Linux too

pulsar isle
#

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.

silent dagger
#

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

umbral trail
#

@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

silent dagger
#

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 ๐Ÿคฆโ€โ™‚๏ธ

pulsar isle
silent dagger
#

oh.. sorry ๐Ÿ˜…

umbral trail
pulsar isle
#

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

silent dagger
#

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());```
silent dagger
#

nice, thanks ๐Ÿ™‚

silent dagger
#

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

kindred tusk
silent dagger
#

Ok, I'll keep it in mind.

undone coral
languid tartan
verbal peak
#

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

austere jewel
#

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.

verbal peak
#

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?

austere jewel
#

Yeah, definitely, a perfect example

verbal peak
#

Great thanks

smoky glade
undone coral
#

i'm sure you can find a linkeddictionary that does not

lean loom
#

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

livid kraken
#

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

lean loom
#

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

compact ingot
#

collider.ClosestPoint ?

lean loom
#

will that work if there are other objects in radius too that I am checking?

livid kraken
#

RaycastHit2d has a point field

#

that would be the world space coords of the collision point

lean loom
#

where's the documentation for 2d closest point?

lean loom
#

does it have a 2D version?

compact ingot
#

you can find that out yourself, can't you?

lean loom
#

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

compact ingot
ember geyser
#

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.

regal olive
#

navmesh agent moving too slow regardless of speed

#

and it only happens when sometimes

#

forsome reason

sly schooner
#

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?

ember geyser
#

@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

hallow cove
#

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

sly schooner
compact ingot
undone thorn
#

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.

kindred tusk
#

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.

tulip sonnet
#

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?

regal olive
#

man

#

can someone help me

misty glade
#

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;
regal olive
#

i am getting so mad that the code doesnt work

#

and it worked like 30 seconds ago

#

everything is going horrible

tulip sonnet
regal olive
#

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

misty glade
#

@regal olive : start with pasting code, vc's are pretty rare or just never happen here

tulip sonnet
#

c

regal olive
#

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

}

misty glade
regal olive
#

the code

misty glade
#

Oh gosh, use backticks please

tulip sonnet
regal olive
#

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

Unless you have some sort of track or something

regal olive
#

when i click play its supposed to transition to level1

#

but it simply doesn't transition

#

and it says this

misty glade
#

in your scene, your "Main" object has a component called transition which is null

tulip sonnet
misty glade
#

(also, "Main" is a terrible name for an object.. main what? mainscene? mainlevel?)

regal olive
#

mainmenu

regal olive
#

transition is the "Animator"

misty glade
fresh salmon
austere jewel
#

None of this is advanced, why are we posting here?

misty glade
#

Or do you want a single float that is the distance apart? if so, you want difference.magnitude

undone coral
tulip sonnet
# misty glade I'm still not understanding. So if one player is at (100,50,0) and the other is ...

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.

undone coral
#

if you wanted to unit test what you're showing, you'd have to "mock" CreatePlayer

misty glade
undone coral
# hallow cove Yeah

it's really challenging to integration test unity games. it's also usually a waste of time

misty glade
undone coral
#

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

sly grove
misty glade
#

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

austere jewel
tulip sonnet
undone coral
# hallow cove Yeah

otherwise, it is as simple as starting another copy of your game in the test, using Process.Start

hallow cove
#

I see

#

Thank you!

undone coral
tulip sonnet
undone coral
#

is that helpful @tulip sonnet ?

tulip sonnet
#

Actually, yes.

#

Thanks!

undone coral
#

do you see what this is doing?

#

it's finding transform B's position in the local space of transform A

tulip sonnet
hallow cove
undone coral
hallow cove
#

I got advice so

#

I said thank you

#

Lol

undone coral
#

how much detail do you want

hallow cove
#

Like

undone coral
#

it's hard to tell what's going on from your code, what you want to test

tulip sonnet
#

So could I also do transformB.TransformPoint(transformA.position).z?

undone coral
#

the snippet isn't that relevant to an integration test

hallow cove
#

I wish I could test if the player gets created correctly and can pick up items correctly

undone coral
#

transformpoint is local to world space

undone coral
#

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

tulip sonnet
#

I just asked because it has "inverse" in the name. I didn't actually check it out yet

#

Anyway thanks.

undone coral
#

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?

hallow cove
#

Because I suck at networking code and don't wanna waste a minute every time I need to test

undone coral
hallow cove
#

Dhgegeev

undone coral
#

lol

hallow cove
#

Wow

undone coral
#

one thing to consider is

#

trust Mirror

#

once you get it working once you're not going to break it

hallow cove
#

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

undone coral
#

like something that you wrote new?

hallow cove
#

Well

#

That's all there is rn really

#

And saving

undone coral
#

do you know what i mean? creating a player is a single call to a mirror api, picking up an item is a little more nuanced

#

saving in a networked game?

#

with moving characters in mirror?

hallow cove
#

Player data like inventories

#

Like in terraria