#archived-code-advanced

1 messages · Page 88 of 1

earnest canopy
#

I debugged everything

#

The content of it is right

#

But i behaves differently in editor

untold moth
#

Content of what?

#

What exactly behaves differently and how?

#

We can't really help you without any details.
The compute shader itself behaves the same both in the editor and play mode.

earnest canopy
#

I have a computer shader that takes a density array and gives me a triangle array back

#

Marching cubes

untold moth
#

Go on.

earnest canopy
#

So if i just generate my terrain everything works

#

But if i modify the terrain with a brush in edit mode then my triangles also kinda lost (half of it)

untold moth
#

Ok, so the issue is not generation of the mesh, but editing it with a brush? Do I get it correct?

earnest canopy
#

Yes

#

But it works in playmode

#

That makes me crazy

untold moth
#

There are many differences between play mode and edit mode. Mostly related to lifetime of objects/buffers and the execution time of events and application loops.

#

But it's hard to say anything specific without more details/code.

earnest canopy
#

I checked the buffers
Everything is right

earnest canopy
#

Does OnValidate behave differently?

#

The code

untold moth
#

!code

thorn flintBOT
untold moth
#

On validate is very specific callback. It shouldn't really be used for anything other than validating changes in the inspector.

untold moth
native beacon
#

I mean, maybe you can't find any flaws in it but that is far from the same thing as it being flawless. The example it gives is basically the 'don't do this' section of any beginner tutorial on the subject.

hot aspen
#

anyone whos advanced with nav mesh agent that can answer my question?

