#archived-code-advanced
1 messages · Page 63 of 1
not strictly tied to post processing, just as an example
public GameObject Car_itself;
RenderTexture buffer;
Texture2D texture;
public void Create_Texture() // Creates Texture from one Material then Send it to Other Material
{
Material This_Object_mat = this.GetComponent<MeshRenderer>().sharedMaterial;
This_Object_mat.SetColor("_Color", Random.ColorHSV(0, 1, 0, 0.6f, 0.5f, 1, 1, 1)); // This Object's Material
buffer = RenderTexture.GetTemporary( /// <--------------------------<-----------------<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-<---------------<--------------
1024,
1024,
0,
RenderTextureFormat.ARGBFloat,
RenderTextureReadWrite.sRGB
);
texture = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false); /// <-------<-- AND MOVE THIS TO START/AWAKE VOID <<<<<<< AND MOVE THIS TO START/AWAKE VOID<<<<<<<-<----
Material material = GetComponent<MeshRenderer>().sharedMaterial;
Graphics.Blit(null, buffer, material);
RenderTexture.active = buffer;
Graphics.CopyTexture(buffer, texture);
RenderTexture.ReleaseTemporary(buffer); /// <--------------------------<-----------------<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-<---------------<--------------
Material Target_Material = Car_itself.GetComponent<MeshRenderer>().sharedMaterial; // Target Object's Material
Target_Material.SetTexture("_MainTex", texture);
}
private void OnDisable()
{
Destroy(buffer); /// <--------------------------<-- AND REMOVE THIS <<<<<<< AND REMOVE THIS <<<<<<<<<<-<---------------<--------------
Destroy(texture);
}
Hey guys, what are good things to do in an Update that wouldn't be possible anywhere else like fixed update or start/awake? I found these input handling, timers and raycasting. But I need more examples and nothing comes to my mind. Whatever I come up with could be done inside an IEnumerator or in a single frame
I don't think there is much you can't do in a coroutine that you could do in Update. This is a bit odd exercise.
What about smooth animations? Those could work better in an Update loop vs coroutine?
There's absolutely no difference between them in that regard.
Not looked into it but what about script execution order?
Say we have ScriptA and ScriptB with the execution order B, A
So Update in B runs before Update in A
Will Coroutines in A and B also run in B,A sequence regardless of starting sequence?
Coroutines are processed in Update as far as I know, and bound to a UnityObject instance like MonoBehaviour. So, probably
'm launching these expecting to create an unhandled exception but they are being treated as common errors (Debug.logError)
is it because im in debug mode with script debugging enabled?
Usually what should happen here is the type would be exception and continue with the method but its not happening
weird, if i do it in editor behaves as expected
Uncaught exceptions will stop execution of a script
Your problem definition is too vague for me to know what's going on
@devout coyote then what is this setting for?
Oh i guess thats just for exceptions happening outside of the unity SDK? native crashes?
No I think that's also for scripts
rider says is handled
how can be handled if theres nothing there to handle it??
is unity handling it by default ?
Even the CrashReporterHandler....
why i cant create an unhandled exception 🤣
why would you want to?
the runtime would terminate the program if it wasnt handled
i want to create an unhandled exception so i can test how Sentry differs before sending a report when is handled or unhandled so i can add logs or not in the report
i think the problem is the place im calling it
Make an unsafe null pointer and write to it?
now worked, accessed a scene missing reference and it was treated like an unhandled one
i was calling the other exceptions from a console plugin, maybe it has a wrapper somewhere that was catching the exception who knows
Should you use pointers? 
you should never use pointers or unsafe code in c# unless you really, really know what you are doing
Ah okay. 
if i have to modify properties in struct inside a unmanaged array, since is it not allowed directly modify the properties in nativearray (i.e nativearray[i].a=A;) so if i directly declare a T* and malloc it, will it faster than the "usual" way to modify the properties? i.e. T t=nativearray[i];t.a=A;nativearray[i]=t vs arrayofT[i].a=A;
You can convert the NativeArray into a Span or a pointer and index into it directly, without reallocating it.
If you're using NativeArray outside of Burst, then it may be faster to use it as a Span. But Burst knows how to optimize NativeArray.
i havent heard of span but i find NativeArrayUnsafeUtility namespace, thank
Anyone familiar with GPGS? I'm trying to implement a save/retrieve using GPGS, but I'm going a bit wrong... First, here's what I want
1. on startup, check if there are any games stored on the Google Play Games server.
2. if there is, load the game.
3. if not, do 3-1.
3-1. Parse the new class into JSON and save it.
4. repeat step 3-1 for each button press.
But... I've got a problem, I'm saving the new class if there's no game saved, but I keep getting NullReferenceExtension, if you know of any code that accomplishes what I'm trying to do, may I ask how you did it?
how do i ancer things
do you mean anchor in UI?
or possibly answer questions
im trying to load a texture2d image and put it on my maintexture and it isnt actually applying the texture i want but rather its making a new one, now everytime i look this up its always the same thing so im wondering if someone could help me with this issue.
Context?
You need to share more details
I know a substantial amount of people do delayed action in a coroutine. When the object is pretty simple, it works perfectly fine, but whenever it starts to be complicated such as CharacterController, it can become really hard to properly manage all those delayed action. The worst is when you have multiple delayed action that could happens at the same time.
A concrete example that I came across recently is a camera fade. (Multiple call to the fade method, Simultaneous call to fade in and fade out, etc.) All of that made the coroutine a real pain in the ass.
So i import the texture from my local path but this isnt the texture i wanted but it just took the data and made a new texture2d, how would i actually import the texture rather than making a new texture2d in script?
public void LoadTextureFromFile(string path)
{
byte[] fileData;
if (File.Exists(path))
{
fileData = File.ReadAllBytes(path);
playerTexture = new Texture2D(2, 2);
playerTexture.LoadImage(fileData); // Load the image data into the texture
}
else
{
Debug.LogError("File not found at path: " + path);
}
}
use unitywebrequest
sorry if i wasnt explaining better, but this was for loading a texture i already have not loading one from a site url
yes, never heard of the file:/// protocol?
nope
open a local .html file in a browser and look at the url it uses
o
alright well i tried this now but it still gave me a new texture2d image
yes, the one you read from disk.
Are you talknig about loading a Texture that is already in your project?
yeah
then your Texture needs to be in a folder called Resources and you can use Resources.Load
o
alr i'll try that
Bruh, i've been stuck on this all day. But it works, thank you!
How would you get the height of an object on a terrain?
For example I can get the coordinates of an object and then get the height of the terrain at that position, but the object has a different height in that position and I want to change the position of the heightmap at those coordinates to the position of the object.
terrain.SampleHeight(position); // More or less the same thing but it takes in a vector ```
These are the two functions being used currently Is there another way to do this without raycasting and getting the distance between object and terrain?
What is the issue with those function ?
@dusty wigeon It gives the the height from the heightmap where the object is at, but it is referencing the height of the terrain and not the height of the object. For example terrain is 10meters at that location, the object is at 15 meters height, it gives me 10 meters and not the height of the object which is 15.
You just need to do (transform.position.y - terrain.position.y) ...?
let me check...
also by the way, the height map is in normalized form so a double/float value between 0.000000001 to .99999999999.
I mention that because I would need to do a conversion there too.
You can probably use TerrainData.heightmapScale to get the range. https://docs.unity3d.com/ScriptReference/TerrainData-heightmapScale.html
I created a similar function for something else a while back and was hoping I didnt have to do that. You might be right though as the only course of action
I am not sure what you do not understand or expecting. This is pretty elementary. Maybe you should to ask in #archived-code-general
it doesnt seem that simple to me... as all other solutions that I've found refer to using a raycast downwards from the object to the terrain to get the distance and offset that way - this is simple. An advanced form of code would be the one we are discussing...
You want to use raycast if you dealing with more than a terrain
If you do not care about the actual height, but the height relative to the terrain, this is as simple as getting the height relative to ANY object/point.
I think I see what you are talking about the simplistic side of scaling/converting etc. I should have mentioned that I have a complex system that creates meshes and terrains and I was looking for a simple solution similar to the Transform.InverseTransformVector/InverseTransformPoint. I figured it would have been something unity would have integrated specifically within terrain functionality ***edit *** that gives your height relative to heightmaps
It is simple as it can be... It is 1 operation...
huh?
(transform.position.y - terrain.transform.position.y)
If you want the non normalize height, it is (probably) as simple as Terrain.SampleHeight(position).y * TerrainData.heightmapScale.y (if this is really normalized)
It is rough, but it works. You were right, I was overthinking it. My data will far surpass the floating point problems... so thus overthinking it. For now it works... lots of work to do though. https://www.youtube.com/watch?v=rbQvHiO4-CY
edit and yes... 1 operation fixed it. thank you
hey I just did an internal release and two of my testers got this:
How would one get the PhysicsShape2D of a tile
You mean the tilemap collider ? There is https://docs.unity3d.com/ScriptReference/Collider2D.CreateMesh.html
is the new class
Class newClass;
or
Class newClass = new Class();
wait mb idk why i come into this chat for the firs ttime and thats right ast the top
Okay, so when I declare a class called VS that is stored in the GameVariables, I've already declared it as new VS.
In [UnityTest] it is said that "yield return null" skips one frame. However this is not what I'm seeing (in 2023.1 beta). I have a simple test:
{
int yieldCount = 0;
var renderedFrameCount = Time.renderedFrameCount;
var currentFrameCount = Time.frameCount;
while (currentFrameCount == Time.frameCount)
{
yieldCount++;
yield return null;
}
Debug.Log($"Wait 1 frameCount required {yieldCount} yields " +
$"over {Time.renderedFrameCount - renderedFrameCount} frames");
}```
And it logs this:
```Wait 1 frameCount required 360 yields over 1 frames```
Is this expected or a bug or an issue on my part?
I read this as: it takes 360 yields to advance both Time.frameCount AND Time.renderedFrameCount by one.
The number of yields varies, and they are extremely high if I do the same in a IEditModeTestYieldInstruction class in the Perform() method.
I have a hunch that this is only true in PlayMode whereas in EditMode tests the frame updates are slowed down a lot. Although I did set the editor to "No Throttling".
wrong venue. !collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
is on the forum unity i just ask for a quik contact
I do not care. This server is not the appropriate venue -- especially not this channel, which is for asking about advanced programming in Unity.
Please, someone help me with this. I couldn't find the solution anywhere:
Trying to remove Hours (TMPro.TextMeshProUGUI) from rebuild list while we are already inside a rebuild loop. This is not supported.
Here's the piece of code it points to:
{
daysActive[child_index] = !daysActive[child_index];
GameObject child = allDaysContainer.transform.GetChild(child_index).gameObject;
GameObject child_text = child.transform.Find("Text (TMP)").gameObject;
child_text.GetComponent<TextMeshProUGUI>().color = daysActive[child_index] ? new Color(0.87059f, 0.31765f, 0.39216f) : Color.white;
GameObject child_time = child.transform.Find("Time").gameObject;
child_time.SetActive(daysActive[child_index]);
}```
Hi! Is there a way to built in/simple way to remove unused serialized fields from a material?
The single thread I found states that these are stripped before the dependency walk but I haven't dug in to confirm that one way or the other, yet.
Hello, maybe it's not the exact place to ask, but I'm looking for a system to be able to destroy a map.
In short, my goal is to reproduce a game you need to kill your opponent, imagine a Worms 3D like.
I want to have the freedom of making all the map/elements from blender or anything, low poly accepted.
For now I tested solution like voxel/marching cube one, it works for generation but not for using existing map without converting it.
So I found a "better" solution using and modifying an open source lib to cut mesh, I made a quick proto with it and the result is cool for testing the system but in the current stats, it's cutting a lot of objects an creating a lot of vertx/tri so from a simple test the fps will drops, a full game using this is not possible.
Probably cause of all objects getting rendered... so I'm trying to find a good solution to create a simple map and be able to destroy it on explosion in an efficient way to be sure we don't duplicate objects or vertices/tri.
I would like to know if there's other technique to do thats? Actually I'm trying the mesh deformation which is a way to simulate a mesh damage but still hard to handle the moment you remove the vertices or re-pos the triangles with a ton of edges cases.
Any help would be appreciate!
Trying to iron out this hiccup, wondering if there is a better way to wait for Async GPU readback:
Is the break ever reached there? Obviously if you're calling WaitForCompletion before it's done, it could take a while.
yeah that's the thing, trying to budget how many frames things are allowed to take but even with a crazy high budget i get them spikes
how would i check if the opponent is able to capture my king in a chess game without causing a stack overflow
ive tried so many times and every time theres a stack overflow
i think its because im checking the opponents legal moves in the same function that im using to check my own legal moves so its like overlapping or something
but idk
Calculating all the possible actions for enemy pieces creates an error ?
yes
Are you using recursion ?
You do not need recursion for 1 move.
^
Well the easiest way but kinda dirty would be to take your king position and check in direction if there is some enemies
For example if you have a rook on the line/column
And trying to find all the possible combination of all action is impossible to hold in memory.
so like make the king able to attack every square, and check each individual square if there is a certain piece?
Pawn in diagonal
It's not really clean because it's code related only for the king so like an exception in your code
But in this way you are sure you are handling the win/lose condition in another function
That you could test/debug easily
i dont have a win lose condition yet
i think that comes after making checks and stuff
Ultimately, you're not going to save much time by enforcing a frame budget here. I don't think calling WaitForCompletion will make it go any faster, apart from potentially lost time while waiting for the next frame to check its status again.
i might just handle checks in a completely separate script and see how that does
It's just an idea but with a 8x8 chess it's not really heavy to calculate the possible cases
this is like a #💻┃code-beginner kind of issue..
Just to be careful to not look for cases hidden by your piece
or you will loose at the first turn 😄
how would you do it to save that precious main thread from lockups?
Btw do you know why this issue is occuring ? The linerenderer is glitching when I am changing direction. Is it a known issue ?
How does it behave if you remove the frame limits and don't call WaitForCompletion? It shouldn't be necessary if done is true.
it freezes up
I have combined same voxels (faces) using greedy mesh algorithm to generate optimized meshes for chunks in my voxel game. Now, I want to be able to control the height of each voxel. In some situations, The height of a voxel (voxels have height 1 generally) can decrease until height = 0, then it should be removed.
My problem is that because I have used greedy mesh to combine faces, it is possible some voxels have been combined and so there is just one face (2 triangles + 4 vertices for each face), I cannot change the height of a specific voxel.
The only way is to regenerate that chunk again.
I think I should forget the greedy mesh combination algorithm and use a simple combination (Just remove hidden faces). What is your suggestion?
Hi,
I am trying to write a function which will take a vector3 lets say(20,30,40) and return a unit vector which I can use to align a gameobject such that its rotated 20degree in x , 30 in y and 40 in z. In following code, its working fine in x and y axis, but giving 0 in z
Vector3 angle;
public void UpdateAngle()
{
Vector3 newOrientation = Vector3.zero;
newOrientation.y = -Mathf.Sin((angle.x * Mathf.PI) / 180);
newOrientation.x = Mathf.Cos((angle.x * Mathf.PI) / 180)* Mathf.Sin((angle.y * Mathf.PI) / 180);
newOrientation.z = Mathf.Cos((angle.x * Mathf.PI) / 180) * Mathf.Cos((angle.y * Mathf.PI) / 180);
Debug.Log(newOrientation);
newOrientation.Normalize();
gameObject.transform.forward = newOrientation;
}```
Forgive me if I am not understanding what you want, but can't you just do gameObject.transform.rotation = Quaternion.Eular(angle.x, angle.y, angle.z);?
Yeah we can do that.
I was going through a tutorial series on gamedev mathematics and trying to understand it properly.
@sand wraith if you look at operator for setting transform.forward in source, it's using quaternion math behind the scenes anyway
so, you may aswell just cut the redundant steps and learn how to use quaternions <_<
is there a way to have different inspector icons for each copy of a scriptable object? I'd like to have my game items' images as icons on the scriptable objects
SetIconForObject changes the icon to the same image for every instance
Does anyone know of any resources on how to use GPU instancing with SRP?
Thanks in advance guys
Hey, what could be causing my OnTriggerEnter2D function to be called twice?
public void OnTriggerEnter2D(Collider2D other)
{
if (other.GetComponent<GroundMoney>() != null)
{
this.GetComponent<PlayerMoney>().AddMoney(other.GetComponent<GroundMoney>().MoneyAmount);
Destroy(other.gameObject);
}
}
Sometimes this gets called twice on one item.
The money collider is a trigger and the other is not. What could i be doing wrong?
2 collisions happen then.
Debug the current and other object/collider to be sure what is colliding.
yeah i did and the collision happens 2 times within one frame
On one object
Which is extremely weird
Cause in another object im using the exact same setup and it doesnt happen
How exactly did you debug? And what did you see?
If you are using the SPR Batcher, then you have to submit the instanced draw calls from script, either using the APIs in Graphics or in CommandBuffer. If you disable SRP Batcher, then Unity will use the same batcher as built-in, which will automatically use GPU instancing where it can.
@sage radish Okay, but let's say I use DrawMeshInstanced? That works the exact same way if you disable to srp batcher?
If you're submitting the draw calls yourself, then it doesn't matter what batcher you use.
Why doesnt it matter? Because it just works? or what do you mean?
I put a debug log in the OnTrigger Enter and it did it 2 times on the collision
Is there a way i can debug it better?
To see what is causing it?
What exactly did you debug? Did you debug the names of the current and other objects?
Share the exact code...
Honestly, this is not the channel where we should be teaching you how to debug...
Yeah, it will always work. The batcher only handles Renderers, not draw calls submitted from script.
any EditorGUIUtility experts around?
That actually sounds like a pretty neat idea which I'll probably look into in the future
Also try asking in #↕️┃editor-extensions
hey guys i am trying to da match 3 blast game like toon blast. I cant write the filling tiles algorithym. Does anyone know how to do it ?
Are there common standards for MVP UI in the industry? In particular, related to screen transition handling? What is the expected approach when a company wants MVP knowledge? A giant state machine for all UI? A bunch of navigation controllers whose sole job is to call .Show() and .Hide() on presenters or maybe views themselves(in which case views would create required presenters)?
There is no standard in UI as far as I know.
But there are standards in the Android and iOS community aren't there 🤔
Yes, for application. Not for game.
That being said, you can still try to apply those standard to your game.
But, a lot of them does not make any sense.
The problem is my brain melts when trying to read Android/UIKit code cause they got a shitton of concepts on top like activities, fragments and a whole bunch more 😄
By example, Android use MVVM principally
Not really an approach that is good for video game.
As you do not have a lot of input to make.
Hmm. Alright then, if we are talking theory wise, does .Show/.Hide API belong in the view(in which case the view will create and activate the presenter when instantiated) or in the presenter(in which case the presenter would forward the calls to view's own Show/Hide API)?
Is this a difference that could melt my lead's brain if I were to enter an MVP project and make the choice they didn't prefer?
Cause I'm stuck doing mobile game contracts(where they like overengineering) and so I'm trying to figure out the desired way.
If you are following wikipedia, it seem the implementation differ a lot. You can probably find both implementation.
MVVM and MVP are both kind of old fashion.
What's the alternative 👀
Component based, where each component is individually a perfect encapsulation of MVVM.
What do you mean ?
MVVM implies that you bind on individual field. That would require a considerable amount of boilerplate code or the usage of library.
Also, I do no consider MVVM a good approach in most video game as it adds a lot of overhead and is most of the time unnecessary as there is little to no input field removing the need of double way binding.
Not sure if you have experience with web frontend, each component drives its own behavior and your app is a tree of components interact with each other without a central brain, per se.
Also, in opposition to more classical way of doing UI where you have a far amount of UnitTest, in video game there is little to no UnitTest which makes it acceptable to have approach such as MVC.
I have limited knowledge on Web technology.
The boilerplatey ness of MVVM is indeed very unfun, in C# MVVM frameworks there are source generators dedicated to help with that issue.
This is a reason why I feel like MVVM is not appropriate for video game development.
Well it’s completely dead in web frontend, no one writes MVVM there already.
Component based like how web frontend frameworks do it
I've used a Unity library for reflection based MVVM binding, not knowing you didn't bind properties correctly until runtime errors start flooding the console is not fun.
This is under the assumption that you actually do need an architecture for your UI, most games have simple enough UI that you can do it quick and dirty.
you can strike a balance
So binding to the model and controlling widgets in the same class?
pick and chose concepts and use sufficiently simple and robust mix
I’m on mobile but here’s an old message to what it was like a year or so ago (it’s been improved even more over time with things like source generators) #archived-code-advanced message
Again, only if you need an architecture; my game’s UI complexity is basically to the level of most frontend apps, with 50+ components and 100+ screens for users to navigate around, this is the point where an architecture is absolutely needed to make sure you don’t start cooking pasta.
For most games that’s not the case.
Neat. So in your case let's say you have gameplay UI with a healthbar and stamina bar, would health bar and stamina bar be completely isolated widgets that check if they should hide themselves on their own? Or would there be a high level controller that hides all of them?
Or would widgets be attached to some sort of Screen concept and that Screen would be managed by something else (when it comes to transitions between screens)?
do these two influence layout of Vector3 in memory?
I added them to my C++ dll Vector3 equivalent but that broke the program 🤔
In my game, the bars would be dumb, they are responsible for displaying a bar and that’s it; the parent is responsible for deciding whether to show the bars or not.
And the parent would bind the bars to a value?
Yeah, it would be something like new Bar().Value(player.HP).MaxValue(player.MaxHP)
Everything (that needs to be reactive) in the game builds upon reactive primitives, so that’s all the code needed, when player HP updates, the UI automatically updates.
You don’t need to remember to “hook up a player HP change event and update the UI” and you won’t have issues with “when HP bar UI is destroyed I forgot to remove that event and caused a NRE”
Hmm. I found animated events hard to deal with with reactive UI in the past.
Cause sometimes I needed to instantly reset something and skip the animation.
For mine I just have a Tween() method, which takes in a reactive value and produces another reactive value with tweeting applied.
I mean like a UI panel appearing.
theories - different RTI, somehow the static instance layout is taken into account
You can build that with tween too, let’s say you have a button that toggles variable isHPBarVisible, to give it alpha transition the code would look something like:
var hpBarAlpha = isHPBarVisible.Computed(x => x ? 1f : 0f);
var tweenedHPBarAlpha = Tween(hpBarAlpha);
(Normally I would just write the above in one line, but split into two here to make it easier to understand)
And simply bind that to the HP bar:
new Bar().Value(player.HP).MaxValue(player.MaxHP).Alpha(tweenedHPBarAlpha)
And that’s it, a togglable player HP bar with alpha transition when you toggle it on/off.
I see. Now I understand your approach better. Though it doesn't seem like something I should bring into client projects due to being overkill.
The important thing here is that the UI code is declarative (I declare that HP bar’s alpha is derived from visibility variable in this way), rather than imperative (when visibility variable changes, execute this code that plays a fading animation), it is very important for complex UI to be written declaratively for it to be scalable.
Yeah definitely, most games have simple enough UI that this is unnecessary.
So I guess simplifying your approach would be simply smashing presenters and views into a singular widget.
@scenic forge wait, does your framework do explicit navigation from screen to screen? Or do you only have isolated screens that show and hide themselves?
Yes it’s like a whole browser, different buttons lead to different screens, and there’s even a history list.
Root component of the game is a Router, each Route can simply call Router.Push(new SomeDifferentRoute()) to navigate away.
The implementation of Router.Push is very simple too: do the tweening like above for the exiting route, then do the tweening again for the entering route, and there’s your transition animation.
What is a Route tho?
It’s like the content of a webpage.
Title screen is a route, settings screen is a route; clicking the “settings” button in title screen is just navigating to the settings screen route.
So the settings screen widget inherits from a route.
is it like mainmenu.settings.audio ?
so you can set the state by a path string if needed
Not how mine work, but that’s basically how routers in web frontend frameworks work: the URL is the reactive source of truth, and what route to display is derived from that.
When you change the URL to something else, router detects it and updates the displaying route according to it.
yo can anyone help me with this - I followed a guide on URP outlines using shadergraph, I downloaded the files from online and got it all to work however when I build the game and play it (it works in the editor though) it comes back with an error "ArgumentNullException: Value cannot be null.
Parameter name: shader" so the script that creates the effect uses the path (Hidden/"nameOfTheShaders") however Im guessing in the built version of the game it cant find this directory? I have tried changing the path in the code but it just causes even more errors.
If the shader is not used (in a prefab or in a scene) then Unity will strip it from the build to reduce the size on disk. You need to add it to the Always Included Shaders list (Edit > Project Settings > Graphics)
(Please forgive me if this is the wrong channel) I'm relatively new to writing shaders and especially with a local to world matrix, but here is the issue at hand:
I have a matrix4x4 in my shader and apply it directly the unity_ObjectToWorld. But I also want to apply a small local offset stored in a float2. Does anyone know what the best way is to approach this issue?
Update: I have the following code in Unity with Mathematics
private void OnDrawGizmos()
{
float4x4 ogMatrix = transform.localToWorldMatrix;
float3 ogPivot = math2D.float3(_pivot);
Gizmos.color = Color.green;
float4x4 matrix = ogMatrix;
float4 transformed = mul(matrix, -float4(ogPivot.x, ogPivot.y, 0, 0));
matrix.c3 += float4(transformed.x, transformed.y, 0, matrix.c3.w);
Gizmos.DrawSphere(matrix.c3.xyz, .1f);
Gizmos.matrix = ogMatrix;
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(-ogPivot, .2f);
Gizmos.matrix = float4x4.zero;
}
This pits a gizmos marker to the position of where I want it to render from, but it doesn't translate into the shader well, since mul(float4x4, float4) returns a float4 instead of float4x4 in Mathematics, does anyone know an fix for that? I have been experimenting with setting the positions manually but with no luck.
Hello, Which one is faster?
Calling RecalculateNormals method or calculate normals for each voxel?
If you can get it multithreaded using jobs/burst, definitely that.
Otherwise it depends on how you calculate the normals. RecalculateNormal is quite heavy, but writing exactly the same algorithm yourself will probably be slower
I made a guide on how to use Jobs + Burst in Unity. Does someone have the time to quickly look over it before I publish it?
Thanks, yes. I use job to combine faces. So, I can calculate and put normals easily there as well
Sure, I can.
My another problem is about regenerating chunks over and over.
In my game, workers can dig voxels. Therefore, I have to regenerate chunks
Awesome!
Your DMs are closed, so if you send me a DM I can send the details
For the chunk regen, maybe have an if else in the job.
If a distance to the player (or other pos) is greater then a treshhold, simply take the old vertex pos. For anything closeby recalculate.
For the normals, if you calculate the jobs in the background and get the data ij late update, the main thread might not even stall, making that a ton faster than recalculate normals
Yes
I just regenerate visible chunks
But because the number of workers can be large, it can take time.
Yes, all jobs are executed in job threads without freezing the main thread
is it possible for unity to take a screenshot when running it in headless mode?
im trying to do that right now and it doesnt seem to be doing anything
@burnt egretafaik all of the render stuff gets wiped out when you compile headless builds
doesn't mean it's not possible. Just probably going to be a huge pain in the ass
@burnt egretDepends what you're doing, but you could always have the server pack up data about the current scene
then it gets sent to a client
and client renders it
whether it's mobile, web, etc it should work
im trying to do some automation, i was thinking of trying to make a github action that would automatically screenshot of the scene and then add it to a PR as a comment
Alright now I know this is a shot in the dark, but i desperately need help. I'm running a playtest for my game and the release is in a week. There is a massive issue though. When you first start up the game for the very first time ever, it freezez or maybe its just taking forever to load? Then upon restart the game works fine. I have no idea if this is maybe some poor coding ive implement or something with maybe the build settings or assets having to load but this is obviously a terrible issue but im not sure where to start... (really no idea what channel to put this in so sorry!) Please help me save my game!
You can look at the profiler
it will tell you what's hogging resources
Build a debug build and connect the debugger. Break during the freeze and see what the main thread is doing.
ah interesting ok!
No idea where to ask this but I have been researching the A* algorithm for AI pathfinding for a game I am planning to make and I am stuck on what would be the best heuristic to use for finding a path through mazes that can be any shape including but not limited to squares, circles, triangles and Hexagonal shapes? If there are any resources I can look at please let me know. This is a game for mobile.
Your heuristic is just an estimation of the cost. It depends if you can even estimate a shortest path while guaranteeing that estimated cost isnt greater than the actual cost.
There really isnt a good way to estimate values for a maze. What values have you tried?
I imagine 0 or just the distance in a straight line from point to point should suffice
Does your maze have many solutions? Its been awhile since Ive looked into these things but i feel A* wouldn't be the optimal choice for performance
hi guys can someone help me with the udp connection thing im stuck with please?
I'm trying to receive a message from arduino through ethernet udp but I can't seem to receive any message in unity, when I test it with sockettest it works. this is my code in unity :
https://paste.ofcode.org/fvvhrk6r6LsrfQZAgr5mrf
and this is my code in c++ for arduino that sends message
https://paste.ofcode.org/iQxb4NJHKcKLTHWQYx7jsM
I intend to have multiple solution yes, I have looked at the Manhattan solution, but it may seem to not work as well for other shaped mazes than a square or rectangular mazes. Im considering Euclidion Heuristics. That may as well have a little over estimation tho.
Yea I didnt suggest Manhattan because you said circle, although I dont know how your maze works. Like if the inner walls are curved, then Manhattan will overestimate.
How would euclidean distance overestimate though? It is a straight line, how would you have a path that's faster than a straight line
If Euclidean distance is a straight line would it not interfere with winding paths?
I'm unsure what you mean by winding paths, but this is just for your heuristic. You can literally plug in all 0s and it will run
It just wont be good obviously if it's a bad estimation
It is the best solution I have so far as considering maze algorithms with multiple solutions and shapes.
You mean using 0?
Still I dont understand what winding paths means in this case. Heuristics are supposed to be an underestimation of the cost to get there. It's not the actual path it will try to take
Sorry, let me rephrase a straight line through a set of paths that do not follow a straight line. The purpose of the Heuristics I understand. It is using the best estimation for approximating the cost and therefor distance to the goal using the shortest path, taking into account for a variety of different shaped mazes and multiple solutions that I am trying to determine while keeping it performant for mobile as I need to run Least Cost Routing on top of the pathfinding for another system in the game as well. Important note I am still researching. All other test I have done with online simulations.
Having the euclidean distance wont interfere with winding paths, itll just set a slightly better estimation than all 0s.
The only better estimations that could exist would be if you solved part of the maze or knew more about the domain possibly and how it spawned. Like if you took how it spawned and could deduce that everytime, it would be at least X cost to get from start to end
The straight line isnt about having your AI take that straight line as a path, it's simply just getting the distance from start to end
Oh ok I understand thank you very much that helped 😀 a lot. I get it now.
i am looking for the best data structure for "visited" in grid-based a* path finding
for each cell in grid, it need three data: distance from source and parent cell (coordinate) and estimation. The "data structure" should provide a O(1) coordinate to values access
the most simple solution (and widely used) is a 2d (or 1-d flatten array) that same size as grid but it need (12+4)*(number of node) memory (there should be 4 padding byte but i am not sure) assuming the coordinate are two short, estimation and distance from source are float
another solution is Dictionary which may have smaller memory consumption depend on search space (O(2**search space*) memory ) but the access time will slightly slower than 2-d array.....
i want to run k pathfinding parallelly and that means i need k such data structure....
a dictionary has very little overhead and is the best built-in solution, anything that would be truly optimal for your implementation would need to be custom and effectively be a variation of a dictionary/hashmap too, just with a potentially faster hashing/de-collision algorithm
a 2D array is not particularly efficient btw, if you want speed you need to use a jagged or flat array
i have test jagged and 2d array
for random access (random i j) 2d array is faster
idk why maybe for jagged access row i have to load the T[] first then column j in that T[]
i have searched how [,] represented in memory but i find nothing
and i think if i implement my custom hashtable it always run slower than built in library since i think they write it on c++
i want to make ai dodge projectiles, meaning move away. an example of how i would want it to work: probably a projectile will have some kind of over time check that predicts list of potential targets, and when it finds any it gives them info. For a slow linear projectile that would be line and velocity, and then the unit would have to stay away from that line. then unit calculates all dodge options, in this case moving away in all directions, and ranks them based on how optimal they are. it either chooses the best or doesnt dodge at all based on that. I want to go even more complex but i'm already digging my grave with my ai aspirations. want to hear some thoughts on this
it sound a deterministic algorithm rather than ai
hey i'm tryna make a shader that gets its variables from objects instead of materials, since these values are gonna be unique for each object and i don't feel like having 1000 df materials in my repository, here's a shitty drawing to explain what i'm tryna do lol. please lmk if u know a solution i'm at a loss idk what to google even
the only solution that comes to my mind'd be writing my own renderer but there's gotta be an easier way to do it
it's fine shouldn't be too hard to implement u got this
Change the material parameters via code. It might not be great in terms of optimization assuming you're on built-in pipeline(I think srps can still batch them).
that won't do i think, the code will change the material for all objects wont it
No, it will create a new instance of the material, unless you're accessing it via shared material.
You can also pass them via vertex data.
what do you mean?
your algorithm will calculate cost for all dodge options in all direction and choose the optimal one, i think it actually backtracking
Anyone that can help me with this?
Why is this suggested?
UNT0024 didn't google properly
Oh, nevermind, I see now. One integer multiply + one vector multiply versus two vector multiplies
can u give me a bit more info on what do i look into
the approach @untold moth gave me doesn't really work for me cus i'd want them to be editable while not in play mode
it causes some weird leak when i run it in edit mode and all sprites get fucked up
Order of execution is faster like this, but in build it's the same speed, so I just always write the formula in the most readable manner
I swear I tested this a million times, this code works as expected in one scene, but in another scene only works if it's in the beginning of the Update(), and if it's at the end of update() it's like it's stripped by the compiler or something:
if (!( isDropping || isRotating)) {
isSpawning = false;
}
}
all 3 isSomething vars are public booleans which I can see in the inspector. isDropping and isRotating are in the same update, and if the object rotates or moves to a given threshold those vars are set to false; then isspawning should get set to false once they both stop animating.
If I leave the above code at the end of update() I can see in the inspector that isSpawning is checked as True, while the other vars are false.
Have you checked with the debugger or with a log that execution reaches this code block? Not necessarily enters the if statements here, but just goes over them until the end of the method.
The only way code would not get executed after some point would be that an exception was thrown at said point
Or a return; instruction was hit
I added the log with $"... {(( isDropping || isRotating))}" and it logs True as if one of the other vars were true, but at the same time I can see they changed to false and the logs I have in their respective if (isRotating and if (isDropping are not printing. It's like whatever fancy thing unity is doing with the serialized vars is going out of whack.
So it's not getting "stripped out" by the compiler after all, it's just not entering the if statements
How can you see that they changed to false, by observing the Inspector? Know that it has a small but noticeable delay updating the visuals after code changed
this is my full Update():
if (isDropping) {
transform.position = Vector3.SmoothDamp(transform.position, dropTarget, ref dropVelocity, dropTime);
if (Math.Abs(transform.position.z - dropTarget.z) < 0.01f) {
transform.position = dropTarget;
isDropping = false;
if (!isSpawning) {
EventBus.onPieceDropped.Invoke();
}
}
}
if (isRotating) {
rotationBlend = Mathf.SmoothDamp(rotationBlend, 1.0f, ref blendVelocity, smoothRotationTime);
if (rotationBlend < 0.99f) {
transform.rotation = Quaternion.Slerp(rotationCached, rotationTarget, rotationBlend);
} else {
transform.rotation = rotationTarget;
trueRotation = rotationTarget;
isRotating = false;
if (!isSpawning) {
EventBus.onMoveDone.Invoke();
}
}
} else {
if (rotationBlend > 0.99f) return;
rotationBlend = Mathf.SmoothDamp(rotationBlend, 1.0f, ref blendVelocity, smoothRotationTime);
if (rotationBlend < 0.99f) {
transform.rotation = Quaternion.Slerp(rotationCached, rotationTarget, rotationBlend);
} else {
transform.rotation = rotationTarget;
rotationBlend = 1f;
}
}
if (isSpawning) {
if (!( isDropping || isRotating)) {
isSpawning = false;
//EventBus.onNextPieceReady.Invoke(currentTemplate);
}
}```
So while the rotating and moving is happening, I can see all 3 checkboxes, after some time when the movement is done, the dropping and rotating are unchecked, and the "spawning" checkmark sits checked.
So you need to set spawning to false when not rotating nor dropping, if I understand this correctly
yes
Also you have a return; statement in if (isRotating). else
Yeah something's up with that return statement, seeing that right after this there's another if/else that checks for rotationBlend, it's very likely the else isn't getting executed here
😦 I am an idiot. @fresh salmon thankyou. I have no idea why the same code works "correctly" (doesn't hit that return somehow)
You got lucky, the value was probably exactly equal to 0.99
Skipping the fist if statement (the return), failing the second if statement and landing in the else block
Have you implemented or used runtime occlusion culling?
I want to use it in my voxel game.
My concern is about time order
I'm trying to make my title screen have some drones that fly around gracefully.. I'm having some trouble coming up with a path that isn't so ... anxiety inducing. I'm currently trying a catmull spline with 2 waypoints with a start and finish on a bounding box that's offscreen. The video above has the rect mask disabled but .. as you can see it's a little wild.
Any suggestions?
Maybe a start and endpoint that are guaranteed on opposite sides of the box, and a single waypoint..?
I'd try slowing down close to the turns. Not sure how to get that easily on a spline, but google probably will give some formula
I shoulda been more clear - I'm only using DOTween DOPath() to animate it
I didn't wanna make it too complicated to use a bezier spline and figure out control points for each waypoint that were "gentle"
Bounding box with opposite sides and a single waypoint in the middle worked pretty well
that does look nice
thanks 🙂 it's a little bit of vector gymnastics but it seems like fewer waypoints works better
Google "unity mesh vertex data shader" and there should be lots of info.
You can use https://docs.unity3d.com/ScriptReference/MeshRenderer-additionalVertexStreams.html or generate your own mesh with those additional data attached on vertexes.
ty 🖤
I want to open a project built from Unity to PC with 2 arguments using cmd. Is there a way to do it?
Hi everyone, I sent this yesterday in the code-general chat but I think it got a bit lost in chat. Since no one replied I was wondering if I sent it in the wrong place so I'm resending it here, hope this is fine.
I'm working on a simple app that uses an Azure back end of which is connected to via the SQLConnection from System.Data.SqlClient. I've been working so far on PC and have everything more or less working, now I'm looking to build it for Android and IOS (though, specifically Android for now). That said I'm getting errors when trying to play it. From what I've read online already their could either be an issue with dll's or its impossible, two very different answers. That said, I did try the dll fix however Unity didn't seem to like this: https://answers.unity.com/questions/492821/sql-connection-doesnt-work-in-standalonebuild.html this is the link I'm referring to here.
I realised when following this link that the path is slightly different for me since this was uploaded in 2013, and I am now using 2022.2.19. Does anyone know of a more recent example of how to fix this that works for Unity 2022?
(If anyone could help with this, please reply or @ me so I can see the notification as the chat will most likely get busy)
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Is it possible to force animation's position changes immediately, within the same frame of when it was called instead of waiting 1 frame in between?
I have tried animator.Play(), crossFadeInFixedTime
and animator.Update() but none seem to give me the results I want
Ahh Play and Update do the job actually. I was debugging and testing it wrong
Hello,
I am trying to add grass to my procedurally generated mesh at runtime.
My map is segmented into chunks, and when a new chunk is generated because a player is getting close, I want the grass to be generated via gpu instancing (about 1 mil prefabs). For the gpu instancing I am using this: https://assetstore.unity.com/packages/tools/utilities/gpu-instancer-117566. Unfortunately, passing 1 mil instances to the gpu in one go freezez my game for minutes, so I want to do it on a sepparate thread, in chunks of 1000 ish.
- I was trying to use the jobs system for this, but as far as I can tell the Job system is mostly for math computation, since I can't pass non blittable data, nor can I instance stuff from there. Am I right?
- Assuming 1 is true, I am stuck with C# multithreading, correct?
- Is there a better way to go about this all?
Thanks!
i know nothing about generate mesh nor gpu instancing
but if you need to access both reference type object (if it is not Transform, there is IJobParallelForTransform but i never used it) and call unity api, then there should be no ways to multithreading
I don't think instantiating 1m prefabs is the play for grass, you are probably better off figuring out another way to do grass
I'm sure that there's better ways to do grass than that
I was mostly curious if gpu instancing would help with the performance
Just doing a quick search led me to this; https://youtu.be/Y0Ko0kvwfgA
An overview of my grass rendering explorations and an implementation of billboard grass, a common technique used in nearly every single video game.
Support me on Patreon!
https://www.patreon.com/acerola_t
Twitter: https://twitter.com/Acerola_t
Twitch: https://www.twitch.tv/acerola_t
Discord: https://discord.gg/FxGQvbfm6Y
Code: https://github.c...
Haven't watched it but other people saying it's good
I wouldn't know if gpu instancing would really help here
But you could be trying to hammer a nail with a screwdriver right now
Okay so the GPU instancing page says that you don't want to do a lot of low vertex meshes (which is what you are doing right now really) but rather do 1 big combined mesh
You can also instance stuff from jobs, take a look at the boids sample
Are you using a library that has been compiled for Android ? If not, you need to compile the library for Android. If you use IL2CPP, you can also drop the files into your project I believe.
1 millions of meshes is too much same if you use instancing.
even the regular instancing without a doubt it will help you spawn lots of them
If thats not enough and you want to spawn much more of them, you can use DrawMeshInstancedIndirect api
note for the latter, you will need to handle culling yourself
Could you elaborate further? Right now I am just using the namespace System.Data.SqlClient from what I believe is just in .Net 4x though I may be wrong. I did try dropping the files mentioned in the link into my project however that started throwing errors and then wouldn't let me build. Just repeated it now and got the error:
This is by moving the libraries into the Plugins folder of the project
Hmm, actually maybe not. I'm going to try a build restarting Unity with the dll already in the project doesn't give the error, I'll check this out
Actually no, still doesn't let me build
Sorry those errors where building still using Mono as the scripting back end, swapped it over to IL2CPP and still failing but with different errors this 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.
Only one error and this was its contents
If you are using System namespace, you should not have to include a DLL as far as I know. Searching Goolge I found this thread that could help you: https://forum.unity.com/threads/please-help-for-il2cpp-problem.302670/
Trying to disable stripping seem to be a potential solution
Ah I'll have a look, thanks
Maybe changing the .Net profile could also be something to look into.
Still doesn't seem to work, though I'm not getting as many option on my editor as the people in the post are, so my guess is that something has changed in unity with the version I'm using. The two API levels I have are .Net Framework and .Net Standard 2.1, 2.1 doesnt seem to recognise the classes for SqlConnector or SqlClient so I'm guessing I have to use .Net Framework.
As for stripping, I have a toggle for stripping engine code and a drop down for stipping level, both are set to minimal / off. Build still seems to fail, That said it does sound like the stripping could be the cause, so I'm going to look into that for a bit, they mention in the post about doing custom XML files to force things to be built too so ill look into that also.
Reading a bit more, it seem that System.Data.SQLClient is not available on Android. Also, as a lot of people suggested, you should use an intermediate between your client and your database removing the needs to use this class.
For mobile, it is also recommanded to use .Net Standard 2.1 over .Net Framework because of the resulting size.
It is also stated that some part of the .Net Framework may not be available on all platform while Unity has committed to support everything in .Net Standard 2.1.
Ah thanks, I did see people where suggesting a PHP kind of middle man approach but since I've never done PHP befoer I was looking into fi there where other options. If not then I guess I'll do that. Thank you for your help, I'll also look into using .Net Stadnard 2.1 instead too ^-^
the asset i am using I think uses DrawMeshInstancedIndirect, with furstrum and occlusion culling.
then go nuts, and plant your virtual treeesss! 🫡
unfortunately it drops to 60 fps even with just 500k triangles, when the performance should be much greater from what i've seen online. do the urp lit / unlit shaders support gpu instancing?
you can do LODs as well with instancedIndirect so that would truncate your verts counts, last you can clump them to a bigger chunk
You can use the FrameDebugger to analyze the issue.
as for LODs, they're a bit different in instancedIndirect api
Also, you want to look at the amount of Batches, not triangle to know if GPU instancing works.
unlike conventional lods
okay thanks guys!
Instancing helps to reduce the cost of draw calls mainly. The GPU cost of drawing the triangles is still mostly the same. If you're getting 60 fps due to the GPU taking too long, then your GPU is always going to struggle rendering that many triangles and pixels with whichever shader and render resolution you're using.
He shouldn't concern with drawcalls, DrawMeshInstancedIndirect will always be 1 drawcall
The central limitation to grass that is procedurally instanced on the gpu is creation of the dynamic meshes and sampling/calculations for stuff like surface alignment. You can jobify that or do parts of it via compute shader, the data upload can be time sliced if necessary and you can fit a lot into 10ms. The most effective thing you can do is reducing the number of world sample points you need to query/calculate on the cpu and consequently the instancing calculations
Once stuff is calculated you can easily render 1mil instances (with say 20 mil triangles) on a midrange gpu
rather than 20mil, which is a heck lot, just normal blend it with the ground and spread them not too close from each other, the normal blending would make your grass field filled with lots of grass tho it's not
GI and Zelda did this
it will give you an illussion that there are lots of grass.. but... it's not
For reference 20 mil tris can fill 300m view distance with grass such that you don’t see the ground texture
usually you’d need way less than that indeed
Depends on how tall the grass can be though
for reference, zelda style grass with NR
A common trick for this is to slightly angled the grass, like almost touching the ground, like this for example
so you won't see the ground texture
this is the prefab that gets instanced, and the shader adds some more skew based on the view normal
@compact ingot @novel plinth
The examples you guys provided look amazing, I hope to build exactly something like that, but before I get to shaders and alingment, I want to gradually build up to it by building something more and more performant. So at the moment I'm just instantiating 50k cubes with and without gpu isntancing, and for the life of me I don't see any difference in fps.
without gpu instancing: 500k verts, 30k batches, 70fps
with gpu instancing + occlusion culling + furstrum culling: 500k verts, 50 batches, 70 fps
both have saved by batching: 0
Perhaps your PC is strong enough to run both at a higher frame rate, but has a frame rate limitation(like vsync or target frame rate set)?
As for the "saved by batching" stat, I think it's pretty buggy, especially with GPU instancing and/or on SRPs.
didn't they recommend looking at # of SetPass calls instead as a better indicator? Also looking at a static scene doesn't reveal much, performance often only drops when the camera/environment move relative to each other and culling/instancing have to be recalculated
in the screenshot posted above with the 900k instances peformance immediately drops to slide-show levels when the camera moves outside the loaded chunks and takes 1-5 sec to recover depending on the streaming budget, 90% of that the time is spent calculating the instance matrices.
How does one go about "clearing" the display between scenes. The issue I'm having is that in our game's main menu scene the Camera's viewport is set to fill the screen. However, when we go into our actual game scene, the viewport is set to only be a certain portion of the screen. That leaves the last image from the last scene filling all other areas of the screen. How can I clear it, so those areas are just black?
@unborn relic https://youtu.be/jw00MbIJcrk https://youtu.be/PNvlqsXdQic
While billboard grass is a performant, easy option for visualizing grass, modern games like Breath Of The Wild are able to utilize real geometry to get more interesting and appealing foliage. How can games nowadays afford to do so?
Support me on Patreon!
https://www.patreon.com/acerola_t
Twitter: https://twitter.com/Acerola_t
Twitch: https://w...
In this video I go over the optimizations I made to the grass in the previous video to cover any size area while still being highly performant.
Support me on Patreon!
https://www.patreon.com/acerola_t
Twitter: https://twitter.com/Acerola_t
Twitch: https://www.twitch.tv/acerola_t
Discord: https://discord.gg/FxGQvbfm6Y
Code: https://github.com/G...
just disable what you don't need.
these are exactly the tutorials I am trying to recreate. I just wish it would go into the implementation a little bit, isntead just a high level description
well I am an idiot. the reason for my terrible performance was that the prefab I instanced on the gpu casted shadows
when disabling that, 100k prefabs are barely noticable fps wise
i know, but im using it as a learning exercise
the best looking grass i've seen was always something on really small scale or really stylized and blending with ground
or both https://www.reddit.com/r/Unity3D/comments/11pgcr2/sometimes_when_making_a_level_i_end_up_just/
that's beautiful as well...
yes, blending the grass with the ground will make it look nice and you don't need bunch of grass to make it look dense
i have a question on job system with unsafelist
when i assign the the unsafelist struct outside the struct (in the class) to the struct (job) ,will it copy all the properties?
if true, then when i resize the unsafelist then the Ptr will be realloc()ed and free()ed that means the address of Ptr inside the struct and address of Ptr outside the struct (in the data copy of that UnsafeList in the class, called classPtr) will be different and the address pointed by classPtr is not valid anymore.
struct MyJob:IJob{
UnsafeList<int> x;
void Execute(){
x.Add(10);
x.Add(10);//here the x got extended, will x.Ptr different from XX.Ptr?
}
}
void Do(){
UnsafeList<int> XX=new UnsafeList<int>(1,XXXXXXX);
MyJob job=new MyJob(){x=XX,};
job.Schedule();
XX.Dispose();
}
How are you planning to resize it?
the add() will automatically resize it
and i am curious if the list got resize in struct how about the address of XX.Ptr
It will probably be fcked up.
yes of course it will change
it's wrapping some internal stuff, so if you're asking how to get the pointer back out: don't cache it, it might change, access XX.Ptr after the job is finished. Your Do method looks very dangerous and crashy
Are all the cube in the same location ? If so, you might have z buffer culling happening.
no, different location, but I provided an update. the performance issues were from the fact that the gpu instantiated prefabs were casting shadows
now i can spawn 500k objects and have about 200-300 fps
Do not forget that a game is more than just grass :P.
yeap, i'll try to remember 😄
although, grass is quite amazing
Also makes people like your game better, so it’s very much worth the effort imo
Hey, would somebody mind helping me how to implement a small thing to my code?
I'm developing a voxel engine. Before going into any complicated meshing algorithms and database stories, I have a script that globally manages chunks. These are essentially cubic regions of the world that are loaded and unloaded with everything in them based on their distance to the player and other loaders.
Now, at a radius of 10 chunks, Unity needs to run a rather small amount of code for 1000 elements. Part of the code is a ComputeShader dispatch and retrieval of its information, which could explain why at 1000 elements it does lag down to ~20 FPS, although my rig is composed of an Intel i9 13900k and an RTX 4090.
For now, I don't wish to focus on optimising per-chunk code, but to keep this algorithm from slowing down the main thread and the FPS of the player. It is no issue at all if a chunk needs 100ms to complete, just that it doesn't slow down the main thread. So, I'm looking for a way to offload this algorithm to execute on another thread/CPU core so that it doesn't slow down the main Update() cycle and FPS of the game. How could I accomplish this?
So question. Is it worth performance wise to use Calculus over Algibra in programing?
Incredibly vague question
Really depends on what you are doing...
Well for physics for example? Using derivatives/integrals to calculate forces?
in what sense would you use derivatives or integrals to calculate forces?
You need to use Calculus for that. Calculus is the study of rate change I believe. How would you know the tangent of something with algebra ?
Unity uses a discrete timestep physics simulation.
If you're talking about writing your own "continuous" physics simulation using calculus, it will almost certainly be slow as hell
All of the computational methods to compute integrals for a general polynomial curve involve many iterations of adding smaller and smaller numbers.
to approximate the actual area under a curve
using Riemann's method for example
that's very computationally intensive
the discrete physics used by Unity is much simpler and dumber than that
i guess directive of finding slope at x=x0 can be done in O(1) time by lim (h->0) f(x0+h)-f(x0)/h
Yeah that was what I was thinking. I was also thinking of using calculus on a server API to check players movement. And give predictive data. Though that gets a bit out of context for Unity.
Off load the work, though wouldn't be a every tik type of thing
For what reason you want to do that ? Authoritative server ?
Dysnc fixing, player ai predictive movement, cheat detection. stuff like that
There is no need for advance calculus.
You should not put energy in that anyway. Except, if you doing an engine and not a game.
If you're using PhysX then doing your own calculus is not going to accurately predict player movement, since PhysX doesn't move things in that way
PhysX is pretty stupid. This is how it calculates object motion:
Vector3 currentPosition = rb.position;
Vector3 nextPosition = currentPosition + rb.velocity * Time.fixedDeltaTime;```
mmhhh, so step one is make a super computer that can run perfect physics. Step two make a game engine that can run perfect physics.
(for a single physics frame)
You may be interested in https://docs.unity3d.com/ScriptReference/PhysicsScene.html, if you really want to do some collision validation.
Hello again,
I'm instancing about 1 mil prefabs using gpu isntancing in my scene.
If my camera is static everything is fine, I get about 300 fps. The problem is the following: In play mode, if I move, the game stutters a bit, every 2 seconds-ish. If I build my game the stutter is completely gone. I've profiled the playmode to see what was going on, and the hiccups are caused by "EditorLoop".
- How can I prevent this?
- Is it normal for games to be almost untestable / unrunnable in playmode? (I imagine that being the case for big games)
- Should I strive for my game to be runnable in game mode, or is it normal to accept that from a certain point you can't really test it well?
Thanks!
I don't know the answer to your question, I'm just curious how you're using GPU instancing to instantiate prefabs, that sounds neat! 😮
I thought it only worked with meshes and simple primitive values
I am using this: https://assetstore.unity.com/packages/tools/utilities/gpu-instancer-117566, but don't know what it does under the hood 😦
Cool, thanks!
It does only work with meshes. Reading a bit on the asset, it seems that it render things with DrawMeshInstancedIndirect.
This may not be the answer but I had a similar issue recently, do you have incremental gc turned on?
no, should I turn it on?
Yes, that's what causes my major lag spikes too when I had almost nothing in my game
Your editor is constantly allocating stuff for some reason, especially quickly when you have the stats tab open. With incremental on, the gc is used on smaller amounts but more times rather than once to deal with all the memory
Tabs other than stats will affect it but that's just the one I remember having a major affect
Thanks a lot, that was a very good tip. Don't know why I didn't turn it on sooner. In the meantime, after the post I made above, I turned on the profiler in the editor, and saw that my hiccups were caused by the netcode package.
which I am unsure how to fix
Im also not too sure, someone told me about incremental gc so that's pretty much all I know.
You can expand that hierarchy in the image though to try and see what exactly is causing the issue
For me when I expanded it, it would always lead to like GUI.repaint and at the end gc.something I forgot the name
it's that node, the children don't take up anything almost
how do I solve the folllowing problem:
- I'm using netcode for gameobjects, which subscribes to EditorApplication.hierarchyChanged, and in the method it uses Resources.FindObjectsOfTypeAll, which is super slow.
- in my scene, I have MANY objects (500k+; grass), making Resources.FindObjectsOfTypeAll calls super slow
- in my game, movement triggers sounds (steps, jumps, ambient etc), which changes the hierarchy, thus triggering the subscribed function above.
- since I have many many GO's, my play mode is unusable.
how do I fix this? thanks
potential solutions:
a. don't create sounds in play mode, thus not triggering hierarchy changes
b. remove the stupid method from netcode from gameobjects; don't know how to do it
PS: the problem is in: GameObjects/Editor/NetworkManagerHelper
So ~6 months away from release and ~12 months away from being in an LTS 😬
At least some part of the build system? 😛
I wouldn't immediately assume this applies to the player.
help me please
jfc, 23 alpha and they add .net 6 which is already depreciated
Nah .NET6 is LTS, support ends somewhere in November 2024
But that only applies to a small part of Unity, porting the whole thing isn't done yet
Maybe .NET 8 or 9 will be out by the time it's fully ported
If you need help, you need to ask a question. If it's not an advanced question, then you can do so in #💻┃code-beginner.
if they port it to any .net from mono updating would be easier
indeed but .Net 6 is a non starter. .Net 7 should be the minimum they should aim for
Hello, I'm trying to make a puzzle game of "Tents and Trees". What I want is to generate unique levels and store them as json files. I know how to store them as json but what I don't have knowledge on is generating the levels.
For people that don't know the game, the rules of Tents and Trees are: the play area is a grid and every row and column has a number assigned to it, which is the number of tents that you need to place. Every tent has to be adjacent to a tree and every tent cannot be next to another tent, both orthogonally and diagonally.
What I would like help with is how to write the ruleset in code and generate the unique levels. Thank you in advance for the help~!
You might want to use a sort of backtracking algorithm with a mix of randomness.
https://www.geeksforgeeks.org/backtracking-algorithms/
https://en.wikipedia.org/wiki/Backtracking
At least, this is where I would start.
I think this problem can speed up by dp
Wave function collapse
If you want to use wfc to generate
The rules are:
The adjacent tile of Tree tile can be none or tent
One adjacent tile of tent must be tree and no other tents in 8 directions
And you will get tent number of each row (or column) after generation
But likely you cannot define it if you use wfc
I looked into backtracking algorithm since I never used it before but it seems more useful for creating a solver for the puzzles than generating levels from what I could understand.
I never used wfc before, still have to look into it but you don't think I'll be able to define the tent numbers with it? If so, it'll be a pretty tedious solution. Also what is dp?
You can random place tree first and define tents to be placed in each row and column then use backtrack to check whether solution exists
Dynamic programming
And i review your question dp cannot be applied
Backtracking would make sense like that. I'm pretty new to these things so I have to ask, how would I go around defining the tents that has to be placed? Would I just use the rules of a tent has to be next to a tree and no other tent in 8 directions?
You need to be able to solve the puzzle to actually make one solvable. At least, this is the easiest way.
You place them random in place that can satisfy the rules.
yes ,you said each tent needed to be next to tree and no other tents in orthogonally and diagonally i,e (x+1,y) (x+1,y+1),(x+1,y-1)....
Thank you both for your help, I'll look more into backtracking and try my way.
I think that WFC will give you solved puzzle and then just remove tents. I'm not familiar with this game so just guessing after seeing few images
WaveFunctionCollapse is just backtracking with constrain propagation with lowest entropy heuristic. If you are not using the "auto" detect constraint. With that you simply use Monte Carlo Chain to sample the constraint. At least, as far as I know. I never actual looked into it. I think it is way to popularize for what actual is.
Not sure what you meant by this...if you meant the camera...that doesn't work.
hello, with gpu instancing, if i want to generate batches of grass at runtime, do I need to resubmit the whole buffer every time a new batch needs to be added, or can I just submit the new batches?
your question a bit vague, there are couple of instancing in Unity
I assume what you want is the procedural one(instanced indirect)? if so, then you can generate as necessary
you don't need a to clear the previous ones if they're of off a different batches
pretty sure the asset you mentioned the other day already handle this under the hood, if not, ask your money back 😄
Hey
I want to use Version Defines and Define Constraints with actual dlls, not Assembly Definitions. dlls do have Constraints but I can't see Version Defines
okay, thank you very much
Uhm, rendering is not a beginner problem. I don't think you have a clue about anything based on these two replies, and seeing some of the other stuff you've said to other people. 🙄
Dll does not have the notion of Version (In Unity) ? At least, not from what I know. You could try to combine assembly definition with DLL ? Alternatively, you could also make a package with your DLL. I have never setup assembly definition myself, take what I say carefully.
Maybe this can help:
https://docs.unity3d.com/Manual/PluginInspector.html#:~:text=General - Auto Reference
https://docs.unity3d.com/Manual/class-AssemblyDefinitionImporter.html#general:~:text=compiles the assembly.-,Auto Referenced,-Specify whether the
https://learn.unity.com/tutorial/working-with-assembly-definitions#
you cannot use defines with dll's because they are compile time directives
I was also thinking of combining them, do you know how I can make them work together?
No I do not, but it might be possible. Try to play with the different option.
Thank you 🙌
hello i need help in coding
Do you know about object pooling?
You can make the sound object, then when the sound has played instead of removing it you reuse it for the next sound.
Drastically reduces the number of new objects you're adding.
I want to use UniTask to create async method, but I want to run it similiar to coroutine, but attached not to game object, but manual iteration instead.
IEnumerator doesn't have much.
So... to mimic coroutine behaviour, do I just MoveNext until it's false?
wait
bruh, looks like it's not actually running task this way, but instead just checks whether it's ready. Sad
Just call move next?
under the hood it's just checking bool is taks is completed
which is triggered via try{} finally{compelted=true;}
so that's fake coroutine really
what behaviour are you looking for?
task creating via await/async syntax but run directly by calling MoveNext
instead of UniTask/.Net loop
That sounds like your are describing an enumerator.
What are you awaiting inside of it?
netcode stuff
Well UniTask has UniTaskCompletionSource, you can create a task out of it which you can await, and MoveNext would be just setting that source to completion.
Odd design though, sounds like a potential XY problem.
This is netcode for entities and I want to make some proper handling for disconnections and other problems during game loading without a need to dispose server world (which at the same time will disconnect all connections). And without disposing world it'll be just a very painful management of every state component, which I kind of want to avoid atm
In that case I don't know enough to comment, but yeah UTCS should get you what you want.
I don't don't really get how. Wouldn't it just create a wrapper for reading, but leave my async operation same as it is (running on UniTask player loop)?
Create a UTCS:
var utcs = new UniTaskCompletionSource();
var waitForNext = utcs.Task;
Then you simply pass waitForNext in some way to your async code:
await NetcodeStuffs();
Debug.Log("Execution will hang at this point until next signal is given");
await waitForNext;
await DoMoreWork();
To signal:
utcs.TrySetResult();
nah, that's not what I want.
I want to run task myself, so no automatic loop is run. So it's tied specifically to ECS system's state (it's update function)
But figures it's not something that is trivially available
That waitForNext is the equivalent of MoveNext
but it's still run on loop
On loop?
UniTask loop
I have no idea what you want then, if you want to execute a state machine step by step with full control, that's just an enumerator.
what I'd want is:
var task = LoadAsync();
on init and then:
OnUpdate()
task.MoveNext();
Which is just an enumerator.
But why? What's the difference between:
IEnumerator Foo()
{
DoSomeWork();
yield return null;
DoMoreWork();
yield return null;
}
vs:
async void Foo()
{
DoSomeWork();
await waitForNext;
DoMoreWork();
await waitForNext;
}
🤔
maybe you're right
I didn't realize I don't really need await for some reason
so what I really need i just
call Foo() and then MoveNext while it's true?
by while I mean non-blocking callback
once per frame
Sure, whenever you want to move next is entirely up to you.
Enumerators are what powers foreach in C# and coroutines in Unity.
wait a second
is there a way to implement it without interface?
so execution cycle is fully unmanaged
so it can be burst compatible
🤔
Not sure why interface has anything to do with it, you can foreach native arrays just fine.
no, I mean
I want to implement such state machine
while keeping it burst compatible/unmanaged
so it's not called via interface
but via direct struct type
Interface has nothing to do with whether something is Burst compatible or not.
Native arrays implement plenty of interfaces and they are Burst compatible.
that's not what I meant
they are burst compatible because you use them via NativeArray<myType> instead of IEnumerable<myType>, where latter is boxed and managed (not-burst compatible)
I'm not really familiar with how enumerators are implemented (especially such complex ones)
IEnumerator Foo() {} is just syntactic sugar, you can look at what it desugars to: https://sharplab.io/#v2:D4AQTAjAsAUCAMACEEB0BhA9gG2wUwGMAXAS0wDsBnAbllgEkBRcgVwFs8AnAQyM08QAxTJgAUASlgBvWIjnIIATlEAiAMpE8AB0QQV42jHkKIyAOyJWuQ8ZTL1mnWH035KUyAtXshgL5A==
C#/VB/F# compiler playground.
The problem isn't the interface, but the fact that it desugars to a class, not a struct.
yeah, that's exactly why I'm worried
because what I need is for compiler to generate everything unmanaged
so declaration of enumerator is struct and all fields are unmanaged
is that even doable?
I mean nothing says you must use the syntax sugar, you can implement your own IEnumerator<T> as an unmanaged struct.
yes, but I want sugar 😅
Too bad, they are bad for your teeth.
You can try implementing your own async/await like how UniTask does it, but not sure how Burst compatible that is.
🤔
so I guess IEnumerator won't be burst compatible
I mean
unless I manually implement struct with this interface
and do async stuff manually without sugar
in MoveNExt
yeah, I should look into own async/await implementation at some point
if it is possible to make compiler generate unmanaged code it would be extremely valuable
thank you very much, i didn't know you could use pooling for sounds as well
You could use IL post processing to modify the compiler generated class to be more optimized. Unity ECS used to do that to optimize the ForEach lambda, and Burst uses it to replace method calls to Burst compiled methods with native calls.
oof. I'm not mentally ready for il post processing
Do you just want a custom synchronization context that updates in your system?
I need some help.
I want to save an item class as json. So the class is the configuration. This should be read later from the json.
But JsonUtility always saves me only
{
"Items": [
{
"instanceID": 0
}
]
}
My Item Class
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Item : MonoBehaviour
{
public string name;
public string description;
public bool grabable;
public Transform Attachpoint;
}
And here is my editor class.
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.
According to the debugger, the item array is also filled up until line 279.
what is JsonHelper?
using System;
using UnityEditor;
using UnityEngine;
public static class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper, prettyPrint);
}
[Serializable]
private class Wrapper<T>
{
public T[] Items;
}
}
Because JsonUtility doesn't seem to handle arrays.
Was an attempt.
With the normal JsonUtility comes the same error
you're trying to serialize a MonoBehaviour
also you won't be able to serialize the Transform field to json either, you'd probably want to make that just a Vector3 if the purpose is to just represent the point where it attaches or whatever
lmao yoy save serialize MonoBehaviour
I thought that would work.
According to Unity docs
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/JsonUtility.ToJson.html
In the example it is also a monobehavior
even if that does somehow work, the next line provides at least one reason why your current setup won't
also
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/JsonUtility.FromJson.html
Only plain classes and structures are supported; classes derived from UnityEngine.Object (such as MonoBehaviour or ScriptableObject) are not
OK.
Then I have to rebuild the system.
is this for runtime or just editing?
writing just in Editor Mode.
Read in Editor and Runtime
why not just use scriptableobjects?
yeah, you could save actual ScriptableObjects instead of writing to json
though I guess you could still load or create them from json too
What is better with scriptable objects?
they will be saved as assets in your project and can be edited with the inspector directly
they will also be able to properly reference UnityEngine.Objects unlike json which would just serialize the instance ID
Ok. I have no experience with that.
Then I have to see how to create SO from scripts and add this to Gameobjects.
In the past, I've used some package that had the functionality of serializing arrays in a Json format. I think it was Newtonsoft Json.
Now I have the SO on the gameobject via a manager class. That is super so.
Can I also display the variables of the SO when I have selected the Gameobject?
You can write a custom inspector. It's quite troublesome though.
just double click the item, though selection history window will help to go back easy: https://assetstore.unity.com/packages/tools/utilities/selection-history-184204
it is not.. UIToolkit makes custom editors super easyy🔥
ooh, that looks handy
Hi folks. Could use some help with this if anyone knows: Question: It looks like Unity automatically changes references to parent Objects in the MonoBehaviors of children when instantiating - to reference the new parent. That makes sense in most cases, but I have a case where I’d like Unity to keep the reference to the original parent object. Is there any way (like an attribute) to prevent this from happening for a specific object reference?
that would modify the prefab?
or are you trying to duplicate something in the scene?
Trying to duplicate something in the scene.
Or copy and paste
I would also want the reference to stay the same when instantiating a prefab. I basically want to turn off the auto-updating behavior for one specific reference field
oh, you don't mean you want to keep the prefab as it's parent, it's some other field?
I have a reference in a component to itself (don’t ask - I swear there is a good reason for this). When I copy and paste the object, this field is updated to the newly pasted copy of the original component. I want the field in the new pasted version to still reference the original component - no matter what.
Haven't used it yet. Gonna try it later. Lets hope it's better than old ways.
Unity updates this field automatically, since it expects that I want to reference the newly pasted component. But in this case I don’t. Is there a way to turn this behavior off?
I feel like I have actually had this issue before, but the solution is probably to probably to change the structure. Afaik there's no way to change the behaviour (though you could just add a function to set it back after you instantiate)
That’s a bummer, but thanks for the advice!
you could try something like making a prefab variant and setting that field to the base prefab, and see what it does
just don't edit the variant
is unsafelist (or nativelist) suggested to use if i dont use the job system? will it perform worst than List<T> ?
Same if it is, you probably wont gain anything by using it.
(I do not know) You can still check yourself, it should not be long.
But, I would use the List in most case, just because it is probably better integrated.
does anyone know how to get the Avatar from the source asset without dragging in the reference manually? im trying to use GetAllAssetPaths but it appears AnimationClips and Avatars dont fall under a specific asset, they are nested but you cant get them using conventional getcomponentsinchildren
Performance, is not the only criteria when you develop.
Note: It will only work in editor.
@dusty wigeon perfect, thank you!
How do I reset mobile input touches to 0? I have a mobile snake game where a snake block is created according to the angle of the swipe the player makes. The game has a press to play/replay. The problem is that the touches from the press to start and press to restart interfere with the swipe motion of the snake. Is there any way to reset the input touches to 0?
are you missing an assembly reference?
I added the using ucs; at the top
that's a using directive. are you missing an assembly reference
and have you actually installed whatever asset/package that namespace/assembly is contained in?
also another useful question: are the files you are editing your own files, or are they from some asset you've downloaded?
oh true its assets i purchased from booth, i usually just drag n drop n not have problems with them
yeah in that case it's probably using assembly definitions, which means you'd have to add the assembly reference to its asmdef file
Oh okay I appreciate you helping me im gonna go learn about adding assemblys im a scrub
Why did I read your name as boyfriend lol
For all advanced programmers
How did u learn unity ? WHERW
Where
I spent the last 2 month trying to find a way
Ping me
2 months? Come back in 2 to 5 years
no man i spent 2 month finding a source to learn from, not learning
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
I am wanting to make a more complicated character controller, one which offers combat in air or the ground, basically you can do combat in other states, getting to the point I have made character controllers in the past using state machines, but I was wondering if there is a better structure to use for this idea, considering with a state machine, as far as I know, there is 2 options, one i build combat into each state, or 2 i layer another whole state machine onto the character to blend combat in. I have used the layer method before, but it gets messy having to go over every state 2 times +. If you have an idea @ me
Maybe this is a better place to post rather than general.
Haven't worked on a Unity engine specific project peofessionaly. But what do larger games usually end up using for managing/referencing important objects/services. Does it usually end up being something like a service locator pattern or DI pattern?
my experience is spaghetti singleton mess so far
I pull the codebase a step towards service locator very time I get a chance to refactor some stuff, but mostly the company is concerned with making stuff fast and not good code practices
That sounds about right then 😅
service locator is kind of an antipattern in my mind too, but it's better than singletons everywhere with if statements checking the game's bundle id and then doing game-specific logic for code shared among multiple games. It was really ugly when I got here, and extremely easy to break stuff. Now it's just pretty easy to break stuff
it depends what kind of code it is, for tools you hand off to another team/co a service locator can make a lot of things go smoother integrating your module, but inside your module you'd generally use manual dependency injection by default and aim to implement neat IoC. You would break away from that when needed, particularly when code gets concerned with performance and adopts a very data oriented nature. Whenever you use a service locator you have to do way too much checking for consistency to make it a convenient pattern in unity.
Ye I wouldnt want singleton mess, had it before. Gets very easy to break order of stuff or create weird dependencies that break order of innitialization or whatever it breaks (not to mention testing would suck as hell if we had some).
Service locator to me seems pretty easy to maintain if done right. Testibility not too bad either.
I can understand manually injection, but seems like effort vs speed but compromise on cleanliness.
what does ServiceLocator done right look like?
Well maybe wrong wording 😅 but use interfaces ofcourse for services. Generics. Auto or manual registering with mono or non mono objects.
architecture is not about speed of code execution it is 99% about speed of implementing unexpected changes 1 year down the road
That is what i meant, not speed of code but implementation of new code ^
thats a IoC container
Ye it is, different word for same thing
no
you could argue that they overlap in what they provide
but they are fundamentally different ideas
an IoC container is the root of a system and "gives" references to components, a service locator is a thing a component can ask for a reference
Ah ye, I thought word container can be used interchangeably because they are both IoC patterns unless I dont know something about Service Locators.
i think the label IoC container is very wrong
Fair enough.
i'd prefer DI container
because you can terribly abuse a DI container in a way that has nothing to do with IoC
and nothing in a typical DI container particularly encourages IoC
just using interfaces with a DI container is interface segregation/dependency inversion but not inversion of control
You mean youd prefer DI Container rather than IoC container for describing the above Service Locator?
if its supposed to stay manageable i'd aim for a DI container before a service locator
a service locator makes sense if your modules truly do not have a shared entry point, come and go in an async and unreliable context etc.
DI containers only work (nicely) in a system you can construct deterministically/synchronously
Its for a game, mostly for services initialized in bootstrap stage and can ideally could be changed for debug, test vs production environments.
thats probably why most people abandon these frameworks eventually, just too incompatible with the nature of how games are constructed
makes sense for those parts
I dont know enough about the DI libraries ive seen floating around, so not 100% tempted to guinmea pig myself unless people suggest it strongly.
some believe that a non-preformance-oriented ECS is the best way to architect a game if you want IoC at all cost
But most of games production ive seen anyway, it all gets messy in the end however much some guy tries to keep it clean.
this is absolutely the case
whether someone likes or dislikes DI containers depends on how they experienced their first large scale use of them
its very easy to do stupid things with extenject for example that are voiding all the reasons for using it in the first place
on the other hand a DI container paired with a good review process can do a lot to give everyon a common understanding of a projects architecture and provide orientation and rails for onboarding new team members
the worst thing for onboarding you can do is invent all new patterns and archiecture for a large project that you have to explain to even senior people
Hmm ye, leaning towards singleton based approach for now. UE does something similar in its architecture.
what do you understand the singleton approach to be?
why would you make up such a thing?
make up what?
singleton approach
Service locator approach then, it would be a singleton.
thats like saying i'm deliberately shooting myself in the foot to see if its as bad as everyone says
depends on what that word means to you
there is practically zero reason to use singletons for "easy global access" in virtually any project.
What do you think a service locator is?
in unity the fundamental service locator is .GetComponent etc.
Ye mine would be ServiceLocator.GetService<Type>()
Services auto register to global ServiceLocator.
(or manually)
does your service locator create services when they do not exist?
Thats a possiblity, I dont think ill allow it though.
and what is the benefit of having a system deal with all the resource acquisition itself?
Well its not set in stone yet. I need to decide fully how I want to register services based on my current work that I've done with bootstrapping. I can see auto registering being beneficial in Unity incase you want to load services as a prefab and they auto register (different prefabs for different environemnts), but thats just a thought. On the other hand its also just easier.
But I may go manual registering due to how I set up my bootstrap flow.
you may want to consider how you are going to use that service locator from the perspective of a service requesting class, and how to make the dependencies it requests explicit and how to decouple the locator API from the system's API/implementation
its quite easy for a service locator to end up as a glorified global-access-singleton with all the same downsides (same thing happens in a DI container)
Ye good thought, I dont think I will bother trying to decouple that far for now, atleast for the game I am making currently. But will definitely re-evaluate if I see problems come up.
Just hard to gauge what will work as I havent seen properly what a large Unity project looks like. I've seen UE and some C++ ones but cant compare.
And also a very bad static/singleton mess of a project in C# 😅 😅
as you said, everything gets messy eventually, clean code is a myth and you can make most things work with enough effort and willingness/opportunity to fix broken systems and correct wrong turns
i've tried pretty much every approach to a unity project architecture there is, none of them was a deciding factor in the success of the project
haha im not expecting it to be based on code arch. 😅 its a personal project with a few others, so just exploring ways of doing things in Unity while I work on it.
but if cooperating with others, #1 priority should be on using stuff the team can understand and get behind, it does not matter how stupid that thing is, only that people can handle it
clever designs are often the ones that don't get used
100% agree
also consider that your team can learn to live with the quirks and shortcomings of an imperfect architecture
thats basically how it is in gamedev
we arent building microservices here 😄
School,
For Reference I did:
3 years (Technique en Informatique Programmation Jeux Vidéo), 2 years (Bachelor in Computer Science), 2 years (Master in Computer Science)
Most people I work with only did a certification which is 1 year and a half.
Multiple singleton that are instanced in the scene. It is just the fastest. There is no Unit test in video game usually. Most manager are not made to have multiple implementation. The only thing that is important is UNIFORMITY. Whatever you do, do it the same way.
does anyone know how to convert transform.right to a local Transform
you mean in local space?
nvm i just had to swap AddRelativeForce With AddForce
In local space that would just be Vector3.right or (1,0,0)
thanks
realized i needed that after my bullet spread rng bugged out at 45degrees
what do y'all think of ECS? hear a lot of good about it
if i use it, which is better? pure ECS, or Hybrid?
i am doing some optimization of my grid based path finding by change the data structure and control flow to see if there is different
for checking if the neighbour nodes of frontier are obstacle, i can either check a cost property of a struct node in Node[,] or value in float[,]
at first i suppose checking (accessing) the float[,] is faster than checking Node[,] since i think accessing the cost property of node should be some statements as:
*(base address+((i*ColumnLength+j)*Struct Size)+element offset)
(or *(*(*(base address+i*8)+j*Struct Size)+offset) but this is more like jagged array's way)
the result of checking Node[,] is faster than checking float[,] by 10ms, idk why, maybe my code is wrong or C# mulitdimensional array is not work in this way
Does anyone know a way to add a menu item to the context menu of a scene object on the hierarchy window?
Either it’s not supported, or there’s maybe an undocumented string you can use to add to it. Never can tell.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Thanks, but I don’t think that answers the question.
I’m looking for a way to add a context menu item to scenes listed in the hierarchy window, not game objects.
Sorry - I said “scene object” in my OP, which wasn’t clear.
I meant “the scene, when it’s shown in the hierarchy window”.
Scenes do have their own context menus, but I haven’t figured out the magic path string needed to add a custom item to it.
ECS is undoubtedly the future.
I would probably go head first into full ECS if I didn't have 10 projects already in OOP unity.
ECS is crap. Most thing you do in a video game does not need the performance ECS gets you. In fact, it will probably be worst in most case. Hybrid is the only way I am using anything ECS related.
But again, it depends on the game.
You're simply wasting performance opportunity by not using ECS.
Any game I buy has trouble running at 144hz on my very modern hardware. If you own a 144hz monitor, you know the struggle
The world needs to move towards ECS for video game applications.
CPUs are at their limit in terms of random access OOP.
Rust and Tarkov, the major unity titles are extremely CPU bound.
half of their problems aren't related to OOP though
I mean, you're probably right
ECS is great when you work with a lot of a given type which is not something you see in most game. If you are doing a Vampire Survive type of game, maybe you will gain and it will be worth the headache of making everything else work, but in more standard game it is not.
you can still apply DoD without touching ECS
I often talk about performance gains I get on projects and people simply don’t believe them, especially when things get 100 times faster…
When I say ECS, I'm more so just talking DoD in general
just linear access patterns that can be vectorized easily
yeah ECS itself is overkill for most projects
UI in ECS most be a nightmare.
does UITK work with it?
Good question
hi! when I try to navigate through the contents of a TMP Dropdown with keyboard or a gamepad, the selected item doesn't automatically scroll into view. manually assigning to scrollRect.verticalNormalizedPosition has no effect, it always stays zero unless you scroll with the mouse scrollwheel or by dragging the scrollbar. has anybody had to deal with that?
I want to clone existing game object mostly as is, but some nested objects that have specific component should be removed and re-created manually. Is there any sane way to do that?
before cloning, I temporary remove parent from these objects and it kinda works, but now I cannot find a good way to match new and old parents. It looks hacky and wrong, but I'm not sure if there is any better way to do that.
How can I create software gore with UI?
talking like glitches and stuff, would figure out which direction you want to go in for it
and apply it as a shader in post processing
Can you share specifics? It's a little unclear what you want.
sure. Let's say that at runtime there is component tree like so
A
- B
- - C
- D
- E
I want to create copy of this component tree (using Object.Instantiate()). But I don't want to copy some of A's (grand-)childs. Let's say that C and E have some DontCopyMe component attached to them. I want to copy A, B and D, but not C and E. And then I'll create them manually from prefabs and place them in the right place in the tree. So the result would be
A(Clone)
- B(Clone)
- - C [created from prefab]
- D(Clone)
- E [created from prefab]
The way how I can currently do that is:
- remove parents from components C and E
- copy the tree
- add parents back to components C and E
- create C and E from prefabs
- set their parents to cloned ones
And the only way I was able to match parents without adding temporary components is to search for them by name. E.g. "B(Clone)" and "E(Clone)". But this is not very reliable and quite ugly. Is there a better way to do that?
what are these things exactly though? I wonder if the design is weird/faulty in the first place? E.g. maybe C and E should be spawned dynamically at runtime rather than being part of the prefab?
These things are basically game environment - room or level if you will. Idea is that you can create copy of it, perform some actions in copy and then "import" them back into original environment. I don't want to clone some component as is, because there is quite a bit of logic to initialize those and I don't really want to be required to ensure that those components state isn't leaked to new copy.
C and E aren't part of the prefab. They will be spawned at runtime.
why not just use prefab variants, or is it too procedural for that?
because these entities can be spawned at runtime and aren't pre-determined at build-time. E.g. enemy units and stuff like that.
yes
What about just not having C and E in your prefab to begin with?
already mentioned haha
Oops.
the problem I think is he wants to clone the modified copy of the object that's in the scene
not the original prefab
sorry, if I wasn't clear enough. In my example C and E aren't part of the prefab, they are added to existing prefab at runtime by game logic.
or not to prefab, but rather to resulting gameobject
So couldn’t you just clone the original prefab rather than the resulting GO then?
sorry, it isn't clear to me what you mean. Even if I do that, I'll still need to copy all of the dynamic objects with correct hierarchy from GO. I don't see how it changes things.
What I mean is that, you say you now have ABE+CD, which CD is generated and attached at runtime to ABE; that means there must be a point in time where you have only ABE (either as a prefab, or in middle of their creation), and you should be able to just reuse the ABE prefab directly, or reuse the code that creates ABE.
Well, ABD+CE.
I mean, it isn't a big problem to create ABD (either with prefabs or with removed parents hack). My problem is that I'll need to add CD afterwards to exact same parents.
Well you already have code that attaches CE to ABD, you couldn't reuse that?
wait, are you trying to swap the room itself without touching contents?
Perhaps I'm missing some critical insight to your problem, but on the surface this feels like it could be solved by simply reusing existing code/prefab.
yes. But then place contents back into it.
yeah there's a trend where to help someone you first have to guess the issue. rubber duck would help a lot here.
not really. One example would be something like projectile that becomes attached to a door. I can easily create room and door, but I'll have to attach this projectile back onto copied door.
That makes sense.
Well in that case and if you are stuck with your current architecture, I don't see other way than doing the obvious "clone, delete what you want to swap away, add back what you want to swap to"
keep a list of the objects that are replaceable
check all objects, and if they're not in a list, check their parent.
check what slot the parent belongs to
remove parent, attach to new parent with matching slot
I mean, I'm not exactly "stuck", I can change it of course, but I don't see any good solution on how to manage general issue of being able to clone GO tree with both static and dynamic objects without copying those dynamic objects.
Without knowing enough context, a potential different approach could be to serialize (not in the Unity sense, but in a general sense) your hierarchy state that can be easily manipulated and recreated.
An example could be your room GO perhaps only have one state (whether the door is opened or closed), thus it can be serialized to a POCO with one field isDoorOpen. With that POCO you can freely manipulate that field, and recreate the room without needing to reference the original GO, because all necessary state is already there.
I already do that. All dynamic objects are serialized into POCO which I'm using to re-create them.
Then your original question could be solved with: serialize the current hierarchy, swap out CE's serialized representations, then create the hierarchy again.
Basically I integrated Amazon Polly to my unity project, so I can send request to generate mp3 of speech voice from text at runtime.
With the current system everytime I send a new request I have to store the file locally and execute an 'AssetDataBase.Refresh()',
the problem is that other than making the program freeze for a couple of frames I can't use this method on WEBGL build since I can't save stuff locally.
Is there a way to generate and Audioclip on the go after receiving the mp3 data so I can dispose it after being played?
This is the current code structure I was preparing:
This was the old script, which as I said worked but have the issues I listed previously
Are you synthesizing audios at runtime or at editor time?
Its all runtime
I don't think AssetDatabase is even available at runtime, WebGL or not.
its probably not
Thats why I want to change how its handled, I think it can be done better than 'Save it locally and then retrieve it locally'
On the topic of loading compressed audio like mp3 as an audio clip at runtime, the last time I looked at it the only way is to use UnityWebRequestMultimedia.
a webrequest to handle a local file? is it me or the name is misleading?
UWR is not for local file, it's for making network requests, which can also handle local files with file:// protocol.
I'm having issues understanding the documentation about it tho, any idea on how I could integrate it?
Three potential ways:
- Ideally if AWS SDK allows you to somehow configure it to use UWR, then you just use that for the request instead so you get the audio clip back directly. Highly doubt it though.
- Alternatively after you get the mp3, write it to file system and then request it with UWR again to get the audio clip. Probably won't work for WebGL.
- If all else fails, you can always send your own request based on Amazon's docs rather than using their SDK, that way you can use UWR for it directly and get the audio clip back.
Ah and a fourth way, if Amazon Polly allows returning the audio in wav, you can do your own parsing (WAV is trivial to parse) and write to audio clip directly.
So 2 of them rely on AWS and the middle one on writing the file (which will not work on WEBGL)
Is parsing not possible with mp3?
Cause aws only sends mp3
It is, you can do your own decoding (if you don't value your sanity) or bring in a library that does it.
Yeh for sure I'll search for a library
I mean the 3rd way is just rewriting the AWS SDK.
Well, only rewriting the part that does the synth request.
I wanted to keep the system flexible cause now I'm using amazon but next time I'll maybe use another service
The core is the same: getting an Mp3 from an external source and use it as Audioclip on runtime in WEBGL
If the external source is network, then that's exactly what UWR does.
But yeah, I remember looking into this awhile ago and got very frustrated that there's no way to let Unity decode an audio clip at runtime except using UWR
So unless things have changed, you either use UWR, or you do your own decoding to PCM so you can load them to audio clip directly.
Ok, thanks, Ill try to take another look at UWR
UWR needs some adress to get the file locally, so its assuming the file will be saved locally, and that is not possible on webgl
So I guess my last option is to actually decode the data I receive from AWS directly when I receive it and convert that to an audioclip
I mean, the address could be the request address to AWS to get that synth file.
You do the requesting directly with UWR rather than AWS SDK client.
Mh.. its to messy to change that system now, as I said it could be another thing that is not AWS in the future
Is the option to decode that difficult/unoptimal?
Don't know, I only briefly looked into it and the few first clicks were libraries that are either unmaintained, untested, or just doesn't support Unity.
I'm not sure what you mean by the former though, if you are going to move away from AWS in the future, you are going to have to rip away the code that requests Amazon Polly and replaces with whatever new service anyways, I don't see how that's different from changing which address UWR sends to.
@scenic forge Is this the integration of WW you suggested? (sorry for ping)
Again this works locally since it has PersistentDataPath but fails once runs on web
Yes
But instead of using AWS client to send that request to get the audio, you construct and send the request yourself with UWR.
can you post your code correctly please
Didnt wanted to make a giant wall of text
paste site
How to post !code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
better, thanks. much easier to read and evaluate
@rancid oxide btw I hate this use of var because it is impossible to know what objects are just by looking at the code
var is fine in my book.
in your own code, yes, but on a paste site it is meaningless
If you can't tell roughly what a variable's type is just by its name, then that's a naming problem than a var problem.
Its think var is fine, you just have to know the context of the whole code.
Basically I need a way turn filestream I get from Polly request into Audioclip without having to store it locally since I cannot use that feature on webgl
I think you have a CORS problem rather than a code problem
you cannot do async on WebGL anyway, you need to use coroutines
Turned async into coroutines
https://hatebin.com/zecabqarhj
Still think it's a CORS problem. Do you have errors in the browser developers logs?
I presume you are hosting this on AWS as well
It will eventually, for now I'm just running locally a chrome
CORS or not, it just wouldn't work if WebGL doesn't allow you to write to a file system
Unless Unity implements a virtual file system for you.
webGL writing to persistentData is no problem at all. it goes into index.db
Oh, that's good to know.
you can even persist it across browser sessions if you wish
Then writing to that and then using UWR to grab it back as audio clip would work
The rest is just a bit of code.
yep, sure
this
var responseTask = client.SynthesizeSpeechAsync(request);
is what concerns me
then why this doesnt work?
Is a problem about the browser blocking some code due to restrictions?
yes, I think so
even if I'm trying it to run locally?
because you are running it locally. that is what CORS is all about
mhhh... so if its hosted on a website it will potentially work?
(sorry dont know nothing about cors)
Open your browser dev tool, if there's a CORS error you will see it either in console, or in network requests tab.
yes, if the site is configured to accept CORS
ok, ill try. give me a seec
(Surely Amazon's API would already have CORS configured to accept everything?)
do you know what CORS is?
me?
yes you
nope
I can imagine is some sort of issue due to files coming from different sources
it is a security feature to stop Cross Site Scripting, in your case you have a local site and you are accessing AWS sites, that is Cross Site
you need to look at HTTP Request Headers to see how to mitigate this
so potentially even if I upload the game on itch and I request a voice from polly it couldnt work
yep, it's a pita unless you know exactly what you are doing. no easy shortcuts
its way more restricted than I expected
it is extremely restricted. things that are 'easy' on pc or even mobile can be very difficult to achieve with WebGL
Look at this:
https://hatebin.com/bhynwszliy
The execution is very simple (it just plays a random mp3 hosted somewhere) and yet still doesnt work on webgl
again CORS
ye
So just one thing about cors in general, this is an issue about the browser in general or just unity? And can it eventually be disable by the hoster of the site or its locked for security reasons?
You should make sure the issue you are having is actually CORS first, by checking browser dev tools.
browser in general. you need to set up your web servers to mitigate this restriction by having the correct request headers
indeed
I doubt the Amazon Polly endpoints don't have CORS configured to accept any origin.
it's not about AWS it's about the requesting site
how can I check if this setting is enbaled or not from the inspector?
the page inspector
still no wiser, what page inspector?
the one of the broswer
Normally, you read the error from the console.
you mean the web developer console?
I guess so
or the network traffic console
that will just show you action and results, it wont tell you if CORS is the problem but you can extrapolate from the messages if that is the case
ok
we recently got some more fantastic acronyms, like CORP and CORB
i am not looking forward to updating my mental model of all of this
you missed COEP
imo, it's a shitty response to the naive design of HTTP
all of cloud is fallout from trying to do things that are fundamentally and forever compromises in attempts to achieving something impossible
This CORP/CORB/god knows what business is there to prevent malicious sites from making your processor run code that depends on sensitive data, and thus learning the data through those cache timing attacks
i guess that’s not really The Cloud for once
it only matters (so much) because of the could, i.e. because everything is constantly connected
I want to add pathfinding for my game enemy's AI however using the A-star pathfinding package in unity I am facing some struggles, firstly my map is generated randomly which means I cant use the grid graph and scan through the component as I have to wait for the map to generate first, I have some unwalkable tiles such as water and other tiles in the future such as (trees and rocks) which will also be unwalkable in the future I am kind of new to the unity so I might be doing something stupid . How could I implement the path finding for my enemy?
this is my mapGenScript = https://pastebin.com/u2jHg09C
I have the seeker component on my enemy prefab, a rigid body 2d and a 2d box collider. How do i make it so that the grid map is scanned according to the randomly Generated map and the grid map also updates in the future when an unwalkable tile is placed like a wooden wall?
i guidline and direction would be quite great!, thanks in advance
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.
In this recorded live training session we show how to work with Unity’s Navigation tools at runtime. We will explore the publicly available Components for Runtime NavMesh Building and look at how we can use the provided components to create characters which can navigate dynamic environments and walk on arbitrarily rotated surfaces, including ene...
Is your easy solution
However, it might be better to do your own solution and generate the graph while you're generating your map but that is probably a further advanced step you can take later
Bro finally some good resource thanks alot 🙏
the path finding algorithm itself should should only consider the V,E but not the grid (or graph) is run time generate or not...
oh you use package, you may consider implement your own path finding
new to game dev so yeah learning i guess
Is there a way to read downloaded mp3/png files from persistent data path in WebGL ?
When I try to read it says access is not allowed (ping me pls)
cinemachine brain switching between vcams, what's the easiest way to have the brain loosely coupled like a dampened rubberband?
It's not allowed. Web pages are not allowed to access most of the system resources.
even if the files are stored in the idbfs ? I thought that it is accessible storage for webgl usage
Hi, I'm new to c# and settled into a pattern of relying on c# events to decouple my code. Everything works out great except I'm stuck thinking about them as "events" and "handlers", where in reality all of that code is called "inplace". So when I call X.Invoke(), and in some onX() handler I want some code to run after all other onX() handlers already run, I often find myself calling unity's Invoke("OtherCode", 0); where the 0 time offset is only there to allow the other handlers to finish. I've already ran into problems because of type-ohs in Invoke(). Is there some other way to run code after the current Invoke() is done with all its listeners?
Should be possible.🤔
Share your code that throws the error.
You can just run your code after invoking the event. It would run after all the subscribers finished responding.
TIL MonoBehaviour.Invoke is a thing, with string name too, yikes.
you can make it slightly better by using nameof().... but yea
I got to the point where I could read it but as byte[] , when I try to convert it to samples (for mp3 audio clip) the sound is corrupted
You can't convert a compressed audio (MP3) to audio clip directly.
Audio clip only accepts PCM, so you need to decode your compressed audio into PCM.
So for example If I have a "Piece" and a "Board", and they both handle an onRestart event. Inside Piece.OnRestart() {... } if I wanted to run code after the Board's on restart has ran I have the choices of:
- Invoke("MoreCode", 0)
- introducing a new event afterRestart and invoke it inside Board's OnRestart (I do this sometimes if the event involves animation, so obviously it takes time to finish.
- introduce the new event, and invoke it immediatelly after first so onRestart.Invoke(); afterRestart.Invoke()
Out of all that the Invoke(..., 0) seems the simplest but at the same time I feel like it's not what it's for (And only works on monobehaviours, so if I wanted to handle Restart in some misc data serialized object I wouldn't be able to)
Unity doesn't expose any other way to use its internal decoding other than UnityWebRequestMultimedia, so you either use that or grab your own audio decoding library.
I was talking about Action.Invoke, since you mentioned C# events.
how to read idbfs file path using that unity WebRequest
Not sure tbh, I'm not familiar with web builds.
YourEvent?.Invoke();
OtherVodeAfterEvent();
I tried to give the unityWebRequest that idbfs (indexedDatabase FileSystem) file path it returns Error 403 is there prefix should be added for the path?
@rancid oxide also asked about the same question earlier, and it seems like there is just no way for UWR to access idbfs, at least from the first few clicks I've found regarding the issue:
https://forum.unity.com/threads/unitywebrequest-load-assets-from-indexeddb.1048646/
https://forum.unity.com/threads/indexeddb-files-and-www.461171/
(Honestly Unity really should expose APIs to decode audio than UWR)
How does your game get your original mp3 file (before saving to idbfs)?
Thanks for your help, but yeah or at least give the Unity WebRequest the ability to read from the idbfs.. thats crazy
In the case of @rancid oxide, they obtain their MP3 from a network request to AWS voice synth, so they could just rewrite that part of the code to use UWR and solve their problem, instead of having to go through a middleman.
I think I will try the NAudio lib to decod the byte[] to pcm
What about this?
It's getting it in zip file that is extracted to idbfs
RIP.
I know the AWS streaming option is valid but I am trying to avoid it because it's gonna cost me every time the user needs to hear the audio
