#archived-code-advanced

1 messages · Page 107 of 1

rancid bane
#

it fixed btw ty

#

hoodoo please hellp

weak ginkgo
#

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;
    }
frosty prairie
#

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.

sick flame
#

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?

weak ginkgo
lost stag
#

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

sly grove
#

The sizeof operator requires an unsafe context.

lost stag
#

ty

charred drum
#

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

charred drum
#

Nevermind, I did it. Was not that hard suprisingly

jade veldt
#

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

austere jewel
soft moon
#

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

quartz turtle
#

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?

soft moon
#

Are they in the same file or have you merged them when sending?

dusty wigeon
soft moon
#

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?

dusty wigeon
#

Sometimes, when debugging events I like to convert to a list temporary. It makes it easier to see what is in it.

soft moon
#

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?

dusty wigeon
#

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

soft moon
#

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

gleaming rock
#

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.

dusty wigeon
thorn dome
# soft moon Yes, if someone asks me to explain what I'm trying to help you with, I won't be ...

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.

soft moon
thorn dome
#

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.

soft moon
#

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

versed solar
#

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)

sage radish
#

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.

charred drum
#

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

versed solar
# sage radish You'd only get -1 if the directions are completely opposite. Perpendicular, or 9...

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.

untold moth
charred drum
#

I don't believe so, no but let me check

#

Where would I find it

charred drum
#

Wait, no, it is off

untold moth
#

Take a screenshot

charred drum
untold moth
#

That means that the domain reload is enabled.

charred drum
#

Ohhhh I see

#

So, yeah I don't know what is going on then

untold moth
#

It's weird that your changes persist between play mode and outside of it. What are the arrays that you modify?

sage radish
#

And you say the expected output is -1?

untold moth
versed solar
charred drum
#

This is it- Maybe it's because I don't have the serialize flag set to it?

#

I'm not getting any weird errors

sage radish
charred drum
#

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

versed solar
#

I'll have to double check that when I get home then

sage radish
untold moth
#

It resetting between scene reloads is totally normal. I thought it was the opposite..?

charred drum
#

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

versed solar
charred drum
untold moth
charred drum
#

Exiting playmode

untold moth
#

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.

charred drum
#

AssetDatabase.ForceReserializeAssets()?

charred drum
untold moth
#

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.

charred drum
#

In the build?

#

You mean, like a built game? This is an editor function...

untold moth
#

Okay. So you want to save some runtime changes for them to persist outside the play mode?

charred drum
#

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?

untold moth
#

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.

charred drum
#

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

untold moth
#

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.

charred drum
#

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

untold moth
#

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.

untold moth
charred drum
#

Let me see if it will work now

#

Alright, that works. Thanks dlich!

haughty sphinx
#

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
}
upbeat path
haughty sphinx
#

well aren't you helpful :)

#

anyways, I got the pointers I needed somewhere else, case closed

lucid crane
hot lintel
normal lagoon
#

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

normal lagoon
#

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

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?

sly grove
#

and for what code

wooden vigil
#

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 parameter ref 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: Field NativeList1.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)
wooden vigil
#

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

carmine hinge
#

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

thorn flintBOT
carmine hinge
#

oooo ty

hoary bane
#

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?

compact ingot
carmine hinge
hoary bane
steel snow
#

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

jolly token
#

UPM is the right option if you are trying it out with Unity (Because Unity uses different API for unsafe)

hoary bane
#

I will give it another try and get back to you on your own discord server if I run into any issues, thanks 🙂

steel snow
#

strange its now decided to work without the error 🤔

sage radish
steel snow
sage radish
#

Yes. Some meshes contain normals, others don't. Some have many UV coordinates, others have none, etc. It can be any layout.

steel snow
#

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

sage radish
steel snow
#

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

sage radish
#

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.

steel snow
#

im using the native array stuff

sage radish
#

Everything in MeshData is using NativeArray.

