#archived-code-advanced
1 messages · Page 88 of 1
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.
I have a computer shader that takes a density array and gives me a triangle array back
Marching cubes
Go on.
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)
Ok, so the issue is not generation of the mesh, but editing it with a brush? Do I get it correct?
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.
I checked the buffers
Everything is right
But why does the generation work called with OnValidate But otherwise it is broke
Does OnValidate behave differently?
The code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
On validate is very specific callback. It shouldn't really be used for anything other than validating changes in the inspector.
Does it work with OnValidate and breaks otherwise? And what is the "otherwise" that you're referring to?
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.
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
It's possible if you get the path and move the character yourself instead of delegating it to the agent.
Trying to push particles away from each other in Sjuriken with this job but instead they wobble at the emitter, even if I remove particle.velocity = newVelocity. Anyone can help me with that?
https://pastebin.com/50mFx3xy
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
anyone have good videos on code architeture for 2d games?
and how owuld i move it myself not using the nav mesh agent and not using nav surface?
You do use the nav surface and the agent to calculate the path. And you can move it in whatever way you want: transform, rb, character controller.
From the brush
What is "from the brush"? Where is the brush code executed from? Where is the entry point?
Share the code properly, so that we can see it.
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
You never shared enough info for us to answer that question.
ik sry
the problem is that i tried to save float4 in float and then i run out of space
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?
you worry when you go past 5k units for when your camera starts to shake because of floating point precisional errors
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?
Yes, addressables can help with this. If you try and load a whole 5kmx5km game world worth of assets at once you're going to run out of memory really quickly.
As a solo developer, I'm not expecting you to have high resolution asset and I am pretty sure you potentially can have all your asset in memory. (For the PC platform)
What is the size of your world for reference in km ?
And how much variety you expect to have ?
Also, what your art style would look like ?
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
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)
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
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?
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.
can you copy and paste your code so that the text is in here instead of the screenshot?
while this is accurate, they are instantiating it correctly. for n4go you instantiate then call Spawn on the NetworkObject component which is what they are doing
i apologize i should read my own docs
my conclusion is that the api is horrible lol
go ahead and share a more comprehensive snippet because ther'es nothing wrong with this code
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.
client rpc would mean the server is telling the client(s) to run code, you shouldnt need it. You should check if the object is in the network prefab list, and try to see if it does exist on the client but is disabled/not spawned
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. 😭
when you test, add debugs because it can be confusing where code is running (client or server). You should see if the server even runs this code in the first place, like is this a network behaviour?
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?
Yes, as mentioned above, the script is Network Behaviour, the prefab has network object component and network transform component, and the server sees the objects instantiated by the clients.
#archived-networking
but also it's probably just not in the right location on the clients rather than being invisible
ok, thank you, I'll check these things tomorrow
does anyone have a script that allows you to export an object's geometry to a file?
why does the exported fbx crash everything I try to open it with?
¯_(ツ)_/¯
not really a code question btw
this is more #🔀┃art-asset-workflow
yeah ig
it just became one
the object only has geometry at runtime, so I need something that can export the geometry at runtime
You can use this https://github.com/atteneder/glTFast
works great... for everything else
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
i'm working on editing this to convert an sdf to geometry https://github.com/keijiro/ComputeMarchingCubes
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.
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)
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.
So just re-rereading what you're saying, there could be something changing the data as its only there as reference.
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.
Hey thank you so much, its what you said about the reference data pointing to the same part of the memory that was the issue. I was adding the objects before fully completing the array process. so the because the data for re-parented to the array container, it mutated the structure in the stack.
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?
https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-of-an-object-in-net
I suggest you dont use reflection if possible, write your custom solution
Thanks for the suggestion, i'll through that.
https://leetcode.com/problems/clone-graph/
deep copy is travelling on a graph
Can you solve this real interview question? Clone Graph - Given a reference of a node in a connected [https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph] undirected graph.
Return a deep copy [https://en.wikipedia.org/wiki/Object_copying#Deep_copy] (clone) of the graph.
Each node in the graph contains a value (int) and a ...
Thank you.
worth noting on unmanaged data it's as easy as a simple memory copy. marshal and memoryMarshal classes have the necessary tools for that.
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?
can someone help me to speed up my jobs in unity
Show your code, say where is the slowdown and maybe someone will know a way to speed it up. https://dontasktoask.com/
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?
Are these types all subclasses of a parent class or something? You might look into SerializeReference
Use SerializeReference maybe ?
awkward example of what im pretty much doing
https://hastebin.skyra.pw/afiluyamuh.csharp
and atm it isnt a subclass of a parent
also what would serializereference do for me here?
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.
yeah thats pretty much what im doing right now, just serializing the class instance into a json then deserializing later on
Finally, you have the option of using ScriptableObject as well.
Using Json would be better than using a dictionnary
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
None of my callbacks are firing. Im not getting any errors or exceptions. Did I not subscribe to the events properly? What gives?
What's the context here? Which network framework is this?
Dumb question but where are you running this subscribe function from
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.
Sorry for the delay. I’m running it from a few other methods. One creates a lobby and the other joins an existing lobby.
It has to be built against .NET Standard 2.1.
Damn. Figured as much but didn't know for sure.
Especially since Unity has a lot of dark magic in the backend.
Cheers for the answer.
I really wonder when Unity finally moves to CoreCLR
Are you running it on the main thread?
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?
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
given how tightlipped they are about it on the roadmap, i wouldn't expect to see anything in alpha until the end of next year at the earliest
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
I can agree with you there, but Unity has always been really late.
Wouldn't surprise me if it came really late, but I truly hope it will come anytime soon next year 🙂
The thing is, once they make this next jump, they will be able to keep up with .net more closely, it's the mono baggage holding them back now
sure, but that doesn't change that there'd be years spent on the current language version and performance status. Given it'd be 3-5 years then for an lts release to happen, that's time the competition which already is on core clr can use to draw users away
I mean, it would change that. Not sure what you mean. Once they jump from mono
Edit: Oh, you mean the time it takes to GET to the point where they leave mono behind? Yeah, I get that
yea
At one point Josh said, they've successfully internally implemented CoreCLR for in-Editor only.
I just want Unity to jump to NAOT bandwagon, all other engines already take advantage of this
For sure! I do wonder if Unity use Reflection though - If it does it could be a problem.
Probably not since the engine is mostly C / C++
The unity methods (start, awake, update, onenable, etc) are collected via reflection iirc
I thought they were C / C++ voodoo
TheMoreYouKnow 😛
NAOT?
IL2Cpp is the solution for environments that disallow JIT like iOS, NativeAOT would also solve that problem.
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
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?
sounds like SIMD
Those break platform compatibility, intrinsic means they are effectively executing instructions that are specific to a given CPU architecture. It’s one step lower level than the vector compute (simd) abstraction from the .Numerics namespace that makes that same stuff cross platform.
Josh said that they haven't looked at NativeAOT yet. NativeAOT probably isn't quite ready yet to replace IL2CPP, especially considering the browser platform which relies on Emscripten. NativeAOT-LLVM branch is active though, so there should be a path available. I imagine Unity would like to offload IL2CPP work to the .NET group.
Yes
Oh, okay. So is the Numerics namespace useful for game-dev ?
we have unity.mathematics
it would be, but every single gfx library ports brings their own math types. That means you have to do some pretty heavy computation before you outweigh the cost of copying all the values when its time to render
so usually its just for ai-heavy stuff or scientific compute
Oh, okay, thanks! 
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hey guys
can you help me to speed up my code?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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:
that data exists on the gpu and you never copy it back to cpu
so is setting shared mesh just some gpu reference?
and how do i get the triangles back from the gpu?
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
frankly, I'm not sure how this stuff works. Most of this code is from https://github.com/keijiro/ComputeMarchingCubes
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)
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
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!
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
alr ty haha
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
Windows?
did you read the stacktrace?
yes
trying to decipher it. So it's just essentially the 'hierarchy' of functions that led to the error? E.g. A was called from B which was called from C, etc.
Take a look at the Windows Event Logs, they may contain additional debug info
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>
=================================================================
DestroyImmediate?
no idea what it's used for
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
DestroyImmediate should not be called outside of Editor code. And, btw, why are you not working from the source code
hang on what do you mean by the second line?
This stack trace is obviously from compiled code
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
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
no idea, there's some super complicated code that I've only just begun to figure out, the guy who made it has dropped out of the project due to mental health issues and also being a dad
you are missing the point. What I am saying is it is not source code in your project generating this error
okay I think I need to double-check what a plugin specifically is to make sure my definition is correct and I know what to specifically look for
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
wait hang on so what bit actually tells you that?
all of it
so is the whole layout different?
yes
ah
methinks you are considerably out of your depth here
this is my first industry job and I have nowhere near enough support from people who actually know what they're doing
but this stuff isn't going to get done otherwise
so I have to learn it
Don't feel too bad, this stuff is very tricky even if you do know what you are doing
it'll help me get ahead in the industry
Aha! I found a use of DestroyImmediate in an OnDestroy() function
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
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
yep that's already the code I've been checking for several hours
using breakpoints and stuff
Aren't stack traces wonderful things?
but for some reason it took me this long to really look in-depth at the crash logs
yeah I use them all the time in the editor
to check where a function is being called from
if you change DestroyImmediate to Destroy it will probably throw an error as well so wrap it in a null check
that's the one
I may need to actually change it and try it tomorrow morning
because it's past midnight
you certainly need to change the DestroyImmediate to Destroy
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
replace all of them
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;
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.
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?
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
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
could you show us some code?
ufff
its some 450 lines of code
I can create some paste bins to share you interested?
create a single pastebin and link it here
whats the best site? pastebin.com?
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);
yep
oh... quaternions... the EVIL
https://pastebin.com/yHQaQJXN
https://pastebin.com/JE2fUn7w
https://pastebin.com/6MsxkdTp
https://pastebin.com/vuKsX1ve
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you 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
you gotta look for the profiler modules
not the hiearchy view
so you can see frame by frame what is causing what
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
thats caused by the generation of the map
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
Gradual rotation is a separate concern. Figure out the correct target rotation (for example with my suggestion) then interpolate towards it with Quaternion.RotateTowards or Quaternion.Slerp
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.
Thank you, I've posted in the webgl channel. I have made functions in jslib but not sure how to access the functions outside of the unity build
Keep questions visible in a single channel at a time.
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 ?
Except for statics not really. Another way to speed up compilation time is to split your codebase into relevant assembly definitions.
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
Basically yeah
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
to keep this example of my case, to save time should i just create a AD in my script folder with everything related to my player (mouvements, inputs) ?
so i save time when compiling, because when i reload it will only reload this AD and not all the other unity stuff (if nothing was updated)
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?
Is there anything at all relevant in the log?
There should be some error and/or stack trace even if not from managed code.
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
This is probably still related to destroying an object.
What components are there on that object?
If you mean the thing that was being destroyed using DestroyImmediate, it's a Mesh
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
Meshes are not collected by gc
probably double free
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
Glad you resolved it
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.
Calling that is unnecessary if things have been correctly destroyed, it's practically just an expensive fallback
hang on in that case what do you mean by 'correctly destroyed'?
UnityEngine.Object types should have Object.Destroy called on them when you're done with them (or DestroyImmediate in edit mode)
yeah the problem is that running Destroy or DestroyImmediate on the mesh causes the whole program (and editor) to crash
It's probably due to when you're calling it, or it's a bug
yeah that'll be a massive pain in the arse to figure out
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
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 😕
you can get the correct StackFrame from the StackTrace class
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace?view=net-8.0
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
What potion?
I'm not sure exactly what your problem is (there's a million little settings in the inspector for the navmesh, agents, etc that can cause undesired behavior) but id recommend working from the beginning with the simplest script you can create and then build up your functionality, testing your additions along the way. And use gizmos and debug lines to visualize what your agent is doing
Can I use Import Package dialog window from code?
probably a better question for #↕️┃editor-extensions
may i hop in vc with someone to help me fix a very specific problem in screenshare?
Thanks for gaettinb back to me
THis is what hte NPC is doing
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
looks to me like your Animator is controlling the player
it's probably overwriting whatever the NavMeshAgent is doing
I am not sure I follow. The NPC sees the player and all I am doing is resetting it back to 'Spawn position'
disable your animator
see what happens
sure. 1 sec
well that seemed to work 
but now the question is,, WTF
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
Spot on. I appreciate this very much. Thank you .
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;
sorry to be a bother but your last suggestion was really solid. I am struggling to get the NPC to rotate correctly.
The NPC spawn rotation is stored on start and upon getting back to it's position I try and reset the position but the AI is doing it's own thing again.
have you tried cinemachine?
you are sophisticated. you will really like it
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
);
}
}
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 😦
not really an advanced issue. but do you have an event system in the scene and a Physics Raycaster 2D on your camera?
oh uhm, its an item that drops that once collected becomes static and is put above a ui slot, what im trying to click here is the ui slot right below that item.
AFAIK all it needs is a collider 2D no?
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?
its not ui, it gets placed in the ui when the item is collected but back to a Dropped item in world when its not
i wasn't referring to the item, i was referring to the slot
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
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
oop i meant chatgpt *
i can screenshare if you want!
well chatgpt is very frequently wrong and now you see part of why
yep! I never ask it to do code i mostly use it to get an idea of "how to"
but it hasn;t been helpfull
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...
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
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
myTime += Time.deltaTime * movementScale
Even better, just use cinemachine and blend between noise profiles https://docs.unity3d.com/Packages/com.unity.cinemachine@3.0/manual/CinemachineNoiseProfiles.html
Generally if you're doing camera stuff and you're not using Cinemachine, you should be
that's not really going to be different since that's just a manually created time.time
why would it not be different
because it already uses time.time??
It's not using Time.time, it's using a scaled Time.deltaTime
never used cinemachine before but heard its very powerful. guess i should be
speghetti at this point
yeah unfortunately
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
jittering is still jittering
I have no idea what you're talking about, but the original question was how to scale time so it doesn't jump around
anyways i'll look at cinemachine
The answer is to track time yourself, and added the scaled time difference, ie. add scaled deltaTime
that wasn't the original question but ok
I have no idea who you even are, so 🤷 you do you
wth does that have anything to do with anything ☠️
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
I'm the one who wrote the code, I work with squidy
im just trying to ask questions not start an argument 😭
Then maybe rephrase the question so it becomes clear why my code answer wouldn't work, because you're probably just misunderstanding it
the question was how to move along the graph at the speed of movement speed instead of scaling the graph based on movement speed
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
Hence my answer.
ok thank you sorry for the confusion with ender
dont cross post, but yes it is widely known
I wasnt sure about which category to post in, can delete
definitely not advanced
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
Looks like you might be using a particle texture, which is a circle. That's what a stretched out circle looks like.
try setting the texture scale really high or really low and see if you get a fully collored low-poly line
maybe I should also change the texture mode?
also what material should I use then?
look like standard material doesnt work on particles
this is with a scale of 10
This isn't a coding question. Use a texture that is solid.
omg sorry I thought to be in the vfx channel .-.
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!
That's how most people do it, in what way does it not work?
Make sure your linerenderer is in the correct space (local/world)
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
Very unlikely
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?
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
Dang, that was it. Thanks!
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.
Does anyone know what returns from Touch
unfortunate friend thanks for the answer, i prefer to mix OOP and Functional Programming
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
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?
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
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
Then typing out a million lines to avoid a loop would be even sillier
can you please answer the question (if you know it)
I did
the million object one?
The answer is the same regardless of how many lines you have
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

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
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
unrolling is faster
and you hard code the value, save one register
and no branching if you hard code all the things
cool thanks
The runtime (or compiler) might even do loop unrolling for you
So it's hard to say if there's a definitive answer
damn
Besides, these questions are so vague that there's no way to properly measure since it depends on a 100 different variables
for-loops perform bounds checks to ensure that the loop index stays within the valid range. So the hardcoded on would be faster.
But you should not care about this... it's too silly
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
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
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
wishful thinking, the compiler is not that clever
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
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.
Are you just trying to zoom the camera?
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.
Is this in VR or something? Because without stereo, there's nothing you can do to the camera projection to make the scale look different. The only difference would be how far the camera moves relative to the world.
Just kinda sounds like zooming/moving the camera closer/further combined with a depth of Field postprocessing effect
The bigger concern would be modifying physics behaviors
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
I do have VR to tackle later, haven't researched that part yet. And yeah maybe there is just no way to do that in "flat" rendering, which would explain why no amount of weird formula is doing something I'm satisfied with. Crap.
Modifying depth of field can also contribute to the scaling effect
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?
Reflection is your friend
For something like this, where the generated code is dependent on a Unity asset, it would be easiest to just write the code generator by hand, as in piecing the source code string together and then writing it to a .cs file in your project.
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.
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";
- clicked on the button in the editor
- the data was pulled from the scriptable object
- and it became like this
/* App constants */
public const string AD_INTERSTITIAL = "new_value";
public const string AD_REWARDED = "new_ new_value";
shall we take this to a thread?
Okay
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.
I got a similair problem like that once. I fixed it by drawing a line from the player/target to the enemy. If the line touches an object first (you can work with layernames or tagnames), then the enemy knows it's safe and won't the player/target shoot.
It's not exactly about the shooting part. It's about finding the nearest cover to the enemy which the player is close to. I'm trying to make them like go against a wall or behind a box and peek out & shoot like in GTA.
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.
the projection matrix does not really change the sense of scale. an ant has a FOV that is greater than a human's, which is what a projection matrix is. however its "camera" (eye) is located very close to the ground, and it can get very very close to things
try to first write the function signature for what you want to do
So like write pseudocode?
you can start with pseudocode, but i think there's a lack of clarity of what values go in, what value goes out
by the time you write this method signature you will have 90% solved your problem
have you tried getting the vectors of all possible points and calculating from there?
I haven't done anything yet. That question was more of a "How would I go about doing this" question, since I didn't really know what to google nor did I have any good ideas of my own
does your system already include something where it calculates where exactly(all the possible points) the NPC can go for cover?
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
Nope, I don't have that yet.
On bigger maps with all sorts of angles and stuff tho, this seems very inefficient to me
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.
he basically says the same thing i say
I personally achieved that by reading the NavMesh triangulation and generating cover points according to the edges. This happens at runtime when the game starts/map is generated but can be baked in editor too.
Then at runtime I get some near points and score them by visibility, cover, distance from self, distance from target etc.
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.
How would you know if the point is at a corner or just in the middle of a wall?
Does it have to be a corner?
The enemy cant peak if it's in the middle of the wall I mean
Yeah ok, do you use a NavMesh?
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
I loop over the edges in the NavMesh and bake a "visibility score" to a few directions from each generated point
That's also pretty interesting
I'll see what I can do tomorrow
I like to visualize this kinda stuff, easier to develop:
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
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.
select the library in the project view and then in it's inspector select the build platforms
So I right-clicked on the folder that will be excluded, what's next?
not the folder the library itself and who said anything about right click?
As far as I understand the "Project" view is a set of folders
and folders contain files
yes, so how do I get to the inspector you mentioned?
This is one of mine.
In the folder select the library, that shows the inspetor
Oh, I see. Doesn't cover my case though unfortunately, as platforms there are just platforms, not "Subtargets" (e.g. any platform could be a client or a server). Is there any other option?
will look into "Define Constraints" there
but you said you wanted to exclude for Android, so select include for all platforms except Android
No, I already completed exclusion as I said, I want to avoid an exception that says "Something is missing".
The exception is thrown for no reason right at launch (I don't invoke the methods from the missing library)
the exception is thrown in real android builds, but when building "android" and running in editor, it runs fine with libraries excluded correctly
sounds like you need to increase your code stripping level
or switch to IL2CPP backend
Hi. my game lag in editor
why I have 100ms of update?
50ms of shaderGUIUtility?
with deep profile
thanks, I tried it, didn't help, unfortunately.
Seems like I'll have to exclude "using" and calls to excluded libraries via #if UNITY_SERVER even from components that are never added to game objects in client builds for Android specifically😦
Look at what class is calling that.
Your material count is also increasing disturbingly fast.
It may be easier to see in the profiler's hierarchy view
The editor might be spamming warning logs about that vector property not existing in that material/shader.
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
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"
First call from the job. There was nothing to batch it with, since it was the first batch apparently.
What are you trying to achieve anyway? Sounds like you're doing premature optimization.
but it wasn't
How do you know that?
because the previus call draws half of the tiles
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.
I want to use materialpropertyblock, but if i do 80 becames 500
Why do you want to use it?
i read that for multiple simple objects like my floor tiles it works better
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)
true
You still didn't explain what you're trying to do..?
How did you get the edges of the navmesh like that? Did you just call Navmesh.GetClosestEdge on each vertex and compare it to the position of the vertex?
Wait it's been a while lemme check
Oh that returns the edge points?
Actually yeah seems like I used GetClosestEdge also
Alright, I'll cook something up with that then
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
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?
But a vertex is the same distance away from two different edges
Since it is shared by those edges
An edge that is between triangles but not a solid/unpassable edge
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
You only want the outer edges. So the green ones here
You don't care about the passable edge between the tris
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? Whatsetare you expecting to run?
Ohh
@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
Makes sense?
Yep
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
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
I fixed the problem, sorry for not detailed more about, I will take care in the future to make more explicit what I need help for
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.
}
Yeah but make sure to normalize the perpendicularDir
So that dot product is in the -1..1 range
Oh right
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.
Wouldn't an edge qualify as an outer edge if the center's distance to the closest edge is 0? This would eliminate the need for the dot would it not?
Looks like I also did a final NavMesh.SamplePosition check from the edge center before adding the edge. I didn't comment it so not sure what it solved but it's probably needed 🤔
Looks like I tried that first, but commented it out and used the dot product.
I can't recall the reason. You can try it though
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.
Actually, I think the reason is that NavMeshHit doesn't actually give you the indices of the edge's vertices. And the NavMeshHit's position is not in the center of the edge.
So you don't know if it's the correct edge or not. Had something to do with edges close to each other or something.
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 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
There we go!
Why do I need the center of the edge which was hit?
Oh wait, you were talking about a different thing than I thought, mb
Yeah. Are you currently using the dot product approach?
No, this is the distance check approach
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
This one was with the dot
At least it's working for now. I'll keep the dot check commented out if I'll need it
My issue might've been that I had multiple overlapping NavMeshSurfaces or something
Use the distance check if it works for you
@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
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?
This is the start of the conversation
@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
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
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
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.
nothing it's definitely doable
I have already thought about and discarded that idea. It'd be pretty tedious having to go and map out all the positions, and walls and stuff, mostly on bigger maps, plus its more adventureous for me to do it like this.
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.
yeah i mean, are you going to add geometry3sharp (or geometry4sharp the updated fork) to your project?
Probably not, I'd rather make these things on my own, however some time in the future I might, if I'll remember this.
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
What's your issue? I guided him to a working solution
How does it not make sense?
it is a long journey to figuring out how to remove the exterior edge or interpret it correctly for taking cover
hi everyone ima need some help
if the user is going to author it from scratch.
anyone here knows how to balance games
anyway you'd probably agree that the user should use a library
i'm not saying you're right or wrong about anything it's good that there's something that works
game balance is a design issue, perhaps you want to describe your game and balance issues in #archived-game-design if you need help with that
Why? What's wrong with the current solution?
I'm literally using it in my own game and it works well
You are implying that it is faulty
nah i actually need help in formulas
And that there's a need to rely on 3rd party libraries, which many people want to minimize, including me
you probably should give some more details and how exactly this is related to code..
balancing in itself is basically tweaking numbers
i think there are some more steps between what is shown in that screenshot and procedurally finding locations for cover
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))
are you trying to make an idle game
jk
you can write about it #archived-game-design
{
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
Yes, I personally generate some points along the edges and bake some visibility and cover data into them. I explained it to them before
yes lmao
Then at runtime you can query those points and score them according to distance, visibility, cover etc.
how do you deal with cover on the exterior edge of the navmesh
heard of inventory idle?
which is only cover if it's on a concave part of the edge
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
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.
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
You can see some of my personal debug info in this #archived-code-advanced message
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.
Tbh I'm not sure what you mean with 'dealing with the exterior edge'
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
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
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.
The whole idea is to have points next to solid geometry
Not just points that are not visible to the player
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
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.
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
Still not certain what you mean. It detects solid geometry on the exterior edges like it should.
Rectangles are cover points
okay well, there are definitely cover points there that will not make sense most of the time
if ever
Super minor issue
i think it will happen all the time. i mean look at my illustration
My thoughts exactly.
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
That's why the points have their visibility angle data cached. Like I said many times.
You query that at runtime
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
Hold on, how would your approach of setting the cover areas by hand fix the issue? You'd still have the exact same problem, but now you don't have the data to figure out the most optimal cover
I just recreated your illustration with my tester script of my system, and it works just like I want it to.
lol i'm not 100% sure! this is a really complicated problem!
can you move target to the right gradually? try to reproduce my illustration
In that case you had no reason to fight the approach which gave better data
you haven't actually recreated my illustration. it's essential that there be green dots on the border of the lower cargo container that are definitely not visible to the target but closer to self than the ones in the upper container
you have to reproduce my exact illustration
target should appear to be directly above self, but still visible to target
but i believe you
Directly above
(Ignore the missing edges, was messing with some thresholds)
there are a lot of spots that are closer that would be better cover
than the place it chose
The system seems to be working great, well done Osmal
Thank you
The heuristics do need some more tuning, but these bots are already wrecking my ass in game
i mean this would be the best spot no?
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
You can't shoot from there, my dude
i think we are moving the goalposts
Were not just looking for the furthest cover point from the player, but somewhere where the enemy could shoot
Did you really miss the part that it's a shooting position with cover, not just a cover position?
Yes, you certainly are
Seeing as you set up the goalposts I don't think it matters lol
well you can't shoot from the position it chose in that illustration either
Yes it can
It's at a corner...
how bout this - Osmal likes it. There. End. Finito.
in #2 in this picture
i mean it "can" "shoot" form there
the npc can move
However a step to the right would provide that ability. The point is that you can be in cover, but at the same time you can also shoot by peaking out
Even if you authored this cover you would still need a step in code to validate the things you are now arguing about
My NPC's can lean to left and right
That's why it looks like that. The green stick figure resembles the shooting pose
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.
"And now let's set the goalposts way over here"
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.
Well, I'm absolutely certain there are games out there that automate this
...maybe, but i don't think that would make sense
Well, you're wrong
just because something exists doesn't mean it makes sense
i'm not sure why that is an unorthodox thing to say
I'm about 100% sure GTA uses it
you know it's true
i would go ahead and message them and ask
i have no idea honestly
You think they mapped out every single place where you can hide? Behind cars who were moving at runtime and stuff
i think they might rely on a much simpler heuristic
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
Its shoulder would be visible to the target from there, when taking cover.
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
It also tries to keep some distance to the target, that's why it most likely prefers the point on the right
maybe the secnario is unrealistic. i think it's worth reproducing my original illustration exactly, which has self barely visible to target
rather than right there in the open
i don't know
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.
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
🤷♂️ 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.
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
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,selfis 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.
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?
Can you show show how you are calling it?
.GetType(); should get what you want
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!
I was wondering if that was what you were doing haha
Lol I've been programming for too long today
In this case, GetType() would not have worked as there is nothing to call it on. As component is null when you would want to get the type.
ah i am dumb, i mentally skipped over the whole null thing
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
How were you testing before? Your paths are all very fishy, including spaces and bundles existing inside Assets folder
Inside the editor and then building the project and testing with the built project as well
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
There's also a chance that something else is opening/locking the file preventing it from being accessed🤔
Some of them have spaces, and a lot of unity command line tools can't work with long file paths. You really should ensure those files are alphanumeric only, no spaces, and shorter (like 12 characters).
I'll try bringing the built project on the desktop or something
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)
well, the most intuitive thing i can do is make the paths relative to the game's build
it may work for development but also hate to distribute files like that
Yeah it's mostly a short term thing. Making sure the paths exist. If they do, they a shorter path. Just troubleshooting the steps of the problem first
That way we know if it is even the issue 🙂
makes sense, i'll try
Because if none of that helps, then no sense worrying about any of it
Same errors, different directory
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
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.
anyone know how to work with .awb/.acb files
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.
No, lambdas could be stored and invoked at a later time, by which point the ref parameter may not exist anymore.
using out should be possible?
the scope is limited and only be applied when you call it
Nope, out results in the same compile error
I know, but I am asking if there is a way to get the same basic behaviour 😛
If you must use lambda then no.
You could extract the logic inside the Action overload, and make both overloads call that
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 🤷♂️
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();
}
anyone here has setup github actions for unity ?
ok then tell where shall i ask this
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
#archived-networking Would probably be a better channel to ask in.
thanks
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 ?
You can convert the recusion into a for loop in almost every case as far as I know.
its a mix of a for and recursive
You can convert the recursive part in a while or foop loop
Share the code and someone might have an insight
its not mine but a friend
Then share his code
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 ?
so if you have no recursive there will not be to much callbacks ?
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
I most say that I have seen stack overflow in the past that was legit, but it was in iterating a huge graph.
ok ty guys
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
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
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
not sure what I did, but at least it compiles now,
does it do what you wanted? no clue what so ever...
public void Input<T>(string key, ref T value)
{
T localValue = value;
Input(key, (T newValue) => localValue = newValue);
value = localValue;
}
public void Input<T>(string key, Action<T> setValue) { /* ... */ }```
Thanks, but no, that doesn't sadly.
I'll flip W arry you one day 🤌
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!
The implementation of: https://www.youtube.com/watch?v=aKd32I0uwAQ&t=228s
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...
I also have the following if you interested
Hey thanks for this! This is insanely helpful for me. I actually have watched this video twice now but math is not my strong suit and I couldn't find the document explaining it like you have linked here!
I did the implementation, the actual document is https://docs.google.com/document/d/1TKhiXzLMHVjDPX3a3U0uMvaiW1jWQWUmYpICjIDeMSA/edit
Yes I saw this commented in your code (:
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?
Sounds like you're trying to reference a scene object from a prefab
Just a lil question, how did you make the panel which displays the info in the editor? Or is this in-game? Because I haven't been able find anything quite like that yet. Is this like a custom editor window?
Yeah it's a custom editor for a component that is just for testing different AI queries
Oh, alright!
That particular panel is drawn with Handles.Label with a custom GUIStyle IIRC
https://hastebin.skyra.pw/dikixatiwu.csharp
https://hastebin.skyra.pw/ekuwafukuh.csharp
does anyone know why this loads the scenes i want but doesn't fully unload and reset the scene i just left? i want to be able to leave the game scene then load it again and for the scene to act as if it's the first time loading it.
What's not resetting?
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.
Any static variables will not reset, and anything that is DontDestroyOnLoad will also not reset.
alr, will have a check
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.
You can do it but you have to write platform specific code by the looks of things
That being getting the position of the window
Then it's just a little bit of math from there
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
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?
The Perlin implementation itself is here: https://hastebin.skyra.pw/kepajolujo.java
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:
Did you try using unity perlin noise instead?
Just to see if the issue is with the noise itself or the way you map it to the vertices.
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?
https://docs.unity3d.com/Packages/com.unity.burst@1.6/manual/docs/OptimizationGuidelines.html
havent heard that burst compiler allows you set branch predicator....
yielding shouldn't cause the loop to break. Maybe the gameObject gets deactivated and that's why the coroutine stops?
It’s with the noise itself, cause built-in looks fine.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
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
cheers dude, thanks it worked
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)
Is there any reason you don't want to use the built-in noise?
I'm not very strong with the noise algorithm itself. There probably aren't many people that are.
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.
I used this page to drive most of my development: https://rtouti.github.io/graphics/perlin-noise-algorithm
It’s in JavaScript, so I had to adapt it to C#. Presumably the bug is occurring because it got lost in translation somewhere.
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).
you may want to show the shuffle you used as well - it looks odd to me that you're creating an array of size 1024, only setting 0..255, then "shuffling" it. On face value that's shuffling a lot of 0's into the 0..512 range you're using.
it's important how the js code builds that array, shuffle then double, and it's not size 1024
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]
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
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
How many objects?
Actually just 16 so that way is actually okay, but I was wondering if there's a better method for larger amount of objects
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)
Yeah you're right
when tf did i become optimization obsessed nerd trying to O(1) every algorithm
You could even run it every few frames (not evrty frame) and lerp if there is a change. At that point it becomes completely negligible