#archived-code-advanced
1 messages · Page 107 of 1
im trying to create a mask for the water simulation so that its calmer around the beach of the island and then gets more rough the futher out. im using a chunk system to generate the island. this is the code im using the generate the texture per chunk and then i stitch them altogether to create the final result. for some reason though it seams to not be calculating based on the vertices height and i cant seem to figure out why. when calling the function GenerateChunkTexture its passing though the vertices array that was used to generate the mesh so its definitely the correct one
Texture2D GenerateChunkTexture(Vector3[] vertices)
{
Texture2D chunkTexture = new(chunkSize + 1, chunkSize + 1);
for (int x = 0; x <= chunkSize; x++)
{
for (int z = 0; z <= chunkSize; z++)
{
int index = x * (chunkSize + 1) + z;
float y = vertices[index].y;
Color color;
if (y > 0)
{
if (y <= 10)
{
float normalizedHeight = Mathf.InverseLerp(0, 1, y/10);
color = Color.Lerp(Color.white, Color.black, normalizedHeight);
}
else
{
color = Color.black;
}
}
else
{
color = Color.white;
}
chunkTexture.SetPixel(x, z, color);
}
}
chunkTexture.Apply();
return chunkTexture;
}
How are you debugging it?
It looks more like the texture chunks are flipped along the line from top left to bottom right.
Yes, this looks wrong:
//Try:
int index = z * (chunkSize + 1) + x; //Row by Row```
Also you may want to flip the for loops to start with z and then x, not change the outcome but the order of array acces, should be more performant on a minor level. Asa rule of thumb you always start from the last index to the first.
Dear all!
If I make a pc build in Unity, where I can find the spir-v shaders, if the project is using vulkan API?
ahhh i see, thank you so much man
is there a non-"unsafe" way to get the size of a nativearray in bytes (I want to double check how many bytes I'm allocating but sizeof(ParticleSystem.Particle) doesn't want to work without using unsafe)?
The sizeof operator requires an unsafe context.
ty
Hi guys, how do I make it so I can edit a list in OnGui in my editor class? I'm trying to make a function that allows me to add multiple items onto a scene script
These objects will be ScriptableObjects
Nevermind, I did it. Was not that hard suprisingly
quick question, when using ecs should I use a 2d material on a plane rather than a sprite render to change the colour of a sprite in ECS. I cant find a way to access a sprite renderer in code using ecs
context
#1062393052863414313 is the correct channel for ECS questions
So only the container GO doesn't receive the events?
But it does receive the events when subscribed to the derived class?
Please, show the code
Hey guys,
I'm coming here after an hours-long browsing session about "cross-platform determinism" in Unity.
I have come to a conclusion that it is not possible without rewrite a big part of Unity Physics 🥲
However one last thing is in my mind, since we can build a game through IL2CPP to WebAssembly and given that WebAssembly is cross-platform deterministic *(if we disable the features that may lead to nondeterminism: https://forum.dfinity.org/t/how-is-deterministic-execution-of-webassembly-ensured/6335) * would it be possible to have a deterministic game thanks to WASM?
Are they in the same file or have you merged them when sending?
Havok is deterministic. However, depending on the deterministic of a physic engine for cross-platform seem to be a really bad plan.
The issue is that only the container object reacts to the event?
The Clicked method is supposed to be called when pressing the button or ending the drag?
Sometimes, when debugging events I like to convert to a list temporary. It makes it easier to see what is in it.
Well, I guess it's much more managable by creating a list of out inputs and adding the listeners via code
Please, show the code of the container object
Is this the only class?
The method is marked as virtual, is it overridden anywhere?
I know what virtual is, I'm asking you whether there is any wrong implementation of it anywhere
The CheckInput is the method, which is supposed to be called?
But is not called by a single object?
Which.. somehow differs from the others?
What does it mean?
Why?
If you want to use an other platform for example.
Convert to a list temporary, you gonna have a way easier time to debbug
instead of an event
List of action
Sometimes, object that are register are not the one you think of
And it is pretty clear what is register and what is not
And it removes the issue where you copy an event and register on the copy
So the same buttons don't react to the event?
Yes, I mean, don't fire it
Is the OnEndDrag method always called?
You have mentioned trying to debug, so you should've debugged this event too..
Well, surely, the events are not going to be invoked if the method is not even called
Also, I suppose, unity's drag interfaces only start when moving with the element a little bit
Yes, if someone asks me to explain what I'm trying to help you with, I won't be able to answer properly
When does InvokeRepeating call the method exactly?
I understand the documentation and know it is repeated every 'repeatRate' seconds. However I am not looking for that information. I am looking for what calls the method and when exactly within unity. For example is it called right after update, or lateupdate. I can't find this information anywhere.
This is because I have bug in my multiplayer game and I have suspicion that InvokeRepeating is causing it.
You should not use invokerepeat for anything important. That being said, I guess that it would be called at the same moment of a coroutine.https://docs.unity3d.com/Manual/ExecutionOrder.html
nvm I figured it out.
I added a new event in the new subclass, I never did that before on my other game subclasses. But then base.OnEnable() needs to be called specifically overridden to enable the superclass' adding event listeners too.
If subclasses have no statements, the superclass onEnable etc are called automatically. Didn't remember that...
But thx for the duck debugging. Talking and a break solved it. I'm gonna leave this now as a solution, if anyone has weird event call problems on subclasses again.
Not sure why you have removed all your messages though
they didn't contribute to anything
true, the context may be gone, but it doesn't matter at all.
It's a general super vs sub problem to remember.
No reason to remove them all, as they've been answered by us. Now half conversation is gone, so you also won't be able to view it in the future, if needed
I'm using Vector3.Dot to figure out the percentage of how perpendicular an object is to the direction of a slope.
I've got all the directions correct based on the Debug.DrawRay's for the slopes direction and left, but the output is never greater than 0.34ish.
Here is the current code dealing with the angles.
var p = Vector3.Dot(transform.forward, _slopeInfo.left);
Debug.DrawRay(transform.position, _slopeInfo.dir * 10f, Color.cyan);
Debug.DrawRay(transform.position, _slopeInfo.left * 10f, Color.blue);
print($"{p} = {transform.forward}, {_slopeInfo.dir}");
The first picture shows the ray lines using directions from the slope.
Here is output in the first picture for the print statement.
-5.970397E-09 = (0.00, -0.34, 0.94), (0.00, -0.12, 0.32)
And here is the second, when the object is perpendicular to the slope.
The expected output should be near -1 in this case.
-0.341187 = (1.00, -0.02, 0.07), (0.00, -0.12, 0.32)
You'd only get -1 if the directions are completely opposite. Perpendicular, or 90°, would have a dot product of 0.
I don't understand what _slopeInfo.dir is for. You're only using it here for the debug rays and printing, the dot product is comparing transform.forward and _slopeInfo.left.
Hey there, yesterday I mentioned I made a quick script that allows me to add multiple scriptableobjects to handlers, which works, however for some reason it doesn't save! It works in game and the array has the scriptobject attached, but it doesn't work
Here's the function attached
{
//Thanks to rhys_vdw on the Unity discord for help with this function
System.Array.Resize(ref inArray, inArray.Length + 1);
inArray[^1] = add;
}``` Here's that ``AstroEngine_AddToArray`` function, but I don't think that's the issue here
This isn't made at runtime, and changes persist between runtime and editor, but when I close/open the scene, the added objects are gone
Here's the way I get the angles. The hit is from the front yellow ray that goes down.
_slopeInfo.normal = hit.normal;
_slopeInfo.left = Vector3.Cross(hit.normal, Vector3.up);
_slopeInfo.dir = Vector3.Cross(hit.normal, _slopeInfo.left);
However, like I said, the debug rays show that I'm outputting all the correct directions based on the inputs. All the directions give the expected results. The only one not expected is the Dot product.
Do you have domain reload disabled in your editor settings?
Wait, no, it is off
Take a screenshot
That means that the domain reload is enabled.
It's weird that your changes persist between play mode and outside of it. What are the arrays that you modify?
You're comparing these two directions, correct?
And you say the expected output is -1?
Items for testing purposes
Share the code of where this array is defined.
No. The second picture is expecting -1.
There are 2 different print statements I provided. The first is for the first picture, the second is for the second picture.
This is it- Maybe it's because I don't have the serialize flag set to it?
I'm not getting any weird errors
Oh I see. _slopeInfo.dir doesn't appear to be normalized, so the dot product will not be normalized either.
The new items just disappear from the array when the scene is unloaded, then reloaded
Or, in the case of last night, closed the editor and opened it just a few minutes ago
Yes, I did save the scene
Oh, is Vector3.Cross not a normalized output?
I thought it was since the debug ray direction was good 😅
I'll have to double check that when I get home then
Where is it stored?
According to the docs:
The result's magnitude is equal to the magnitudes of the two inputs multiplied together and then multiplied by the sine of the angle between the inputs.
https://docs.unity3d.com/ScriptReference/Vector3.Cross.html
Huh? You said that it doesn't reset between play mode and editor mode..?
It resetting between scene reloads is totally normal. I thought it was the opposite..?
Yes, when I play, then come back to the editor it is fine, but when I unload the scene in the editor, and reload it is gone
I appreciate the help! That more than likely is the issue. But I'll see once I get home tonight 😅
Just a Mono script attached to the gamehandler gameobject
Wdym by " come back to the editor"?
Exiting playmode
Well it should be resetting on exiting play mode as well. Unless scene reload is disabled(but we've seen it enabled previously).
Anyways, if you need that data saved between sessions you'll need to save and load it from disk.
AssetDatabase.ForceReserializeAssets()?
It should just be modifying the array directly
Unity doesn't actually serialize the runtime state of objects. Also, there's not gonna be a convenient system like that in the build. You'll need to implement your own save system.
Okay. So you want to save some runtime changes for them to persist outside the play mode?
No, this is not in play mode, it's while I'm in the editor
I guess I should explain what this function is used for;
I have a lot of apparel objects (like 40-50) I want to add all at once because adding it all separately would be tiresome, so this automates the process, as well as preventing duplicates of objects being added to those arrays
Do you understand my issue now?
I see.
What I'd do is have the data stored in the scriptable objects. Making sure they are saved and serialized correctly. Then it should work as you expect.
They are saved correctly, all the data in the objects is 100% fine
Yeah, it's not saving for some reason
I don't get what is causing this issue
You should remember that what you modify is loaded in RAM representation of the data. Unless it's saved to disk, it's gonna be lost after unloading.
When you modify the fields in the inspector unity knows to serialize them right away, but modifying doesn't code doesn't.
Oh, yeah that makes sense. So, how can I force a save?
Cause even if I use Ctrl+S and File>Save it doesn't seem to save to disk
You'll probably need to use something like EditorUtility.SetDirty and AssetDatabase.SaveAssets to manually mark objects as dirty and save the asset.
I'm not an expert in that field so you'll need to do some research in the docs.
Probably because the objects are not marked as dirty, so unity doesn't save them.
I'm trying to implement a texture2d resize function that makes sense but not sure about these details (documented in code comments)
any pointers would be helpful
public static Texture2D Resize(Texture2D source, int newX, int newY, FilterMode filterMode)
{
RenderTexture rt = new RenderTexture(newX, newY, 24);
rt.filterMode = filterMode; // Do I need to set filter mode for my source tex2d as well? Second source does it, but it seems like redundancy?
RenderTexture.active = rt;
Graphics.Blit(source, rt);
Texture2D result = new Texture2D(newX, newY);
result.ReadPixels(new Rect(0, 0, newX, newY), 0, 0);
result.Apply();
rt.Release(); // This seems like it would be desired behavior? (Even though Unity warns about the active RT being released)
return result;
// Source 1: https://stackoverflow.com/a/56949497
// Source 2: https://gamedev.stackexchange.com/a/114768
}
Did you actually read that code or just copy/paste it?
well aren't you helpful :)
anyways, I got the pointers I needed somewhere else, case closed
The writer was looking for a code reviewal
Anyone from Unity who can tell me if "Game Foundation" is on pause or discontinued?
https://docs.unity3d.com/Packages/com.unity.game-foundation@0.9/manual/index.html
I have an issue related to the Zenject framework. Project Context works fine, and Scene Context does as well. If I have a GameObject Context that is attached to the scene, the installer works because Zenject resolves all dependencies, so everything works perfectly. However, when I create an instance through a factory, i.e., diContainer.InstantiatePrefabForComponent<CarBootstrapper>(prefab);, I encounter errors because dependencies are not being resolved. How can I solve this problem?
NullReferenceException: Object reference not set to an instance of an object
Zenject.MonoKernel.Initialize () (at Assets/Plugins/Zenject/Source/Runtime/Kernels/MonoKernel.cs:54)
Zenject.MonoKernel.Start () (at Assets/Plugins/Zenject/Source/Runtime/Kernels/MonoKernel.cs:37)
Var 2 :same
var instance = diContainer.InstantiatePrefab(prefab);
diContainer.Inject(typeof(CarInstaller));
PROBLEM SOLVED :
public async UniTask CreateCarAsync()
{
currentCarType = currentProgressService.ProgressNr1.CurrentSelectedCarType;
string path = СarPrefabPathProvider.GetCarConfigPath(currentCarType);
assetProvider.WarmupAssetsByLabel(AssetLabels.Car);
var prefab = await assetProvider.Load<GameObject>(path);
var instance = diContainer.InstantiatePrefab(prefab);
diContainer.Inject(typeof(CarInstaller));
}
using BaseCode.Infrastructure.States;
using BaseCode.UI.CarElements;
using Car;
using UnityEngine;
using Zenject;
namespace BaseCode.Gameplay.Car
{
public class CarInstaller : MonoInstaller
{
public override void InstallBindings()
{
Debug.Log("Start car installer");
Container.BindInterfacesAndSelfTo<CarBootstrapper>().AsSingle().NonLazy();
Container.BindInterfacesAndSelfTo<StatesFactory>().AsSingle();
Container.Bind<CarStateMachine>().AsSingle();
Container.Bind<ICarService>().To<CarService>().AsSingle();
Container.Bind<ICarUpgradeService>().To<CarUpgradeService>().AsSingle();
Debug.Log("Finish car installer");
}
}
}
Hi, I got excited today when I realized that I can simply [BurstCompile] static methods (I was previously doing things with IJobs), but I quickly run into [BurstCompile] apparently refusing to compile methods that take in NativeArray as a parameter??
The simple use case I attempted is a method that loops over NativeArray<T> and filters down elements to the existing NativeList<T> based on some calculation, is it possible to do it with a naked static method?
What error message are you getting?
and for what code
Give me a sec for code, I reverted it to job
Basically first I added 'ref' to NativeList<T> parameter, because structs are disallowed,
But than it also refused to call list.Add() method, 'cali forbidden' something something
(0,0): Burst error BC1063: Unsupported parameterref Unity.Collections.NativeList1<Unity.Mathematics.int2>for calli opcode in function Physics2D.BroadPhaseJob2.Physics2D.Execute_00000018$BurstDirectCall.Invoke(ref Unity.Collections.NativeArray1<bool> isStatic, ref Unity.Collections.NativeArray1<Physics2D.Collider> colliders, ref Unity.Collections.NativeArray1<Physics2D.AABB> aabbBuffer, ref Unity.Collections.NativeList1<Unity.Mathematics.int2> contacts) -> void_c31a63c64119e50ba88ee42630b4edd0 from Physics2D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null: FieldNativeList1.m_DisposeSentinelof typeUnity.Collections.LowLevel.Unsafe.DisposeSentinelis not blittable. When compiling a method for use as a function pointer, only blittable types can be used in the method signature, including parameters and return type. To fix this issue, replace the non-blittable type with a blittable type. Blittable types include: void, byte, sbyte, short, ushort, int, uint, long, ulong, float, double, UIntPtr, IntPtr, pointers, and blittable structs (i.e. structs containing only blittable types). Alternatively, use a pointer -Unity.Collections.NativeList1<Unity.Mathematics.int2>*- instead of ref -ref Unity.Collections.NativeList1<Unity.Mathematics.int2>- for this struct parameter.
Ok now I see it wrote a novel as well
Basically the burst preference is for me to use naked pointers in this case?
[BurstCompile] public static void Execute(in NativeArray<bool> isStatic, in NativeArray<Collider> colliders, in NativeArray<AABB> aabbBuffer, ref NativeList<int2> contacts)
OK resolved the mystery - NativeList was originally non-blittable type, which Unity fixed at some version later - I just tried this in an old project of mine, it went away when I upgraded Unity.Collections package
i didnt see a dedicated ui code channel (if there is one pls direct me there) how can i get the background to "move" with the children so it looks like they stay in the same place on the nodewindow
https://paste.ofcode.org/cZjXpxSYu8uVcwi9abFDRk
example video of what i want to NOT HAPPEN
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oooo ty
Is anybody aware of any good plugins/libraries that either make linq faster/ alloc free with no hangups (e.g. limited API), or offer generic methods to replace linq e.g. orderby, selectmany etc offered without linq?
@jolly token made something like that and may have insights https://github.com/cathei/LinqGen
im not sure if i went about it the best way, i am looking to add node-based programming into my game in the same style as unreal engine blueprints
I I tried to use this earlier (I tried a few actually) I installed from nuget and had a spiral of dependency issues, e.g. it needed unsafe and then another, until it finally conflicted with a built in package so I'm not sure if there's a good fix for this because it was actually my first choice, when installed as a package it also resulted in some errors (via upm)
any one know why i get this error:
ArgumentException: Type passed to GetVertexData can't capture the vertex buffer. Mesh vertex buffer size is 1416 which is not a multiple of type size 48
UnityEngine.Mesh+MeshData.GetVertexData[T] (System.Int32 stream) (at <5a87366a6dc74b3aa0e0421cf80e3ae5>:0)
for this bit of code:
using (var data = Mesh.AcquireReadOnlyMeshData(mesh))
{
Mesh.MeshData meshData = data[0];
var vertexData = meshData.GetVertexData<VertexData>().AsReadOnly(); //here
. . .
the error seems obvious but its not obvious why the vertex buffer must be a multiple of 48 that seems like a strange restriction for manipulating meshes unless i misunderstand it
I have been summoned 👀
UPM is the right option if you are trying it out with Unity (Because Unity uses different API for unsafe)
I will give it another try and get back to you on your own discord server if I run into any issues, thanks 🙂
strange its now decided to work without the error 🤔
It only mentions 48 bytes because that's how big VertexData is. The total size of the vertex buffer is 1416, which is not a multiple of 48, so the data cannot match VertexData. You have to have a struct that matches the actual data in the vertex buffer if you want to read it directly like this.
so my vertex data struct must contain the same as what the mesh contains?
Yes. Some meshes contain normals, others don't. Some have many UV coordinates, others have none, etc. It can be any layout.
the issue there is i would need to make variations and check each mesh some how in order to have a valid struct that seems a bit... troubling
What data do you actually want to read? If you don't know the layout, I assume there's only one or a few attributes you're interested in and not the whole thing.
so i need to get the vertices and the uvs for this particular jobs but i have other jobs that need normals, tris and tangents
other jobs need uvs aswell
theres a bunch of different jobs doing different things
and they need to work for any mesh i pass in
struct VertexData
{
public Vector3 Position;
public Vector3 Normal;
public Vector4 Tangent;
public Vector2 Uv;
}```
this is my vertex data struct atm
it was all working fine until i passed in a mesh that didnt have tangents and uvs
Are you specifically trying to avoid making copies of the data? Because there are simpler methods for reading the mesh data, which populates an existing array. MeshData.GetVertices, MeshData.GetNormals, etc.
im using the native array stuff
Everything in MeshData is using NativeArray.
You're trying to use MeshData.GetVertexData, instead of MeshData.GetVertices and etc.
oh wait im thinking of mesh
from the description it reads as if its create a copy which i dont want
the method i chose is just a pointer to the raw data as readonly which is far more performant
These methods handle a lot of the specifics for you. Each attribute can be in a different mesh stream, at different offsets, and can even be in varying formats, like 32-bit float, 16-bit float, 32-bit integer, 16-bit integer.
Populates an array with the vertex positions from the MeshData. this reads like its making a copy which i didnt want
If you want to dynamically read directly from the vertex buffer, you need to pass byte as the VertexData type to get a byte array, and then use MeshData.GetVertexAttributeOffset, GetVertexBufferStride, GetVertexAttributeDimension, GetVertexAttributeFormat and GetVertexAttributeStream to know where to find each attribute and how to interpret it.
where as the GetVData GetVertexData returns a direct "pointer" into the raw vertex buffer data without any memory allocations, which seems far better
Sure, it's better. But it's also more complicated and you have to deal with pointers and reinterpret casting to correctly read from it.
not sure why i need to use attributes here?
Position, Normal, Tangent and UV are all attributes.
i dont need to deal with pointers the struct returns a readonly native array
Yes, but you don't know the layout. So you have to read from it as a byte array instead of a struct array.
ah i see
UV isn't guaranteed to be a Vector2. It's often a Vector4.
But can be any dimension, 1-4.
Same with all the other attributes.
can it 🤔 thats news to me
If your meshes are as small as 1416 bytes, you really don't need to worry about the cost of copies.
I'd start with that and then profile. If you're not happy with the performance, you can implement it using the byte array.
yeh but im doing it each frame
I'm not worried about it. You only allocate the arrays once, unless you're reading a different size mesh every frame, so it's just the copies that are happening each frame.
Even with the byte array approach, you're still reading and interpreting the data, which the copy methods are doing for you. So the only extra thing that is happening is an extra store and read on a native array.
i see
ok ill do some changes then
such a shame because it was super clean the approach i had until now 😄
Is it necessary to divide polygons into triangles? The painters algorithm isn’t working for me so I want to combine scan line and z buffer. However I need to be able to find the z values of points bounded by the now 2d polygons. I believe barycentric interpolation is the fastest way. Should I split all my polygons into triangles at the very beginning when reading the .obj files, or is there a way to interpolate z depth just as quickly for non triangle polygons? Thanks ahead of time!
I would guess working with the triangles would be the easiest way even if there might be slightly faster way to do it. One problem with polygons other than triangles is that they are not always flat coming out of the 3D modelling programs which means there's for example two ways to triangulate a quad (see the example below) which both produce different result. Even if you find a general interpolation algorithm for n-gons, it likely wouldn't work at all for those non flat polygons since in mathematical sense polygon that doesn't lay on any flat plane simply doesn't exist. Triangles are usually the easiest way to represent a mesh because of their unambiguous nature. Just out of curiosity, why are you using the painters algorithm or something similar to begin with?
Hello there,
I have a project on the Oculus Quest 2. Essentially, I need to be able to see what the person using the Quest is seeing on another Windows application.
To achieve this, I connected my Quest 2 to this Windows application using Unity Render Streaming for the video, and Node.js for everything else. Node.js works fine, but Unity Render Streaming keeps throwing errors.
It works in the editor, but not in builds.
Here is the error message:
08-02 14:57:41.314 23049 23344 E Unity : at System.Net.Sockets.SocketAsyncResult.CheckIfThrowDelayedException () [0x00000] in <00000000000000000000000000000000>:0
08-02 14:57:41.314 23049 23344 E Unity : at System.Threading.Tasks.TaskFactory1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func2[T,TResult] endFunction, System.Action1[T] endAction, System.Threading.Tasks.Task1[TResult] promise, System.Boolean requiresSynchronization) [0x00000] in <00000000000000000000000000000000>:0
08-02 14:57:41.314 23049 23344 E Unity : at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00000] in <00000000000000000000000000000000>:0
08-02 14:57:41.314 23049 23344 E Unity : — End of stack trace from previous location where exception was thrown —
08-02 14:57:41.314 23049 23344 E Unity :
08-02 14:57:41.314 23049 23344 E Unity : at System.Net.WebConnection.Connect (System.Net.WebOperation operation, System.Threading.CancellationToken cancellationToken) [0x00000] in <000000000000000000000000```
I've tried the following:
Ensuring all options are correctly set in the editor (I set the "Internet Access" property to "Require", the "Allow downloads over HTTP" property to "Always Allowed", and verified that the "Force Remove Internet Permission" property was not true in my Oculus settings).
Creating a custom manifest and adding these options:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Adding the property android:usesCleartextTraffic="true" in the Application tag.
Changing IL2CPP to Mono, but it didn't work since OpenXR requires IL2CPP.
Does anyone have an idea what could be causing this error? Any help would be greatly appreciated, as I am currently very stuck.
Thank you very much.
just to check, are you sure the headset can access that URL? like can you get a connection from the web browser?
Yes I can. The url is basically my own IP since the applications works on local, not on a distant remote.
Plus, Node JS works since I have a feature where a yellow appears on quest where we clicked on the windows application, and I do see it when I test.
Basically, it seems it the video which is not working, since it's render streaming who give me this error non-stop
so what ip address are you using?
It's my ipv4 ip address, something like "192.XXX.X.XXX"
ok, so a local ip address. Port number?
It's 8080
and that's open in the firewall and the quest is on the same network?
According to the commad "netstat -aon" I don't think so, the port does'nt appear
so open the port
dont know if the quest has a web browser, if not you can use your phone's browser to test the connection. Just make sure you have mobile data turned OFF and WIFI turned ON
im guessing your ip address is something like 192.168,1,103
so
http://192.168.1.103:8080
in the browser should do the trick
Ok so
Yes I can acces my desktop application, it opens me a windows with the name of my company.
So the problem seems to be in game...
But it doesn't help me at all since it works in editor, it's in build that the error appears...
working in editor and working from an external device are 2 completely different things
(I did test in oculus and on my phone)
Yes I know
But I'm at loss of solutions right now, and I tried a lot of things :/
I guess you're using the node http package
I'm using Node JS, and Unity Render Streaming
I know that, I asked if you were using the node http package for the network connection
just to try another debugging avenue, can you try making HTTP requests from game code, separate from all the video streaming stuff, and see if those work?
that might at least indicate if it's a permissions issue or something
Oh sorry !
No I don't think so, there is a node js connection AND a connection with Unity Render Streaming, both are independant.
Node JS is working, Unity Render Streaming isn't
now I am confused
Unity Render Streaming is used just for the video, everything else pass by a node js connection which is working
I can try but Unity render Streaming is only used for the video, and the others requests works and use Node JS...
isn't the stack trace you posted from the render streaming code, assuming the other bit is OK? so i guess it's making HTTP requests to that URL which are failing?
The other bit is ok yes, but both are using the same url
so are you making requests to that same url using UnityWebRequest?
that is not possible
they must, at least, be using different port numbers
I'm not using Unity WebRequest, I'm using node js and Unity Render Streaming
Yes the port are different
I just meant the base url is the same
OK, well i'm saying try requesting the same URL with UnityWebRequest and see if it can access it that way
i don't know how render streaming makes its own requests but it'll be a lot simpler to debug if plain old UnityWebRequests are also failing
so did you open both ports in the firewall?
and test from a browser?
hi there
does anyone have any experience with UniTask?
I'm aware thats a 3rd party library, but it doesnt really have a support way
I'm trying to cancel an async function from outside with a CancellationToken
this is my test code so far
CancellationTokenSource cts = new ();
cts.CancelAfter ( TimeSpan.FromSeconds ( 3 ) );
await UniTask.Create ( async testCt => {
while ( !testCt.IsCancellationRequested ) {
await UniTask.WaitForSeconds ( 0.5f, true, default, testCt );
Debug.Log ( $"Running: {Time.time} " );
}
}, cts.Token );
Debug.Log ( "Completed" );
so far the function inside create does terminate, but .Create itself never does so Debug.Log("Completed"); is never called
any ideas how to write this properly?
I want to render depth correctly. Imagine a floor with a table on it. Pointers algorithm doesn’t render this properly, so I am combining scan line (to find all pixels in a polygon) with z buffer (which requires barycentric interpolation) to update. We know the vertices depth, but what about the 2d points bounded by the projected vertices?
Since you need triangles to do this, and some obj contain non triangle polygons, I was wondering if good practice is to split all polygons into triangles.
where are you calling this from? i don't remember exactly but UniTask.WaitForSeconds ought to throw TaskCanceledException once the token is cancelled so it's possible the last line is never reached (because of the throw) and you're not logging the error properly
you're right
adding .SuppressCancellationThrow fixed that
Hello
How to readback data from a async compute shader (via async command buffers + ExecuteCommandBufferAsync)? I'm having trouble to figure out, how to wait for them and readback buffers...
Probably I need a separate command buffer (synchronous), then wait for the compute shader and then request the readback... right?
You could use a fence if your target platform supports it.
https://docs.unity3d.com/ScriptReference/Rendering.GraphicsFence.html
Cool, thanks!
Is anyone coding a 3d engine from scratch? (Using OpenCV or numpy, no OpenGL)?
I asked a question but it got buried.
How do you do depth sorting? I was imagining taking each polygon, doing scan line to find all pixels inside, then using barycentric interpolation to find the depth of the points inside the polygon, in order to compare them against a Z buffer to know if we should display the pixel on that polygon. However that works only on triangles right? So you need to split all polygons into triangles at the start before you do this. But when clipping (for triangles partially behind you) do you need to also clip the triangle, and then triangulate again?
Dont you think this is a rather odd question to ask in a Unity server?
Sir this is a Wendy's
#1157336089242112090 is the closest thing on this server
I was hoping someone did some source code reading.
Why don't you use depth buffer like any other 3D engine out there? Isn't really unity related then though as others pointed out
I'm getting an error when I try to add NewtonsoftJson package via the package manager. Does anyone know whats going on here?
The package should be added by its name:
com.unity.nuget.newtonsoft-json
After the download is completed, reload Unity
Hello, I am trying to use the Entities.ForEach function but it doesn't seem to exist in the new versions of the Entities package. Does anyone know what the alternative is?
Finally, that worked. I found so many variations in the documentation and online but none of them worked.
thanks
The traditional foreach is all you use now. Thankfully
But ask for more in #1062393052863414313
ah I see thank you!
oh sorry didn't notice the channel ;-;
am i stupid or can you not for each over an ienumerator
You can't. It has to be an IEnumerable.
But one class/struct can implement both and just return itself in the GetEnumerator method if you like.
i probably should have made it an ienumerable anyways i was trying not to for some reason
thanks
A single one?
yeah a method which yield returns
If you have references yeah.
Like a list or an array
if it is a single one you can't but I don't know why you want a single one.
i think youre thinking of ienumerable
No. I know what you're talking about
i was just triyng to create a customer iterator, thats all
Yes you can
yeah i figured it i just made my class ienumerable
Whatever floats you boat 🤷
Been pullin out my hair a couple days on this one. I'm having trouble building (for the first time) to iOS from Unity. I have a working project for android that I can build on my windows box or my CICD tools. I'm trying to build an iOS version on my (new) macbook - I'm not an ios/macos person at all.
The xcode project is generated just fine, but trying to compile it leads to frameworks not found (specifically IronSource.h). I've tried nearly everything ten pages deep on google/SO, including installing the proper version of cocoapods (I'm on the latest, confirmed in unity's verbose output), manually bringing frameworks into both/either xcode and unity's plugins folders, manually linking all of the suggested frameworks/libraries in xcode (libz, libsql3.0, javascriptcore, ... etc), and trying a number of variants of the external dep resolver, including generating the xcode project/workspace/none and doing the pod install command myself manually. I even thought maybe it was a space or a special character in the directory so I removed all of those and ensured the env variable LANG was set to utf-8 and en-US.
No luck. Anyone got any advice/tips, or barring that, a favorite alcohol to drown myself in tonight and forget about this?
why does unity's example use normals with 2 components ? aren't they vector3
seems a bit odd
It's just trying to show all the different format and dimension options you can use.
ah i see
Okay so need some help with deciding what sort of pattern/design I'm going to go for. I'm currently working on making a flexible agent-based AI system (not ML but just usual game AI). I already have decision making and actuation figured out so I'm not trying to make that part modular, instead I'm looking to make all the other things such as locomotion, animation, equipment/weapons, health, etc. modular components (probably also MonoBehavior components for easy designing in the editor) that I can essentially plug and play, and make everything loosely coupled so that if something is missing and a behavior/action requires it, it won't cause compilation errors or crashes but rather that particular behavior just doesn't run properly. This way, I can have generic behaviors such as MoveToPoint, AttackTarget, etc. that work across multiple agent types that might have different locomotion, animation, or combat components without needing to define the interactions with these different components in the behaviors themselves, just generic objectives that would get executed by the components with callbacks so the behavior knows when they're complete.
Is the IronSource.h even exists ? If not, have you look where it search, sometimes with builder/compiler you can look at command Unity is doing to build. (In theory, you should be able to manually make all the command, some of them are simply batch files. There is also the case where manually doing command give a more verbose error)
bool[][] tileGrid = new bool[tiles][]; // Create an array with 50 rows
for (int i = 0; i < tileGrid.Length; i++)
{
tileGrid[i] = new bool[tiles]; // Initialize each row with 50 columns
}```
i have this 2d boolean grid which rappresents the coordinates i want tiles to be placed. i googled but can't find an algorithm that generates tiles as if they were rooms in a dungeon. Any suggestions?
trying to recreate this line in the new ECS versions, any idea how I can specific the components?
var newParams = new Params...
}
Hi, everyone! I have a racing game where players earn points in races which accumulate throughout a grand prix.
Points are stored in an unsorted int array whereby player0 is the first entry, player1 is the second entry, etc.
At the end of the grand prix, I sort a copy of the array to determine the winner, but I need a way to determine which points set belongs to which player.
I am trying to check through each entry of sortedPoints[] and compare it to originalPoints[] so I can determine which player owns which set of points and can therefor determine the grandPrix results order, but I am having a hard time going through the list and comparing and setting up the sorted array correctly.
There might be a much better way to associate an owner to each value than how I'm doing it too. Let me know if so.
public int[] points;//copy of GameManager gpPoints array.
int[] oriPoints;//copy of points for storing before sorting.
int[] sortedPoints;//same as Points but used for applying inverted sorted values (largest first, descending).
int[] standings;//list of player IDs 1-30 for being sorted in the same order as points array when determining standings order.
public Text messageText;
void Awake()
{
oriPoints = points;
sortedPoints = new int[30];
standings = new int[30];
Array.Sort(points);
for (int i = 29; i >= 0; i--)//copy the points array after it was sorted to invert it
{
sortedPoints[i] = points[29-i];//inverts the order of the array so it is descending.
}
for (int playerID = 0; playerID < 30; playerID++)//30 racers
{
for (int pointsEntry = 0; pointsEntry < 30; pointsEntry++)
{
if (sortedPoints[pointsEntry] == oriPoints[pointsEntry]) standings[playerID] = playerID;//check to see which points value belonds to playerID
}
}
}
This really isnt an advanced issue. Simplest way would be having a class store your playerID and their points. Have an array of that new class
sounds like you need a SortedList<Points,Player>
Thanks, this looks to be what I'm after.
It's usually a good idea to make your own class instead of using primitives. Something like:
public class PlayerData
{
public string name;
public int id;
public int points;
public List<RaceData> results;
}```
That way you can easily extend any data you might need later on.
Ok, so I could make a class with two ints, the playerID and the score. What would be the best way to sort the array of Classes by score? (or am I misunderstanding?)
List<PlayerData> sortedList = playerDataList.OrderBy(x => x.points).ToList();
note it's not an array of classes. It's a list of instances of that class.
Yeah, it does.. It was kind of a long chase down a rabbit hole, not even sure entirely what fixed it in the end. 😐
xcode is really... not great. And me (the mac noob) just found out that VS for macos is being sunsetted.. so I am .. exploring IDEs. Anyone with strong feelings on an IDE (for unity dev) on macs? Rider seems to be the consensus..?
VS Code and Rider pretty much are your only options. I use VS Code everywhere though.
why does my plane in editor looks great, but in run mode just white?
so, im having a problem that i have never had before in my years using unity, i THINK it might be a memory leak, but honestly i have no idea and ive never dealt with a memory leak before, but when i start up my project which btw is a practically empty project right now, it runs great, 200fps in play mode, but then as soon as i change something in the scene for example changing a value of my move script, add/remove any script, add/remove a mesh, ANYTHING, my frames instantly are reduced to a constant 50/60fps when already in playmode or when clicking play the next time until i reload the scene or restart unity. No fucking clue whats going on here any help is appreciated
Any time you want to diagnose a performance issue you need to use the profiler
mann i was trying to avoid that cause honestly that goes right over my head

I would first try a different unity version / fresh install / use a different PC to narrow down the issue
Probably your in-game camera doesn't render something or does it incorrectly. Use the frame debugger to debug that/compare draw calls from the scene view and the game view.
There's a lot of things that it could be, but it's probably not a memory leak. If you're dealing with managed CPU code with strictly managed object, it is near impossible to create a leak because garbage collection will handle it. The only way is to allocate memory on some other part of memory that is not managed, like a nativecontainer, computebuffers, rendertextures, etc. Usually this doesn't slow down performance at all, and unless you're physically mallocing memory with UnsafeUtility or Marshal, your memory is tracked and it'll tell you if you have a leak
Basically leaks won't happen unless you're being very unsafe
How wasteful is returning a struct from method calls with information on the operation? ```cs
public struct CommandResult<T>
{
public Exception Error;
public string Message;
public bool Success;
public T Target;
}
public class Test
{
public CommandResult DoThing()
}
I would use a ref parameter and maybe return the bool Success
Is that to avoid extra garbage like copies of the Message in memory?
yes
also you might like to constrain your T
I generally do not like structs which contain objects
Why is that
Because of the impact it has on the managed and unmanaged memoty
Ah, I see. I'll keep that in mind as I'm trying to be as conservative as possible with resources
then make it a class unless you have a really good reason for it to be a struct
I may not even have a good enough reason to do it this way in the first place 🤷♂️ I'll have to think about it a bit more
lol, that's why we design our data structures BEFORE we write any code
I already print out the relevant error messages and throw exceptions in the methods called, so it's a bit redundant to then return that information back to the caller
I may just return a number denoting the result of the function and use out parameters for return values
public EnumResult AddNumbers(int a, int b, out int c)
{
c = a + b;
return EnumResult.Ok;
}
Like that
that looks more like app dev rather than gamedev
It's a library for game dev
ok, library code is much more similar to app dev
While I'm here, do you have any idea how to get around Unity's garbage collection issues with reflection?
now that is a very complex issue with no simple answer
tbh I would just ignore it unless it really becomes a severe performance issue because it's a rabbit hole you really do not want to go down
Okay thanks
Hey, just thinking... This SHOULD be fine. Right?
you could also use a UniTaskCompletionSource for that fence.passed state/event here and await it, witch would be the "clean" pattern.
Thanks!
but "technically" it would do the same thing... you're just more expressive about it, with some easier to follow logic
You can also use UniTask.WaitUntil
But if you are going to do this many times, it's better to use UTCS to wrap it into a task so you can await it.
Anytime you have callback based code and you want to turn it into a task, use UTCS.
I’ve decided to post this here since #💥┃post-processing seems not the place for it, no one asks about scripting issues there. I’m not sure where to post this tbh.
So I’ve created this custom render pass but it only works in play mode, in edit mode the screen goes black. Assume the shader/material isn’t the problem (it works just fine as a render feature fullscreen pass).
https://gdl.space/exomumucuk.cpp
What is wrong with my code? Releasing the _target RTHandle causes the black screen, but if I don't I get a huge memory leak from the render texture constantly being allocated.
In the frame debugger, one step it’s fine, blitting to the blit texture, the next it just goes black. Weirdly enough, in play mode when it works, it still goes black in the frame debugger (but not in the game view).
I know this is a long shot but I wonder if anyone has come up with a good metric for predicting how much a prefab will effect performance when Instantiated? I have built a test to measure the FPS drop + time to instantiate each prefab, and have also pre-calculated the following information for those prefabs:
- Size on Disk (within the Unity Editor).
- Size on Disk of the prefab's dependencies (meshes/textures, etc.)
- Time it takes to instantiate the prefab within the editor (outside of play mode)
- Total Vertex count of all MeshRenderers on the prefab or children of the prefab.
- First level child count of each prefab.
However, none of these metrics correlate with the measured FPS or time to instantiate.
Does anyone have any other ideas for other metrics that might be correlated? Or even better, has anyone tried to do something similar to this and can offer suggestions? Or is the only approach to just test out the game and look out for lag?
For context the prefabs are basically an empty parent game objects with a variable number of child objects (which contain the actual content used in the game), and I have control over how the prefabs are organized (i.e., the makup of the children). So I am attempting to write an algorithm that will optimally setup the prefabs so they don't impact the FPS when loaded (for example, limiting the amount of children on each prefab such that the vertex count doesn't go over 10,000).
Your approach seems... wrong.
- Why do you need to predict the performance? Just measure it in build 🤷♂️
- Profile (deep) the instantiate and you'll probably see what eats the most time. I assume vertex count doesn't matter. All instances are by default gonna use the same mesh, so that would only be instantiated once.
- You should obviously pool things, and if something is too slow to instantiate - do so in a loading screen as to not drop FPS in the middle of the game
Those are my... starter tips, basically. One needs to investigate (measure performance) and try different things to see what matters.
this is probably intended for edit mode
Respected,
In unity,
i want to get the multiple points of like oval shape where raycast hit on the mesh object, and update the color of textures on those points..
i have tried but i didn't get the oval shape and my solution update the color of texture but get the wrong points..
e.g A building texture, different parts are present at different places on the texture..
If anyone have any solution then please guide.
Thank you
Main point remains - profile the thing you want to optimize, see where the problem is, experiment, address. 🤷♂️ No guesstimates or predictions.
i think the use case is for some sort of automatic world sharding
I have a product that dynamically loads/streams in content at runtime, based on different criteria, but typically player location. It's primarily intended for large worlds where loading the entire game is just not possible due to memory constraints.
As part of this product, I have a tool that breaks down large scenes into smaller game objects (which can be stored in scenes or as prefabs). Each of these game objects is just an empty parent with child game objects; those children are the original objects in the previous large scene.
So to answer your question, if there is some criteria or metric that I can use to predict load performance, I can design the tool to organize the child game objects in a more efficent manner.
there isn't really any metric that works generically, you would have to make a rather complex system that analyzes everything based on your knowledge of what works well (performance wise) in unity
typically such a system would ask the game-dev to make these judgements and the automation would just use fixed counts/sizes, or tiers, again defined by the dev
Thanks. That is what I figured; but just wanted to ask in case something like this had been done before. I know there are a lot of variables, for instances the way meshes are used can change whether the Async Upload Pipeline is used.
Interesting problem, haven't had to deal with it myself. I'd profile in runtime to see which part of this loading is slow / fast. And then look into how to balance the things.
which can effect performance
you would basically create the unity-performance-guide ebook in script-form
It was a long shot but still worth asking haha
if this were a well defined individual project, you could maybe come up with some metrics
but even then it seems very difficult, not just deciding on the weight, but also puzzling the shards together
Having an automated system to run the game with the objects in various combinations is probably the easiest way to attach cost to objects, but it will never be super accurate. Hardware differences aside, even the way rendered objects are arranged in the scene or how algorithms scale with few vs many objects will skew the results.
regardless, things like that are being done in various forms at runtime for performance optimization, just not on the gameobject level, rather at a very low level and for very specific data
👍 Thanks everyone for your answers!
Respected,
In unity,
i want to get the multiple points of like oval shape where raycast hit on the mesh object, and update the color of textures on those points..
i have tried but i didn't get the oval shape and my solution update the color of texture but get the wrong points..
e.g A building texture, different parts are present at different places on the texture..
If anyone have any solution then please guide.
Thank you
I'm importing a large number of prefabs (with meshes, animations, sounds, particles, materials, scripts) from a defunct project that we're repurposing. Unity doesn't make "copy and paste" between projects easy, but the export of the old project is 5GB.
Anyone have any good strategies for this?
My initial thought was to create a "[redacted]-Import" folder (in the new project), import everything, and copy and paste them (within the new project) to a better location as part of a .. digital asset import workflow. The problem with this is.. I'm not sure how to ensure that any references to the old stuff are clean.
Do you have a picture of what you're talking about? Also please check your english I'm having a hard time understanding what you're saying
is there a way to prevent unity from making *.meta files in the StreamingAssets folder?
no, Unity needs those
for inclusion in a build
it's internal for mobile and WebGl builds
interestingly they dont end up in the streamingassets folder of a standalone build, but know you cannot seperate .meta files from their host
because Unity needs WebRequest to extract them and that uses the asset database which relies on .meta files
that makes no sense, u can read a unityasset file without .meta
its basically a zipfile.
webrequest doesnt need .meta, its simply a webrequest
not in a build
even in a build, u dont download an asset with its .meta using the webrequest.
u only get the .unityasset package.
then fetch inside it.
what are you talking about?
nothing nvm
You can prevent unity from making .meta with Hidden Assets. https://docs.unity3d.com/Manual/SpecialFolders.html#:~:text=Library Project.-,Hidden Assets,-During the import
Hi, I set one of my uv coordinates like so
uvs[0] = new Vector2(0f, 0.12345f);
_meshRenderer.sharedMesh.uv2 = uvs;
print(_meshRenderer.sharedMesh.uv2[0]);
and here is what gets printed
why does it lose precision?
how can i prevent this?
what is displayed is not the full contents. use a ToString to add your own formatting string
let me try
i was worried, thanks
Anyone have experience launching to the windows store using the Microsoft GDK? Specifically, I'm getting a 403 response when using the GDK store association tool, and I'm wondering if there's some privilege I seem to be missing to authorize that call. The documentation doesn't seem discuss privilege access as it relates to test accounts and the GDK.
I did made the integration with Microsoft GDK and I do not remember to have any particular issue. Just be sure that the account you use to link the Microsft store and the game is correct.
Thanks, ya pretty sure it's an issue with the account I'm using as the login. Will sort it 
RegisterCallback<ValidateCommandEvent>(OnValidateCommand);
RegisterCallback<ExecuteCommandEvent>(OnExecuteCommand);
Hi , i can catch TextField copy paste actions with these callback when i press right click and open menu if i trigger paste these actions will catch but when i trigger them on keyboard (CTRL-C etc.) it wont trigger these callbacks how can i catch them ?
From what I understand by reading the documentation, the keyboard shortcuts are supposed to work too. I think this is a bug.
@sly grove
Probably so, I will have to catch them all one by one from the keyboard event and do something custom...
Report a bug!
GUIUtility.systemCopyBuffer this field is all competiable with (win,macOS,linux) right i dont have to implement platform spesific regions ?
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Anyone done a Google SSO & unity WebGL (Unity Web) integration? Any tips? My plan was to do the SSO external to the unity applet then ... call it from one of the methods here: https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
I don't need firm auth - the client just wants to collect email addresses via google sso for a web based demo. Not sure what the best architecture is for this.
https://assetstore.unity.com/packages/tools/integration/google-sign-in-webgl-217671#content
Seems good, maybe... Didn't think about just embedding all of the auth workflow directly in the app..
Hi, i have a spicy question :
I have a voxel "game" where i have a bunch of chunks. I heard that in games their is the simulation layer and on top of it their is the display layer.
But in a voxel game, is it usefull ? like i still need a bunch of data to hold all the chunks information and the display seems not to be much...
For the simulation i would still need to have a lot of information running in the background.
Simulation layer typically refers to the gameplay rules and transient data model that holds the gamestate. The view/display layer is then the representation of that state. Whether your voxels participate in both or just one of those layers would decide where to put it. Maybe you want to put parts of it into the sim layer and others into the display
The display layer typically refers to the rendering engine building draw commands, setting up the GPU state, etc, via the graphics API.
Game engines, like Unity, handle most of it for you. So you usually don't have a display layer in your code base, unless you implement some custom rendering features.
Ohhh okay thanks for both of you.
Another question, i was able to find that some objects and data were not destroyed when the playmode was exited, in the basic memory profiler (not the plugin) i wasn't able to find which kind of object was not destroyed.
Do you have things that could help me find what is not destroyed ? I will try to find with the memory profiler package but if you have other ideas i'm all ears
For starters, how do you know that there are objects that are not destroyed?
When i start Unity, the memory usage in the task manager is about 2.5GB, when starting the playmode it goes to almost 9GB and Unity's profiler says the game use 6.5GB then when stopping the playmode, unity still takes around 6.5 to 7 GB of RAM, and when restarting the playmode, Unity takes 10 GB of ram and use the disk as ram because i have no much ram left. And the Unity's profiler now says 10 GB
First, it could be just memory reservation. Unity wouldn't release all the memory after consuming it once so that it can reuse it.
If you see the memory consumption increasing every time though, that might be an indication of a memory leak.
You can use the memory profiler package to see what eats the memory. Aside from that you can see if there are any allocation during the average frame and investigate them for a leak.
Hi everyone, I also come with a very specific question: I have a very complex system, that is streaming data (meshes/textures) into unity. This is realized using async tasks in our own worker threads. To be able to do changes to game objects etc, I created a queue that queues calls into the main thread. In general, this works very well, until it does not 😩 I get random lag spikes where calling the method takes several ms while the method itself runs fine. I tried to create a minimal code example but could not reproduce the problem. I will attache a screenshot of the deep profile. The call to <>c_DisplayClass115_0.<SetUpGameObject>b_0() is making it slow.
The question is: What could trigger this kind of behavior? I already wasted weeks on this. Thank you for your help!
What's runinmainthreadtimed
Its a wrapper action that adds the ability to wait for the execution
- the weird name shown denotes how lambda expressions are compiled, in some precise cases a private class will be created to store the eventual variables captured by the lambda
Show code
Known by the compiler as display classes
yes, it has lambda calls
gets called like this RunInMainThreadTimed(() => { runns in main})
Basicly this:
RunInMainThreadTimed(Action mainAction) {
QueueItem item = new();
item.action = () => {
//code to do wait
mainAction.invoke();
//code to signal finished
}
queue.Add(item)
}
Problem is, its random when the code will be slow
Is the queue thread safe? As in, it should be from the System.Collections.Concurrent namespace, like a ConcurrentQueue<T>
Weird, I don't remember it having an Add method
Sorry, its mainQueue.Enqueue(item); and if (mainQueue.TryDequeue(out e))
Can I post full code here?
Yes, use a paste website if there are multiple classes or if it's longer than 20 lines or so
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Thats the minimal example without the waiting SemaphoreSlim, has the same problem as the Deep Profile
Seems like your loop just runs all that time.
no, it does not. It either stops if there are no items left or the time budged of 5ms for that frame is used up
I moved the conditions inside the loop to better debug
Well, the profiler doesn't lie. You can put the markers right before and after the loop and see for yourself.
You could put more markers in the loop. To see what's going on in details
Sorry, Im not sure what you are profiling. A endless loop in Update() would lock up unity
And it does. for 19 ms in your case.
What's RunInMainThreadTimed? Is that a different class/method?
The while loop is not looping in my deep profile. Its the call to <>c_DisplayClass115_0.<SetUpGameObject>b_0() that takes the 19ms and then the loop is exited
The difference betweeen the minimal example RunInMainThreadTimedNoAlloc and RunInMainThreadTimed from the profiler image is the ability to wait for the execution in another thread. The same problem occurs in both.
the call of the lamda fuction <>c_DisplayClass44.0.<RunInMainThreadTimed>b_0() makes it low, <>c_DisplayClass115_0.<SetUpGameObject>b_0() is fast again
Share the real code then
I can not share the whole project for obvious reasons, the code that I posted is the 1:1 the code causing the issue. I will try to get a matching profile of it
Now looks like this. Time is used in the sample ThreadHelper:RunTimedInternal, but not in the called methods. I'm going crazy
this is a deep profile!
Does it take as much time every time it's getting called?
No, thats the issue. Its random
Then it could be the GC
It doesn't appear in the profiler when it collects
Since you allocate quite a bit in that update
That was my first thought, but its not gc
Do you have the incremental GC enabled in the project settings?
How do you know that?
there are other gc spikes 😄
Try enabling the incremental GC and see if you can reproduce the issue
incremental gc is enabled and fps are caped at 90fps
the streaming of textures causes a lot of GC with larger chunks. The GC should not hit this method every time so we already looked into it. I Suspected some JIT issue, but I have no idea how to locate that
Can you reproduce it if you only keep the action invoke?
item.action = () =>
{
UnityEngine.Profiling.Profiler.BeginSample("ThreadHelper:RunTimedInternal");
action.Invoke();
UnityEngine.Profiling.Profiler.EndSample();
};
Well, if you're right and it's the JIT compiler, then all you need to do is just not use lambda expression
I could use a named function, but I was under the impression, that lambdas should not have any performance impact
You could also use Il2cpp to try
Test it and see for yourself. And tell us the results.
Well, you can test it first and worry about real implementation later
Maybe that's not the cause at all. Who knows.
Then it is not JIT isnt ?
Is there something I'm not aware with lambda? Since lambda just compiles to a class where captures are the class members, and the lambda itself is a method of the class. I don't see how lambda could be the cause, especially if it's in IL2Cpp.
no, that was my assessment as well
fact is: Im loosing time in a function that is not captured by the profiler nor a stopwatch
Lambda is just syntax sugar where compiler turns it into a class method, it shouldn't matter if it's the compiler that does it or you manually write it.
Well, there are not many other clues, so why not test it out anyway
Also, I wonder if il2cpp is working at all in the editor🤔
I've only just reading the conversation now, have you looked at the time of each individual task (with stop watch) and compare it to the total time of all tasks (also with stop watch) in a frame?
My impression was that it's only compiling with il2cpp during the build.
That's correct, which makes profiling iffy that the performance characteristics in editor may not match the actual build.
yes, I have a stopwatch outside the function that says 19ms for the call , than a stopwatch inside the function that says <5ms
build has the same problem
Its not that the calls down the line could not cause the delay. The methods called using this method are mostly time intensive like create go or texture. But without seeing the real problem, I can not fix it
Well, for starters I'd eliminate all the possible culprits:
- profile only in the il2cpp build
- get rid of the lambda
- get rid of the allocations inside the suspect method.
If despite all of that you can reproduce, then there's really some magic invisible something taking the CPU time.
If you disable the incremental GC and have no allocations inside the target method, the GC shouldn't collect in it's scope I think, so that would help eliminating the GC as a culprit.
Running without allocation is nearly impossible in my current use case, even for tests. Streaming data always requires some kind of allocation. I started using pooling but have a long way to go
I will start start with the lambdas and report back
I mean without allocation in the immediate scope of the method that causes the issue.
basically, get rid of the stopwatch
Or construct it outside
The stopwatch was added after the problem was discovered
Well, at this point we're not sure it's the same problem you had originally. Things might have moved and shifted. All we can judge now is the current code.
Besides, there's no point in a stopwatch, since you have the profiler data
When debugging/profiling, you should be careful not to introduce changes that might affect the results of the debugging/profiling or your interpretation of them.
That's why native profiling tools are always better than timers in your code.
Logs are a good example of that too.
I agree, the stopwatch was added to find the missing time from the profiler, only to discover that the time is also missing with the stopwatch
I'm a developer for over 15 years now. Most of the the problems I have seen over the years, but this one is new
Just playing catchup on this thread but a thought - could it be something like, if it "hits" the main thread as the main thread has just sent everything to the GPU and is waiting for the next frame, it stalls for that period?
The action is executed from Update, so I don't think that's the case.
its inside update it should be between sending to the gpu
its possible that its some kind of context switching problem
weird, but that would be my bet.
But how could I debug that🙃
😬
Context switching usually happens on mutexes/locks or some platform system API. I don't think there's any of that in the method with the issue. The only place that might be happening is when you dequeue the action, which is in different place.
Hello, I have a problem that block me for my Unity game, can someone help me please ? I would really appreciate it.
https://discussions.unity.com/t/fatal-error-in-unity-cil-linker-failed-to-resolve-assembly-unity-tasks/1496019
dequeue is very fast, I profiled that
Yeah, I can see that from the profiling data that you shared.
Wonder if there's a way you could rewrite the main thread stuff to all live in Coroutines or similar and see if the issue still occurs?
Do you have a Unity.Tasks asmdef in your project assets?
Just a sanity check, have you tried logging watch.Elapsed.TotalMilliseconds at the top of while (true) loop in Update?
I could try that
Did you have a chance to profile the il2cpp build yet?
Yes, lastExecTime and lastDequeue are near zero
Hello guys, how can i update Google Play purchases? Is it enough to update Unity com.unity.purchasing package?
Share a screenshot of the profiler data, when you do.
no, it is supposed to be in the parse folder right !?
It's not supposed to be anywhere by default
Thanks for your help guys, my workday is over😄 I will report back after some more testing!
But unity is trying to compile it, so I assume you have it somewhere
Coroutine wouldn't solve it.
No I'm saying to log the watch.Elapsed.TotalMilliseconds, not those two.
The priority right now should be to understand why the problem is happening, not randomly suggesting rewriting in different ways to see if it magically solves the issue.
let me check that one min
lastExecTime = watch.Elapsed.TotalMilliseconds; is assigned every loop run
There are a few things things that breaks out of the update loop:
destroyanditemQueue.TryDequeue(out e), presumably these aren't the issue.singleWatch.Elapsed.TotalMilliseconds > TimeBudged, which you already have logs in place to check that.watch.Elapsed.TotalMilliseconds > TimeBudged.
Hence why I suggested logging and checking the last one which you don't have anything for that.
i don't found it in my file explorer : ( Is it possible to have it, without it appearing here ? )
the loop exited with watch.Elapsed.TotalMilliseconds > TimeBudged are all fine. They run a few tasks and then exit the loop. the loops that are exited by singleWatch.Elapsed.TotalMilliseconds > TimeBudged are the problematic ones. A single execution of a task should never take more than the time budged
Wdym by the latter, so if a task takes 10 ms to complete, do you expect it to stop at the 5 ms mark?
no, if you start a task at 4.5 it will be started after that, the time will be > 5ms and the loop will exit.
Because execution is synchronous, if e.action() takes 20 ms to finish, that's how long it's going to take, and your if check won't execute until after that 20 ms has past, so it's going to go over budget no matter.
yes, correct. The problem is the e.action() taking 20ms where the time is not accounted for. Its not clear, why a e.action() sometimes (not always, and at random) takes that long. The time is not listed in the profiler
I see, that's a very different problem then.
if someone can help me with my problem, I would really appreciate it. 🙂
There's a one crazy assumption that could be related to context switching.
As I said earlier, some platform API could be causing a context switch. Well, depending on the implementation, memory allocation or release could include of these API.
So, when you allocate the stopwatch in that method, it could be that the main thread is switched out, and for some weird reason it has a lower priority than other queued threads. If there are no idle cores at that time, the main thread will be waiting until another thread switches out and all other waiting threads have lower priority.
It's a pretty far stretched assumption, but definitely a possibility.
Now, it doesn't seem like you can see context switches in unity profiler. You can see them in PIX, but I'm not sure if unity instruments PIX with it's markers, so you might not be able to see the profiler markers.
However, you should be able to see it with CPU samples.
So maybe try profiling with PIX.
Is that the only error in your console? Take a screenshot of all the errors.
that's all i have, when i try to build
It does say 3 errors though. Even if you count these 2, it's still just 2.
Also you have a warning. What does it say?
yes, idon't understand why, the warning is :
Okay. The warning is unrelated.
There might be more details in the !logs
But perhaps the issue is it doesn't find the assembly Unity.Tasks, rather than failing to compile it.
here is the Editor.log
i think yes
any idea with the logs ?
I'd assume that the issue is with one of the plugins, like firebase. Did you install it correctly? Did you delete any files that belong to it?
Tbh i don't know, someone made this project several years ago, i need to update the project on a new unity version, so i can't tell you
Well, that makes things a lot more complicated. The issue could simply be a version compatability issue.
yes 😅
that's why i don't really know how i can fix this error
Start from researching the plugins that the project uses and removing them one by one until the build is successful
ok, thank you, i'll do it, i come back when i finished.
I'm going to sleep. Good luck.
The character controller's velocity directions seem to stay stationary despite the object being rotated, I'm trying to do a check on the forward velocity so I need it the forward velocity to be relative to where the object is currently facing. Any ideas?
transform.InverseTransformDirection
how do you suggest I use that
I understand that, but getting my object's transform doesn't directly give me local velocity
unless I calculate it myself
huh
I'm not telling you to "get your object's transform"
I don't understand what you're suggesting I do
I'm telling you to convert the velocity into the object's local space using that function
Vector3 worldVelocity = cc.velocity;
Vector3 localVelocity = cc.transform.InverseTransformDirection(worldVelocity);```
I guess that makes sense
didn't think about it in that way
thank you
but it's returning these when solely moving left
what are we looking at here?
these numbers are all roughly 0 btw
but i have no idea what you logged
what's the best way to shoot a raycast through the screen at a specified point to check which UI element is selected?
Use the event system built into the #📲┃ui-ux
well I'm aware of that, but I'm looking into GraphicRaycaster.RaycastAll and can't figure out how to specify a point of where to shoot the raycast
is it the pointer data?
yes, it's part of the PointerEventData you pass in
I have a very random and specific question: in my game, I want the player to be able to take a picture in game of themselves and use that as an icon that can persist across different play sessions. Are there any good guides on this? I don't know where to start exactly
Break it down:
- rendering the character to a texture
- saving and loading the texture to/from the save files
- using the texture in the UI(or whatever way you want)
Research every step in order and you'll get to it. Good luck.
That's what I was thinking, I was just wondering if there was some other way I wasn't thinking about
I'm struggling to create a task chain in C# ```cs
public void Read()
{
CancellationTokenSource tokenSrc = new();
while (!_token.IsCancellationRequested)
{
if (!_reader.TryRead(out T @event))
{
_waiter.SpinOnce();
continue;
}
var e = @event;
Task.Run(async () =>
{
Options.CancellationToken = tokenSrc.Token;
BufferProcessStep<T> step = FirstStep;
while (!_token.IsCancellationRequested && step != null)
{
await step.ExecuteAsync(@event, tokenSrc);
step = step.Next;
}
e.Dispose();
_pool.Push(e);
});
}
}
This is the #ExecuteAsync() code: ```cs
public async Task ExecuteAsync(T @event, CancellationTokenSource tokenSrc)
{
T currentEvent = Unsafe.AsRef(@event);
CancellationToken token = tokenSrc.Token;
Task taskRoot = null;
if (_handlers.Count == 1)
taskRoot = Task.Run(() => _handlers[0].Handle(ref currentEvent), token);
else
{
taskRoot = Task.Run(() => Parallel.ForEachAsync(_handlers, Buffer.Options, async (handler, cancelToken) =>
{
if (cancelToken.IsCancellationRequested || !handler.Handle(ref @event))
tokenSrc.Cancel();
}));
}
await taskRoot;
}
Sometimes the tasks are running out of order somehow
One step can have X number of handlers and those handlers can handle in parallel, but steps can't run in parallel
ok I have the icon working now, but it just makes it from a screenshot taken when the weapon is created. What I need is for it to somehow be able to like simulate rendering the item in a separate environment since it seems like I can't choose a camera which I would normally do and just change the render flags
so is it possible to simulate rendering it in a separate environment with some code that I can output to the Texture2D?
right now I'm just saving a screenshot to a folder and then storing the filepath of the folder so I can read from it later
so basically I guess another question I could ask is if there's a way to take a screenshot with render flags?
because I need the background to be transparent
I'm gonna try just setting the culling mask on the line before and after
I see that Camera.Render() is a thing. Can I take the result of the render somehow?
wow this is exactly what I needed, thanks
I absolutely love seeing messages like this. It gives me hope lol
hahaha
I'm consider myself pretty good at Unity but I don't know what I don't know, so all my questions are just asking what to search up basically and that link was literally exactly what I was looking for
It’s always nice to get exactly what you were looking for without a fight
When I ask for help it’s usually after I’ve already looked at a ton of resources and I’m about at my wits end
what concerns me is that you knew about the Camera.Render method and yet did not bother to go and look it up in the docs yourself
I mean I knew about it but didn't know how to use it since it only returned void
I only knew about it because I was looking through the functions with intellisense
I don't think looking through the docs would've found me that RTFM thing, only the other way around
That is why you go and read the docs. A simple google of 'unity camera.render' would take you straight there
Well it seemed unrelated since I didn't figure that rendering the camera using .Render would help since it returned void. I had no clue that you could do an action immediately after and it would use the render so I just ignored .Render() since it seemed unrelated to my problem
Is there a way to cache and reuse data of a video loaded from a local file? I'm building a scene where tapping on the UI loads a local video by setting the URL and using VideoPlayer.Prepare(); The triggering of loading a video can be done multiple times, so I'm looking for a way to speed up loading videos by not having to read from a local file each time. Is this possible?
You can have one VideoPlayer dedicated for each video you want to have loaded in memory, always ready to play.
I don't think there's a lower level API than VideoPlayer for managing loaded VideoClip assets.
Ok thanks. I am using a shared Video Player for a single instance UI, so I will avoid that solution as it will complicate things a bit. Thanks anyway 🙂
I have a scriptable object that I need to call with an array so its part of another script but the asset I created doesn't have a script attached to it as seen in the pic which means that renaming it or duplicating it makes the new version broken. Is there a way to fix this?
Unclear what we're looking at, what do you mean by "the asset I created"? And what do you mean by it's part of another script?
ScriptableObject and MonoBehaviour classes need to both go in their own file with the same name as the class name
So I have a scriptable object which in my mono behaviour script can't be called unless the scriptable object code is part of that script
https://pastebin.com/gzu52EXp this is the code
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.
Separate them
when I seperate them I can't make an array of the scriptableobject
can you cehck my script and tell me what I did wrong?
this
You would have to show what you tried
what do you mean show?
Yes that's wrong because they're in the same file
Show what you tried when you have them in separate files. Including where in the asset folder you put each file
trying to call the scriptable object from the monobehaviour script when the scriptable object code is in another script
What's the error
script is in the editor folder cause I have dropdowns in the scriptable object
the error is that it can't find it
That's not the error
no I didn't
Also isn't this name incorrect
It should be capitalized, no?
the second one is correct but they have the same error fixed it now and its still not fixed
That's a bold claim
Show the two files
Where do they live
Also make sure the error is also in Unity as well not just visual studio
cardmanager in scripts card asset in editor folder cause I have dropdwon stuff
Yeah that's your problem
Assets\Scripts\Gameplay\CardManager.cs(12,30): error CS0246: The type or namespace name 'CardAssetCreator' could not be found (are you missing a using directive or an assembly reference?)
editor folder is for editor only code.
Separate the custom editor code as well and put that in the editor folder
Yes but it will break once you try to make a build because you can't have editor code in your normal files
That's what the editor folder is for.
which part of the code should be in this folder
The editor
so the ones with the [editor type blah blah]
[CustomEditor(typeof(CardAssetCreator))]
public class CardAssetCreatorEditor : Editor```
this
this is the editor
Damn, and it's only got the word Editor in it 3 times, easy to miss
has anyone used mediapipe plugin for unity?
in a normal C# project I can right click the properties for project and set the RuleSEt to use for Code Analysis, but a Unity project doesn't seem to want to let me bring up the properties for the assembly project. Anyone messed with this?
unity will create & manage your solution and project files, so if you're talking about VS, any settings you make in VS regarding those, will be gone on the next Unity project/asset refresh
Hello guys, i'm trying to create a small multiplayer online game ("MMO" but not massive), but i'm struggling with the architecture. Should I create a separate backend (in nodejs or .NET core 8) connecting it to mongodb, or call mongodb directly in the respective (I'm using FishNet) [ServerRpc] method to persist the players data (like getting gold, xp, drops, inventory) etc??
If it's not massive, maybe you don't need a database
you typically call all your persistence APIs asynchronously to your gameplay netcode. Those can be regular REST/grpc endpoints depending on the throughput you need. Typically those would be on the private/protected network your server runs on so you could connect to those with minimal security.
if you have just one server you could even store that stuff via SQLite and ditch all of the "backend"
I'm taking inspiration from Spiral Knights, so something about 200 players would be the "peak".
on a single server?
that's my problem xD, i'm trying to figure out this. maybe using kubernetes to scale multiple instances of my backend and use gRPC on the fishnet server-side methods
you can't solve that with off the shelf web-dev stuff
but idk... there'll be many lobbies that can handle 32 players each, and dungeon instances that handle 4 players each
I'm new at game dev but have some years with web. Nice to know, thanks!
well, those web dev years might get in the way 😉
understood, i think only the C# experience will help me so
the issue is that you need to realign your goals from maximizing throughput (webdev) to minimizing latency (gamedev)
and once your latency is where it needs to be for your project, you can again think about throughput or rather faking throughput (CCU)
interesting... maybe creating various instances of fishnet server would help in this case? how about using redis or something else to store players data?
and one option that is compatible with web-dev architectures is horizontal scaling via lobbies and short-lived arenas, but that typically doesn't produce whats understood to be an MMO
my main inspirations are Spiral Knights and Dofus/Wakfu
in an MMO you need a shared, persistent world, not restarting servers every 15 minutes
in my case i don't need an open world, but i need various lobbies and dungeon instances (parties)
so long as you can keep that world on one server (think wow classic) your complexity is manageable, but if you want to combine multiple servers into one world you're diving into the land or arcane knowledge and custom code top to bottom
your lobby is a UI or a 3d world? Or rather can players see each other in the lobby?
2D world that can handle 32 players max in each instance
topdown based
and those 32 are the only 32 that can play together?
or say 4 of those 32 can play together in a group?
sorry for my poor explanation, let me tell more about
anyway, seems you are creating a lobby inside a lobby
i want to create a game that can handle something like 200 players in total. players can add each other, create parties (4 max) and join other parties. there will be a lobby like a VR chat room, that can handle max 32 players, but if a player quits, other player can join this lobby. if there are more than 32 players in this lobby, reallocate the player in a lobby that have only 7 players for example
ok so you are making multiple variations of servers
the dungeon instances are different scenes, different "instances" of the game
you have a classic lobby to find one of those party servers, then from there you move to a group-dungeon-server-thing and once thats done back to the party server
i couldn't handle a lobby that can handle 200 players at the same time, so i need to load balance this
but each one of the 200 players can play with each other, if they have each other in the friends list or guild or so
yeah
exactly like spiral knights
anyway, sounds like you are building a MMO alright. you can probaly skip the woes of scaling this to many CCU and the trouble that brings, but as far as the complexity goes, you are already way up there of what a small team could achieve, in addition to building the game
i have no idea what that is
spiral knights is an old steam mmo made in java by sega/three rings
the main map is "Haven" that is the lobby i'm refering to, it can handle something like 50 players at the same time, but can have Haven 1, Haven 2, Haven 3 and so on
to load balance
initially only me, it's for studies, but in the future, 4 people
it's a dream project so it does not matter, can be 2, 3 or more years
the game is not that complex but it's not simple too 😦
all games are complicated
yeah xD
to be fair i should tell you that making an MMO is the prototypical beginner gamedev folly
everyone fails
haha
not because you can't technically do it all
just because you will never finish any part of it satisfactorily because of the time it takes
i had a private game server years before that could handle 150 players at once, using flash, java and mysql
but to create one from zero is the problem
that doesn't mean anything on its own
i can make a game server that supports 10000 CCU if they don't see each other
it's easier if i create a lobby that has only one player (like league of legends client) and create the dungeon instances separatelly with 4 players each?
anyway, the problem is not in any of the individual parts, it that they are so many, so intertwined, async, hell to test and hell to get right without any experience.
you will probably have to redo the whole thing a couple of times
yes, that is much easier
so it could be
with a integrated store/economy
that players can sell items, resources, etc.
a store is trivial CRUD
right!
dont worry about the store, chat and social featurws
your only issue is with live-state persistence and updating the persistent state + whatever happens live in your groups
having a way to the players play together in a group of 4, the rest does not matter
yes... maybe i create a party, other players join, the party keeps the players state and when something change the party state, it saves the data
like one player quitting, completing the dungeon, etc.
you could start with just making the dungeons and a UI-based lobby, like any arena shooter
it's better than saving each req of a player getting one many times coin right?
nice
my problem is with the persistence with low latency and high security
then you aint making an MMO, just a coop-2D-game, which is MUCH more feasible
a way that players cannot fake the gold saving endpoint req or something
you can outsource all that to services like playfab
yes, it's a co-op game with multiple dungeon instances
not open world
and if there's one "open world", it'll be many instances that can handle 32 players each, like a bigger version of the dungeons (4 players each)
open world is a marketing term, all worlds are "open" except if they actually are tunnels with bulkheads.
i see, playfab is a good idea too
the complicated part is the joining/phasing of these open worlds into something that feels united, even if it isnt
yes, its a bit tricky to do with the regular unity netcode middleware
those are all geared towards arena experiences
i'll be using fishnet for networking and server authority
you can make those work in a way you describe, but it will be straining these architectures to the limits
your choice, they all work more or less the same
i found a cool youtube tutorial about creating multiplayer lobby system using the "boss room" sample, is something like this
the other mechanics like crafting, trading and so i think that aren't so difficult
you will be surprised
my main concern is about persiting data in a secure way
you are scaring me haha
maybe thats your web experience that makes you feel this is difficult, to me this seems to be the easy part... but im no webdev so i'm probably worng there 😄
it's because i'm used to the same arch... controllers, usecases and repositories connected to a db, not that complex
but in games this is different
basically, whatever seems easy to you that you are a novice at, is probably very hard.
it seems easy because you don't see the full problem yet. Thats why i think web stuff is easy 😛
i agree with you, web dev is easy
the most difficult part that is learning programming is in point. the other things we can learn in some time
well, games cannot use most of the patterns that make web/app dev easy
sure
you have totally different concerns, you can solve almost nothing by wasting resources
I think I'll be into playfab so
easier than creating and integrating a self made backend
playfab is quite expensive (its regular Azure)
i think that may be a major benefit for you, you can think normally about playfab and don't have to contort yourself into a service that doesn't offer generic server tools/containers
but if I need to use another solution, what's the best?
creating a SQLite file and it's it?
SQLite obviously only works if you have only a single server.
but its an option.
but so would be saving stuff to json files
😄
most readymade gamedev backends are just key-value stores, you may find some that offer a document store
to multiple servers i can use something like mongo or cassandra?
mongo is very good tho. it's key-value too
you can use anything you like
mongo is not a key value store in a meaningful way,
a key-value store would be something like redis, purely in memory
but with a persistence fallback
i see
just not saving to disk on every write and definitely not reading from disk on all reads
when thinking small scale, you don't need beasts like cassandra i think
maybe cassandra is overkill so
as they say, you're not building netflix or twitter
yeah
postgres 😛
the company that i've worked uses cassandra, but is a payment solution
the classic
cassandra and the like a great for making money off clueless clients
can i use it directly in [ServerRPC] calls in unity?
i know that i can use with C# driver
but if that's optimal I'm asking
well, databases in unity are a bit weird to use
you would certainly not use them directly
(except maybe redis or something simple like that)
yeah, because of this i thought about creating a web backend so the ServerRPC calls the endpoint XD
i think it would be easiest to make a regular .NET based web API for the DB access
you can make that gRPC if you like and call that from the unity app
yes, to mitigate the latency
maybe initially is a good solution
i can use a service to handle the auth and another server to game
you can use anything you like, its likely on a private network, so you can probably be relatively loose on the security
playfab has all the auth and account management you could ever need
having a secure way to avoid players "poisoning" the req and receiving gold and XP without killing the monsters is already perfect
and you can store all the "valuable" tokens in its secure DB (skillpoints, items)
for the stuff that doesn't have much value to players (runtime state) just use something fast and insecure
the fast and well supported data format for backend messaging in unity would be MessagePack btw.
so, the way is calling the gRPC endpoints in the [ServerRPC] methods so i can be server authorative and validate if the player killed the monster before right?
cool, how about websockets?
why do you want to use those?
yeah... ignore websockets, i'm telling shit haha
gRPC or MessagePack so
i think its important to really understand your different types of messaging needs and the correct tools for solving these
you'd classify those mostly by latency/frequency
you can use HTTP/REST for the slow secure stuff, grpc/messagepack/etc. for the fast but not really live stuff, and proper reliable (but insecure) UDP for your live gameplay
nice. the UDP is handled by the netcode frameworks?
yes
we've had HTTP3 in gamedev for decades 😛
that's insane
I only learned how to code to learn games, but you know, we cannot live without $$$
so I'm learning now after 3 years of web dev
I'm dumb lol
if you care to know details, this is the secret sauce behind most "modern" game netcode transports: https://github.com/skywind3000/kcp/blob/master/README.en.md
good to know
its 1000 lines of magic
thanks for your knowledge, I'm very happy and motivated to continue my project, even if it fail
i think latency using a custom backend will not be a problem, because most of the reqs i will send when the party state changes or important actions like trading or buying something in the store
and i know how to scale web servers, so that's not the problem, the focus will be in the game mechanics
using .NET CORE or golang with the good old postgres will satisfy my needs
with MessagePack too
well, i hope it works out for you in some way
thanks man, hope i can reach you in the future and show the results or dev logs
can i add you? i promise i will not bother you hehe
in 2005, 3 french guys made Dofus in 1 year and after more 1 year they become millionaires with their new flash game, it's my biggest inspiration
i can fail but i will try
and the knowledge is the most important for me
big thanks and have a nice day/afternoon/night man
the key to finishing these ambitious things is A) knowing exactly what you want & need and B) that thing you want is lean a.f. and cuts through all the crap you normally need
just saying... 200 is nothing nowadays. A single core on modernish hardware can do this no problem (for the server). The game Rust does on average like, what, 500 players per server. Unity engine made. Horrible slow codebase as well.
I haven't read much of the conversation, but I saw the word "websockets" which is not what you want for performance networking.
thanks for your feedback too man, appreciate it, I'm accepting more tips 🙂
what is your end goal? custom netcode?
a game like Spiral Knights would be perfect for me
create custom dungeon instances and lobbies
regardless of the tools and frameworks
yeah load balancing a single world across multiple servers is very difficult.
spreading them across scenes (dungeons) would probably be very simple
that's it, even for the lobbies, they can be different scenes
not having 200 players in the same scene, that's it
yeah, theres a handful of existing networking frameworks that can easily do this
unless you need a custom one for whatever reason
I'm thinking about fishnet pro, but i can use whatever helps me
mirror has been around a lot longer than fishnet and doesn't have a goofy name
and I think they've recently added clientside prediction which is pretty nice
nice to know
fyi you'll probably want a good chunk of your dungeons on the same server process
so like one unity instance and a ton of additive scenes
pinning each server process to it's own dedicated CPU core probably isn't a bad idea either
perfect, I'm watching some Bobsi tutorials on youtube about this
thanks for all the sharing guys, it means so much for me
protected override void ExecuteDefaultAction(EventBase evt)
{
if (keyDownEvent.ctrlKey && keyDownEvent.keyCode == KeyCode.V)
{
int characterLength = GUIUtility.systemCopyBuffer.Length;
if(characterLength > maxLength)
{
GPGraphLogger.Log(GPGraphLogTypes.WARNING, "Max character limit exceed !");
string overflowText = GUIUtility.systemCopyBuffer;
evt.StopImmediatePropagation();
}
}
}
I catch event in TextField and tryingto handle manualy max character limit on that .
I stopped event propagation but still when i paste somethink valueChangeCallback firing after evt.stopImmediatePropagation
What can i do ?
i need to catch value change callback with original value not a culled with max character count version
void INotifyValueChanged<string>.SetValueWithoutNotify(string newValue)
{
newValue = ((ITextEdition)this).CullString(newValue);
if (m_Text != newValue)
{
renderedText = newValue;
m_Text = newValue;
IncrementVersion(VersionChangeType.Layout | VersionChangeType.Repaint);
if (!string.IsNullOrEmpty(base.viewDataKey))
{
SaveViewData();
}
}
if (editingManipulator != null)
{
editingManipulator.editingUtilities.text = newValue;
}
}
is there a way to edit these base methods with reflection i need to set m_Text original value but renderedText must continue with culled text
any suggestion ?
I am trying to handle that max character limit in this way after all if user wanted to paste any text in TextField that exceed max character count due to rendering side limitations (65k max vertex) user can copy paste text data in field without see the original text on field but field can hold original real data . What do you think ,is it absurd or what do you recommend ?
protected override void ExecuteDefaultAction(EventBase evt)
{
if (evt.target == this)
{
if (evt is ExecuteCommandEvent)
{
ExecuteCommandEvent executeCommandEvent = (ExecuteCommandEvent)evt;
evt.StopPropagation();
evt.PreventDefault();
Debug.Log(evt.isDefaultPrevented);
}
}
}
this is not preventing default actions log is true but still performing actions , how can i fix this
okay found a solution
RegisterCallback<ExecuteCommandEvent>(OnExecuteCommandEvent,TrickleDown.TrickleDown);
private void OnExecuteCommandEvent(ExecuteCommandEvent evt)
{
evt.StopPropagation();
evt.PreventDefault();
}
with this u can force to stop events i guess overriden method trickle if tricke means stage is different from trickleDown therefor u cant override
Hi
I posted a question on unity forums, I dont wanna repost it as it has a video and picture
if anyone is experienced with Texture2D api, i would appreciate some help
@dry hatch I think issue related to max dist and compress section , firstly i thouth like float precision kinda error but idk
First step u need to check is data is same as before when reading from texture also there is a repo u can find helpful things
https://github.com/chenjd/Render-Crowd-Of-Animated-Characters
I thought so too, but i removed those steps (even though it clipped some vertices) and the remaining vertices still jittered around
but reading back the data is a good idea, thanks
Hello,
I have a Question about Font Asset.
I used TMP for font and Build to Android Phone and use Memory Profiler for capture memory and I see my font is duplicated in memory.
How can I fix that? 🥺 🥺
this is my TMP font setting
Dynamic font assets comes at cost. change the atlas propogation to static and see what you are getting. i am thinking thats the problem.
Hi experts
I'm baking large area for AI navmesh
In this case , what is the best solution?
At runtime?
The best solution is to bake the navmesh
anyone good with procedural animations here?
im looking for an answer to this question: https://gamedev.stackexchange.com/questions/211629/what-is-wrong-with-my-animation-retargeting-algorithm
Hi, is there a way to show Functions for Unity Events in Inspector which use an Enum as a parameter?
create another overload that uses an int and cast it to the enum? not sure if the compiler will let you, just a random idea
no
I mean, it's also less than ideal since the inspector method will show an int instead of an enum, but... it's something. 😛
private void OnPostprocessTexture(Texture2D texture)
{
TextureImporter textureImporter = (TextureImporter)assetImporter;
textureImporter.maxTextureSize = 16384;
textureImporter.SaveAndReimport();
}
even though i can see that the texture size has been changed to 16k in the editor, it doesnt actually apply it
it only takes effect if i lower the value and then it comes to its senses and sets it to 16k
use 1024 * 16 imo for easier edits 😛 other than that I didn't understand your (question?)
it doesnt work
ah
it show like this in the inspector, but it doesnt actually apply it
how are you certain it doesn't? Also, are you doing this during play mode?
no
well the textures actually are created through code
but i run the code in editor
and I am certain, because its physically visible
the max size is used for compression only btw. You're not resizing the texture with that.
oh wait...
maybe its whole thing not applying
i actually have more code, i just didnt show it for brevity sake
private void OnPostprocessTexture(Texture2D texture)
{
String folderName = "Anim Baker";
if (assetPath.IndexOf("/Anim Baker/") == -1)
return;
TextureImporter textureImporter = (TextureImporter)assetImporter;
textureImporter.maxTextureSize = 16384;
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
textureImporter.sRGBTexture = false;
textureImporter.filterMode = FilterMode.Bilinear;
textureImporter.npotScale = TextureImporterNPOTScale.None;
textureImporter.mipmapEnabled = false;
textureImporter.SaveAndReimport();
}
I have compression off, you are right it shouldnt even be affecting it
I think whole thing is not applying for some reason
yeah I would expect it to re-apply the compression algorithm during SaveAndReImport(). Maybe try AssetDatabase.Refresh() after reimporting?
there's also a special ForceUncompressedImport enum option there for Refresh
the ui itself changes, thats the weird part
again, are you just trying to uncompress it?
because it won't magically become a 16k texture just because you disable compression
yes but there are other stuff that i need to disable/enable also
look at the code above
can't go wrong with ImportAsset(path, ..ForceUncompressedImport), then
I did, but neither the code nor the screenshot show the texture's original resolution.
it could be 64x64 for all I know lol
the texture is 2395x37
yeah, it won't become 16k no matter what
if my changes dont get applied it will be compressed to 2048
the default value is 2048
I think your texture can't be compressed no matter what you do, since it's dimensions are not a power of 2
i also need to disable sRgb, and mipmaps, which also dont get applied
but yeah ^
okay forget about the texture size, i also need to change this
textureImporter.SaveAndReimport(); should technically call AssetDatabase.Import(AssetDatabase.GetAssetPath(texture));, but maybe it doesn't (?)
didnt work
did you put a Debug.Log there to make sure it's called?
no, i thought no need since the ui changes
its just it doesnt get applied
i can record a video of the problem if you want
it didnt get called...
private void OnPostprocessTexture(Texture2D texture)
{
String folderName = "Anim Baker";
if (assetPath.IndexOf("/Anim Baker/") == -1)
return;
TextureImporter textureImporter = (TextureImporter)assetImporter;
textureImporter.maxTextureSize = 16384;
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
textureImporter.sRGBTexture = false;
textureImporter.filterMode = FilterMode.Bilinear;
textureImporter.npotScale = TextureImporterNPOTScale.None;
textureImporter.mipmapEnabled = false;
textureImporter.SaveAndReimport();
Debug.Log("Imported");
}
didnt print Imported
public class VertexTextureImporter : AssetPostprocessor
{
private void OnPostprocessTexture(Texture2D texture)
{
Debug.Log("Imported");
String folderName = "Anim Baker";
if (assetPath.IndexOf("/Anim Baker/") == -1)
return;
TextureImporter textureImporter = (TextureImporter)assetImporter;
textureImporter.maxTextureSize = 16384;
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
textureImporter.sRGBTexture = false;
textureImporter.filterMode = FilterMode.Bilinear;
textureImporter.npotScale = TextureImporterNPOTScale.None;
textureImporter.mipmapEnabled = false;
textureImporter.SaveAndReimport();
}
}
also didnt print
well you can probably take it from here lol
but how could it be...importer tabs interface changes...
you might have messed with the defaults
ughhh not really lol
its already in the Editor folder...
wtf
take it outside and wrap with #if UNITY_EDITOR idk :p
most likely your texture is never imported
also docs say this might cause unpredictable results for compression settings specifically
let me see
it is
Hey does anyone know how to integrate kafka with Unity3d? I plan to write a producer in unity which reads from a json file and sends the data to a kafka topic. I tried to add the NuGet package manager in Unity and then added confluent.kafka and librdkafka with newtonsoft.json for reading the json files. But its not working as i keeping getting this error: "System.DllNotFoundException: Failed to load the librdkafka native library"
I would probably not publish directly to kafka from my Unity app. Easier to have some middleman web service. That lets you have proper access control as well.