#

You're trying to use MeshData.GetVertexData, instead of MeshData.GetVertices and etc.

steel snow
#

yes but the GetVertices populates a list

#

not a native array

steel snow
#

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

sage radish
#

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.

steel snow
#

Populates an array with the vertex positions from the MeshData. this reads like its making a copy which i didnt want

sage radish
#

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.

steel snow
#

where as the GetVData GetVertexData returns a direct "pointer" into the raw vertex buffer data without any memory allocations, which seems far better

sage radish
#

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.

steel snow
sage radish
#

Position, Normal, Tangent and UV are all attributes.

steel snow
#

i dont need to deal with pointers the struct returns a readonly native array

sage radish
#

Yes, but you don't know the layout. So you have to read from it as a byte array instead of a struct array.

steel snow
#

ah i see

sage radish
#

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.

steel snow
#

can it 🤔 thats news to me

sage radish
#

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.

steel snow
#

yeh but im doing it each frame

sage radish
#

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.

steel snow
#

i see

#

ok ill do some changes then

#

such a shame because it was super clean the approach i had until now 😄

lime owl
#

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!

somber swift
# lime owl Is it necessary to divide polygons into triangles? The painters algorithm isn’t ...

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?

unkempt moat
#

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.

stuck plinth
unkempt moat
upbeat path
unkempt moat
upbeat path
#

ok, so a local ip address. Port number?

unkempt moat
#

It's 8080

upbeat path
#

and that's open in the firewall and the quest is on the same network?

unkempt moat
#

According to the commad "netstat -aon" I don't think so, the port does'nt appear

upbeat path
#

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

unkempt moat
#

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

upbeat path
#

working in editor and working from an external device are 2 completely different things

unkempt moat
#

(I did test in oculus and on my phone)

unkempt moat
upbeat path
#

I guess you're using the node http package

unkempt moat
#

I'm using Node JS, and Unity Render Streaming

upbeat path
#

I know that, I asked if you were using the node http package for the network connection

stuck plinth
#

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

unkempt moat
upbeat path
#

now I am confused

unkempt moat
#

Unity Render Streaming is used just for the video, everything else pass by a node js connection which is working

unkempt moat
stuck plinth
unkempt moat
stuck plinth
#

so are you making requests to that same url using UnityWebRequest?

upbeat path
#

they must, at least, be using different port numbers

unkempt moat
#

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

stuck plinth
#

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

upbeat path
#

and test from a browser?

raw path
#

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?

lime owl
#

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.

stuck plinth
raw path
supple perch
#

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?

lime owl
#

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?

upbeat path
sly grove
lime owl
#

I was hoping someone did some source code reading.

somber swift
magic bobcat
#

I'm getting an error when I try to add NewtonsoftJson package via the package manager. Does anyone know whats going on here?

soft moon
jaunty swallow
#

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?

magic bobcat
#

Finally, that worked. I found so many variations in the documentation and online but none of them worked.

#

thanks

half swan
jaunty swallow
jaunty swallow
serene jetty
#

am i stupid or can you not for each over an ienumerator

sage radish
#

But one class/struct can implement both and just return itself in the GetEnumerator method if you like.

serene jetty
#

thanks

lucid crane
serene jetty
#

yeah a method which yield returns

lucid crane
#

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.

serene jetty
#

i think youre thinking of ienumerable

lucid crane
serene jetty
#

i was just triyng to create a customer iterator, thats all

serene jetty
#

yeah i figured it i just made my class ienumerable

lucid crane
#

Whatever floats you boat 🤷

misty glade
#

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?

steel snow
#

why does unity's example use normals with 2 components ? aren't they vector3

#

seems a bit odd

sage radish
steel snow
#

ah i see

fading cobalt
#

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.

dusty wigeon
somber storm
#
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?
jaunty swallow
#

trying to recreate this line in the new ECS versions, any idea how I can specific the components?