I have an agent that goes to a destination. (this destination keeps getting set on update since the destination target can move.

is there a way to add extra motion to his path?> for example. lets say i want him to travel in a SIN wave pattern but still get to its destination. is this possible? so its not just a str8 line

untold moth
dapper cave
trail flax
#

anyone have good videos on code architeture for 2d games?

hot aspen
untold moth
untold moth
#

Share the code properly, so that we can see it.

earnest canopy
#

i fixt it

#

not unitys fault

#

my fault

#

so basically i used the wrong array type

#

used float instead of vector4

#

but why does it work in playmode but not in editor xd

untold moth
#

You never shared enough info for us to answer that question.

earnest canopy
#

ik sry

#

the problem is that i tried to save float4 in float and then i run out of space

stone quarry
#

if i am creating some kind of "open world" rpg game at what point do i need to worry about things like streaming content/advanced memory management in the world and what technique works best for Unity? as a solo developer i want to make a reasonably big open world, but i am not trying to break any records or create anything ridiculous. i've had trouble finding good answers to this kind of question, but i also don't know when exactly it's necessary. i don't have any rigid requirements; i can be flexibile in my approach. any good articles or examples? think valheim, but smaller.

#

is this something i can accomplish using addressables?

regal lava
#

you worry when you go past 5k units for when your camera starts to shake because of floating point precisional errors

stone quarry
#

haha ok, but i do want to structure the engine a bit before getting too deep. you know, plan for having to stream the content around the player in square chunks or something

#

it's hard to say how big relative to existing games because we all know how nuts they are today in scale. i guess mine would be considered "small" by comparison and the target platform is PC. i just wish i had a rough guide to say if i can jam it all in ram or if i should plan from the get-go to have world streaming.

if it's just addressables being used is it as simple as breaking the world into square chunks and streaming in the chunks surrounding the player's current position?

potent pecan
dusty wigeon
#

And how much variety you expect to have ?

#

Also, what your art style would look like ?

stone quarry
#

it would be low poly for sure. think valheim-esque with regard to graphics. so nothing crazy. i don't have a specific size determined as of yet, but i would definitely call it small by any modern standards, just big enough to feel like it's a world. i don't want a giant empty world; it has to have enough content to interact with and explore (i am thinking cave entrances that will load a new scene). so an overworld with cave/building entrances that load a new scene.

#

sparsely populated with enemies, but things like landscape objects are probably a big thing; trees, rocks, etc.

#

i am seeing some people just additively load/unload scenes together in something like a 3x3 grid around the player or trigger loading somehow. and addressables for intra-scene streaming if that is even necessary with my PS1 style low poly art

dusty wigeon
#

From what you say, I'm almost sure you can fit your whole world in memory. Keep your texture not to high resolution (and maybe you will have your terrain that needs to be loaded/unloaded)

stone quarry
#

yeah you may be right. i can probably throw together a prototype and profile it. my laptop is a decent gaming rig, but it's a few years old at this point. probably a decent base for performance testing.

#

i dont want to overcomplicate things for sure

odd tulip
#

Hello! I'm new to Unity Netcode. I have a snowball that I instantialize, which has a script of network behaviour.

When I enter the app and create a session (so I'm the server, I can instantiate and see others instantiate their snowballs just fine), but as a client I can not see mine or server's snowballs.
What am I doing wrong here? Can anyone help?

undone coral
#

In Unity, you typically create a new game object using the Instantiate function. Creating a game object with Instantiate will only create that object on the local machine.

undone coral
thin mesa
undone coral
#

my conclusion is that the api is horrible lol

undone coral
odd tulip
#

Well thats all I shared, because when the gun is shot, it triggers just this function, and nothing else.

#

That's why it's all I shared. I don't know what else I'm missing!

#

I did notice there is a [ClientRcp]? Should I also make a duplicate of this function as ClientRcp and make that function execute as well??
Because The server can see both snowballs instantiated by themselves and the clients. But the clients see nothing.

tall ferry
odd tulip
#

It's already night time here, but I will run some more tests tomorrow. Its definitely in the network prefab list, I've checked it so many times from all the googling I've done about this. 😭

tall ferry
odd tulip
#

It's a bit hard to do testing with unity editor, because I'm doing this in VR, and for some reason, pc and vr headset don't like connecting to the same session 99% of the time. VR to VR headset, no problem though.

#

But I can make debug show up in VR headset though.

#

On an off topic, has anyone tried using Vivox? It's another pain.. Their documentation to me personally was completely useless... I just don't get it. I got the sample project, ran it, and it didnt even work...

#

Is Vivox worth a go?

#

By the way, what would that mean if it is spawning but it is just invisible?

odd tulip
thin mesa
#

#archived-networking
but also it's probably just not in the right location on the clients rather than being invisible

odd tulip
#

ok, thank you, I'll check these things tomorrow

loud cypress
#

does anyone have a script that allows you to export an object's geometry to a file?

loud cypress
sly grove
#

not really a code question btw

loud cypress
#

yeah ig

loud cypress
#

the object only has geometry at runtime, so I need something that can export the geometry at runtime

ashen shard
loud cypress
#

idk why, but it seems like the script isn't properly interpreting the values sent back from the gpu for the triangles, so it renders fine, but the cpu side geometry is all messed up

cobalt hemlock
#

Hey guys, i'm working on implementing an undo and redo system in my application using the command pattern. Everything works, but i've come across this weird issue that the data in the stack data type changes slightly when doing a redo but only for redo.

The group and array classes for use the same Stack<List<gameobject>> to store the data, but for the array it seems the data changes slightly in structure after being added.

Does anyone know what could cause this issue?

I have attached an image with the issue highlighted in the visual studio editor when debugging the data.

The code used to set the gameobject list is the same for both groups and array.

tiny pewter
#

what is "doing redo" means (you show the undo only)
btw are you sure than everything is deep copyed when pushed into stack? otherwise if you put some managed type but still holding the reference and change the data, the data in stack also be changed (since they are pointing to the same memory block)

cobalt hemlock
#

Thanks for responding @tiny pewter , the implementation for undoing the grouping operation is the same as the array. Its when I start to do the undo operation on the array, the list of games objects when popped from the stack, doesn't go into the ref List<GameObjects>. It works for the group, but for array it doesn't even though the setup is pretty much the same.

#

I am trying to see what the differences are to change the structure in the sack (The bit i highlighted in red.) because the data is still there, but it seems to be nested one extra level, so it doesn't get added to the ref Array.

cobalt hemlock
tiny pewter
#

oh, mb
it is fine to cache the object that needed to be restored (otherwise no way to know which one is needed to be undo), but data still needed to be deep copyed.

cobalt hemlock
#

So i just had to make sure when I add the items to the stack, it was done when the process is fully complete, so now I can toggle back and forward with the undo and redo.

#

I just have to make sure when its added, no further operation needs to be acted on the object.

#

@tiny pewter appreciate the help. Thank you.

#

@tiny pewter just one thing, is possible to deep copy a reference type object?

tiny pewter
cobalt hemlock
tiny pewter
real blaze
rancid oxide
#

I need some help on bulding remotely using AWS, looks like in the lastet version my build requires too much RAM and it fails. Is there any way to change settings relative to the build so it uses less RAM?

earnest canopy
#

can someone help me to speed up my jobs in unity

livid kraken
pliant geyser
#

So i have a weird case where Im trying to serialize an unknown type based on an enum, so pretty much the flow is:

  • Select an enum in the inspector window
  • A set of fields show up which have different fields

The way im managing this right now is that based on the enum, i grab whatever corresponding class (fetched from some other source), and the way im serializing this unknown type is that Im saving all field names and values into an array of a serializable class (With 2 fields being the field name and the field value as a string)

When I want to deserialize, I take this class and shove it into a Dictionary<string, string>, then deserialize that into the resulting class. I can provide some small example code to show off what im doing, but is there any way I can improve on this?

sly grove
dusty wigeon
pliant geyser
#

and atm it isnt a subclass of a parent

#

also what would serializereference do for me here?

dusty wigeon
#

It enable you to have different serialization base on the type. By example, you could have an abstract Field which would the be overriden by IntField, FloatField, etc.

#

All of them would then be serialized correctly and you wouldnt need to have a custom serialization structure.

#

Alternatively, you could simply use Json or XML instead of relaying directly on Unity serialization.

pliant geyser
#

yeah thats pretty much what im doing right now, just serializing the class instance into a json then deserializing later on

dusty wigeon
#

Finally, you have the option of using ScriptableObject as well.

dusty wigeon
pliant geyser
#

that was my old solution but it didnt scale all too well (SO)

#

hmm i guess this dictionary solution is a bit awkward

#

might be better to just fully commit to json then

stark shore
#

None of my callbacks are firing. Im not getting any errors or exceptions. Did I not subscribe to the events properly? What gives?

sly grove
stark shore
#

Unity built in

#

Im using Lobby Events

sly grove
#

Dumb question but where are you running this subscribe function from

chilly talon
#

Does Unity support libraries written in .NET 8.0?
Or do I have to use .NET Standard 2.1?
I'm guessing not, but worth to ask.

Currently writing an interpreter and taking advantage of source generated regex.

stark shore
sage radish
chilly talon
#

Cheers for the answer.

#

I really wonder when Unity finally moves to CoreCLR

sly grove
plush elk
#

hey guys I need some sugestion, I am making a dungeon generator, I am making the rooms and with walls good, now I am trying to figure out the best aproach to make doors, I already have navmesh being done on the rooms

#

any ideas on how to aproach this?

undone coral
#

hey guys I need some sugestion, I am

#

None of my callbacks are firing. Im not

#

So i have a weird case where Im trying

woeful sleet
chilly talon
woeful sleet
# chilly talon Right, my guess is late 2025.

shipping the alpha then would mean net10 is already out, which means unity would be 6 versions behind everyone else at that point. seems very risky to put something this important that far in the future

chilly talon
half swan
woeful sleet
half swan
novel plinth
chilly talon
#

Probably not since the engine is mostly C / C++

half swan
chilly talon
#

TheMoreYouKnow 😛

scenic forge
#

IL2Cpp is the solution for environments that disallow JIT like iOS, NativeAOT would also solve that problem.

novel plinth
#

also as long as the RYUJit supports the CPU it can run it no problem

#

meaning any future consoles (upcoming gens) would be easy to support

#

the god tier free reflection-mode

#

been seeing FNA folks bragging their NAOT ported games lately, damn, I'm so jealous

ebon jungle
#

Hey, I have a general question, does anyone happen to know classes from System.Runtime.Intrinsic would be useful in any way in Unity? Or is that something game-devs don't really use?

tiny pewter
#

sounds like SIMD

compact ingot
hushed fable
ebon jungle
ebon jungle
tiny pewter
#

we have unity.mathematics

woeful sleet
#

so usually its just for ai-heavy stuff or scientific compute

ebon jungle
earnest canopy
#

!code

thorn flintBOT
earnest canopy
loud cypress
#

why does this correctly render, but the vertices and triangles lists are full of garbage?

        _builder.BuildIsosurface(_voxelBuffer, _targetValue, 1.0f/_gridScale);
        MeshFilter meshFilter = GetComponent<MeshFilter>();
        meshFilter.sharedMesh = _builder.Mesh; //renders perfectly
        int[] triangles = meshFilter.sharedMesh.triangles; //full of nonsense
        Vector3[] vertices = meshFilter.sharedMesh.vertices; //full of nonsense
#

what's in the vertices:

#

then later on:

long ivy
loud cypress
#

and how do i get the triangles back from the gpu?

long ivy
#

setting the shared mesh isn't just a gpu reference, but your data is on the gpu and not system memory so reading its geometry that's in system memory (triangles, verts) is not going to be correct

#

what did you try so far? You should start by reading the docs for the classes you're using to reference that data, now that you know it's on the gpu and you need to do something extra with it

loud cypress
#

looks like I have to use ComputeBuffer.GetData

#

but I have no clue how to make it the correct format (or how to use it)

plush elk
#

hey guys need some sugestions

I am working on a map generatrion usig a grid system, my logic is, when there is a change in floor it meant I whent trought a wall, for example I start doing the corridor at the center of the room A to B so when I stop seeing floor it meant I whent trought a wall so a door is placed

#

and vice versa

#

now my problem is, how can I flip the door in the correct side of the square grid and the direction

left quiver
#

https://hastebin.skyra.pw/mepehivabo.pgsql

would anyone be able to help me with my unity2d level editor script? this was mostly generated by chatgpt through many iterations but it doesn't save my changes from 2+ iterations previously.

#

i'm sleeping now so please ping me if you reply, thanks!

plush elk
#

chatgpt sucks for code

#

at least the free one

#

try to debug the code little by little and try to undertand what it is doing

wet burrow
#

So I'm trying to unpack a crash report and got this error:
Got a UNKNOWN while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application.
Anyone experienced with this sort of thing and how to better troubleshoot it (e.g. unpacking the conventions of what's being shown in those reports)? I don't want to just upload the whole file because I'm under NDA and trying to be on the safe side of not accidentally revealing stuff

tiny pewter
#

did you read the stacktrace?

wet burrow
wet burrow
upbeat path
# wet burrow yes

Take a look at the Windows Event Logs, they may contain additional debug info

wet burrow
#

I'll copy this in, I realised it isn't giving anything serious away

=================================================================
    Managed Stacktrace:
=================================================================
      at <unknown> <0xffffffff>
      at UnityEngine.Object:DestroyImmediate <0x00094>
      at UnityEngine.Object:DestroyImmediate <0x00022>
      at Obi.DynamicRenderBatch`1:Dispose <0x00182>
      at Obi.ObiClothRenderSystem:Dispose <0x00052>
      at Obi.ObiRenderer`1:UnregisterRenderer <0x0015d>
      at Obi.ObiActorRenderer`1:DisableRenderer <0x000de>
      at Obi.ObiClothRenderer:OnDisable <0x00093>
      at System.Object:runtime_invoke_void__this__ <0x00087>
      at <unknown> <0xffffffff>
      at UnityEngine.GameObject:SetActive <0x0009b>
      at GarmentDesign.Mannequin:Undress <0x000e2>
      at GarmentDesign.Mannequin:InitializeOutfit <0x00022>
      at <DismantleGarments>d__43:MoveNext <0x0006a>
      at UnityEngine.SetupCoroutine:InvokeMoveNext <0x0004f>
      at <Module>:runtime_invoke_void_object_intptr <0x0008e>
      at <unknown> <0xffffffff>
      at UnityEngine.MonoBehaviour:StartCoroutineManaged2 <0x0009b>
      at UnityEngine.MonoBehaviour:StartCoroutine <0x00072>
      at <LoadSequence>d__9:MoveNext <0x0017a>
      at UnityEngine.SetupCoroutine:InvokeMoveNext <0x0004f>
      at <Module>:runtime_invoke_void_object_intptr <0x0008e>
=================================================================
upbeat path
#

DestroyImmediate?

wet burrow
#

I'm trying to decipher a heap of code someone else made

#

but it's probably good to check where DestroyImmediate could be running from

#

thanks for the lead @upbeat path

upbeat path
#

DestroyImmediate should not be called outside of Editor code. And, btw, why are you not working from the source code

wet burrow
upbeat path
#

This stack trace is obviously from compiled code

wet burrow
#

I was running the program in play mode in the editor and it crashed, and in the bug reporter window it listed crash log files that I opened

upbeat path
#

then the stacktrace should trace source, that is not the case here

#

which would suggest it is not crashing in your code but in a plugin

wet burrow
upbeat path
#

you are missing the point. What I am saying is it is not source code in your project generating this error

wet burrow
#

I searched for 'plugin' in the crash log and got some repeated lines:

Refreshing native plugins compatible for Editor in 85.86 ms, found 3 plugins.
Preloading 0 native plugins for Editor in 0.00 ms.
#

oh right

wet burrow
upbeat path
#

all of it

wet burrow
#

so is the whole layout different?

upbeat path
#

yes

wet burrow
#

ah

upbeat path
#

methinks you are considerably out of your depth here

wet burrow
#

but this stuff isn't going to get done otherwise

#

so I have to learn it

upbeat path
#

Don't feel too bad, this stuff is very tricky even if you do know what you are doing

wet burrow
#

it'll help me get ahead in the industry

wet burrow
#

a thing that's runtime and not editor

#

and is the base class of the class that seems to be running OnDestroy() at the time the editor crashes

upbeat path
#

this is where to look

at UnityEngine.GameObject:SetActive <0x0009b>
      at GarmentDesign.Mannequin:Undress <0x000e2>
      at GarmentDesign.Mannequin:InitializeOutfit <0x00022>
      at <DismantleGarments>d__43:MoveNext <0x0006a>

you have a coroutine DismantleGarments which calls GarmentDesign.Mannequin:InitializeOutfit which calls GarmentDesign.Mannequin:Undress which tries to call SetActive on a null or destroyed gameObject

wet burrow
#

using breakpoints and stuff

upbeat path
#

Aren't stack traces wonderful things?

wet burrow
#

but for some reason it took me this long to really look in-depth at the crash logs

wet burrow
#

to check where a function is being called from

upbeat path
#

if you change DestroyImmediate to Destroy it will probably throw an error as well so wrap it in a null check

upbeat path
#

that's the one

wet burrow
#

because it's past midnight

upbeat path
#

you certainly need to change the DestroyImmediate to Destroy

wet burrow
#

thanks for the help though, even if that doesn't specifically solve it there are a bunch of other DestroyImmediate instances I need to snoop out and double-check

#

as in ones that aren't used in the editor

upbeat path
#

replace all of them

sudden rapids
#

Hi everyone, I'm trying to rotate an object in a way that its transform.up would be aligned with the normal of the ground it is standing on, and at the same time indepedently rotate it around the y axis in order to reach a certain target.
When I do these rotations separately on my object, they work perfectly, but when I add them together, one of them always decides not to work properly.
In this implementation, the y rotation kind of works, but the normal doesn't.

Any help would be greatly appreciated! 😃

Code snippet:

//Calculate the rotation based on the Y axis rotation
Quaternion yRotation = Quaternion.Euler(0, Time.deltaTime * currentAngularVelocity, 0);

//Calculate normal
Vector3 v1 = rightLegTargets[0].transform.position - leftLegTargets[^1].transform.position;
Vector3 v2 = rightLegTargets[^1].transform.position - leftLegTargets[0].transform.position;
Vector3 normal = Vector3.Cross(v1, v2).normalized;

//Calculate rotation to align transform.up with the normal vector
Quaternion normalRotation = Quaternion.LookRotation(transform.forward, normal);

//Combine the normal rotation and the Y-axis rotation
Quaternion combinedRotation = normalRotation * yRotation;
transform.rotation = combinedRotation;
native jasper
# sudden rapids Hi everyone, I'm trying to rotate an object in a way that its transform.up would...

To rotate around the normal, you want Quaternion.AngleAxis. This will make your transform's "up" direction align with the normal vector (you can imagine the axis, normal, skewering the transform, and then twisting it by myAngle):
Quaternion normalRotation = Quaternion.AngleAxis(myAngle, normal)
The second part you describe isn't clear to me: and at the same time indepedently rotate it around the y axis in order to reach a certain target. I think what you want is to calculate that myAngle above in a way that points (roughly, since it's tilted by the normal vector) to some target? But I'm not sure what you mean by "independently rotate".

Quaternion.LookRotation isn't behaving the way you expect here, it will rotate the transform off the normal axis. The up vector param in Quaternion.LookRotation is not the same conceptually as the axis param in Quaternion.AngleAxis. I very rarely pass anything here, I just let it default to Vector3.up, unless I am inverted for some reason and want to pass Vector3.down.

sudden rapids
# native jasper To rotate around the normal, you want Quaternion.AngleAxis. This will make your ...

Hi, thanks for replying.
I changed my code to this now:

 Vector3 v1 = rightLegTargets[0].transform.position - leftLegTargets[^1].transform.position;
 Vector3 v2 = rightLegTargets[^1].transform.position - leftLegTargets[0].transform.position;
 Vector3 normal = Vector3.Cross(v1, v2).normalized;

 
 float angleY = Time.deltaTime * currentAngularVelocity;
 Quaternion normalRotation = Quaternion.AngleAxis(angleY, normal);
 transform.rotation *= normalRotation;

This results in my object rotating toward the specified target, but the transform.up isnt the normal, instead it just stays as is. (for clarification, the target is a sphere somewhere in the scene, and my object needs to rotate by a constant angular velocity value every frame to face it)

Am I doing anything wrong here?

sly grove
#

This is way over complicated. Just do Quaternion.LookRotation with:

  • first parameter your look direction projected on the normal plane (Vector3.ProjectOnPlane)
  • second parameter is the normal
plush elk
#

hey guys I am doing a map generator, I think I need to use the proffiler to try to debbug the problem but I dont undertsand much about it, the problem is that after I generate the map, unity becomes slow untill I delete the list of rooms I created, I already checked the methods that use the list but I dont find the problem, unity slows doen even after the generation finishes

dire bramble
plush elk
#

ufff

#

its some 450 lines of code

#

I can create some paste bins to share you interested?

dire bramble
#

create a single pastebin and link it here

plush elk
sudden rapids
# sly grove This is way over complicated. Just do Quaternion.LookRotation with: - first para...

It probably is over complicated, I'm pretty much a noob when it comes to quaternion shenanigans.
I understand your suggestion, it's just that I'm not sure how I'm supposed to gradually rotate toward the target every frame when I must give the vector direction toward the target as a parameter.
When I put the vector that points toward the target here, it works, but sometimes it causes my object to spaz out ;-;

Vector3 v1 = rightLegTargets[0].transform.position - leftLegTargets[^1].transform.position;
Vector3 v2 = rightLegTargets[^1].transform.position - leftLegTargets[0].transform.position;
Vector3 normal = Vector3.Cross(v1, v2).normalized;

transform.rotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(<direction here>, normal), normal);
dire bramble
plush elk
#
dire bramble
#

you should definetely try to profile it

#

there could be many things that could slow it such as asynchronous operations, instantiate issues and bad handled algorithm

plush elk
#

but then it does not show in what onGui is using all of these resources

dire bramble
#

you gotta look for the profiler modules

#

not the hiearchy view

#

so you can see frame by frame what is causing what

plush elk
#

if I run the map generator while I am running it is less slow, in scene view is slower, could it be that the async functions when used in the editor are slower?

#

this last print was taken while in game mode, the spikes persist after the map is generated, but some time after. they disapear

dire bramble
plush elk
#

it must be, I have a inspector button to remove the lists of rooms and the moment I do it the performance go back to normal

#

but I am not finiding what is still using the lists that is my problem, thats why I wanted to use the profiler to see if I could find who were still running

#

nah I dont know the cene runs at 360 fps

#

I think its the editor

#

but I dont know wht

#

nah I take it back, the fps count goes up again if I delete the list

#

yeah... have no clue

#

I think I know what is the problem, I have a list<Rooms>, and each class rooms have a list of<Rooms> that are connected and each of those Rooms from the list have is own list of connected<Rooms>

#

yeap, problem found 😄

#

I just replaced the list of connected Rooms to conneded IDs

sly grove
undone coral
#

Thread

#

Hi everyone, I'm trying to rotate an

ivory glen
#

Hey guys, with a WebGL build is there a way to interface with the website code?
I've used a .jslib file but I want to import functions from javascript that is included with the website
outside of the Unity build.

devout hare
#

#🌐┃web but make functions in jslib that call those functions that you want

ivory glen
hushed fable
vague flame
#

Hello
I have question regarding disabling domain reload when working with c# scripts
I lose a lot of time waiting to test features, so I was looking to disable it (except if there is another way to save time)
So my question after looking the Unity Docs, except for static stuff, is there any side effects ?

livid kraken
#

Except for statics not really. Another way to speed up compilation time is to split your codebase into relevant assembly definitions.

vague flame
#

ok ty

#

i looked in the docs about assembly definitions, tell me if I read wrong (i didnt got the time to read all the page ofc) : By "default" Unity compile all user created scripts in one assembly file ? (idk if its right term)

#

so thats why it takes time, because even if you wrote 1 ligne somewher, it compiles ALL other scripts that are in the default assembly def

flint sage
#

Basically yeah

vague flame
#

in the docs i quit didnt understood how the "modularity" works when using AD

#

except for the compilation time & storage, whats the difference between creating multiple scripts and working with modular methods

vague flame
wet burrow
#

So yesterday I was investigating a bug that causes the editor to crash, and in the editor log file I noticed the error: Got a UNKNOWN while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application.
@upbeat path pointed out the stack trace and some instances of DestroyImmediate being used at runtime, which were likely responsible. I tracked down the instances causing it and replaced them with regular Destroy calls. Problem is, the crashes are still occuring and now there's absolutely nothing in the 'managed stacktrace' part of the editor log.
Anyone have an idea of what's happening here?

untold moth
wet burrow
# untold moth Is there anything at all relevant in the log? There should be some error and/or ...

here's everything from where the log starts talking about the crash

=================================================================
    Native Crash Reporting
=================================================================
Got a UNKNOWN while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries 
used by your application.
=================================================================

=================================================================
    Managed Stacktrace:
=================================================================
=================================================================
Received signal SIGSEGV
Obtained 17 stack frames
0x00007ff78bc42a58 (Unity) delete_object_internal_step1
0x00007ff78bc3f1d0 (Unity) DestroySingleObject
0x00007ff78bf5d7fd (Unity) DestroyObjectHighLevel_Internal
0x00007ff78bf5d394 (Unity) DestroyObjectHighLevel
0x00007ff78bd7a77b (Unity) DelayedDestroyCallback
0x00007ff78bd7c664 (Unity) DelayedCallManager::Update
0x00007ff78bf8c5a9 (Unity) `InitPlayerLoopCallbacks'::`2'::PostLateUpdateScriptRunDelayedDynamicFrameRateRegistrator::Forward
0x00007ff78bf736bc (Unity) ExecutePlayerLoop
0x00007ff78bf73793 (Unity) ExecutePlayerLoop
0x00007ff78bf793d9 (Unity) PlayerLoop
0x00007ff78cebd018 (Unity) PlayerLoopController::UpdateScene
0x00007ff78cebb1ff (Unity) Application::TickTimer
0x00007ff78d306b6a (Unity) MainMessageLoop
0x00007ff78d30b41b (Unity) WinMain
0x00007ff78e63ab6e (Unity) __scrt_common_main_seh
0x00007ffe8ccb7344 (KERNEL32) BaseThreadInitThunk
0x00007ffe8dbe26b1 (ntdll) RtlUserThreadStart


untold moth
#

What components are there on that object?

wet burrow
#

actually unity's garbage collector should handle deleting that stuff automatically

#

so I'll comment out the regular Destroy call as well

#

and see what happens

untold moth
#

Meshes are not collected by gc

tiny pewter
#

probably double free

wet burrow
#

It worked!

#

I commented out the 'destroy' call and the function was carried out perfectly

#

but I guess I still need to figure out how the GC works properly

upbeat path
wet burrow
untold moth
# wet burrow trying to look for this info

The rule of thumb is that it would clean up (C#)objects when they are not referenced by anything. Assets are a bit different though. Unity keeps them alive in the background. You can call unload unused assets for it to unload them iirc.

austere jewel
#

Calling that is unnecessary if things have been correctly destroyed, it's practically just an expensive fallback

wet burrow
austere jewel
wet burrow
austere jewel
#

It's probably due to when you're calling it, or it's a bug

wet burrow
#

I'm trawling through somebody else's (very complicated) code

#

I'll have to deal with it tomorrow

#

thanks for now and goodnight @austere jewel @untold moth @tiny pewter

hybrid belfry
#

Hello. Is there a way to mimic the behavior of Debug.Log, where double clicking the Console Entry takes you to the Call location? I'm implementing a simple Color method but can't get that functionality to remain 😕

upbeat path
fallow dune
#

I would really love some help. I have a FSM that controls my AI and For the life of me I can see the Navmesh being set but the NPC is just doing his own thing.
I can't get the NPC to reset to initial potion .
https://gdl.space/cavupetiho.m

untold moth
#

What potion?

native jasper
brazen girder
#

Can I use Import Package dialog window from code?

native jasper
humble gale
#

may i hop in vc with someone to help me fix a very specific problem in screenshare?

fallow dune
#

You can clearnly see the destination being set yet it walks away from the destination and it looks like it's walking into an invisible wall

sly grove
#

it's probably overwriting whatever the NavMeshAgent is doing

fallow dune
sly grove
#

see what happens

fallow dune
#

sure. 1 sec

fallow dune
#

well that seemed to work notlikethis

#

but now the question is,, WTF

sly grove
#

Again, your animator is overriding the position

#

you've made the classic mistake with the animator a lot of people make

#

your Animator should not be animating the root object

#

The visual/renderer piece of your character should go on a child object

#

the animator should animate that child object's local position

#

the root object should have the nav mesh agent and move itself that way, unimpeded by the animator

fallow dune
cold canyon
#

Hello. When I rotate my camera with any interpolation-based (?) method on high "speed" rotation and with enough "smoothness time" it just stops. I tried LerpAngle and Quaternion.Lerp, same result

transform.rotation = Quaternion.Euler(
            Mathf.SmoothDampAngle(transform.eulerAngles.x, _targetV, ref _cameraVelocityEulerV, time),
            Mathf.SmoothDampAngle(transform.eulerAngles.y, _targetH, ref _cameraVelocityEulerH, time), 0);
        
        transform.position = target.position - transform.forward * distance;

Video: https://streamable.com/vrppq2

fallow dune
undone coral
#

you are sophisticated. you will really like it

acoustic vapor
#

Any ideas for a fix? bullet is not accurate on 60 degrees camera. It's all good when camera is 90 degrees. But my game is on 60 degrees

the projectile launches from rangedAttackPoint and the direction is changing based on mouse cursor

this is my RangedAttackScript:

using UnityEngine;

public class RangedAttackScript : MonoBehaviour {
    private Rigidbody _rigidbody;
    public int damageAmount = 0;
    public GameObject rangedAttackPrefab;
    public Transform rangedAttackPoint;
    public float bulletVelocity = 30f;
    public float bulletPrefabLifeTime = 3f;

    public void InitializeRangedAttack() {
        GameObject rangedAttack = Instantiate(
            rangedAttackPrefab,
            rangedAttackPoint.position,
            Quaternion.identity
        );

        rangedAttack
            .GetComponent<Rigidbody>()
            .AddForce(rangedAttackPoint.forward.normalized * bulletVelocity, ForceMode.Impulse);
        Destroy(rangedAttack.gameObject, bulletPrefabLifeTime);
    }
}```

the codelet that handles player facing rotation:

```cs
private void HandleRotation() {
        float rayHit;
        Vector2 mousePosition = _inputActions.PlayerActions.MousePosition.ReadValue<Vector2>();
        Plane playerPlane = new Plane(Vector3.up, transform.position);
        Ray ray = Camera
            .main
            .ScreenPointToRay(mousePosition);

        if(playerPlane.Raycast(ray, out rayHit)) {
            Vector3 targetPoint = ray.GetPoint(rayHit);
            Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
            transform.rotation = Quaternion.Slerp(
                transform.rotation,
                targetRotation,
                100 * Time.deltaTime
            );
        }
    }
humble gale
#
using UnityEngine;
using UnityEngine.EventSystems;

public class Slot : MonoBehaviour, IPointerClickHandler
{
    public bool isBusy = false; 
    public  GameObject itemObj;

     private void Start()
    {
        // Check if this object has a 2D collider, add one if none exists, and set it to trigger
        Collider2D collider2D = GetComponent<Collider2D>();
        if (collider2D == null)
        {
            Debug.LogWarning("No 2D collider found on this object. Adding a BoxCollider2D...");
            BoxCollider2D boxCollider2D = gameObject.AddComponent<BoxCollider2D>();
            boxCollider2D.isTrigger = true;
        }
        else if (!collider2D.isTrigger)
        {
            Debug.LogWarning("2D collider is not set to trigger. Setting it to trigger...");
            collider2D.isTrigger = true;
        }

        // Check if EventSystem is present in the scene
        if (FindObjectOfType<EventSystem>() == null)
        {
            Debug.LogWarning("No EventSystem found in the scene.");
        }
    }
    public void Update(){
        if(isBusy){
            //sets its position to my position
            itemObj.transform.position = transform.position;
        }
    }
    public void AssignItem(GameObject x){
        itemObj = x;
        isBusy = true;
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (isBusy)
        {
            Item item = itemObj.GetComponent<Item>();
            // Change isEquipped to true when the object is clicked
            item.isEquipped = true;
            Debug.Log("ITEM EQUIPPED");
        }
    }
}

When i click it nothing happens 😦

thin mesa
#

not really an advanced issue. but do you have an event system in the scene and a Physics Raycaster 2D on your camera?

humble gale
thin mesa
#

that's all this object needs. you still need those other things i asked about

#

also if this is a UI object, why does it have a collider on it?

humble gale
thin mesa
#

i wasn't referring to the item, i was referring to the slot

humble gale
#

oh uhmm

#

its cuz i asked chatgpt to help me find the issue and it said nothing happened when i clicked cuz it didn;t have a collider

thin mesa
#

i don't know what you mean by "i asked unity to help" but your ui objects do not need colliders

#

as long as it has some sort of graphic it will be clickable as a ui object

humble gale
#

i can screenshare if you want!

thin mesa
#

well chatgpt is very frequently wrong and now you see part of why

humble gale
#

but it hasn;t been helpfull

untold moth
#

It's also probably due to you asking wrong questions. You need some understanding of what you're doing anyway to ask the correct questions for it to be helpful.

#

I've no idea why this conversation is in advanced code channel...

undone coral
white pulsar
#

i'm trying to find a way to change how the 2DAseprite importer handles importing assets, mainly what i'm looking for is to moddify the source code so the textures it generates are basically the Aseprite file, but with the data from the "Exported" PNG.

What i mean by this is basically have it so the generated texture looks exactly like a regular .png export, instead of what the importer ddoes, where it pads the texture's size to make sure all sprites fit

#

i'm trying to do this mainly for these small, tiny texture files that i plan to use for VFX using custom shaders and particle systems

#

I've had some luck by forcing certain aspects to be the same as the aseprite canvas width and height, issues arises whenever i try to do this for a sprite that doesnt fully encompass the canvas (pic related). where instead the generated picture just looks like a mess of pixels

pseudo trout
#

Looking for some insight on this issue. If anybody has any help, please let me know! I've never manipulated Time.time in this manner

austere jewel
#

Generally if you're doing camera stuff and you're not using Cinemachine, you should be

bitter magnet
austere jewel
#

why would it not be different

bitter magnet
#

because it already uses time.time??

austere jewel
#

It's not using Time.time, it's using a scaled Time.deltaTime

bitter magnet
#

this is basically the bob code right here

pseudo trout
#

never used cinemachine before but heard its very powerful. guess i should be

pseudo trout
bitter magnet
bitter magnet
# bitter magnet

also it used to be * time.time but now it's + time.time as a test

#

it did cause less jittering but

#

it also y'know doesn't look right

pseudo trout
austere jewel
#

I have no idea what you're talking about, but the original question was how to scale time so it doesn't jump around

pseudo trout
#

anyways i'll look at cinemachine

austere jewel
#

The answer is to track time yourself, and added the scaled time difference, ie. add scaled deltaTime

bitter magnet
austere jewel
#

I have no idea who you even are, so 🤷 you do you

bitter magnet
austere jewel
#

I don't know why you're telling me that my interpretation of the question is wrong, when you're not even the one who asked the question

bitter magnet
pseudo trout
#

im just trying to ask questions not start an argument 😭

austere jewel
#

Then maybe rephrase the question so it becomes clear why my code answer wouldn't work, because you're probably just misunderstanding it

bitter magnet
#

the question was how to move along the graph at the speed of movement speed instead of scaling the graph based on movement speed

pseudo trout
#

to make the question more clear, I want time to track normally (literally time.time) BUT i want it to go faster based on movement speed. (Time.time * movementSpeed). the issue is that i want it to be additive. so for example, I move 1 unit per second for 5 seconds. that means the current x coord on the wave would be 5. after moving that amount i move 2 units/sec for 3 seconds. it should add 6 to the previously elapsed time. making it 11. does this make it more clear? @austere jewel

#

that way i can just plug in the x coord to move along a static graph

austere jewel
#

Hence my answer.

pseudo trout
austere jewel
upbeat path
#

dont cross post, but yes it is widely known

lusty basalt
upbeat path
#

definitely not advanced

rancid oxide
#

I'm trying to make a simple shooting star (its green so u can see it), I've added the trail to the point I move in arc but I noticed that the trail start transparent, then turn color and after that goes transparent again

#

I need it to be attached to the ball i generate

#

How can I keep the color in this section?

#

There is no fade to alpha so I can't figure out where is the issue

#

these are the Trail settings

sage radish
lusty basalt
#

try setting the texture scale really high or really low and see if you get a fully collored low-poly line

rancid oxide
#

maybe I should also change the texture mode?

#

also what material should I use then?

#

look like standard material doesnt work on particles

humble leaf
#

This isn't a coding question. Use a texture that is solid.

rancid oxide
regal olive
#

Hi, working on a Baldur's Gate 3 like quest. I have movement working using NavMesh. I am trying to get the path that is being taken to display on the screen. Right now what I'm doing that is not working is using a child object attached to player, giving it a line renderer and a script that tries to display the line. Anyone tackled this that can help me out? (Script available upon request) Thanks!

lament salmon
#

Make sure your linerenderer is in the correct space (local/world)

timid sinew
#

hey i was wondering if anyone knows a way that Unity supports F#(even if its a separate open source library made by the community) that doesnt force me to use a ddl file?

#

its not really a big thing for me but still

prisma ravine
#

I'm trying to instantiate a particle effect prefab (ParticleSystem) in code. Everything I've been able to find says I should be able to do it like this:

var particle = Instantiate(particlePrefab, parent.transform.position, Quaternion.identity);

but this throws an exception:
InvalidCastException: Specified cast is not valid.
(wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at /home/bokken/build/output/unity/unity/Runtime/Export/Scripting/UnityEngineObject.bindings.cs:295)

If I wrap it in a try/catch, it seems to work as long as I have "play on awake" selected, and "stop action: destroy" does actually destroy the instantiated prefab, but after I instantiate a certain number of these, the client crashes.
Anyone know why I'm getting that exception?

thin mesa
#

not really an advanced issue. most likely you changed the type of your prefab variable and just need to drag the reference in again because it's still serialized as a GameObject reference

prisma ravine
#

Dang, that was it. Thanks!

radiant spear
#

Does anyone know what returns from Touch.Radius? I'm receiving wildly different values from different devices that have similar specs. Does it differ per brand/device? For instance on a Google Pixel 7a I get on average 130 which translates well to pixels, but on a S23 Ultra I get an average of 2, which might be millimeters according to some threads.

In the docs it's described as "An estimated value of the radius of a touch", but not in what units.

undone coral
#

Does anyone know what returns from Touch

timid sinew
#

due to the inherent benefits when it comes to certain aspects of Game Developments for each one

#

but i guess i wont be able to use the cool other language for it lol

lofty inlet
#
for(int i = 0; i < 5; i++){
objArr[i] = 5;
}

vs

objArr[0] = 5;
objArr[1] = 5;
objArr[2] = 5;
objArr[3] = 5;
objArr[4] = 5;

which is faster?

devout hare
#

If there's any difference it's so vanishingly small that you can't even measure it. Don't make your life harder with useless micro-optimizations

lofty inlet
#

that was just an example
what if the array was 1million in size

#

I just didn't want to type the second block with 1million lines

devout hare
#

Then typing out a million lines to avoid a loop would be even sillier

lofty inlet
#

can you please answer the question (if you know it)

devout hare
#

I did

lofty inlet
#

the million object one?

devout hare
#

The answer is the same regardless of how many lines you have

lofty inlet
#

there's no way that's true

#

I just realized the second one has got to be faster
since you are not iterating over the i variable

#

unless the for loop somehow caches the array

devout hare
#

Well actually if you have millions of separate rows then in practice the computer might need to use extra resources to handle the whole thing so it might even be slower

lofty inlet
#

ohh like the actual file size

#

true

#

hmmm so you're saying they're about the same if the array is like 20 objects or less

#

same speed that is

tiny pewter
#

unrolling is faster

#

and you hard code the value, save one register

#

and no branching if you hard code all the things

lofty inlet
#

cool thanks

flint sage
#

The runtime (or compiler) might even do loop unrolling for you

#

So it's hard to say if there's a definitive answer

lofty inlet
#

damn

flint sage
#

Besides, these questions are so vague that there's no way to properly measure since it depends on a 100 different variables

novel plinth
flint sage
#

Go and measure your actual use case, on your actual target hardware

#

And the loop is obviously a lot safer, which makes the performance pretty irrelevant unless this is the hottest of paths

upbeat path
#

if we are talking clock cycles option 2 is considerably faster with very large arrays. The compiler will be able to determine an exact address whereas in a loop that address will need to be evaluated at runtime

flint sage
#

Except.. it could do some optimization since the runtime knows you're iterating an array (and thus touching all elements) instead of in arbitrary order

#

Meaning it might be able to load things more efficiently into the cpu cache

upbeat path
#

wishful thinking, the compiler is not that clever

flint sage
#

I mean we're talking about hypotheticals at this point, since you can't talk about this in a generalized manner since it depends on the platform etc

fickle mountain
#

Anyone has experience toying with Camera.projectionMatrix or Camera.worldToCameraMatrix?
I'm trying to have an effect that change the world's scale, without the hassle of actually scaling the level itself.
Pretty sure what I need is somewhere in one of those two, but no matter what I try I can't get the effect I want.

sly grove
fickle mountain
#

Not really. Changing the scale. Having the camera render the perspective of a 1x1x1 object as if it was 1000x1000x1000.
It's to make an effect as if you were turned into a mice or a giant (think Alice in Wonderland, or CS maps like De_rats).
Right now I'm just scaling the entire level, but that break a ton of things.

sage radish
sly grove
#

The bigger concern would be modifying physics behaviors

timber flame
#

I want to distort a flow texture in my voxel based water shader according to directions.
For each water voxel, a direction is calculated. My approach is to change texture uv based on the direction and its magnitude. What is your idea?
Also, because the directions is calculated for each voxel, all pixels belonging to that voxel will have the same direction. To resolve this problem and change direction smoothly, I need an interpolation technique. Passing all directions of neighbors and interpolate between them based on the distance

fickle mountain
lament salmon
brazen girder
#

Has anyone done code generation? Here I have a SO, and I need to generate fields with the same values as in this SO in a regular empty class. What can be used for this? Does anyone have any thoughts?

sage radish
#

The bigger question is when to trigger the generator. You could try to implement an automatic trigger, but you probably don't want Unity to recompile every time you change a single field.

brazen girder
# upbeat path Reflection is your friend

Well, in the file .cs it was like this

    /* App constants */
    public const string AD_INTERSTITIAL = "ad_interstitial";
    public const string AD_REWARDED = "ad_rewarded";
  1. clicked on the button in the editor
  2. the data was pulled from the scriptable object
  3. and it became like this
    /* App constants */
    public const string AD_INTERSTITIAL = "new_value";
    public const string AD_REWARDED = "new_ new_value";
upbeat path
brazen girder
inland knoll
#

Hello! I'm trying to make an enemy npc who can essentially hide behind objects/walls, perhaps something like you'd see in GTA with the cops. However, I'm currently struggling on figuring out how to do this. The first thing that came to mind was something like in BTD 6 (aka on the picture) where it creates this red area in places where the troop cant reach. I'm wondering that maybe I could do this for the player, get the two points where an obstacle originates from and set it as a cover point for the enemies. Another idea is to just put gameobjects to the places where the enemies could take cover, however this feels very inefficient, plus I'm certain that GTA does this at runtime.

gusty kernel
inland knoll
gusty kernel
# inland knoll It's not exactly about the shooting part. It's about finding the nearest cover t...

Oh. In that case would I place zones which are the shooting/hiding spots. Then the enemy will search the closest zone (using 2d/3d distance calculations in a loop) and will move to that place. It'll stand on a specific distance from the corner and maybe you can trigger an animation which shows the shooting.

If a spot is already taken, then you have to make sure that the hiding spot is removed from a list containing all hiding spots. Then other enemies will search for another spot. (You prob don't want 2 enemies glitched into eachother)

#

I would do it like this, but maybe there are other more effective ways.

undone coral
undone coral
inland knoll
undone coral
#

by the time you write this method signature you will have 90% solved your problem

timid sinew
inland knoll
timid sinew
#

or do you need to do that as well

#

im unaware what gta does but the more duct tape solution is to place areas on the prefab which indicate where an NPC can possibly look for cover

timid sinew
#

the other way would probably be

#

if i were to take a guess

inland knoll
timid sinew
#

some sort of equation including the rotation of both characters and their vector 3s and the possible corners and/or something that has to do with raycasts

#

id have to think about it a bit more if i actually wanted to make a solution though

#

heres a solution i found atleast

#

In real-time calculate corner areas wide enough for the NPC to hide and that aren't exposed to the player. Choose the nearest for the player to hide.

timid sinew
lament salmon
#

If you don't use a NavMesh then you could just brute force it by picking random points around the player, raycasting from those points towards the target player. Discard visible positions and score them by distance etc.

inland knoll
lament salmon
#

Does it have to be a corner?

inland knoll
#

The enemy cant peak if it's in the middle of the wall I mean

lament salmon
#

Yeah ok, do you use a NavMesh?

inland knoll
#

I do

#

I think I could actually even be fine if I get a point in the middle of a wall, then generate a new path from there to the player and stop at the point before the point where a raycast would hit the player

lament salmon
#

I loop over the edges in the NavMesh and bake a "visibility score" to a few directions from each generated point

inland knoll
#

I'll see what I can do tomorrow

lament salmon
#

I also bake different firing poses (lean left/right, center) which is visualized here by the green stick figure 😄

#

The rectangles on the ground are the generated points.
Green points have a line of sight towards their cover direction from any pose. Red ones are bad for shooting, they just provide cover

#

So I generate as much info as I can when baking, and do some additional checks at runtime

jagged fiber
#

How can one exclude libraries from build in a safe way? (To avoid "The type or namespace name X could not be found") .
I excluded certain server-only things from client, but an android build crashes with "The type or namespace name X could not be found" exception (I don't use the components, that use the excluded libraries on the client).

When launching in the editor, the client build runs just fine.

upbeat path
jagged fiber
upbeat path
#

not the folder the library itself and who said anything about right click?

jagged fiber
upbeat path
#

and folders contain files

jagged fiber
#

yes, so how do I get to the inspector you mentioned?

upbeat path
#

This is one of mine.
In the folder select the library, that shows the inspetor

jagged fiber
#

will look into "Define Constraints" there

upbeat path
#

but you said you wanted to exclude for Android, so select include for all platforms except Android

jagged fiber
#

the exception is thrown in real android builds, but when building "android" and running in editor, it runs fine with libraries excluded correctly

upbeat path
#

sounds like you need to increase your code stripping level

#

or switch to IL2CPP backend

glacial wedge
#

Hi. my game lag in editor

#

why I have 100ms of update?

#

50ms of shaderGUIUtility?

#

with deep profile

jagged fiber
austere jewel
#

It may be easier to see in the profiler's hierarchy view

sage radish
glacial wedge
#

the property exist, no warnings.

#

I found out that i was wrongly call an instantiate now it is running better, but still not enought i'm still checking

glacial wedge
#

why "first call"?

#

and shouldn't be better use gpu instancing instead of srp batcher for render my multiple tiles?

#

but trying to use the materialpropertyblock with gpuinstancing material it still try to use srpbatcher with tons of batches caused by "different materialpropertyblock"

untold moth
#

What are you trying to achieve anyway? Sounds like you're doing premature optimization.

glacial wedge
#

but it wasn't

untold moth
glacial wedge
#

because the previus call draws half of the tiles

untold moth
#

Well, there are no guarantee that they are in order and/or batched in the same job.

#

80 draw calls /batches is very little. I don't understand what you're trying to do here.

glacial wedge
#

I want to use materialpropertyblock, but if i do 80 becames 500

untold moth
#

Why do you want to use it?

glacial wedge
#

i read that for multiple simple objects like my floor tiles it works better

untold moth
#

It would work good if you have several tens of thousands of these objects. And then again, it would just offset the work to the gpu. I bet that there are other things that actually affect the performance more(like culling and stuff)

glacial wedge
#

true

untold moth
#

You still didn't explain what you're trying to do..?

inland knoll
inland knoll
#

Oh that returns the edge points?

lament salmon
inland knoll
#

Alright, I'll cook something up with that then

lament salmon
#

Yeah, lemme know if you have troubles I can compare our approaches then

#

I totally improvised this

#

I check all the edges in each triangle and do a FindClosestEdge on that edge's center

#

Then I do a dot product check between:
A. The normal of the NavMeshHit from FindClosestEdge
and
B. The normal perpendicular to the edge we are currently iterating
If the dot is > some threshold (I just used 0.9) then it is a valid outer edge

#

@inland knoll Hope that helps

#

Hacky but it works

inland knoll
#

Oh, I was just planning on calling FindClosestEdge on each of the vertices and checking their distance.

#

I don't exactly get the point of getting the normal and the dot stuff. What would be a not valid outer edge?

lament salmon
#

Since it is shared by those edges

lament salmon
inland knoll
#

But it would return the distance as 0 if it's on an edge? I don't think it gets the distance to the center of the edge

lament salmon
#

You only want the outer edges. So the green ones here

#

You don't care about the passable edge between the tris

sly grove
#

when I try to change the value, The set is not being called.
What do you mean? How are you trying to "change the value"? What function are you calling? What set are you expecting to run?

lament salmon
#

@inland knoll FindClosestEdge finds outer edges only, not edges between triangles

#

That's why I use it to check if it's on the outer edge

lament salmon
inland knoll
#

Alright, so we're finding the outer edges not only the vertices, right?

#

Since I was trying to get only the vertices before. I guess edges are actually a lot better to get, lot more info with that

lament salmon
#

Yeah, you want to work with edges

#

They are just a pair of vertices anyway

#

You can then generate some points along those edges and check their cover score and such

viscid remnant
inland knoll
# lament salmon Then I do a dot product check between: A. The ``normal`` of the NavMeshHit from ...

Is this what you meant? ```cs
private bool IsOuterEdge(Vector3 vertexA, Vector3 vertexB){
Vector3 center = vertexA + (vertexB - vertexA)/2;

    NavMeshHit hit;
    if(!NavMesh.FindClosestEdge(center, out hit, NavMesh.AllAreas)){
        return false; //For some reason, found no edge
    }

    Vector3 perpendicularDir = GetPerpendicular(vertexB - vertexA);
    float dot = Vector3.Dot(hit.normal, perpendicularDir);

    if(dot > 0.9 || dot < -0.9){ //Since getting the perpendicular direction might have given us the negative of what we want
        return true;
    }

    return false;
}

private Vector3 GetPerpendicular(Vector3 vector){
    return new Vector3(vector.z, vector.y, vector.x); //Switch the X and Z coordinate.
}
lament salmon
#

Yeah but make sure to normalize the perpendicularDir

#

So that dot product is in the -1..1 range

inland knoll
#

Oh right

inland knoll
#

It's kind of working, however a lot of edges all over the place too. Gotta do some tweaking. I believe one problem is that if a random edge in the middle of the play area is aligned with a wall which is the closes edge on the navmesh, then it takes that as a valid edge, I think a simple distance check would do tho.

inland knoll
lament salmon
lament salmon
undone coral
#

it's really frustrating that unity doesn't expose the underlying navmesh data structure. they are using recast (https://github.com/recastnavigation/recastnavigation) which is open source anyway. it's a real dick move.

@inland knoll it might be easier to adopt granberg's A* because then you can query this stuff directly on a navmesh.

GitHub

Navigation-mesh Toolset for Games. Contribute to recastnavigation/recastnavigation development by creating an account on GitHub.

lament salmon
undone coral
#

if you need to find the edges of geometry (i think you mean the corners), there are standard algorithms for that. you can use it on the triangulation.

inland knoll
#

Now we're talking

lament salmon
#

@inland knoll The dot product's point is to check if the point is along the edge. You don't know what is the center of the edge that was hit

lament salmon
inland knoll
#

Oh wait, you were talking about a different thing than I thought, mb

lament salmon
#

Yeah. Are you currently using the dot product approach?

inland knoll
lament salmon
#

You can try with a distance check, but there's a reason I changed to the dot product, but I can't recall what exactly

inland knoll
lament salmon
#

My issue might've been that I had multiple overlapping NavMeshSurfaces or something

#

Use the distance check if it works for you

undone coral
#

@inland knoll well in case you need something more robust, you can use geometry3Sharp and load the navmesh triangulation into it. then, simply enumerate the edges and ask it directly if it is a boundary edge
https://github.com/gradientspace/geometry3Sharp/blob/8f185f19a96966237ef631d97da567f380e10b6b/mesh/NTMesh3.cs#L866

GitHub

C# library for 2D/3D geometric computation, mesh algorithms, and so on. Boost license. - gradientspace/geometry3Sharp

#

it looks like you are going to want to do more advanced queries on your navmesh surface eventually so this is probably going to be helpful to you. it explicitly supports unity and i think it is used by many games

#
var mesh = new DMesh3();
foreach (var v in vertices) {
    mesh.AppendVertex(v);
}
for (int i = 0; i < indices.Length; i += 3) {
    mesh.AppendTriangle(indices[i], indices[i + 1], indices[i + 2]);
}
var boundaryEdges = new List<Index2i>();
foreach (int eid in mesh.EdgeIndices()) {
 if (mesh.IsBoundaryEdge(eid)) {
  var edge = mesh.GetOrientedBoundaryEdgeV(eid);
  boundaryEdges.Add(edge);
 }
}

@inland knoll pretty much all it would be once you've triangulated the navmesh

#

but... what is this for?

inland knoll
lament salmon
#

@inland knoll Yeah I just checked, I was using dot product because some of my navmeshes were overlapping so the distance check could catch a different edge

undone coral
#

i see... it is good you shared an actual screenshot of your game

#

it was kind of confusing

#

you want npcs to take cover

#

that's what i'm hearing

#

in something that looks like XCom

#

generally those places are designed. like you can't take cover on an exterior wall

lament salmon
#

What's wrong with automating it?

#

I personally did it because the maps are procedural

#

Of course it's good to have the option to hand-author them too

undone coral
#

you can procedurally determine places that you can get cover. first the navigable areas are painted by the designer for stuff that actually makes sense to take cover on. let's call that the "coverable area." then the coverable area is voxelized, and you query which voxels can be seen by the player (raycast from voxel to player) and remove them. then the npc navigates to the voxel closest to the npc.

undone coral
inland knoll
undone coral
#

procedurally i guess there are a lot of ways to do this. at a high level:

find all the boundary edges (exterior and interior) of a navigable mesh surface
compute a convex edge for the whole navigable mesh. remove all the edges that are both in the mesh and its convex counterpart.
 this leaves all the concave edges of the exterior of the navigable surface and the interior edges.
using the concave exterior edges and interior edges, place voxels inside the mesh bordering these edges.
keep the voxels that are wholly contained in the mesh. this is your coverable area, procedurally determined.
whenever an npc needs cover...
  raycast from each voxel nearby the npc to the player.
  if the raycast hits the player, remove it as a potential location.
  choose from the remaining voxels heuristically and move to it.
undone coral
inland knoll
undone coral
#

there you go.

#

i mean i can only help you do stuff that makes sense. right now your decisionmaking is "whatever @inland knoll feels like." it isn't sensible. you can't in the same breath reject an external library - i got news for you, Unity is an external library - and then also complain about it being "pretty tedious to go and map out all the positions"

#

you have to do stuff that makes sense

lament salmon
#

How does it not make sense?

undone coral
foggy verge
#

hi everyone ima need some help

undone coral
#

if the user is going to author it from scratch.

foggy verge
#

anyone here knows how to balance games

undone coral
#

i'm not saying you're right or wrong about anything it's good that there's something that works

thin mesa
lament salmon
#

You are implying that it is faulty

foggy verge
lament salmon
#

And that there's a need to rely on 3rd party libraries, which many people want to minimize, including me

remote pumice
undone coral
#

i think there are some more steps between what is shown in that screenshot and procedurally finding locations for cover

foggy verge
#

how do u come up with formulas like this (1-sign(floor(x/200001)-1/2))/2*10*(139+1.55^139*1.145^360*(Product[1.145+0.001*ceiling(i/500),{i,501,x}])+((1+sign(floor(x/200001)-1/2))/2)*ceil(1.545^(x-200001)*1.24e25409+((x-1)/10))

undone coral
#

jk

foggy verge
#
{
    Block, // converts damage into defense more effective on shields
    BlockPct, // block 3% of damage, 
    Defence, // Block +X damage 
    Immunity, // every X turns turn immune of x cooldowns
    Defect, // defect x% of damage back 
    Parry, // 1% chance to completly block the attck
    Motivation, // take x% less damage for first 5 secs 
    Shield, // + x health
    RockAttack, // every 2 attack throw rock to enemy 
    EarthQuake, // slow both you and enemy down but Both take more damage
    Dust, // enemy attacks are x% slower
    HeavyWeapon, // attack very slow but do large damage
    Dig, // Every 10 cooldown dig inside for 2 cooldown
    BuriedTreasure, // on death recive X amount of gold 
    Mineral, // gain x ruby per victory 
    LevelBoost, // all ice of this weapons +x levels
    FullBlock, // fully block the first hit of the battle 
    RandomTypeBoost,
}``` this is like one out of 10 blocks
#

and i need to balance the skills

lament salmon
foggy verge
lament salmon
undone coral
foggy verge
undone coral
#

which is only cover if it's on a concave part of the edge

lament salmon
#

Detecting cover? Simply a bunch of raycasts when baking

#

It is a bit more complex than it sounds, I admit

#

But doable

#

Each cover point has info about its cover angles and available shooting angles

undone coral
#

the player is the green star, the npc is the red star. without dealing with the exterior edge correctly, all the blue areas would be cover. if the npc navigates to the closest cover area, it will be in kind of a bullshit place

#

i agree it's complicated.

lament salmon
#

I don't just score the cover point by distance when querying.
I calculate the visibility to the target and cover amount from the target

undone coral
#

i think without explicitly dealing with the exterior edge, you will have issues with one or both of the situations above

#

there's no heuristic.

lament salmon
#

Tbh I'm not sure what you mean with 'dealing with the exterior edge'

undone coral
#

the exterior boundary of the traingulated navmesh ground surface

#

let's say you omit the exterior edge
okay, because you've omitted the exterior edge, the npc does not see the cover that makes the most sense

#

so there are two situations that need to be dealt with. if you treat all the areas around edges of the navmesh surface as potential spots of cover, you must deal with the exterior border of the navmesh specially.

#

it cannot be dealt with heuristically.

#

there is definitely something there with whether or not the edge is concave. but it's an open surface in 3d, so i can't imagine querying that ad-hoc. you'd have to use a library to determine concave edges of a 3d surface

lament salmon
#

I think I see what you mean now, the very exterior edge
I don't generate any cover points on edges that don't have any cover, detected by raycasts

#

So they are basically ignored

undone coral
#

i think you're back to the first illustration then

#

as an issue

#

there are points on edges that have cover detected by raycasts in that illustration

#

you'll see that the outermost border / exterior edge of illustration 1 indeed has areas of it that are not visible to the player according to raycasts.

lament salmon
#

The whole idea is to have points next to solid geometry

#

Not just points that are not visible to the player

undone coral
#

okay... well then you are in the issue in illustration number 2, which is that sometimes the exterior border of the navmesh could or could not have "solid geometry," where solid geometry is meant to be a heuristic that is supposed to include the part of the level's exterior border that is concave.

#

it really depends on definition of solid geometry. maybe the whole level is made out of kitbashed stuff

#

you'd still have to write a bunch of heuristics for solid geoemetry, you couldn't do it in a general way

#

maybe that geoemtry that is making the exterior border of the level isn't "solid"

#

i don't know. one thing i know for certain is, if i want to query facts about geometry, i'm going to use a library.

#

@inland knoll anyway, you know, you use libraries. you better start believing in libraries, because you're in one (unity). if you don't want to use libraries, it's your game, write stuff that is error prone. i mean i'd use the word buggy, but maybe you don't make the errors and don't write the bugs. i don't know.

#

you can blub through a bunch of heuristics.

#

that's a perfectly good way to do this

#

it will be faster and less buggy to hand design the valid cover areas

#

you're going to want to exclude valid cover areas from ever being used as cover anyway

#

just stylistically

#

so you will need to do it by hand eventually.

#

i have literally never met someone on this chat room who has had a valid reason not to use a good external library. not even the people trying to minimize load times for webgl, because it's always going to take longer than 6s, so you will have lost most of your audience due to loading no matter what you do.

#

i guess education was valid

#

that's pretty much it

#

if the academy required that you not use libraries

inland knoll
# undone coral <@767297192783511562> anyway, you know, you use libraries. you better start beli...

If I were to only use libraries, I wouldn't learn. The more I handle these kinds of situations on my own, the more capability I'll have in the future. If you wish to praise libraries as greek gods and ignore other possibilities such as making it yourself, you go do that. I just rather do these things on my own, learn and get experience. What if one day, there isn't a library that would do the work for you? Also, I'm not on a deadline, so I can just make progress as I like and make the things how I want them to be. Another good thing about doing it myself would be that I actually know what's going on and I can modify the code, or use it as a base for future things more easly.

undone coral
#

yeah i mean, you can write a mesh analysis library

#

i don't know how much there is to learn from that experience.

#

you can do this

lament salmon
#

Rectangles are cover points

undone coral
#

if ever

lament salmon
#

Super minor issue

undone coral
#

i think it will happen all the time. i mean look at my illustration

undone coral
#

in this situation, if the npc who is visible to the player right now is seeking cover, the closest cover is in kind of a bullshit place

#

i am actually not sure if there is a general way to deal with this, which is why i think people hand design valid cover areas

lament salmon
#

That's why the points have their visibility angle data cached. Like I said many times.

#

You query that at runtime

undone coral
# lament salmon That's why the points have their visibility angle data cached. Like I said many ...

while i don't know how that solves the problem in the illustration, supposing it does, surely you see that "an agglomeration of heuristics" is harder to get right, in every sense, than "specify the areas by hand". even in a procedural level generation setting, i would probably generate cover areas directly and build geometry around it, or something like that, then do it as a procedural pass afterward

#

i mean you're a reasonable person of course you agree

#

just because something exists - just because it's even your code and it exists today, right now - doesn't mean it makes sense

inland knoll
lament salmon
undone coral
undone coral
inland knoll
lament salmon
undone coral
#

you have to reproduce my exact illustration

#

target should appear to be directly above self, but still visible to target

#

but i believe you

lament salmon
#

Directly above

undone coral
#

okay well

#

that's kind foa weak choice

lament salmon
#

(Ignore the missing edges, was messing with some thresholds)

undone coral
#

there are a lot of spots that are closer that would be better cover

#

than the place it chose

austere jewel
#

The system seems to be working great, well done Osmal

lament salmon
#

Thank you

#

The heuristics do need some more tuning, but these bots are already wrecking my ass in game

undone coral
#

i mean this would be the best spot no?

austere jewel
#

If you found any issues, I imagine it would be minimal effort to write an extra heuristic to prune them out if you required

#

Or hell, just use this as a fantastic starting point to authoring

lament salmon
undone coral
#

same with this illustration

#

although it is already not visible to the target

undone coral
inland knoll
lament salmon
#

Did you really miss the part that it's a shooting position with cover, not just a cover position?

half swan
austere jewel
#

Seeing as you set up the goalposts I don't think it matters lol

undone coral
#

well you can't shoot from the position it chose in that illustration either

half swan
woeful kraken
#

how bout this - Osmal likes it. There. End. Finito.

undone coral
#

i mean it "can" "shoot" form there

#

the npc can move

inland knoll
austere jewel
#

Even if you authored this cover you would still need a step in code to validate the things you are now arguing about

lament salmon
#

That's why it looks like that. The green stick figure resembles the shooting pose

undone coral
#

i'm not really arguing one way or another. i guess if i wanted to implement a cover system, i would look at a pre-existing game, and implement it exactly, since that's kind of what players expect

#

i wouldn't make any decisions about which heuristics to use, i wouldn't choose the areas procedurally, and i wouldn't ad hoc anything. i already think that this cannot be done generally.

half swan
#

"And now let's set the goalposts way over here"

undone coral
#

it's like arguing over the best way to move fps characters. i don't have any opinions about that.

#

i would just do exactly what my audience expected from playing counterstrike.

austere jewel
#

Well, I'm absolutely certain there are games out there that automate this

undone coral
#

...maybe, but i don't think that would make sense

austere jewel
#

Well, you're wrong

undone coral
#

just because something exists doesn't mean it makes sense

#

i'm not sure why that is an unorthodox thing to say

inland knoll
undone coral
#

you know it's true

undone coral
#

i have no idea honestly

inland knoll
undone coral
#

but i don't know. i really don't know. iw ould ask them

#

anything is possible. they make beard growing simulator games inside their games. if you wanna do what GTA V does, by all means, do it

#

i don't think it's easy to make counterstrike in unity either. it's possible, it's just not practicable for an individual with a limited lifetime.* heuristic after heuristic is possible but it is not practicable

#

it can exist with flaws, and you can pick and choose which flaws you care about, but in which case, you know, try to do it as simply and as lazily as possible

#

back to square one: use a library.

#

i'm not sure you have strong opinions about which flaws you do or don't care about

#

my instinct is to look at exactly what xcom does - this is turn based right? - because it's written in python, it's right there for you to see not sure yet

#

because that's what players expect

#

i mean i can shoot from this blue rectangle, it seems like it's the best place for cover

#

i don't know what to say, it made a bad choice

#

but perhaps i'm not understanding what "shoot from here" means

#

i think the closer it looks like my illustration, the more simultaneous bad choices will appear

lament salmon
#

Its shoulder would be visible to the target from there, when taking cover.

undone coral
#

i am not sure what the game is, but if it were an FPS, you know, every player would choose blue rectangle. if it were a turn based tactical, i am not sure.

#

surely the most sensible option, if its shoulder was visible, would still be a square currently marked red near the blue rectangle, it's going to be sensitive to how much "moving" around a corner is valid

#

doesn't this successfully illustrate the problem with having a lot of heuristics?

#

how could it not? everyone would choose the blue rectangle for cover. an extremely simple heuristic (closest not ivsible location between me and the player) would also choose the blue rectangle, although it might be an inferior firing position, i'm not sure if in aggregate the simplest heuristic chooses worse firing positions on average

#

it's all very finnicky

lament salmon
#

It also tries to keep some distance to the target, that's why it most likely prefers the point on the right

undone coral
#

rather than right there in the open

#

i don't know

lament salmon
#

Anyway, I'm not here to convince you that it works. It works really well for me, and I'm happy with it. If you want to only use libraries and ChatGPT, then you do you.

undone coral
#

i hope this is interesting

#

obviously i just want the game to be good

#

my goal isn't to find flaws personally, it's just to say, okay, it's possible to think about this like, a tiny bit, and come up with a pattern of terrain that is very challenging for heuristics

#

clearly that's a very challenging scenario

#

everyone looking at that illustration surely agrees the blue rectangle is not just a little superior* but a lot

tall ferry
#

🤷‍♂️ if talking about enemy AI and making a challenging game, it could be better that its unexpected where it will go.

#

As the player, if you can predict where it will be always then there is no challenge.

austere jewel
#

if I was a real person I definitely wouldn't choose to take cover right in front of my target in a way that caused me to run in a direct line towards them

undone coral
# austere jewel if I was a real person I definitely wouldn't choose to take cover right in front...

that caused me to run in a direct line towards them
looking at the actual screenshot, the difference between the exposed parts of the two paths would maybe not be very large. anyway, self is fully exposed in this scenario, and i think the most interesting scenario is still the one that was illustrated.
i don't know, maybe i'm not looking at the right thing, or maybe i'm looking at the wrong details, i am surprised that is a "direct line" in the screenshot. it's not my game.

#

this has been a very informative conversation.

eternal musk
#

    public static bool ReportIfNull<T>(T component, Object reporter) where T : Component
    {
        if(component == null)
        {
            Log($"{typeof(T).Name} could not be found!", reporter, LogType.Exception);
            return true;
        }

        return false;
    }```

I've only worked with generics a couple times, but I'm trying to learn them more. Writing this method that logs a message if a component was found null just for practice. When I print ```typeof(T).Name``` it just prints Component. Can I print the *exact* Component that was passed into the function?
urban warren
tall ferry
eternal musk
#

Ah just realized my mistake lol I feel so stupid

#
        Component test = null;
        if (Logger.ReportIfNull(test, m_Processor)) return;```
#

This is how I was testing it

#

It prints exactly what I want, just was testing it incorrectly. My mistake!

urban warren
#

I was wondering if that was what you were doing haha

eternal musk
#

Lol I've been programming for too long today

urban warren
tall ferry
desert hare
#

Hey, did anyone work with addressables before? I am looking to build a moddable game and, whatever I tested was working just fine until I made two new projects, one for building the mods and another one which is the actual project that loads created mods.
However in those last projects I am getting the same errors when attempting to load any mod from any of the three projects, nothing has changed internally so i am very lost to tracking down the issue, they're pointing out to a .bundle file that couldn't be imported or something like that

 /// <summary>
        /// Called when the addressable finishes loading.
        /// </summary>
        /// <param name="obj"></param>
        private void OnCompleted(AsyncOperationHandle<IResourceLocator> obj)
        {

            //find prefabs in the addressable with the tag specified in the first parameter
            IResourceLocator resourceLocator = obj.Result;
            resourceLocator.Locate(findByLabel.labelString, typeof(GameObject),
                out IList<IResourceLocation> locations);

            //if there are loactions in the adressable spawn them
            if (locations != null)
            {
                foreach (IResourceLocation resourceLocation in locations)
                {
                    GameObject resourceLocationData = (GameObject)resourceLocation.Data;
// NOTE: Apparently when debugging, the next line causes errors, but i am still not sure what to do.
                    AsyncOperationHandle<GameObject> prefab = Addressables.InstantiateAsync(resourceLocation);                        
                    prefab.Completed += OnModInstantiated;
                }
            }
        }

this is getting very overwhelming to work on ngl

long ivy
#

How were you testing before? Your paths are all very fishy, including spaces and bundles existing inside Assets folder

desert hare
#

did the same for the other two projects and well, errors

#

they are all located in the same directories

#

i mean, the same root folder where i save all my unity projects

untold moth
#

There's also a chance that something else is opening/locking the file preventing it from being accessed🤔

wooden cedar
desert hare
#

I'll try bringing the built project on the desktop or something

wooden cedar
#

I'd go shorter, like C:\dev (just because of the long filenames). Desktop will still be a long path. It's also important to mention no non English characters in the path (which happens a lot when you use My Documents or Desktop with a non English username)

#

I wouldn't worry about it normally, but worth a test if getting odd permission errors

#

You can also manually browse to parts of that path and see if it is iniecting spaces where they shouldn't be (just copy paste the path into explorer)

desert hare
#

it may work for development but also hate to distribute files like that

wooden cedar
#

That way we know if it is even the issue 🙂

desert hare
#

makes sense, i'll try

wooden cedar
#

Because if none of that helps, then no sense worrying about any of it

desert hare
#

I feel like it may be something in the settings but I don't really understand them

#

I have modified the same fields between all projects

#

I'm noticing something weird tho, the backward and forward slashes

#

I know that could be an issue but it is weird that it worked on the first project whatsoever

#

the worst thing is that i can't load a simple stretched cube, while in the previous one i was able to load a complete model with textures

#

ok i have noticed something

#

it works if i dont move the bundles from their original build place

#

Well this is terrible, found this inside the "mod" json file, I'll have to do more research on this

runic tendon
#

I'm loading adressable scenes additively using Addressables.LoadSceneAsync(). For heavy scenes this is freezing the editor which doesn't make sense as the addressables are supposed to be asyncronous. Anyone have any idea why this could be the case?

None of the gameobjects in the addressable scenes are addressables atm.

sudden stone
#

anyone know how to work with .awb/.acb files

urban warren
#

I have two methods. Is there any way for me to have the first one call the second one to set the ref value (I could switch it to a out if needed)

public void Input<T>(string key, ref T value)
{
  Input(key, newValue => value = newValue);
}
public void Input<T>(string key, Action<T> setValue) { }

The above code doesn't compile of course cause you can't reference a ref parameter from a lambda.

scenic forge
#

No, lambdas could be stored and invoked at a later time, by which point the ref parameter may not exist anymore.

tiny pewter
#

using out should be possible?

#

the scope is limited and only be applied when you call it

urban warren
#

Nope, out results in the same compile error

urban warren
scenic forge
#

If you must use lambda then no.

#

You could extract the logic inside the Action overload, and make both overloads call that

urban warren
#

The Action is stored and called at a later date :/

#

Oh well, I guess it isn't the end of the world. Just syntax sugar at the end of the day really 🤷‍♂️

finite sundial
#

I'm following the tutorial of xzippyzach, I'm using this code! https://github.com/xzippyzachx/UnityFirebaseDatabaseTutorial/blob/main/FirebaseDatabaseTutorialCompleteProject/Assets/Scripts/FirebaseManager.cs

I have my logout button from another scene instead of a UI panel
so the only thing I changed would be instead of using the UI manager, I'm accessing the scene

    {
        auth.SignOut();
        UIManager.instance.LoginScreen();
        ClearRegisterFeilds();
        ClearLoginFeilds();
    }

I have this

{
   auth.SignOut();

   // Wait for the sign-out operation to complete
   StartCoroutine(WaitForSignOutAndLoadScene());
}

private IEnumerator WaitForSignOutAndLoadScene()
{
   // Wait for a short time to ensure the sign-out operation completes
   yield return new WaitForSeconds(0.5f);

   // Now, load the scene
   SceneManager.LoadScene("FirebaseLogin", LoadSceneMode.Single);

   // Clear fields or perform other actions as needed
   ClearRegisterFields();
   ClearLoginFields();

   // Reinitialize Firebase in the FirebaseLogin scene
   ReinitializeFirebase();
}
GitHub

These are the example projects used for a YouTube tutorial on the Firebase realtime database in unity - xzippyzachx/UnityFirebaseDatabaseTutorial

unique mountain
#

anyone here has setup github actions for unity ?

bleak citrus
#

what is your question?

#

(this also isn't really a code question)

unique mountain
#

ok then tell where shall i ask this

random summit
#

Guys do you know how can i start a client with an URI instead of an ip and a port on Netcode for GameObjects 1.6.0?

#

on Mirror i would do this

urban warren
vague flame
#

quick question
if i have lets say a recursive function that causes sometimes a stack overflow, does running it in background in a coroutine or another thread can make it "slower"/reduce the risk/totaly avoid the risk ?

dusty wigeon
vague flame
dusty wigeon
#

Share the code and someone might have an insight

vague flame
#

its not mine but a friend

dusty wigeon
#

Then share his code

vague flame
#

i will try to simplify, but so coroutine doesnt make it not stack overflow ?

#

a stack overflow isnt a result of to much operations in 1 frame ?

sly grove
#

No

#

It's a result of running out of stack memory

#

Due to too deep of a callstack

vague flame
#

so if you have no recursive there will not be to much callbacks ?

sly grove
#

Generally stack overflow is a sign that you had infinite recursion

#

It's a logical error

#

Similar to an infinite loop

#

It means you need to fix your logic, not switch to another style of iteration

dusty wigeon
#

I most say that I have seen stack overflow in the past that was legit, but it was in iterating a huge graph.

vague flame
#

ok ty guys

sly grove
#

Yeah that's super rare

#

But possible

vague flame
#

after reviewing his code we found a way more easy solution to avoid a big for loop and a recursive :)

#

but i note everything you said as future advices

cyan gale
#

can anyone help me I have this script were im trying to spawn objects on terrain based on texture
but i get an index out of bounds error when i hit play and nothing spawns

thorn flintBOT
regal olive
urban warren
regal olive
#

I'll flip W arry you one day 🤌

hoary yew
#

Hello everyone! I'm currently trying to predict my targets position using rigidbody velocity, i already have a method for prediction regular projectiles and it works great however, I'm really struggling to find a way to predict where an enemy will be at the end of a parabola or how to make it so the parabola always ends at my predicted position. This is the method that the mortar projectiles use

private float progress;
    protected void MoveAlongArc(Vector3 startPosition, float arcHeight, Vector3 targetPosition, float stepScale)
    {
        progress = Mathf.Min(progress + Time.deltaTime * stepScale, 1.0f);
        // Calculate a parabolic value for vertical movement, creating an arc effect
        float parabola = 1.0f - 4.0f * (progress - 0.5f) * (progress - 0.5f);

        Vector3 nextPos = Vector3.Lerp(startPosition, targetPosition, progress);

        // Adjust the y-coordinate of the next position to create the parabolic arc
        nextPos.y += parabola * arcHeight;

        transform.LookAt(nextPos, transform.forward);
        transform.position = nextPos;

        if (progress == 1.0f)
        {
            //damage target
        }
    }```
#

And this is the method I use to predict positions regularly (In a separate script (: )

 protected Vector3 PredictTargetPosition(GameObject target, Rigidbody targetRigidbody, float projectileSpeed)
    {
        
        // Estimate the time of flight based on the distance and projectile speed
        float timeToImpact = Vector3.Distance(transform.position, target.transform.position) / projectileSpeed;

        // Predict the future position of the target using the current position and velocity
        Vector3 predictedPosition = target.transform.position + targetRigidbody.velocity * timeToImpact;

        return predictedPosition;
    }```
#

Any help would be greatly appreciated!

dusty wigeon
# hoary yew Hello everyone! I'm currently trying to predict my targets position using rigidb...

whether it's recess basketball, captain blubber's shenanigans or the alien kangaroo invasion, having an aimbot is always useful

0:00 Intro
0:21 Basketball
1:20 Basketball Maths
1:54 Captain Blubber
3:41 Captain Blubber Maths
4:06 Captain Blubber Part 2
4:49 Space Kangaroos
5:24 Space Kangaroos Math
6:05 Root Finding Algorithm
7:28 Finale

White...

▶ Play video
hoary yew
hoary yew
honest furnace
#

does some1 know a salution my player is a prefab and i have: public GameObject inventoryObject; where i need to put a ui on but i cant if i do i get a type mismatch does any1 know a salution?

inland knoll
lament salmon
inland knoll
#

Oh, alright!

lament salmon
#

That particular panel is drawn with Handles.Label with a custom GUIStyle IIRC

left quiver
left quiver
#

I'm not sure really. If I load the scene for the first time everything works fine but if I go to my main menu and return to the game my player can't move etc. I want it to load like it loads the first time around.

austere jewel
#

Any static variables will not reset, and anything that is DontDestroyOnLoad will also not reset.

left quiver
#

alr, will have a check

grand dagger
#

hey so what im trying to do is make an object stay in its absolute position, and what i mean by that is for it to stay in one place on the screen not the game window, here is some poorly drawn pictures in paint to help understand.

silk trench
#

That being getting the position of the window

#

Then it's just a little bit of math from there

tribal ridge
#

I've got a snippet of code here that I can't figure out. It's in a while loop, but it breaks out at a yield return statement. I can't figure out why it does that. If anyone can explain how it could be breaking out of that while loop I would really appreciate the help ```
while (true)
{
destLoopIterations++;

            checkMatchesAgain = false;

            var destroyItemsListed = field.GetItems().Where(i => i.destroyNext).ToList();
            if (destroyItemsListed.Count > 0)
                yield return new WaitWhileDestroyPipeline(destroyItemsListed, new Delays());

            yield return new WaitWhileDestroying();
            yield return new WaitWhile(()=>StopFall);
            yield return new WaitWhileFall(); <- It's breaking out here !!!!!!!
            yield return new WaitWhileCollect();
            //yield return new WaitWhileFallSide();
            var combineCount = CombineManager.GetCombines(field);
            if ((combineCount.Count <= 0 || !combineCount.SelectMany(i => i.items).Any()) && !field.DestroyingItemsExist() && !field.GetEmptySquares().Any() &&
                !checkMatchesAgain)
            {
                break;
            }

            Debug.Log("got here 6");

            if (destLoopIterations > 10)
            {
                foreach (var combine in combineCount)
                {
                    if(combine.items.Any())
                        combine.items.NextRandom().NextType = combine.nextType;
                }

                combineCount.SelectMany(i => i.items).ToList().ForEach(i => i.destroyNext = true);
            }
        }```
#

it's breaking out at WaitWhileFall();

#

But it shouldn't be able to do that right?

#

The whaitwhilefall function is does not have anything that would break the loop that I can see

#

There's no errors saying something went wrong when i run it either

#

I was thinking maybe I didn't understand yield return statements enough or something

north tundra
#

Not sure if this is considered enough to be advanced, but can anyone help me figure out why my Perlin noise implementation is giving me strange results?

#

If anyone needs info on the way I implemented random numbers, I can provide that, but based on my tests it doesn't seem to be the issue

#

When I apply the noise to the Y value of verts on a plane, I get this:

untold moth
#

Just to see if the issue is with the noise itself or the way you map it to the vertices.

tired fog
#

I've been working with Jobs and Burst compiler for a while and I feel like i never know enough to optimize it, does anyone have any good tutorials /documentation to better know about the methods available and different techniques to apply?

tiny pewter
fickle mango
north tundra
sacred epoch
#

!code

thorn flintBOT
sacred epoch
#

Hello, i need urgent help, highly appreciate if some can help

https://gdl.space/uxaqipoxil.cs
https://gdl.space/niyijodewu.cs

these are 2 code for 2d chess game, my Rook chess piece, highlight the legal moves correctly but when a chess piece comes in the path it highlights that tile as well, how to stop highlighting tile if there a chess piece comes

tiny pewter
#

i think it is not advanced topic
BTW Chess is turn based, and i assume the highlight function is showing the valid movement (the tiles) of each chess, so why there can be chess moved while not during its turn....
Or i misunderstand, the function cant handle highlighting correctly....

#

Actually i suppose there is some abstract class eg ChessPiece and each type of chess piece eg rock, knight has an overload method to highlight different valid destination
rock:
started from its position(x,y) having four for loops from x-1 to 0, x+1 to 7, y-1 to 0, y+1 to 7, check if there is any other pieces (at that point the loop must breaks), highlight that tile only if the piece is opponent

sacred epoch
static vessel
#

Hello. I have a question about Vivox Participant Tap.

I'm using a script to create participant tap on joining the channel but I want it to set their positions to relevant player objects in order to make 3D Audio. How can I achieve this?

(I tried to make it in positional channel but it doesnt work for me)

untold moth
north tundra
# untold moth Is there any reason you don't want to use the built-in noise? I'm not very stron...

For this particular project, I plan on using different types of noise in different combinations to create landscapes, and so I figured it might make more sense (for standardization and cleanliness) if I implemented all of the used noise algorithms myself. I have considered giving in and using the built-in Unity noise, but the thing is that the Perlin algorithm isn’t actually too complex or difficult to understand. I understand it myself to an acceptable degree, it’s just that my implementation went wrong somewhere and I can’t identify where.

#

It’s in JavaScript, so I had to adapt it to C#. Presumably the bug is occurring because it got lost in translation somewhere.

untold moth
#

The simple advice would be: don't reinvent the wheel.
Even if you need to use different noise types and/or blend between them, there's absolutely no need to implement this particular noise yourself.

#

Also, if you really understand the implementation, it shouldn't be too difficult to apply it in C#.

#

But generally, looking at the result screenshot, I'd just guess that you're supposed to sample points within some range and you're going over it.

#

Perlin noise always has the same value at the corners.
And it doesn't seem like the implementation accounts for sampling outside the specified range. Didn't look to deep into it.
My final verdict:
Use an existing implementation(the one provided by unity or one that is thoroughly documented and doesn't require translating to a different programming language).

obsidian glade
obsidian glade
#

you've also flipped this:
float xf = xCoord - X, yf = Y - yCoord;
in the js code xf,yf are in [0,1], here you'll have yf in [-1,0] - it's not clear exactly what effect this will have, but it likely wont play nicely with the ease function that is supposed to be mapping [0,1] -> [0,1]

brittle charm
#

I have a bunch of game objects that are moving upwards on Y axis let's say. How can I make camera track the top one? It may change as objects move with different velocities at different moments. Simply going through list of transforms and getting one with max Y each frame seems inefficient

tiny pewter
#

Sad, but this is the only way, since maintaining a ordered structure requires at least nlogn time complexity

#

but getting maximum can be simply multi threaded

brittle charm
compact ingot
#

Well, so long as you don’t sort them and just find the top one you stay in O of N and iteration without moving memory around and simple float value comparisons (finding a max/min) is so quick as to be irrelevant at your order of magnitude (10-100 objects)

brittle charm
#

Yeah you're right

#

when tf did i become optimization obsessed nerd trying to O(1) every algorithm

harsh lion