var newParams = new Params...
}
molten socket
#

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
        }
    }  
}
tall ferry
upbeat path
molten socket
fickle mango
# molten socket 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.
molten socket
fickle mango
sly grove
misty glade
#

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

scenic forge
#

VS Code and Rider pretty much are your only options. I use VS Code everywhere though.

formal lichen
#

why does my plane in editor looks great, but in run mode just white?

crystal oar
#

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

sly grove
crystal oar
sly grove
#

that's the only way to do it

#

anything else is guesswork

crystal oar
unreal haven
untold moth
worldly pecan
# crystal oar so, im having a problem that i have never had before in my years using unity, i ...

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

royal island
#

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()
}

upbeat path
#

I would use a ref parameter and maybe return the bool Success

royal island
upbeat path
#

yes

#

also you might like to constrain your T

#

I generally do not like structs which contain objects

royal island
#

Why is that

upbeat path
#

Because of the impact it has on the managed and unmanaged memoty

royal island
#

Ah, I see. I'll keep that in mind as I'm trying to be as conservative as possible with resources

upbeat path
#

then make it a class unless you have a really good reason for it to be a struct

royal island
#

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

upbeat path
royal island
#

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

upbeat path
#

that looks more like app dev rather than gamedev

royal island
#

It's a library for game dev

upbeat path
#

ok, library code is much more similar to app dev

royal island
#

While I'm here, do you have any idea how to get around Unity's garbage collection issues with reflection?

upbeat path
#

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

royal island
#

Okay thanks

supple perch
#

Hey, just thinking... This SHOULD be fine. Right?

compact ingot
supple perch
#

Thanks!

compact ingot
#

but "technically" it would do the same thing... you're just more expressive about it, with some easier to follow logic

scenic forge
#

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.

lilac lantern
#

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

wary blaze
#

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:

  1. Size on Disk (within the Unity Editor).
  2. Size on Disk of the prefab's dependencies (meshes/textures, etc.)
  3. Time it takes to instantiate the prefab within the editor (outside of play mode)
  4. Total Vertex count of all MeshRenderers on the prefab or children of the prefab.
  5. 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).

fallow echo
# wary blaze I know this is a long shot but I wonder if anyone has come up with a good metric...

Your approach seems... wrong.

  1. Why do you need to predict the performance? Just measure it in build 🤷‍♂️
  2. 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.
  3. 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.
compact ingot
vital fossil
#

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

fallow echo
compact ingot
wary blaze
# fallow echo Your approach seems... wrong. 1. Why do you need to predict the performance? Jus...

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.

compact ingot
#

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

wary blaze
fallow echo
#

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.

wary blaze
#

which can effect performance

compact ingot
wary blaze
#

It was a long shot but still worth asking haha

compact ingot
#

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

hushed fable
#

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.

compact ingot
#

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

wary blaze
#

👍 Thanks everyone for your answers!

vital fossil
#

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

misty glade
#

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.

worldly pecan
wet sail
#

is there a way to prevent unity from making *.meta files in the StreamingAssets folder?

wet sail
#

for?

#

its an external folder

upbeat path
#

for inclusion in a build

wet sail
#

not a project folder.

#

streaming assets will include everything anyway

upbeat path
#

it's internal for mobile and WebGl builds

wet sail
#

ah

#

so, can i make the meta files in a separate folder or sth bc they are annoying

upbeat path
#

interestingly they dont end up in the streamingassets folder of a standalone build, but know you cannot seperate .meta files from their host

wet sail
#

honestly makes 0 sense for them to be included in webgl/mobile too

#

but whatever

upbeat path
wet sail
#

that makes no sense, u can read a unityasset file without .meta

#

its basically a zipfile.

#

webrequest doesnt need .meta, its simply a webrequest

upbeat path
#

not in a build

wet sail
#

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.

upbeat path
#

what are you talking about?

wet sail
#

nothing nvm

dry hatch
#

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?

upbeat path
#

what is displayed is not the full contents. use a ToString to add your own formatting string

dry hatch
#

let me try

fickle obsidian
#

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.

dusty wigeon
fickle obsidian
short junco
#
            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 ?

sly grove
short junco
#

@sly grove
Probably so, I will have to catch them all one by one from the keyboard event and do something custom...

short junco
#

GUIUtility.systemCopyBuffer this field is all competiable with (win,macOS,linux) right i dont have to implement platform spesific regions ?

austere jewel
#

!collab

thorn flintBOT
#

: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

misty glade
#

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.

pallid glacier
#

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.

compact ingot
untold moth
pallid glacier
#

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

untold moth
pallid glacier
# untold moth 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

untold moth
#

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.

pallid glacier
#

okay i'll check that

#

thanks

old sluice
#

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!

flint sage
#

What's runinmainthreadtimed

old sluice
#

Its a wrapper action that adds the ability to wait for the execution

fresh salmon
#
  • 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
flint sage
#

Show code

fresh salmon
#

Known by the compiler as display classes

old sluice
#

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

fresh salmon
#

Is the queue thread safe? As in, it should be from the System.Collections.Concurrent namespace, like a ConcurrentQueue<T>

old sluice
#

Yes, its a ConcurrentQueue

#

Takes only nanoseconds to dequeue

fresh salmon
#

Weird, I don't remember it having an Add method

old sluice
#

Sorry, its mainQueue.Enqueue(item); and if (mainQueue.TryDequeue(out e))

#

Can I post full code here?

fresh salmon
#

Yes, use a paste website if there are multiple classes or if it's longer than 20 lines or so

#

!code

thorn flintBOT
old sluice
#

Thats the minimal example without the waiting SemaphoreSlim, has the same problem as the Deep Profile

untold moth
old sluice
#

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

untold moth
#

You could put more markers in the loop. To see what's going on in details

old sluice
#

Sorry, Im not sure what you are profiling. A endless loop in Update() would lock up unity

untold moth
#

What's RunInMainThreadTimed? Is that a different class/method?

old sluice
#

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

old sluice
#

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!

untold moth
old sluice
#

No, thats the issue. Its random

untold moth
#

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

old sluice
#

That was my first thought, but its not gc

untold moth
#

Do you have the incremental GC enabled in the project settings?

untold moth
old sluice
#

there are other gc spikes 😄

untold moth
#

Try enabling the incremental GC and see if you can reproduce the issue

old sluice
#

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

untold moth
#

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();
};
old sluice
#

yes

#

even item.action = action

#

then calling that action can be slow

untold moth
#

Well, if you're right and it's the JIT compiler, then all you need to do is just not use lambda expression

old sluice
#

I could use a named function, but I was under the impression, that lambdas should not have any performance impact

dusty wigeon
#

You could also use Il2cpp to try

untold moth
old sluice
#

project is running using il2cpp

#

named functions will be hard without any allocation

untold moth
#

Well, you can test it first and worry about real implementation later

#

Maybe that's not the cause at all. Who knows.

dusty wigeon
#

Then it is not JIT isnt ?

scenic forge
#

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.

old sluice
#

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

scenic forge
#

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.

untold moth
#

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🤔

scenic forge
#

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?

untold moth
#

My impression was that it's only compiling with il2cpp during the build.

scenic forge
old sluice
#

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

untold moth
#

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.

old sluice
#

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

untold moth
#

basically, get rid of the stopwatch

#

Or construct it outside

old sluice
#

The stopwatch was added after the problem was discovered

untold moth
#

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.

old sluice
#

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

crisp temple
#

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?

untold moth
#

The action is executed from Update, so I don't think that's the case.

old sluice
#

its inside update it should be between sending to the gpu

#

its possible that its some kind of context switching problem

crisp temple
#

weird, but that would be my bet.

old sluice
#

But how could I debug that🙃

crisp temple
#

😬

untold moth
#

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.

sacred star
old sluice
untold moth
#

Yeah, I can see that from the profiling data that you shared.

crisp temple
untold moth
scenic forge
untold moth
old sluice
lucid crystal
#

Hello guys, how can i update Google Play purchases? Is it enough to update Unity com.unity.purchasing package?

untold moth
#

Share a screenshot of the profiler data, when you do.

sacred star
untold moth
old sluice
#

Thanks for your help guys, my workday is over😄 I will report back after some more testing!

untold moth
scenic forge
#

Coroutine wouldn't solve it.

scenic forge
#

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.

sacred star
old sluice
#

lastExecTime = watch.Elapsed.TotalMilliseconds; is assigned every loop run

scenic forge
#

There are a few things things that breaks out of the update loop:

  • destroy and itemQueue.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.
sacred star
old sluice
#

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

scenic forge
old sluice
#

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.

scenic forge
#

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.

old sluice
#

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

scenic forge
#

I see, that's a very different problem then.

old sluice
#

Unfortunately yes

#

I have to got but I will be back tomorrow 😄

sacred star
untold moth
# old sluice its possible that its some kind of context switching problem

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.

untold moth
sacred star
untold moth
sacred star
untold moth
untold moth
thorn flintBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

untold moth
#

But perhaps the issue is it doesn't find the assembly Unity.Tasks, rather than failing to compile it.

sacred star
sacred star
#

any idea with the logs ?

untold moth
sacred star
untold moth
#

Well, that makes things a lot more complicated. The issue could simply be a version compatability issue.

sacred star
#

that's why i don't really know how i can fix this error

untold moth
sacred star
untold moth
#

I'm going to sleep. Good luck.

jaunty swallow
#

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?

sly grove
jaunty swallow
#

how do you suggest I use that

sly grove
#

You use it to convert your vector into local space for the object

jaunty swallow
#

I understand that, but getting my object's transform doesn't directly give me local velocity

#

unless I calculate it myself

sly grove
#

I'm not telling you to "get your object's transform"

jaunty swallow
#

I don't understand what you're suggesting I do

sly grove
#

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);```
jaunty swallow
#

I guess that makes sense

#

didn't think about it in that way

#

thank you

#

but it's returning these when solely moving left

sly grove
#

what are we looking at here?

#

these numbers are all roughly 0 btw

#

but i have no idea what you logged

jaunty swallow
#

oh wait I was logging the z not the velocity

#

woops

frozen ravine
#

what's the best way to shoot a raycast through the screen at a specified point to check which UI element is selected?

frozen ravine
#

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?

frozen ravine
#

cool

#

thanks

frozen ravine
#

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

untold moth
frozen ravine
#

That's what I was thinking, I was just wondering if there was some other way I wasn't thinking about

royal island
#

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

frozen ravine
#

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?

frozen ravine
#

wow this is exactly what I needed, thanks

royal island
frozen ravine
#

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

royal island
#

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

upbeat path
frozen ravine
#

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

upbeat path
frozen ravine
#

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

hybrid belfry
#

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?

sage radish
#

I don't think there's a lower level API than VideoPlayer for managing loaded VideoClip assets.

hybrid belfry
#

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 🙂

regal flax
#

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?

sly grove
#

ScriptableObject and MonoBehaviour classes need to both go in their own file with the same name as the class name

regal flax
#

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

sly grove
#

That doesn't make any sense

#

There's no reason to put them in the same file

regal flax
sly grove
#

Separate them

regal flax
#

when I seperate them I can't make an array of the scriptableobject

sly grove
#

Incorrect

#

You absolutely can

regal flax
#

in my case it doesn't

#

it doesn't let me call it

sly grove
#

In your case you are doing something wrong

#

Show what you tried and what happened

regal flax
#

can you cehck my script and tell me what I did wrong?

sly grove
#

You would have to show what you tried

regal flax
#

what do you mean show?

sly grove
#

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

regal flax
#

trying to call the scriptable object from the monobehaviour script when the scriptable object code is in another script

sly grove
#

What's the error

regal flax
#

script is in the editor folder cause I have dropdowns in the scriptable object

#

the error is that it can't find it

sly grove
#

That's not the error

regal flax
#

type or namespace could not be found

sly grove
#

You put it in the wrong place then

#

Show where you put each file

regal flax
#

no I didn't

sly grove
#

It should be capitalized, no?

regal flax
#

the second one is correct but they have the same error fixed it now and its still not fixed

sly grove
#

Show the two files

#

Where do they live

#

Also make sure the error is also in Unity as well not just visual studio

regal flax
#

cardmanager in scripts card asset in editor folder cause I have dropdwon stuff

regal flax
#

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

sly grove
#

One is in the editor folder

#

Can't do that

#

That's why I asked

lost crest
#

editor folder is for editor only code.

sly grove
#

Separate the custom editor code as well and put that in the editor folder

regal flax
#

thanks will do that

#

don't have to inspector working how it should

#

thanks

sly grove
#

That's what the editor folder is for.

regal flax
sly grove
#

The editor

regal flax
#

so the ones with the [editor type blah blah]

sly grove
#
[CustomEditor(typeof(CardAssetCreator))]
public class CardAssetCreatorEditor : Editor```
#

this

#

this is the editor

upbeat path
#

Damn, and it's only got the word Editor in it 3 times, easy to miss

scenic thicket
#

has anyone used mediapipe plugin for unity?

untold pagoda
#

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?

compact ingot
ruby hearth
#

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

untold moth
compact ingot
#

if you have just one server you could even store that stuff via SQLite and ditch all of the "backend"

ruby hearth
ruby hearth
# compact ingot 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

compact ingot
ruby hearth
#

but idk... there'll be many lobbies that can handle 32 players each, and dungeon instances that handle 4 players each

ruby hearth
compact ingot
#

well, those web dev years might get in the way 😉

ruby hearth
compact ingot
#

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)

ruby hearth
#

interesting... maybe creating various instances of fishnet server would help in this case? how about using redis or something else to store players data?

compact ingot
#

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

ruby hearth
compact ingot
#

in an MMO you need a shared, persistent world, not restarting servers every 15 minutes

ruby hearth
#

in my case i don't need an open world, but i need various lobbies and dungeon instances (parties)

compact ingot
#

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

compact ingot
ruby hearth
#

topdown based

compact ingot
#

and those 32 are the only 32 that can play together?

#

or say 4 of those 32 can play together in a group?

ruby hearth
#

sorry for my poor explanation, let me tell more about

compact ingot
#

anyway, seems you are creating a lobby inside a lobby

ruby hearth
#

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

compact ingot
#

ok so you are making multiple variations of servers

ruby hearth
#

the dungeon instances are different scenes, different "instances" of the game

compact ingot
#

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

ruby hearth
#

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

ruby hearth
#

exactly like spiral knights

compact ingot
#

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

compact ingot
ruby hearth
#

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

compact ingot
#

what is your timeframe?

#

team size?

ruby hearth
ruby hearth
#

the game is not that complex but it's not simple too 😦

compact ingot
ruby hearth
compact ingot
#

to be fair i should tell you that making an MMO is the prototypical beginner gamedev folly

#

everyone fails

ruby hearth
#

learning a lot about game dev is already great

#

i like to learn in the difficult way

compact ingot
#

you arent choosing the difficult way

#

you are choosing the impossible way

ruby hearth
#

haha

compact ingot
#

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

ruby hearth
#

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

compact ingot
#

i can make a game server that supports 10000 CCU if they don't see each other

ruby hearth
#

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?

compact ingot
#

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

ruby hearth
#

so it could be

#

with a integrated store/economy

#

that players can sell items, resources, etc.

compact ingot
#

a store is trivial CRUD

ruby hearth
compact ingot
#

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

ruby hearth
#

having a way to the players play together in a group of 4, the rest does not matter

ruby hearth
#

like one player quitting, completing the dungeon, etc.

compact ingot
ruby hearth
#

it's better than saving each req of a player getting one many times coin right?

ruby hearth
#

my problem is with the persistence with low latency and high security

compact ingot
#

then you aint making an MMO, just a coop-2D-game, which is MUCH more feasible

ruby hearth
#

a way that players cannot fake the gold saving endpoint req or something

compact ingot
ruby hearth
#

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)

compact ingot
ruby hearth
compact ingot
#

the complicated part is the joining/phasing of these open worlds into something that feels united, even if it isnt

ruby hearth
#

yes... a better example is how vr chat or gartic handles the worlds

#

or rooms

compact ingot
#

yes, its a bit tricky to do with the regular unity netcode middleware

#

those are all geared towards arena experiences

ruby hearth
#

i'll be using fishnet for networking and server authority

compact ingot
#

you can make those work in a way you describe, but it will be straining these architectures to the limits

compact ingot
ruby hearth
#

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

ruby hearth
#

my main concern is about persiting data in a secure way

ruby hearth
compact ingot
ruby hearth
#

but in games this is different

compact ingot
#

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 😛

ruby hearth
#

the most difficult part that is learning programming is in point. the other things we can learn in some time

compact ingot
#

well, games cannot use most of the patterns that make web/app dev easy

compact ingot
#

you have totally different concerns, you can solve almost nothing by wasting resources

ruby hearth
#

I think I'll be into playfab so

#

easier than creating and integrating a self made backend

compact ingot
#

playfab is quite expensive (its regular Azure)

ruby hearth
#

maybe only in the beginning

#

to use

compact ingot
#

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

ruby hearth
#

but if I need to use another solution, what's the best?

#

creating a SQLite file and it's it?

compact ingot
#

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

ruby hearth
#

mongo is very good tho. it's key-value too

compact ingot
#

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

ruby hearth
#

i see

compact ingot
#

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

ruby hearth
compact ingot
#

as they say, you're not building netflix or twitter

ruby hearth
#

yeah

compact ingot
#

postgres 😛

ruby hearth
#

the company that i've worked uses cassandra, but is a payment solution

ruby hearth
compact ingot
#

cassandra and the like a great for making money off clueless clients

ruby hearth
#

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

compact ingot
#

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)

ruby hearth
#

yeah, because of this i thought about creating a web backend so the ServerRPC calls the endpoint XD

compact ingot
#

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

ruby hearth
#

maybe initially is a good solution

#

i can use a service to handle the auth and another server to game

compact ingot
#

you can use anything you like, its likely on a private network, so you can probably be relatively loose on the security

compact ingot
ruby hearth
compact ingot
#

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.

ruby hearth
#

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?

compact ingot
ruby hearth
#

gRPC or MessagePack so

compact ingot
#

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

ruby hearth
compact ingot
#

we've had HTTP3 in gamedev for decades 😛

ruby hearth
compact ingot
#

we just had reliable UDP

ruby hearth
#

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

ruby hearth
compact ingot
compact ingot
#

its 1000 lines of magic

ruby hearth
#

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

compact ingot
#

well, i hope it works out for you in some way

ruby hearth
#

can i add you? i promise i will not bother you hehe

compact ingot
#

sure

#

but mind you, i've only ever failed at making MMOs 😛

ruby hearth
#

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

compact ingot
#

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

plush hare
#

I haven't read much of the conversation, but I saw the word "websockets" which is not what you want for performance networking.

ruby hearth
plush hare
ruby hearth
ruby hearth
#

regardless of the tools and frameworks

plush hare
#

yeah load balancing a single world across multiple servers is very difficult.
spreading them across scenes (dungeons) would probably be very simple

ruby hearth
#

not having 200 players in the same scene, that's it

plush hare
#

yeah, theres a handful of existing networking frameworks that can easily do this

#

unless you need a custom one for whatever reason

ruby hearth
#

I'm thinking about fishnet pro, but i can use whatever helps me

plush hare
#

and I think they've recently added clientside prediction which is pretty nice

ruby hearth
#

nice to know

plush hare
#

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

ruby hearth
#

thanks for all the sharing guys, it means so much for me

short junco
#
    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 ?

short junco
#

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 ?

short junco
#
        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

dry hatch
#

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

short junco
#

@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

GitHub

Animation Baker and Instancing for Animated Characters: Using GPU to implement large-amount animation characters rendering. The animation map for vertex shader to modify the vertex position of the ...

dry hatch
#

but reading back the data is a good idea, thanks

fringe blaze
#

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

fringe blaze
#

this is my TMP font setting

obsidian stump
thorny moss
#

Hi experts

#

I'm baking large area for AI navmesh

#

In this case , what is the best solution?

upbeat path
#

At runtime?

untold moth
#

The best solution is to bake the navmesh

wet sail
hybrid belfry
#

Hi, is there a way to show Functions for Unity Events in Inspector which use an Enum as a parameter?

misty glade
misty glade
#

I mean, it's also less than ideal since the inspector method will show an int instead of an enum, but... it's something. 😛

dry hatch
#
    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

hardy sentinel
hardy sentinel
#

ah

dry hatch
#

it show like this in the inspector, but it doesnt actually apply it

hardy sentinel
#

how are you certain it doesn't? Also, are you doing this during play mode?

dry hatch
#

well the textures actually are created through code

#

but i run the code in editor

#

and I am certain, because its physically visible

hardy sentinel
#

the max size is used for compression only btw. You're not resizing the texture with that.

dry hatch
#

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

hardy sentinel
#

yeah I would expect it to re-apply the compression algorithm during SaveAndReImport(). Maybe try AssetDatabase.Refresh() after reimporting?

dry hatch
#

ok 1 sec

#

no it didnt work

hardy sentinel
#

there's also a special ForceUncompressedImport enum option there for Refresh

dry hatch
#

the ui itself changes, thats the weird part

hardy sentinel
#

again, are you just trying to uncompress it?

#

because it won't magically become a 16k texture just because you disable compression

dry hatch
#

look at the code above

hardy sentinel
#

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

dry hatch
hardy sentinel
#

yeah, it won't become 16k no matter what

dry hatch
#

if my changes dont get applied it will be compressed to 2048

#

the default value is 2048

hardy sentinel
#

I think your texture can't be compressed no matter what you do, since it's dimensions are not a power of 2

dry hatch
#

i also need to disable sRgb, and mipmaps, which also dont get applied

dry hatch
hardy sentinel
#

textureImporter.SaveAndReimport(); should technically call AssetDatabase.Import(AssetDatabase.GetAssetPath(texture));, but maybe it doesn't (?)

hardy sentinel
dry hatch
#

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

hardy sentinel
#

yeah, sure.. put a Debug.Log in there too

#

also include the "manual fix" in

dry hatch
# hardy sentinel yeah, sure.. put a Debug.Log in there too

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

hardy sentinel
#

well you can probably take it from here lol

dry hatch
#

but how could it be...importer tabs interface changes...

hardy sentinel
#

you might have messed with the defaults

dry hatch
#

its already in the Editor folder...

#

wtf

hardy sentinel
#

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

dry hatch
#

thanks let me try

#

that might have been it

#

yup

#

fixed

#

thanks a lot

hardy sentinel
#

np

#

is Debug.Log still not appearing tho?

dry hatch
dry hatch
wind kayak
#

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"

sly grove