#archived-code-advanced

1 messages · Page 111 of 1

steel snow
#

wouldnt indirect be more for same meshes like trees etc?

sly grove
#

Yes? I'm not exactly sure what you're rendering though

steel snow
#

roads like cities skylines

sly grove
#

"spline generated geometry" I guess one mesh?

steel snow
#

uh well its generating the meshes data in jobs

#

so they are a new mesh every time the spline changes

#

so i guess they are considered all uniquely diffrent so maybe i cant use indirect ?

#

they all the same material though

sly grove
#

(for a single road at least)

#

You're talking about when you're editing the road and it's changing yeah?

steel snow
#

yeah

sly grove
#

Ideally you don't create a new mesh each frame for that

steel snow
#

well its very complicated to re-adjust uvs when manipulating the same one

#

so i just start again

sly grove
#

Well you can certainly just completely overwrite the vertices/uvs/triangle arrays all the time

#

just - creating a new mesh is a lot of GC

#

and you have to Destroy the old ones

steel snow
#

well i have to create a new mesh instance either way from the original for each new spline

#

then i appliy the native arrays to the new mesh instance

#

if im manipulating the same one i just do work on the native arrays and apply the arrays to the same mesh class

#

dont know why they dont have mesh struct which just has refereces to array data

#

would be nice if they gave us a readonly mesh struct that accepts array data then you just send it off and unity engine applies it as a mesh - would work well with their new mesh api for jobs

silver hill
#

It's a dilemma. I'm rendering a giant 2d map, chunked into smaller pieces. Since everything except water tiles is using the same material, this means about 80% of the chunks are essentially the same mesh and therefore can be drawn in an instanced way. However, I'm not sure what to do with textures

#

They only way to keep the instancing is to use a texture atlas, which if I'm not mistaken is limited to around 16k

#

Which sounds a lot but I'm really not sure about some potential drawbacks of feeding those gigantic atlas textures to the gpu

#

But breaking all this stuff into their own materials is basically giving up on instanting and doing a lot of stupid draw calls

brave cairn
silver hill
#

Surpsingly

brave cairn
#

Anyway consider compressed texture formats. More free GPU memory and faster shaders (less memory to read = bigger throughput)

silver hill
#

Obviously all images are compressed differently

brave cairn
#

This calculator is set up for 16384x128 texture. It is small. Try 16K x 16K

silver hill
#

16384x128 is the current worst case for my tile map so

#

Yeah, pretty small

#

128 unique tile textures, basically. Each 128x128px

#

Really underestimating how much stuff can modern hardware process

somber swift
silver hill
#

Or is it selected automatically based on platform

#

Either way you could probably pack it in a 1:1 ratio instead of a strip if needed

somber swift
untold moth
silver hill
somber swift
#

Also might be easier to work with not that squashed textures. The texture preview in unity for example might be suboptimal with textures like that

silver hill
#

My idea was to stich them at game startup into a single atlas, then use in a shared material to enable instancing

somber swift
unkempt moat
#

Hey there!

I'm sorry to bother you, but we've been stuck on an issue with our Trainer Station project for about three weeks, and I thought you might have some insight, if you don’t mind, of course.

The Trainer Station is a project aimed at tracking the progress of a learner in a VR application on the Oculus Quest 2. It allows us to see what the learner sees and sometimes interact with the application itself. However, we're facing a persistent problem with Unity Render Streaming, which never connects and doesn’t load properly.

Basically, everything works fine on the same PC, but when we switch to a different machine or from Oculus to PC, it fails with the same error (PeerConnection).

The errors we keep encountering are:

InvalidOperationException: [impolite-PeerConnection ConnectionState:New IceConnectionState:New SignalingState:HaveRemoteOffer GatheringState:Gathering] sendoffer needs in stable state, current state is HaveRemoteOffer
  at Unity.RenderStreaming.PeerConnection.SendOffer () [0x00000] in <00000000000000000000000000000000>:0 
  at Unity.RenderStreaming.PeerConnection+<OnNegotiationNeeded>d__36.MoveNext () [0x00000] in <00000000000000000000000000000000>:0 
  at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00000] in <00000000000000000000000000000000>:0
#

And previously, we were getting this:

Signaling: HTTP request error. url:http://xxx.xxx.x.xxx/signaling?fromtime=1722603235614 exception:System.Net.WebException: Error: ConnectFailure (mono-io-layer-error (111)) —> System.Net.Sockets.SocketException: mono-io-layer-error (111)
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
#

The second error is quite generic, but the first one is more specific. I haven’t been able to find much about the first error online, and the second one used to appear but has since been replaced by the first.

There’s also something strange happening: if I restart both PCs, it works once, but crashes as soon as the application is launched a second time. I suspected it was a process not closing properly and keeping the port in use, but after checking with netstat -ano -p tcp, the port doesn’t seem to be in use after the application closes.

Another issue is that all firewalls have to be completely disabled for it to work right now, which is a bit of a hassle.

I've tested this on two different PCs and from Oculus to PC, and the PeerConnection error remains the same.

Thanks a lot if you have any ideas, and I apologize for the disturbance 🙏

midnight violet
unkempt moat
midnight violet
unkempt moat
#

if you want to, here :

NetworkManager.cs :

        public void CreateStreamingConnection(string pIP)
        {
            if (IsClient == false) return;

            AudioListener audioListener = _ParentNetworkStreaming.GetComponent<AudioListener>();
            if (audioListener != null) audioListener.enabled = false;

            if (_Fonctionnement == Fonctionnement.UnityRenderStreaming)
            {
#if !UNITY_WEBGL
                _instanciedStreamingClient = Instantiate(_StreamingClientURS.gameObject, _ParentNetworkStreaming.transform.position, _ParentNetworkStreaming.transform.rotation, _ParentNetworkStreaming.transform);
                _instanciedStreamingClient.GetComponent<StreamingClient>().StartBroadcasting(string.Format(mIPStreamingHTTP, pIP));
#endif
            }
            else if (_Fonctionnement == Fonctionnement.WebRTCPlugin)
            {
                /*Debug.Log("Streaming" + _ClientId);
                _instanciedStreamingClient = Instantiate(_StreamingClientWebRTC.gameObject, _ParentNetworkStreaming.transform.position, _ParentNetworkStreaming.transform.rotation, _ParentNetworkStreaming.transform);
                _instanciedStreamingClient.GetComponent<OneToMany>().ID = _ClientId;
                _instanciedStreamingClient.GetComponent<OneToMany>().StartOneMany();*/

            }

            OnClientGetControlled.Invoke(string.Format(mIPStreamingHTTP, pIP));
            IsFocusClientSide = true;
        }```
#

StreamingClient.cs :

        public void StartBroadcasting(string pIP)
        {
            IP = pIP;

            HttpSignalingSettings settings = new HttpSignalingSettings(IP,null, interval);

            Http = new HttpSignaling(settings, SynchronizationContext.Current);
            renderStreaming.Run(Http, handlers.ToArray());

            inputReceiver.OnStartedChannel += OnStartedChannel;
            videoStreamSender.OnStartedStream += OnStartedStream;
            videoStreamSender.OnStoppedStream += OnStopStream;

        }

midnight violet
#

Do you get any specific point in code, where the error occurs? As your code is talking about a task, it might be a background thread, thats still running and will never be cancelled

unkempt moat
#

Well, no

#

Since it's working on editor, but not on build

#

And the error on build is litterally the one I showed you...

#

I did have this errror on editor sometimes

#

But it doesn't point to any of my code

#

It pointed to URS code

midnight violet
#

Okay, so its also happens on editor, not as often as in build

unkempt moat
#

Yes

midnight violet
#

Maybe #archived-networking would be a good place to ask, as this seems to be related to WebRTC which is still a pre-package. I myself had some "fun" with that package already just doing weird things or totally missing the plugin register on build too. Ive seen, you also created a git issue thread for this which someone has been assigned a month ago, lets hope they might find the issue. The only thing you could do right now is to debug, that all connections are established and closed correctly, that you are opening. Are you doing this already, as I can see you register some OnStoppedStream events. Are you unsubscribing correctly too there?

unkempt moat
#

Okey, I'll go aske there, thank you !

For the connection, On Stop STream is not used, but there is a code which close the cmd opening, the one used for the server... So it's like closing the server. I, myself, thought there was a problem and that's why I checked the port were closed after thanks to the netstat command, and yes it is. Wait, I'll show you the code

#
   public void StartWebServer()
        {
            if (_NetworkManager.IsServer == false) return;

            _WebServer = new Process();
            _WebServer.StartInfo.UseShellExecute = true;
            _WebServer.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            _WebServer.StartInfo.FileName = $"{Application.streamingAssetsPath}/webserver.exe";
            _WebServer.Start();
        }

  public void StopWebServer()
        {
            if (_NetworkManager.IsServer == false) return;
            if (_WebServer == null) return;
            KillAllProcesses(_WebServer.ProcessName);
        }

  private void KillAllProcesses(string pName)
        {
            if (string.IsNullOrEmpty(pName)) return;
            Process[] pProcess = Process.GetProcessesByName(pName);
            for (int i = 0; i < pProcess.Length;i++)
            {
                pProcess[i].Kill();
            }
        }
midnight violet
#

But the error occurs randomly or everytime you start the application a second time?

unkempt moat
#

It works if I'm staying on the same computer as well

midnight violet
#

So your application serves as server and client at the same time, do I get this right from your NetworkManager.IsServer check?

unkempt moat
#

Basically, there is the server part on one unity project, on the other, the application have the same code, and the network manager on its client scene, but is not the same application, the network manager is cofigured for a client, and the firt app is configured as server

#

I don't know if it's clear 😅

midnight violet
#

Not really 😄

unkempt moat
#

How can I explain

#

Huhh

midnight violet
#

Maybe its just me 😄

unkempt moat
#

Okay so

App 1 and 2 : Have the same code, but are not the same project.

App 1 : Have specifics scenes, is server sides. Launch WebServer.exe and open the connection.

App 2 : Have the VR application, and its scenes. On its client scene, have the networkmanager configured to client, so it can connect to the server opened by App 1. Is does not start the webserver.exe or open any connections, just connect to the connexion that exists from App 1

#

I don't know if it's better ?

midnight violet
#

Ah, okay, that makes sense now 🙂

#

And your App 1 is running constantly while you get the error when reconnecting?

unkempt moat
#

Yes

midnight violet
#

And the error is on client side, right? Did you check your servers current connections? Maybe its still holding a reference to the client after stopping the client app?

unkempt moat
#

Yes it is.

No, but what confused me is the error still appear even if I stop the App 1 and start it again. It could not keeping any reference if it's stopped, could it ?

midnight violet
#

If its a background thread, it can still run.

#

and since you are getting an error from Task, something seems to be calling a task and probably on a backgroundthread and therefore it will keep running if its not cancelled correctly

unkempt moat
#

I'll go check on it, thank you

#

I caome back after :)

untold moth
unkempt moat
untold moth
rancid patrol
#

I'm going insane trying to track down the cause of this error. I've had the exact issue before, a million years ago, but according the manual (as per screenshot) this should be supported anyway? I've resorted to just checking every instance of #if UNITY_EDITOR and changed a couple of bits of my own code, to no avail.

Any tips? Untiy 6000.0.18f1

A scripted object (probably UnityEngine.Rendering.HighDefinition.RequiredSettingsSO_HDRP?) has a different serialization layout when loading. (Read 56 bytes but expected 164 bytes)
Did you #if UNITY_EDITOR a section of your serialized properties in any of your scripts?```
#

I initially suspect an issue with RealtimeCSG since one instance of the error references one of its classes, and its geo is also not showing up in builds... however I tried to repro in an empty project and had no joy.

Wondering if it might be some new Unity 6 project level setting that I haven't spotted

lapis bone
#

Hello
I facing some issue with controller joystick. I have removed the dead zone from the look and move actions. So now if I move the joystick slightly it directly affects the character which is what i wanted. But this same thing does not work on the IOS device. If I connect the xbox controler to the IOS 13 the dead zone is still there. I tried changing the min dead zone value but still same thing.

How does the input values work differently on the editor and IOS device.

Can anyone please help with this issue

timber flame
#

There are multiple sources and sinks and a bidirectional graph. I would like to convert it to a DAG graph based on sources and sinks. I think about CSP (constraint satisfaction problem) algorithm but is there any better straightforward algorithm?

compact ingot
# timber flame There are multiple sources and sinks and a bidirectional graph. I would like to ...

There are no efficient algorithms for cyclic graphs due to there not being any one correct solution and therefore no inherent property of the graph that can be used for optimization. Consequently, your particular algorithm choice depends on how you decide to prioritize one cyclical path over another. Depending on use case you can do various things that do provide an efficient solution to your specific problem where a ‘perfect’ solution from graph theory would be too expensive or complicated.

#

Fundamentally a graph with cycles cannot be converted to a DAG without some form of heuristic for deciding which cycles to drop.

#

One such heuristic could be an incremental BFS performed from all sinks concurrently with a shared open/closed list. Another could be calculating a minimal spanning tree from any node.

timber flame
compact ingot
# timber flame Thanks, there are several sources and sinks and a bunch of pipes. I would like t...

consider that often the intuitive direction or order of how things should be evaluated does not produce the desired result, in case of flow, starting from the sinks, which are the points of congestion, may be more desireable. i've recently has a similar situation where sources and sinks are dynamically added and removed at runtime and the whole DAG calculation would have been too difficult to solve upon such changes as the previous state would have to be corrected, and the solution was instead to simulate pressure on each node update that passed a token on to the next where pressure was an accumulation of failed transition events, so changes would then naturally propagate through the network and cycles would solve themselves. this is effectively an iterative calculation of a DAG where old and new state temporarily overlap without ever pausing the simulation. It also does not require additional memory. Depending on the implementation this (self organization while simulating) can even be very cache friendly since you will only ever update adjacent nodes which you can put in a heap using your locality heuristic as an ordering key.

timber flame
compact ingot
# timber flame Appreciated but this way is time consuming, isn't? I thought finding DAG is more...

the easiest solution is the concurrent BFS with shared open/closed lists, that gives you data for a minimum spanning tree with directional information, which is a DAG. other options for finding one exist, not all have directional information https://en.wikipedia.org/wiki/Minimum_spanning_tree

A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. That is, it is a spanning tree whose sum of edge weights is as small as possible. More generally, any ed...

fresh olive
compact ingot
upbeat path
#

not a code question. Do not cross post

timber flame
sturdy timber
compact ingot
sturdy timber
#

Does anyone know a better alternative to marching cubes or surface nets alghoritims?

misty glade
dusty wigeon
sturdy timber
#

Right, performance would be most important however the simpler the algorithm the easier for me it is to extend it with other stuff

zealous summit
#

I'm writting my own level editor and decided to make an extended class of a dropdown. It worked fine until I started adding new options with a loop. I'm getting "ArgumentOutOfRangeException: Index was out of range" and it's very hard to debug. The line causing the problems is the Action declaration.

Here's the dropdown code:

public class ExtendedDropdown : TMP_Dropdown, IExtendedUI
{
    public TMP_Text _labelTMP;
    public string Label { set => _labelTMP.text = value; }
    public List<(string label, Action onChanged)> Settings
    {
        set
        {
            onValueChanged.RemoveAllListeners();
            onValueChanged.AddListener((int newIndex) => value[newIndex].onChanged());

            options.Clear();

            for (int i = 0; i < value.Count; i++)
                options.Add(new(value[i].label));

            value[0].onChanged();
        }
    }
}

Here's the method:

    private void InitializeTabsDropdown()
    {
        List<(string label, Action onChanged)> settings = new();

        for (int i = 0; i < _editorTabs.AllTabs.Count; i++)
            settings.Add((_editorTabs.AllTabs[i].Label, () => _editorTabs.AllTabs[i].EnableTab(_tabLayoutGroup.transform)));

        _tabsDropdown.Settings = settings;
    }

And here's how I was debugging it:

    private void InitializeTabsDropdown()
    {
        List<(string label, Action onChanged)> settings = new();

        for (int i = 0; i < _editorTabs.AllTabs.Count; i++)
        {
            Debug.Log(i);
            Debug.Log(_editorTabs.AllTabs.Count);
            Debug.Log(_editorTabs.AllTabs[i].Label);
            string label = _editorTabs.AllTabs[i].Label;
            Action onChanged = () => Debug.Log(_editorTabs.AllTabs[i].Label); //ERROR COMES FROM HERE

            settings.Add((label, onChanged));
        }

        _tabsDropdown.Settings = settings;
    }
scenic forge
#

Your onChanged lambda captures the variable i, not the current value of i. By the time that action is called, i has changed.

zealous summit
#

interesting. Do you know how to make it capture the current value?

scenic forge
#

Make a new variable that you won't change, and capture that instead.

#

It's quite a common mistake and affects many languages not only C#, so just something you need to keep in mind of.

zealous summit
#

good to know. First time seeing this type of error, but it makes sense to work like this. Capturing the current value in a new variable ruins the nice one-liner, but it's works ;)

sleek cloud
#

Hey folks!
Hope you're doing well.

I don't know if it's a good chat for the question and if there people who could help (maybe only unity-devs could help here), but.
I'm checking how il2cpp works, using Unity 2022.3.39f1, building "dummy" app for android.
I have C# class just to log constant and another class to "store" this constant.

This code is part of Assembly-CSharp and is compiled in Assembly-CSharp.cpp:

As you can see, it uses identifier _stringLiteral9425139C080CFB8E61ED9C7B329DC7A307EFF0D7 to access "hello world!" string.
Also, this identifier declared as:
String_t* _stringLiteral9425139C080CFB8E61ED9C7B329DC7A307EFF0D7 = (String_t*)(uintptr_t)2684359951;
It feels like it's a pointer(offset) to string inside global-metadata.dat
So, I tried to open global-metadata.dat and find string there and it exists, but it has different offset 001ad4c6.

And here's my question:
What exactly is 2684359951? How does it match to offset 001ad4c6 in global-metadata.dat ?
OR
Maybe I'm missing something and would like to hear any advice.

stuck plinth
tepid osprey
#

Hey! How could I make a mouse sensivity slider, or atleast 3 buttons for sensivity?

tepid osprey
sly grove
#

don't crosspost

misty glade
#

I'm building a new side project and have a need for admin tools. I've done this a few different ways in the past, none of which I'm super happy with:

  • Blazor/Razor web on Azure, hooked into CosmosDB (too fickle with the UI, expensive, hell of a time to configure networking)
  • Standalone Unity app that read/write binary/json files that were shipped with the game
  • The worst solution - hard coding content directly into the app/code

I'm intending this to be multiplayer so I'll have a need for a persistent data store and likely some sort of containerized C# server. Looking for suggestions for data management that are relatively robust but also not a huge pain in the ass to setup and manage. I might even be OK with a nosql front end to start..

regal olive
#

When I create a C# script, how do I stop it from reloading the domain every time? It kills productivity immensely.

long ivy
#

it's free unless you have a pro license

cold canyon
cold canyon
# long ivy it's free unless you have a pro license

You can enjoy Hot Reload with an unlimited 30-day free trial. After that, regardless of your Unity version, you'll still have access to 2 free hours of Hot Reload each day. This lasts until you decide to buy a license.

long ivy
#

I've been using it for many months (via github package link) so maybe I'm grandfathered into the old model

cold canyon
long ivy
sturdy idol
#

I managed to integrate the Roslyn compiler into a Unity game and do 'live' game coding (using C# as script):

cold canyon
timber flame
#

I have implemented a save system for my game.
The entities are spawned at the beginning of the game. There are some zenject factories for each type. They have Create method for TypeSpawnData argument.
My problem is when loading the entities. In the load time, the data structure is not TypeSpawnData. It is a different type PersistenceData. So, I cannot use the implemented zenject factory. There are different solutions. For example, defining different Create methods with different args. Another solution is to define zenject factory with Create method without argument. So, I can call Create method for both situations (load time and at the beginning of the game) and then create different methods in the main component of the entity Load(DataPersistence data) and Initialize(SpawnData data)

Also, I guess I am able to convert SpawnData to DataPersistence when spawning the entities at the first time. Therefore, I can populate data just by calling Load(DataPersistence data) and remove Initialize method

What is your approach? have you faced this type of problems?

violet iron
#

hi! I'm running into some issues trying to use a AndroidJavaProxy to use an interface declared inside an AAR. I'm getting a java.lang.ClassNotFoundException when I instantiate my object. I don't get it in the editor, but I do on my device. Does anyone know anything about this type of stuff?

violet iron
#

nvm, i think i figured it out. should've used '$' in the path to my interface instead of a '.'

#

java sucks so bad... lol

late wedge
#

I'm looking to implement a node-based navigation system to draw arrows from the nearest node to the player to the next closest node to their destination. What search algorithms would work best for a problem like this?

misty glade
#

what are your nodes shaped like? square/grid? are there gaps? different weight for traveling through each node/destination?

#

A* pathfinding if you need to roll your own, NavMesh (built into unity) is another option

#

But if your "closest nodes to a destination" are just simple "Manhattan distance" then just calculate a list of distances of nodes from a destination whenever it's appropriate (whenever a node or destination is created/deleted)

mild patio
#

I'm trying to do something pretty simple

  1. Allocate a 2gb persistent memory arena via Malloc
  2. From that 2gb, sub-allocate NativeArray<Color32>s, which I then use for AsyncGPUReadbackRequests (with callback)

I'm using

        outArr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Color32>(ptr, len, Allocator.Invalid); // (Allocator.None?)
#if ENABLE_UNITY_COLLECTIONS_CHECKS
        AtomicSafetyHandle safetyHandle = AtomicSafetyHandle.Create();
        AtomicSafetyHandle.SetAllowReadOrWriteAccess(safetyHandle, true);
        NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref outArr, safetyHandle);
#endif   

However, I'm getting the following error : AsyncGPUReadback - NativeArray does not have read/write access

#

I think this only happens when I call the above in the same frame as the AsyncGPUReadbackRequest,
Nevermind, not a thing. It seems to only happen the first time we call AsyncGPUReadback on a given NativeArray<Color32> though? Like subsequent calls are fine?
And weirdly it almost seems like it works anyway? Wtf?

#

I found this in the issue tracker, but I'm only ever doing one readback request per frame... period

#

Like not even one per native array. There is exactly one readback request reference in my game, and it is called once per frame.

#

For NativeArrays that are allocated the 'normal' way (new NativeArray<Color32>(...)), it works fine. No errors.

#

Should I just not worry about the error since everything I'm doing is legal?

#

Sometimes the readbackrequests come in out of order, like they take multiple frames to come in, and maybe the issue is they're both touching the same tracked memory block?

#

I've been looking into this thread for salvation and finding nothing

#

I don't think I'm doing anything illegal?

#

Yeah, the first time AsyncGPUReadback touches a NativeArray allocated this way, it throws that error, but not. subsequent times. ?

#

I'm new to dealing with low-level stuff through Unity's library and C# - are there good ways to get a better look at what might be happening here?

mild patio
#

Frustratingly, the only hitches I'm getting are... Unity logging this error
Which does mess with my ability to test stuff, at least in editor

mild patio
#

Yeah. Unity hitches a little bit the first time it reads into one of these NativeArray<>s, but it still works and doesn't report an error in the readbackresult

#

Then I return it to the pool, and then the next time that same NativeArray<> gets passed into the readback function... no hitch, and no error

mild patio
#

I'm on 2022.3.5f1 for what it's worth

upbeat path
vague ferry
#

Hi, i got a question about external file management.
I have an application that is design to build with webgl

My application have a card deck that is configured by a json file read by the game at start. But for the moment, the file is include in the build so if i want to change my deck configuration, i have to build the app again.

Is there a way to have this json file in the game repo, so i can edit the file when i want without having to rebuild and redeplay my app ? Like giving him a relative path to a file to read an asset repo

upbeat path
vague ferry
#

but this force me to have a backend server with rest api no ?

upbeat path
#

no. You need a server to host the WebGl build anyway, that server can host the json file, no rest API required

vague ferry
#

mhh, i will check for this solution, thx ❤️

#

but just one thing, with this method, i have to put the entire web url, i can't have something like "./config/deck.json" right ? he will not automaticly bind to his local repo online.

upbeat path
#

I have no idea what you mean by local repo, we are talkiing about web servers here

vague ferry
#

i mean if i do something like http.get("./config/deck.json"); will unity do a http.get to "https:/myserverURL/[pathofmyapp]/config/deck.json", or do i have to put the entire URL to access to my json myself

sturdy idol
#

Hello. I installed the roslyn scripting packages over NuGet and they kind of work, until I get NotImplementedException: The method or operation is not implemented in System.Runtime.Loader. I found a 'workaround' by replacing the System.Runtime.Loader.dll in the Unity editor assembies by the one supplied by NuGet. Why is the System.Runtime.Loader assembly 'broken' in Unity like that? This prevents me from doing 'C#-as-a-scripting-language' in the Unity editor...

flint sage
#

Can't really guess if we don't knwo what method is throwing that

upbeat path
upbeat path
flint sage
#

I doubt unity can resolve the url since it doesn't really know what server it's running on, from Unity's PoV it's just a call to a random website

sturdy idol
flint sage
#

Unity uses roslyn to compile, and as such some compiler level features are available

sturdy idol
# flint sage Can't really guess if we don't knwo what method is throwing that

NotImplementedException: The method or operation is not implemented. System.Runtime.Loader.AssemblyLoadContext.LoadFromStream (System.IO.Stream assembly, System.IO.Stream assemblySymbols) (at <997b8c902a604dd8b0889a2946a845e5>:0) Microsoft.CodeAnalysis.Scripting.Hosting.CoreAssemblyLoaderImpl.LoadFromStream (System.IO.Stream peStream, System.IO.Stream pdbStream) (at <b649ee56de854dcfa111602d7b9fff6d>:0) Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader.LoadAssemblyFromStream (System.IO.Stream peStream, System.IO.Stream pdbStream) (at <b649ee56de854dcfa111602d7b9fff6d>:0) ...

flint sage
#

But that exception might as well come from the runtime mono libraries, and not from System.Runtime.Loader

#

(yes that repo is xamarin, which is effectively mono)

sturdy idol
#

Yes, I guessed that much, but can Unity please integrate this. It makes possible to do stuff like 'live c# code modification' inside the game.

flint sage
#

I mean you can do that anyways, just not in the same way as you're doing now

#

Also this is not the place for feature requests

sturdy idol
flint sage
#

Yeah

sturdy idol
#

the top google hits on 'unity hot reload' are either commercial products or implementations based on reflection? my solution (on the video above) allows to type a code snippet and get results immediately in your game (see my video above). don't think anyone is doing this...

flint sage
#

Idk what video you're talking about

sturdy idol
flint sage
#

But there's also things that let you execute C# in your game as well

sturdy idol
#

I can execute C# in another app domain sure (so I can unload it properly), but it prevents me from accessing my game assembly and Unity at all.

cold breach
#

I need to be able to enable/disable the individual channels of an impulse tracker file at runtime, but I can't find any scripting references.

floral marten
#

hmm do unity's transforms store matrices and derive quat/pos/scale, or do they store the quat/pos/scale and derive the matrices?

#

at runtime that is, not the serialized data

sage radish
# floral marten hmm do unity's transforms store matrices and derive quat/pos/scale, or do they s...

It would be interesting to know the answer to this. I don't think anyone can answer this definitively except those with source access.

I personally think it's likely they store TRS and calculate the matrices as necessary. I'm basing this on:

  1. the fact that their Matrix4x4 type has methods for creating TRS matrices, but not for deconstructing.
  2. TransformAccess, which is a lower level access to transforms for jobs, gives you read and write access to position/rotation/scale, but only read access to the matrices.
  3. gut feeling
floral marten
#

I would guess so as well, if anything, to ensure serialization <-> deserialization is idempotent

late wedge
late wedge
misty glade
#

so 3d world.. do you need to "point" in a direction as the crow flies, or along the path the user should take

#

like if there's halls in an L shape and the player and destination are at the endpoints, do you care if the arrow points "through" the world

late wedge
# misty glade like if there's halls in an L shape and the player and destination are at the en...

Trying to keep them inside the station ideally. Way I'm conceptualising right now is to have the arrows drawn from the start point to the final point, moving from point to point inside the station as needed. Since there's only ever going to be one valid path between linked nodes I need an algorithm to find said path. (I guess this means I'll need nodes to know which nodes are directly linked to it.)

misty glade
#

Yep, you're smellin what I'm cookin - and you're likely gonna need to implement some sort of A* if you have any loops in your maps

#

A* isn't too bad, but you'll definitely have to sink a little time into it to understand it.. but what I'm sorta thinking is that you've got a graph (some set of nodes each connected to some set of other nodes; each of which has a weight, likely just the distance between nodes).. then you'll A* it using those distances between each node and some sort of manhattan distance to the goal (probably just worldspace distance so your pathfinding doesn't travel in the wrong direction)

austere jewel
late wedge
#

Maybe I'll mess around at home and see if I can get something working

#

Thanks ^^

mild patio
#

This wouldn't be bothersome if it wasn't accompanied by a little hitch every time the read/write error comes up... I'm wondering if I'm doing something wrong, but I can't come up with a reason why it'd only happen the first time we pass that array into the GPU readback call

#

For context, I'm using this to record video - and I'm sub-allcoating from the 2gb chunk because I don't want to have to free + re-allocate the memory for all my NativeArrays every time I change the recording resolution (and thus the length of the NativeArrays I'm reading back into)

#

I could try to do a thing where, the instant I change the video resolution, I build a ton of NativeArrays out of the malloc'd block and fire readbacks 'pre-touch' all of them so I hit these errors and stutter the game upfront, vs. when I'm playing it.
Do I really need to do that?

#

That seems like a slightly ridiculous workaround, especially if there's something I'm doing wrong I could just fix

#

I'm just really struggling to come up with an explanation for this behavior. Especially since this error doesn't seem very well-documented. Why is this only happening for arrays allocated from the Malloc'd block, but not new()d normally? I've verified that the arrays don't overlap

misty glade
#

OK. Brain is hurting so I'm turning here.

I have a struct HexPoint and an extension method to calculate optimal path between points on a map (each point can have varying movement costs - integers). My map is a Dictionary<HexPoint, TerrainType> . Signature of this method is:

public static bool TryGetPath(HexPoint from, HexPoint to, Dictionary<HexPoint, TerrainType> map, out List<HexPoint> path) { ... }

Note that the map doesn't have to be contiguous or dense - holes are ok.

I have units that have an integer based move speed. I want to be able to highlight all the hexes within range when I select a unit. The map is about N=300 so I probably could just brute force it (ie, pathfind to every single hex on the map, and show hexes where the move cost is LE the unit's movement capacity) but that feels like it might be a big CPU workload.

Any ideas?

mild patio
#

Have you looked into doing a flood fill algorithm?

misty glade
#

the pathfinding is currently fast enough to draw the path when the mouse position changes at 60fps

#

oh, hm... that seems like the obvious solution actually

#

I just flood outward, starting with the movement capacity and subtracting each hex by the movecost

#

wow.. why did I think A* was the right approach at all

#

(I was literally going to a place where I was going to cache a dictionary of hexes that exist on paths as I iterated the map)

mild patio
#

We've all been there haha - overcomplicating things for ourselves is a fact of life

#

we are only human
(plus maybe you want to use the a* pathfinding cost as the metric for whether to continue the flood at some point, who knows... unless that'd be the same value either way? shrug)

unkempt moat
#

Hello!

I have the following script:

void CreateRenderPass()
{
    if (BlitColorMaterial == null)
    {
        Debug.Log("Material is null. The pass won't be created and injected.");
        return;
    }

    // Creates the render pass and specifies it to be injected at AfterRenderingSkybox event.
    m_ColorBlitPass = new BlitPass(BlitColorMaterial, RenderPassEvent.AfterRendering, _RenderTexture);
}

The problem I’m encountering is that in VR, my UI doesn't appear. I’ve had this issue before because I didn’t select the correct RenderPassEvent. I fixed it by using RenderPassEvent.AfterRenderingPostProcessing, and it worked fine in the editor.

However, in the Android build for VR, it doesn't. I changed it to RenderPassEvent.AfterRendering, but the UI still doesn't appear.

Does anyone have any ideas on how to resolve this?

misty glade
#

red highlight on the "origin" unit, hexes in range are green-to-red colorized, hexes out of range are uncolored

#

took like... 3 minutes to implement.. can't believe I was hung up on some sort of wonky solution

mild patio
#

beautiful

novel cairn
#

Quick Optimization question, What is the Overhead of an LOD Group Component? I have many different objects in my scene, Im wondering if i should add an LOD GROUP Component to each object or if this would be too costly and counteract some of the performance gained. Is it better having fewer LOD Group Components with large groups of objects?

dusty wigeon
#

And, the performance you gain is different. You trade CPU for GPU

#

In other words, if you are CPU bottleneck, you are going to lose FPS.

#

If you are GPU bottleneck, you are going to gain FPS.

novel cairn
dusty wigeon
silver hill
#

For a voxel world, what would be a better way to store additional info regarding certain cells?

#

Similar to how minecraft stores its block state with a hash map of <String, value> I'm pretty sure

#

For one, since the value seems to be a different type across blocks, it's not very easy to design a clear data model

#

And then string tags are kind of a pain in general

#

I initially thought about something similar to a universal int flag since it doesn't take up a lot of space but can represent a fair bit of data

brisk pasture
#

i am not familar with how minecraft works data structure wise

#

what is the string in this case?

#

also how many tiles compared to all of them have additional data?

#

there are a lot of ups and downsides to different approaches and its really going to come down to how you want to access it, and what the data is like and how you want to allocate it all

#

like not voxels but in a game i am making that has a very dense 2d grid, i found its much better to just allocate every tile in the whole grid up front, and use value types for them, since the size of my data is the same size as a pointer anyways. As a result its all allocated on a 1D array and i just do some math to convert a 2D tile coord to a 1D index hashmap had more overhead for this case then i wanted

regal lava
#

<Vector3int, BlockType> where BlockType represents each type of block that derives from it

#

Oh, yeah Minecraft is infinite, right? I guess that makes sense to use a string lookup then

silver hill
#

In minecraft the implementation is stupid simple, just a map that goes:
"GrowthStage": 4

#

And alike

#

Theoretically I could just do that, but strings seem rather cumbersome, especially since I plan to use dots for this project (which hates strings)

#

I thought to maybe give some flag data type to a state and if the memory needed to describe it is greater than it's capacity, then it should be an entity instead

misty glade
#

I wouldn't use strings for this.. Not exactly sure what you're trying to store but if it's biome/chunk specific then you likely want to inherit from an abstract chunk data type that stores generic stuff, and add data points to inheriting children

#

and then your chunks are programmatically determined by a "secret" formula, some perlin noise, and a random seed.. you fill out your chunk with individual pixels/blocks when your player is close enough to it

misty glade
#

I have an interesting usecase/problem. I'm going to put all of the rendering "stuff" in an abstract GameObject EntityRenderer that stores stuff like the meshes, textures and cameras for the unit; but I'm also going to store some stuff like a profile picture (sprite).

In the past I've stuffed all this junk in a ScriptableObject "database" and looked it up from wherever I needed it.

For this project, though, there's going to be a limited number of unit types (5?) and I was thinking of just putting all the info in one prefab for convenience.

That being said.. accessing it from "anywhere" is tricky. The units and their meshes live in a map gameobject, but they're instantiated in a singleton. Am I gonna have problems Destroy()ing an object if it's got a pointer to it somewhere else? I'm assuming it'll be fine since Destroy just marks an object for deleting at the end of the frame, but the C# reference will work fine for the remainder of the frame? IE, if I make a dictionary of Dictionary<EntityBehaviour, EntityRenderer> where EB is a POCO and ER is the game object, and I move those game objects to a transform that I delete or destroy all children - is Unity gonna handle that OK? Or am I creating issues by doing it this way

#

my actual use-case is that I want to have a little profile picture (sprite) that I can access and display throughout the UI in the game

#

see "portrait image" - it's just a sprite, not used in the mesh rendering, but I'd like access to it in the UI:

#

for UI things like this:

#

some code:

    public class InterfaceManager : BetterMonoBehaviour // a DDOL singleton
    {
        private readonly Dictionary<EntityBehaviour, EntityRenderer> _renderers = new();
        private void OnEnable() => GameManager.NewGameStarted += OnNewGameStarted;
        private void OnDisable() => GameManager.NewGameStarted -= OnNewGameStarted;
        private void OnNewGameStarted()
        {
            _renderers.Clear();
            UnitContainer.DestroyAllChildren();

            CommanderRenderer commander = Instantiate(CommanderPrefab, UnitContainer.transform);
            commander.Initialize(GameManager.Commander);
            _renderers.Add(GameManager.Commander, commander);
            ... etc for all units ...
        }
    }

.. elsewhere in the UI ..

PortraitImage.sprite = InterfaceManager.Renderers[_commanderBehaviour].PortraitImage;
#

then I just pass around these references to the behaviour and the UI can just listen to events and "get the truth" directly from the behaviour (sorta like a ReactiveProperty)

#

Just not sure what's gonna happen if I eventually start unloading scenes or something with dangling references to GOs in a DDOL

midnight violet
#

And with addressables you could even split the sprites and the unit and just try to use the reference ids to load the sprites separately

unkempt mesa
#

anyone know what's the currently best CI/CD solution for unity android / IOS? Except Unity Cloud Build

stuck plinth
#

if you need the portrait image and have a reference to the prefab, why not fetch it from the prefab instead of from an instance which may or may not have been destroyed?

idle pilot
#

anyone knows why my OcclusionGroup does not work?

Left pic occlusion turned on in the SceneView camera, right view Occlusion turned off in the SceneView.

Both have the main camera's occlusion culling enabled.

#

Frustum culling works, the spheres show up red when not visible in the camera frustum

#

Again, this is using the CullingGroup api, it seems as if it does not take into account the baked occlusion, which it should

#

any help appreciated

idle pilot
#

for context this is a box in which I have the bounding spheres

#

The occlusion is baked and is working, visible by the bushes amd such disappearing in the first image

idle pilot
#

nvm

#

it works

#

disregard all of what I said

#

I sabotaged myself by creating a render pass in which occlusion culling is turned off

#

And since that pass is rendered last the last result of the check will be true

gleaming onyx
#

exists a way to check if player is clicking when pointerenter?

soft moon
misty glade
#

as it stands, it "works" nicely, I just don't know what problems I might have down the line if I'm restarting levels, or adding/removing instances .. I might have an issue with race conditions within one tick if I delete items (and the UI tries to draw a frame with items that have been Destroyed but the C# reference is still valid)

#

all the name/color/profile picture is stuffed in the prefab and managed through a singleton

#

just... not sure if I like the approach [yet]

#

new question: I have a scene with some UI and some 3d stuff, and I want to have a method that determines if the current mouse position will "hit" some raycast-blocking UI object (UGUI). Any ideas? Like, I don't want my mouseover and clicking functionality in the world to happen when the user is interacting with the UI

#

(best I can come up with is creating a component that has a single method - IsMouseOver - calculating the mouse position and seeing if it's within the recttransform and iterating every single one of these components)

soft moon
misty glade
#

But I still need to iterate all these objects, yeah? Like I can't get some sort of "raycast" array of UGUI objects..?

#

I just don't have any sort of master UI manager - like every dialog sorta takes care of itself

#

but I'm doing 3d mouse position .. like, without checking into whether or not the mouse is over a UGUI object somewhere

soft moon
misty glade
#

cool, will try this out.. should be what I was looking for, thanks

echo zinc
#

Is anyone here familiar with inverse kinematics? I've written an IK script, and I've been trying to set rotation restrictions, but I've been having difficulties.

somber swift
echo zinc
#

I'm using the fabrik algorithm yeah, and I'm talking about rotation restrictions between nodes, as marked by the yellow lines

somber swift
echo zinc
#

Here, I hope this explains it a bit better. It means that the yellow lines of node 3 restricts node 4's freedom to rotate, and the yellow line of node 2 restricts node 3, and so on

#

the yellow line represents the max angle that the next node can bend to

#

actually, now that I think about it, I don't think my idea of restricting rotations was good

somber swift
#

I see now, I can’t think of a way to achiece that on top of my head though. FABRIK is very well known and researched algorithm so chances are there is paper somewhere descriping just that. Remember seeing a paper about different FABRIK constraints somewhere but don’t know if it covered that exactly

echo zinc
#

I was trying to do it like in this video, but I don't really understand the math behind it, and the code was written in godot, while I'm using c#

somber swift
# echo zinc https://www.youtube.com/watch?v=lJCeHXXPf5w

Of course someone has made yt video on it already. Seems to be bit math heavy solution though which isn’t too surprising. Never used GDScript but looks a lot like python. With the help of some python knowledge and the godot documentation, it shouldn’t be super difficult to translate that to C#

echo zinc
#

would you recommend using unity's in-built animation and rigging system for procedural animation, or doing it directly from scripts?

somber swift
#

I have very little knowledge about unitys animation and rigging stuff but I assume procedural animations rely quite heavily on custom code

echo zinc
#

The only reason I even wanted to restrict the rotation of the joints was because I hoped it would solve this problem

#

whenever the target moves closer to the root position, either of the middle joints bends first, but it seems that the order of what joint bends up first is random

#

idk why, but I thought restricting rotations might fix that

#

ideally, I would want the middle joint closest to the target to bend up first

sly grove
echo zinc
sly grove
#

So you're using DitzelGames' FastIK package?

echo zinc
#

yes, I followed along with the code used in the video

sly grove
#

Does it help if you move the pole object towards one of the sides?

echo zinc
#

last time I tried it didn't help, but I'll upload another clip of me trying again

sly grove
#

Although honestly I'm not sure how to specify a preference of bones to move first

mild patio
#

Hey, y'all, stupid question I'm trying to answer because the profiler won't give me a complete call stack:
Does ScreenCapture.CaptureScreenshotToRenderTexture not, in fact, Capture a Shot of what is already on Screen, but instead cause the entire render pipeline to be invoked a second time?

#

Because it really seems like it causes the entire render pipeline to be invoked a second time (i am now instead at least 90% sure this is not happening

#

But I can't verify it for sure, because it's out of the scope of the callstack Unity gives me in the profiler
And it's not documented anywhere

coral citrus
#

heya, I was wondering if someone could help me figure out why my marching cubes has this stepped look despite it being interpolated correctly
the red texture is the texture I'm using to determine density, and it's of decent resolution + antialiased, so it shouldn't be just the texture quality
doing a simple distance to a point check generates a perfectly smooth sphere, so I know it can work

this is the code I'm using to pull from this texture

exotic wraith
#

I would like to imitate an ECS architecture, instead of Unity's EC design where Component's have both data and update() functions that modify it's data. I want Components to strictly have data, and then define Systems that will operate over all entities with the relevant component type each frame, with the update() function defined here in the system.

I don't want to use a framework like Entitas. What is the most native way for me to do this?

(To clarify, I am not talking about Unity's built in "ECS/DOTS/JOBS" thing. I don't care about performance optimization. Just want a more flexible way of organizing code)

Could I make empty game objects to represent Systems, and attach a System script, and have it's update() be to grab all entities and update them?

tall ferry
#

<@&502884371011731486> job posting spam
linked the collab message here already too
#💻┃code-beginner message

and i guess now they wanna DM me too..

austere jewel
#

!kick 692295716575510528 don't return if you intend to rule-break by spamming the server. We have no job-posting channel.

thorn flintBOT
#

dynoSuccess muratslmn was kicked.

exotic wraith
untold moth
# exotic wraith are there other ways?

Many different ways. You could make your systems plain C# classes or derived classes of a base abstract ECSSystem class, instead of components for example.

exotic wraith
untold moth
#

But is there any issue with the approach that you mentioned?

exotic wraith
plush hare
untold moth
exotic wraith
#

i don't know where the entry of the program is

untold moth
plush hare
#

that'll plug you into Update().

#

theres documentation somewhere for it

#

you can have a static method somewhere that automatically gets called when the game starts, with that code

#

and you'll have your own custom game ticker

untold moth
#

Yeah, that's an option as well I guess.

#

Though it might be a bit confusing if you introduce new devs to the project.

plush hare
#

I haven't read much of the conversation. All I heard is that you wanted to call the update loop in a custom way

untold moth
#

It's intuitively clear if you see systems/managers components/objects in a scene. It's more obscure if you hook to the loop somewhere in code secretly.

somber swift
# echo zinc

I think the way DizelGames implement the pole logic is just nondeterministic. The way I implemented my IK was to start by placing the bones in a straight line towards the pole (you can also do a line from the target to the pole which might what you want there, see the second image below) and then do the forwards and backwards passes as usual without any additional constraints. That way the bones will stay in the plane containing the pole, starting point and the target point as they should. This solution might not generate nice arcs for large amount of bones and it also does not accumulate over the frames so it may require couple extra iterations to get close enough to the target but at least for me that worked nicely. Basically it allows more control over the first or last bones (according to whichever way you choose to place the bones at start) rotation with the pole.

#

So you could also place the bones like this at the start to get the bone closest to the target pointing to the pole

empty tangle
#

Hey guys i just published my first long term project and now i want to take a few months off to learn and improve my unity skills. Are there any advanced tutorials/ resources you would reccomend using? Also, what unity features should i practise (ex shader graph). I am very good at the basics (basically built a whole game on what a 10 hour unity course would teach you), but now i want to learn more advanced techniques for bigger projects moving forward

slow jay
#

I'm learning how to optimize my Unity projects so that the Editor runs faster

#

Do you guys know of any resources about typical times it takes to run different methods

#

e.g my FinalizedReload takes 2000ms when I modify a script, and I'm wondering if that's too long or not

#

one thing that stands out inside FinalizeReload is that InitializeOnLoad InputSystem takes 150ms, does that sound like too long or is it common?

#

yes I know this topic is complicated and depends so much on the specific project, but I'd appreciate any resources on this

lucid crane
unique quail
#

I want to turn a flat 2d tilemap into a mesh made of cubes. I'm worried about some issues:
If the tilemap has islands(group of tiles that are isolated from other tiles in all directions), does that cause issues in the mesh? It would have holes inside and
I need to dynamically generate the collider. Except the game uses 2d colliders. Mesh colider is a no-go. what's the next best option? Polygon collider? Maintaining a fake tilemap just for colliders?
Also the tilemap/mesh can be edited in runtime. The player can delete/move tiles around. I'd need to split the mesh

The other option is to just use cubes/quads. I'm taking about several 20x20 tilemaps. Probably around 400x3 = 1200 cubes. Is that a perf concern?

slow jay
#

Is it possible to disable domain reload when creating a new script?

compact ingot
slow jay
compact ingot
#

yes

slow jay
#

it doesn't work

#

if i create a new C# script, it still relodas the domain

compact ingot
#

it works if you make the script in your IDE

slow jay
#

After optimizing, I'm getting a ~4 second domain reload. I heard from someone that that is often as good as it gets.

#

thoughts?

#

on a brand new project I'm getting ~2500ms for the domain reload frame

compact ingot
#

you should worry when you regularly get more than 30 seconds.

wispy stump
#

it will not cause a second rendering

mild patio
#

I appreciate the double-check. The CPU pressure doubling the clock time of the SRP function must be coming from elsewhere.

#

Thanks!

mild patio
#

someone is lying to me

#

returns, eventually: [Sample Range: -3.221226 2.842275]

#

how is this possible

#

How does OnAudioFilterRead return values outside the -1 to 1 range?

#

Does Unity not clip it?

mild patio
#

It must be some other audio effect. I just built a soft clipper.

modern oar
#

does anyone have a tip or something reference i could read? I want this kind of floor map. I want to use Prim Algorithm however if there are much more simpler approach please I would love to know.

sly grove
modern oar
#

I been suggested that prim can have minimal deadends unlike depth first but for now my main goal is to create a node map for my floor plan like this then generate randomly each level.

tropic vigil
# modern oar I been suggested that prim can have minimal deadends unlike depth first but for ...

Prim's algorithm is supposed to consider connection weights. I have a hard time coming up with reasons to use weighted connections during the map generation. I think such algorithms are meant to be used for processing already existing data rather than generating data. I suppose in your case you could assume that diagonal connections have approximately 1.4 times bigger weight (since they're longer and it takes more time to move from one node to another one).

I think your approach is a bit reversed in general. I feel like the right approach is to generate optimized data rather than optimizing generated data. E.g. instead of creating a connection to the nearest node, you could simply generate a node in the nearest space available.

pastel mulch
#

does anybody knows how NetworkLists work? Im using Netcode and I want the client to be able to change a list

tall ferry
cold canyon
#

Hello everyoneUnityChanThumbsUp . Does anyone know how to recreate this effect in Unity? When you pick up the ring it moves from the WORLD (meaning it can intersect with the player) to the position in the camera view. I was able to rotate it correctly, but I don't understand how to move it

tall ferry
cold canyon
#

also I tried WorldToScreenPoint, but it sends the object somewhere in the sky

sweet niche
#

@cold canyon this looks more like the UI ring center is converted from UI space to world space on the camera's near clipping plane, then this position is offset by camera forward multiplied by some small constant(to make the 3d rings not clip through the near plane). Then a 3d ring is animated to lerp to this target position(with the target position updated every frame so it always ends up in the same place as the UI ring icon visually even if you move the camera/character).

misty glade
# sweet niche <@922043507894534164> this looks more like the UI ring center is converted from ...

probably don't want to do it that way since it'll get bigger/smaller if you're moving fast during the animation.. I feel like the best way is gonna be to put this in another layer entirely and then just move it from point A to point B - someplace that intersects a plane that's normalized to the camera and has a raycast from the player and the UI object (draw a ray from camera to player, see where it intersects your "coin plane", and draw another ray from the camera to the UI element and see where THAT intersects the coin plane)

#

(and keep the moving coin parented to the camera while changing the local position)

#

or just do it entirely in UI

hollow pivot
trail spoke
#

Is unity 6 clr ready? I have unity6 but not updated tho can anyone confirm?

hollow pivot
cold canyon
cold canyon
light topaz
#

Hi, I am making a unity card game 1v1 , I have server that handle all the things , but I don’t know how to handle the game itself . When the player finds a match I don’t want the server to handle the game It’s too much for the server I think , i think the server needs to redirect to game room server that handle the match itself how can i make it? Any tips?

dreamy basin
#

Pls if am publishing a game on steam for the first time using unity engine do I need to pay

dreamy basin
#

Ahhh

#

How much

upbeat path
#

steam is $100

dreamy basin
#

Mission fail

upbeat path
#

you do know google exists?

dreamy basin
#

No

upbeat path
#

well, next time you have simple to answer questions, use it

dreamy basin
#

Ohh what is google

#

Ohh sorry search engine

upbeat path
#

which planet are you from again?

dreamy basin
#

I can't remember the name

#

But I will google it

upbeat path
#

good plan, try google earth

dreamy basin
#

Ohh there are type of google

#

Can you tell me all of there name

upbeat path
#

no, google them

dreamy basin
#

Which google will i use

upbeat path
#

any one of them, they all interlink

dreamy basin
#

Back to business
Pls do Godot take charges for publishing on steam
Sorry to ask but I really want to know from those that have the experience

upbeat path
#

you are asking about Godot on a Unity server?
also this is a code channel please use the correct channel for Unity related questions

dreamy basin
#

Why are always angry

#

It is a question

#

And should have said it in a polite way

#

Anyway let me move to godot

frozen imp
sly grove
tired fog
#

How should I go to check if a Ray is inside a view frustrum?

#

I was thinking about getting the frustrum planes and simply doing raycast to them but it doesn't seem to be working as expected

lament salmon
tired fog
#

Mmmm sounds interesting

#

Altough Im not sure how I would go about implementing it

lament salmon
#

So you need the corners of the near plane and the far plane

#

Then you can do ray-triangle intersection for each of the quads connecting those corners

tired fog
#

Actually, just saw that cam has a CalculateFrustrumCorners method

lament salmon
#

Ahh yeah that should do it

#

I was looking at GeometryUtility, which only has public static Plane[] CalculateFrustumPlanes(Camera camera);

#

Just noticed that unity has built in MathUtils.IntersectRayTriangle but of course it's editor only 🤦‍♂️

tired fog
#

lol

lament salmon
#

Though you can find a ray-triangle intersection implementation online

tired fog
#

I can also copyu paste unity implementation XD

#
    public static object IntersectRayTriangle(Ray ray, Vector3 v0, Vector3 v1, Vector3 v2, bool bidirectional)
    {
        Vector3 lhs = v1 - v0;
        Vector3 vector = v2 - v0;
        Vector3 vector2 = Vector3.Cross(lhs, vector);
        float num = Vector3.Dot(-ray.direction, vector2);
        if (num <= 0f)
        {
            return null;
        }

        Vector3 vector3 = ray.origin - v0;
        float num2 = Vector3.Dot(vector3, vector2);
        if (num2 < 0f && !bidirectional)
        {
            return null;
        }

        Vector3 rhs = Vector3.Cross(-ray.direction, vector3);
        float num3 = Vector3.Dot(vector, rhs);
        if (num3 < 0f || num3 > num)
        {
            return null;
        }

        float num4 = 0f - Vector3.Dot(lhs, rhs);
        if (num4 < 0f || num3 + num4 > num)
        {
            return null;
        }

        float num5 = 1f / num;
        num2 *= num5;
        num3 *= num5;
        num4 *= num5;
        float x = 1f - num3 - num4;
        RaycastHit raycastHit = default(RaycastHit);
        raycastHit.point = ray.origin + num2 * ray.direction;
        raycastHit.distance = num2;
        raycastHit.barycentricCoordinate = new Vector3(x, num3, num4);
        raycastHit.normal = Vector3.Normalize(vector2);
        return raycastHit;
    }
lament salmon
#

What do you need this for btw?

tired fog
#

I'm trying to solve the issue of shadows disappering when doing frustrum culling with GPU Instancing

#

so i m trying to make another method to perform frustrum culling for shadows taking the sun direction into account

charred drum
#

Quick question, what is this:
bool ? int : int
This came up with autocorrect, is it where if the boolean is true or false, it uses the left/right number?

charred drum
#

Oh thank you thank you

shy nebula
#

if true, then the first int is used. if false, then the second one is used

charred drum
#

Thank you Ash, I learned something new today

#

I hope I retain it!

untold moth
charred drum
#

Oh, sorry, never heard of this before to be honest!

untold moth
#

Anything syntax related would be a beginner question.

patent bear
#

I'm running into an issue where I get a compiler error on build related to a reference not getting included when compiling an assembly from a custom package. Looking at the editor log, it's not included a managed dll reference set up on the package assembly definition. When I try to force it's inclusion using a csc.rsp, it throws an explicit error stating that the dll referenced doesn't meet the conditions to be included in the build, though that looks incorrect when inspecting the dll settings.

I've used this package on several other projects, including one in the same version of the editor, without this issue. It makes me think something is incorrect with the setup but everything is set to their usual defaults. I've tried deleting the Bee folder as well to clear out the build cache with no affect on the result.

More details in thread.

mellow plinth
#

Any idea what could be causing this error?:

EXCEPTION_ACCESS_VIOLATION_READ

Thread: AssetGarbageCollector
[ 0 ] MarkDependencies(struct GarbageCollectorThreadState &,unsigned int)
[ 1 ] MarkAllDependencies
[ 2 ] public: static AGCThread::RunThread(void *)
[ 3 ] private: static Thread::RunThreadWrapper(void *)
[ 4 ] public: virtual DualThreadAllocator<class DynamicHeapAllocator>::Allocate(unsigned __int64,int)
[ 5 ] BaseThreadInitThunk
[ 6 ] RtlUserThreadStart
[ 7 ] UnhandledExceptionFilter
muted karma
upbeat path
mellow plinth
# upbeat path At a guess you have something in Managed Memory pointing to something in Unmanag...

We use Burst + Jobs and some unsafe code, but no ECS.
But I'm the only programmer in our project which uses that things and I think that is not the source of the bug. I think that because we are getting a lot of EXCEPTION_ACCESS_VIOLATION_READ and the majority of them has in their callstacks graphic stuffs such as Shader, GpyProgramParameters, GfxDeviceWorker, etc, and I don't code anything related to visuals 🤔

upbeat path
mellow plinth
#

Oh, then I guess there is more than one bug which causes the AVE

upbeat path
#

most likely to be your Burst/Jobs stuff

mellow plinth
#

Ok

upbeat path
#

I must say I am not a fan of Unsafe Code and Unity's implementation of Burst/Jobs. It defeats the whole point of C# and managed memory, you may just as well write everything in C++ and have done with it

mellow plinth
upbeat path
slim fulcrum
#

If I'm outputting a camera to a raw image for a splitscreen setup does anyone know how I'd display the UI onto that raw Image? Currently It's just displaying the UI to the whole display.

#

I want to hide it from the full display and show it on the respective player's RawImage.

#

For example, this "Turbo D Speedway" should show up on each screen instead.

#

Any input is appreciated.

glacial obsidian
#

Hey, so I'm not like, looking to make this way faster by using a shader. The resolution will be small so this is going to fast enough for the one time this happens. But I have this code that copies and creates a new texture with a hole in it. This hole is defined by some points.


    private void SlicePumpkin() {
        _col = PolygonColliderUtil.CutHoleInPolygon(_col, _vertices);
        Texture2D copy = new Texture2D(_sprite.texture.width, _sprite.texture.height, TextureFormat.ARGB32, false);
        copy.SetPixels32(_sprite.texture.GetPixels32());
        copy.name = "GeneratedTexture";
        Vector2 size = _sprite.bounds.size;
        Vector2 pivot = _sprite.pivot;
        Vector3 scale = transform.localScale;
        Rect rect = _sprite.rect;
        for (int y = 0; y < copy.height; y++) {
            for (int x = 0; x < copy.width; x++) {
                Vector2 worldPos = CalculateWorldPosition(x, y, copy, pivot, size, scale);
                if (!_col.OverlapPoint(worldPos)) {
                    copy.SetPixel(x, y, new(0,0,0,0));
                }
            }
        }
        copy.Apply();
        Sprite newSprite = Sprite.Create(copy, rect, pivot, 100, 1, SpriteMeshType.Tight);
        newSprite.name = "GeneratedSprite";
        _sprite = newSprite;
        _renderer.sprite = _sprite;
    }

And the texture actually generates correctly according to the inspector preview!

But for whatever reason, its just not visible ingame. I can't resolve why. I thought maybe the normals were backwards, but its not visible from any direction in 3D.

Some ideas would help greatly. This is for a tiny like 5 minute thing in a jam project, so its ultimately like, not a speed thing so I'd rather not rework the whole solution if not actually necessary.

lament salmon
untold moth
glacial obsidian
#

well it actually does show

#

interestingly enough with a lot of huge visual bugs

#

but its there

#

looks nothing like the preview lol

#

Nvm fixed the visual bugs, it looks fine as an image

#

wonder why that is

lament salmon
#

What was the issue?

#

Image works but SpriteRenderer didnt?

#

(Im assuming that _renderer was a SpriteRenderer)

glacial obsidian
#

Yeah, _renderer was orignally a spriterenderer.

But upon just swapping to an image (and adding it to the canvas and such) it works as expected

#

guessing im missing some config in SpriteRenderer that makes it not invisible

slim fulcrum
lean flare
#

i have a script "Button". i have a manager "ButtonDataManager":

using _Scripts.ScriptableObjects.Scripts;
using UnityEngine;

namespace _Scripts.UI
{
    public class ButtonDataManager : MonoBehaviour
    {
        [Serializable]
        public class ButtonGroup
        {
            public string groupName;
            public ButtonDataOverride bdo;
            public ButtonData bd;
            public Button[] buttons;
        }
        
        [SerializeField]
        public ButtonGroup[] buttonGroups;
    }
}```
the manager displays arrays of Button scripts. works fine. but is there a way to see and edit individual Button scipt instances from this manager in unity inspector?
Thank you in advance!
lean flare
#

was hoping i could avoid that. thanks for calrification

sly grove
lean flare
#

i will give odin a shot

graceful pumice
#

I'm finally attempting momentum physics into a from-scratch 3D sonic engine i'm creating so that moving downhill and uphill feels more natural. i've got the variables in and I'm already able to check for the slopes angle and whether Sonic is moving uphill or downhill (for the most part the upHill check is kinda inconsistent) but I'm not sure where to go next. i thought it would be something like:

if (slopeRotation != 0 && isGoingUphill)
{
     currentSpeed -= slopeRotation * slopeDrag;
} 
else if(slopeRotation != 0 && !isGoingUphill)
{
    currentSpeed += slopeRotation * slopeAssistance;
}

Buuuuuuut that isn't working at all so I'm looking for a better solution

Here's my movement script: https://pastecode.io/s/7s3zhz1m

graceful pumice
#

sonic-style slope physics so when Sonic is running on flat ground, gravity does not directly affect his speed and when Sonic runs up or down a slope, the angle of the ground influences how gravity affects him, causing him to slow down or speed up.

sly grove
#

what is slopeRotation though

graceful pumice
#

Let's me get the angle of the slope to determine how much sonic should accelerate or decelerate

sly grove
#

slopeRotation = Vector3.Angle(Vector3.up, groundInfo.normal); < this is definitely not enough information

#

Yeah but an unsigned angle is not enough information

#

it would be better to use the surface normal directly

graceful pumice
#

I mean I did have this piece of code in another script but I was just using it for debugging cuz something was off so I wanted to check the actual player's angle:

void CalculateUpDownAngle()
    {
        Vector3 forward = transform.forward;
        Vector3 projectedForward = Vector3.ProjectOnPlane(forward, Vector3.up).normalized;


        float cosAngle = Vector3.Dot(projectedForward, forward.normalized);


        float angleInDegrees = Mathf.Acos(cosAngle) * Mathf.Rad2Deg;


        float sign = forward.y > 0 ? 1 : -1;


        upDownAngle = angleInDegrees * sign;
    }
sly grove
#

more or less the dot product of the gravity vector and the surface normal vector will tell you how much acceleration you will get

#

or 1 - that dot product

graceful pumice
#

oh alright, so would that be something like:

accelerationValue = Vector3.dot(gravity, groundInfo.normal)

#

my code for gravity is literally just:
RB.velocity -= Vector3.up * gravity * Time.deltaTime;

sly grove
graceful pumice
#

it's a kinematic rigidbody so yeah it's home-grown

sly grove
#

oh unless it's a 2d rigidbody

graceful pumice
#

wait i think i didn't say that right lol

#

one sec

#

Here's how the player is set up in the scene, the rigidbody settings, and the player physics material settings

pure berry
#

Hello, I am currently coding a state machine based on this tutorial : https://youtu.be/kV06GiJgFhc

Depending on the state my character is in, the logic applied will be different.
I precize that to move my character, I use a RigidBody to which I apply a force.
Each state has an EnterState(), ExitState() and UpdateState() method. The first is executed at the frame when you enter the state in question, the second when you leave it, and the last for the duration of the state.

I have the SlidingState, which is activated when the slide button is pressed. In this state, my character moves momentarily faster as I apply greater force with the AddForce method. I'd like to add a SlideJumpState. This would be activated when the character is in the SlidingState and makes a jump.

But the problem I'm having is that, as I'm moving from one state to another, the extra force applied when in the SlidingState will no longer apply by the time I move to the SlideJumpState.
So my question is this: How can I ensure that the force of the slide applied in the SlidingState continues to apply during the transition to the SlideJumpState and during the SlideJumpState ?

I've tried using a hierarchical state machine but I can't get it to work. I've also thought about moving the slide force application logic to a more global scale but I think that would force me to move all my sliding code. I've also tried inheritance but haven't succeeded.

If anyone has an idea to help me solve this problem, I'd love to hear from you.
Thank you for reading all that.

Learn how to program a Hierarchical State Machine in Unity with this new video break down and tutorial!

Want to learn how to program state machines in Unity? This video will help get you there! Today we'll go over important concepts of the State Pattern and refactor our overly-complex code into a clean hierarchical state machine! With a detaile...

▶ Play video
thorn flintBOT
dusty wigeon
#

I believe that you want to pass data from one state to another.

#

If you show your code we could suggest a way to do that that is coherant with what you have.

pure berry
#

Hello, thank you for taking the time to answer. I'll show you the code right now but it's very long 😅

#

Here is the code :
StateMachine : https://gdl.space/onofebalox.cs
SlidingState : https://gdl.space/xiqujuviyu.cs
SlideJumpState : https://gdl.space/ulexitudey.cs
WalkingState : https://gdl.space/neliqejixi.cs

The code for SlideJump is absolutely not finished and doesn't make any sense right now. I was just trying things.
I added the WalkingState for you to understand what an almost finished state look like.
And watching this video will help you understant the code structure that I follow : https://www.youtube.com/watch?v=kV06GiJgFhc

Thank you for taking your time

Learn how to program a Hierarchical State Machine in Unity with this new video break down and tutorial!

Want to learn how to program state machines in Unity? This video will help get you there! Today we'll go over important concepts of the State Pattern and refactor our overly-complex code into a clean hierarchical state machine! With a detaile...

▶ Play video
dusty wigeon
# pure berry Here is the code : StateMachine : https://gdl.space/onofebalox.cs SlidingState :...

So, I believe the best way to get information accross different state would be add parameter to your factory function. In your case that would be _factoryG.SlideJump(). Base on the code of the video, you would then be able to pass the parameter on the constructor of the state.

private float _slidingForce;

public SlideJumpState(StateMachine currentContext, StateFactory stateFactory, float slidingForce) : base (currentContext, stateFactory)
    {
       _slidingForce = slidingForce;
    }
...

public override void FixedUpdateState()
{
   ... Handle Sliding Force
}

#

It is also worth mentioning that if you want to slide during the start of the jump animation, you might consider making either the sliding jump state a child of sliding state OR externalize the functions Sliding(), SlidingMovement() and SlidingMySpeedControl() such that you can call them from your jump sliding state.

#

There is also the possiblity to add the behaviour directly in your SlidingState which instead of directly switching state, it change after a given trigger (Time or AnimationEvent).

#

Finally, I would add that SlidingJumpState seem a bit overlay specific, given that I am not sure to what extends SlidingJumpState and JumpState would differ. Maybe simply adding a parameter (SlidingVelocity) in the JumpState would be enough. Obviously, it depends on the game as I can easily see how you might want to have different behavior jumping depending (Keep following the slope) on if you slide or not.

pure berry
dusty wigeon
#

There is no moment where you are no longer in state.

pure berry
pure berry
pure berry
#

Thank you very much for your help, @dusty wigeon . I'm going to try and implement what you've just suggested. 😁

urban warren
#

I have a struct with generics, and one of the constrained generics is a interface that takes generics. Is there some way I can 'reuse' the generic arguments from the defined interface that is passed in?

interface ICondition<TComp1, TComp2> {}

struct CheckAnimals: ICondition<Cat, Dog> {}

struct Group<TCondition, TComp1, TComp2>
  where TCondition : ICondition<TComp1, TComp2>

To define, I gotta do new Group<CheckAnimals, Cat, Dog>();, which looks bad, and adds a lot of boilerplate and mental overhead. (if is relevent, this is for jobs in ECS)

scenic forge
#

I don't think so. Are TComp1 and TComp2 used by Group<>, or they are unused and only there for ICondition<>?

regal blaze
#

what does time.deltatime do?

urban warren
austere jewel
thorn flintBOT
austere jewel
regal blaze
#

sorry

scenic forge
hallow aurora
#

Is there a "slice" type in C# either built in or open source that doesn't allocate memory? Or are there any tricks to avoid IEnumerator<T> allocating when the concrete type is an array or list?

#

I'm trying to write a generic GetClosestTarget<T> function but if I pass in an IEnumerable<T>, calling foreach will allocate on GetEnumerator()

sly grove
hallow aurora
#

I have a function that takes an IEnumerator<T> instead of a concrete Array or List

flint sage
#

Span?

hallow aurora
#

And that does seem to be allocating, even if the concrete type is one of those

#

Does Span<T> allocate if I call GetEnumerator?

flint sage
#

Idk

#

You're doing something weird

sly grove
#

Have you considered IReadonlyList<T> instead?

hallow aurora
#

Let me test it then

sly grove
#

and not using foreach

hallow aurora
#

I can try that

hallow aurora
sly grove
#

C# has span

hallow aurora
#

Right, let me try that

#

:/

sly grove
#

I say just use IReadOnlyList<T>

#

and use for instead of foreach

hallow aurora
#

Ok, let me try

#

Cause this seems to be a dead end

#

But what if it's an array?

sly grove
#

it works

hallow aurora
#

Great, without copying?

sly grove
#

array implements that interface

hallow aurora
#

Oh great

sly grove
#

why would it copy

flint sage
hallow aurora
flint sage
#

Ah sorry got confused then 😅

hallow aurora
#

No worries

#

I don't think i can use IReadOnlyList because it provides a window into the whole array, I need the equivalent to doing a Take(n) without allocating, all examples I found suggest to do a Take then call ToList() which defeats the purpose

#

ArraySegment is the closest thing I've found to what I want, but then it doesn't work for lists

#

I guess I should just limit myself to working with fixed sized arrays :/

sly grove
#

what's wrong with seeing the whole array

hallow aurora
#

Because it's a generic function that should return a window into the array so I don' thave to pass around the collection + a length

#

IEnumerator works but it allocates

flint sage
#

Just create a struct which contains the list and the length?

sly grove
#

YOu could use System.Range no?

#

var slice1 = array[2..^3];

hallow aurora
#

C# has no syntactic way to access "ranges" or "slices" of collections. Usually users are forced to implement complex structures to filter/operate on slices of memory, or resort to LINQ methods like list.Skip(5).Take(2). With the addition of System.Span<T> and other similar types, it becomes more important to have this kind of operation supported on a deeper level in the language/runtime, and have the interface unified.

sly grove
#

keep reading

hallow aurora
#

Yeah, this looks promising

#

Oh this is interesting

#

I didn't know C# added this... it's been a while...

carmine lion
#

Dudes that develops his game, please add udpate

hallow aurora
#

why

hallow aurora
flint sage
#

IReadOnlyList should do that no? Your struct will just expose the subsection so you don't have to deal with being able to see the whole collection

hallow aurora
#

Yes the issue is getting an IReadOnlyList

flint sage
# hallow aurora

A bunch of these probably have to do with that the runtime is still net fx

hallow aurora
#

Let me read the docs because other than calling Take() I didn't find a way to specify a range

flint sage
hallow aurora
#

ArraySegment<T> is the closest thing I've found

hallow aurora
sly grove
#

I mean...

public struct MyRange<T> : IEnumerable<T> {
  IReadonlyList<T> collection;
  int start;
  int length;

  public IEnumerator<T> GetEnumerator {
    return new MyRangeEnumerator(this);
  }
}

public struct MyRangeEnumerator<T> : IEnumerator<T> {
  public MyRange<T> range;
  int i;
  T current = default;

  public T Current => current;
  public bool MoveNext() {
    i += 1;
    bool toReturn = i < range.Length;
    if (toReturn)
      current = range.collection[i + range.start];
    else
      current = default;
    return toReturn;
  }
}```
#

Something like this?

flint sage
#

Or


public readonly struct SpanPolyfill<T>
{
    public readonly IList<T> Buf;
    public readonly int              Offset;
    public readonly int              Length;

    public SpanPolyfill(IList<T> buf, int offset, int length)
    {
        Buf    = buf;
        Offset = offset;
        Length = length;
    }

    public T this[int index]
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Buf[Offset + index]; }

        [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Buf[Offset + index] = value; }
    }
}
#

(Should do more validation of course but should work)

hallow aurora
#

I like that implementation

#

Did you just whip that up?

flint sage
#

I didn't bother implementing IEnumerator but should work as Praetor posted

hallow aurora
#

Or did you have it somewhere?

sly grove
#

I think we both whipped them up lol

hallow aurora
#

Nice

flint sage
#

Yeah

#

We used to have something similar but deleted it since

hallow aurora
#

Right so ReadOnlySpan is not feasible because I can't convert a List to it apparently, not without copying

#

So now let me try SpanPolyfill

#

I'll grab lunch and finish implementing, y'all seem to know what you're doing so I really appreciate the help, maybe once I have it done y'all can suggest further enhancements

#

Thank you so much!

hallow aurora
#
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

public readonly struct ListSlice<T>
{
    public readonly IList<T> Buf;
    public readonly int Offset;
    public readonly int Length;

    public ListSlice(IList<T> buf)
    {
        Buf    = buf;
        Offset = 0;
        Length = buf.Count;
    }

    public ListSlice(IList<T> buf, int length)
    {
        Buf    = buf;
        Offset = 0;
        Length = length;
    }

    public ListSlice(IList<T> buf, int offset, int length)
    {
        Buf    = buf;
        Offset = offset;
        Length = length;
    }

    public T this[int index]
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)] get => Buf[Offset + index];
        [MethodImpl(MethodImplOptions.AggressiveInlining)] set => Buf[Offset + index] = value;
    }

    public ListSlice<T>.Enumerator GetEnumerator() { return new ListSlice<T>.Enumerator(this); }

    public struct Enumerator : IEnumerator<T>
    {
        private ListSlice<T> slice;
        private int idx;
        private T current;
        public T Current => current;
        object IEnumerator.Current => Current;

        public Enumerator(ListSlice<T> slice)
        {
            this.slice = slice;
            idx = -1;
            current = default;
        }

        public bool MoveNext()
        {
            idx += 1;
            bool inRange = idx < slice.Length;
            if (inRange)
            {
                current = slice.Buf[slice.Offset + idx];
            }
            else
            {
                current = default;
            }
            return inRange;
        }

        void IEnumerator.Reset() { idx = -1; }
        public void Dispose() {}
    }
}
#

This is what I came up with

#

Sort of merged both implementations, going to confirm there are not allocations now

#

Amazing, I'm allocation free

#

Thanks a lot everyone!

#

I can add some implicit conversions now

#

So I thought this would work

    public static implicit operator ListSlice<T>(List<T> list) => new ListSlice<T>(list);
    public static implicit operator ListSlice<T>(T[] arr) => new ListSlice<T>(arr);
#

But apparently not

#

The point was to avoid this;

            var buildings = new ListSlice<Building>(Game.State.buildings);
            var target = GetClosestActiveEnemy(buildings, position, soldier.faction);
#

I could add an extension method, but also though I could just have it cast implicitly when passing it in as an argument

#

I guess this is better anyway...

public static class ListExtensions
{
    public static ListSlice<T> AsSlice<T>(this List<T> list) => new ListSlice<T>(list);
    public static ListSlice<T> AsSlice<T>(this List<T> list, int length) => new ListSlice<T>(list, length);
    public static ListSlice<T> AsSlice<T>(this List<T> list, int offset, int length) => new ListSlice<T>(list, offset, length);
}

public static class ArrayExtensions
{
    public static ListSlice<T> AsSlice<T>(this T[] arr) => new ListSlice<T>(arr);
    public static ListSlice<T> AsSlice<T>(this T[] arr, int length) => new ListSlice<T>(arr, length);
    public static ListSlice<T> AsSlice<T>(this T[] arr, int offset, int length) => new ListSlice<T>(arr, offset, length);
}

#

It's called ListSlice, but I guess I could call it Slice, doubt it's going to collide

hallow aurora
#

Oh

#

I misread the error

flint sage
#

What's the actual error?

hallow aurora
#

/home/joe/Development/Game/Gameplay/Combat.cs(343,26): error CS0411: The type arguments for method 'Combat.GetClosestActive<T>(ListSlice<T>, Vector3, Faction)' cannot be inferred from the usage. Try specifying the type arguments explicitly

#

I just have to pass in a type parameter

#
GetClosestActive<Soldier>(Game.State.aliens, soldier.transform.position, soldier.faction)```
#

Not as nice

#

But oh well

#

And here is the original reason why I wanted to do this;

    public ListSlice<Collider> OverlapNonAlloc(int layer = 1)
    {
        int hits = Collider switch
        {
            BoxCollider b =>
                Physics.OverlapBoxNonAlloc(b.bounds.center, b.bounds.extents, hitResults, Quaternion.identity, mask: 1 << layer),
            SphereCollider s =>
                Physics.OverlapSphereNonAlloc(s.bounds.center, s.radius, hitResults, layerMask: 1 << layer),
            _ => 0,
        };

        if (hits > hitResults.Length)
        {
            Debug.LogWarning("Collider hits were ignored because the ref array is not large enough", this);
        }
        return hitResults.AsSlice(hits);
    }
#

It's a helper component to make working with OverlapNonAlloc functions easier

midnight violet
#

Whats the up and downside of NonAlloc versions? Just curious, why its not always using nonalloc

devout hare
#

Nonalloc requires you to pass in your own array and estimate how big it needs to be. It takes some effort to get it right so that you get the benefit from it

midnight violet
devout hare
#

That's happening in the C++ part but the difference is that if you pass in your own array it doesn't have to make a new one (regardless of how it makes it)

#

making a new array is the "alloc" part

midnight violet
#

Ah, okay. Got it. Interesting topic I had not touched yet. Thanks for clarification 🙂

hallow aurora
#

Another interesting benefit or downside, depending on how you like to program

#

Is execution flow

#

I find that OverlapNonAlloc allows me to do physics queries sequentially rather than needing to handle callbacks with OnTriggerEnter or forcing me to put my entity's data in a MonoBehaviour just so I can use the OnTriggerEnter

#

I can also decide when I want to make a physics query, so I can skip frames when trying to detect enemies within range

tall ferry
#

instead of NonAlloc vs physics messages

hallow aurora
#

Oh if that's the question, the only answer to me seems to be convenience

trail spoke
earnest heron
#

Hey guys,
I'm working on implementing rod bending by blend tree.
Once, I've made a system to achieve that but then after I found out it doesn't work correctly in every angles and situations.
I fills directionX (First parameter of blend tree) and directionY (Second parameter of blend tree) by using this code:

            Vector3 projectedLineXY = Vector3.ProjectOnPlane(_baitHandler.transform.position - _context.rodTip.position, _context.rod.transform.forward);
            float angleSignXY = Mathf.Sign(Vector3.Dot(Vector3.Cross(_context.rod.transform.up, projectedLineXY), _context.rod.transform.forward));
            float angleXY = Vector3.Angle(_context.rod.transform.up, projectedLineXY) * angleSignXY;
            Vector3 projectedLineZY = Vector3.ProjectOnPlane(_baitHandler.transform.position - _context.rodTip.position, _context.rod.transform.right);
            float angleSignZY = Mathf.Sign(Vector3.Dot(Vector3.Cross(_context.rod.transform.up, projectedLineZY), -_context.rod.transform.right));
            float angleZY = Vector3.Angle(_context.rod.transform.up, projectedLineZY) * angleSignZY;

_baitHandler.transform.position is bait position and _context.rodTip.position is tip of rod position. _context.rod is rod gameObject and other things related to that are its directions.

Please if you know how I can achieve the correct solution for that, explain what exactly I can fill these 2 parameters of blend tree.

timber flame
#

I have implemented a save/load system. It is OK but not flexible.
There are different entities in my game, structures, characters, vehicles. Each of them has different factories. I use zenject framework and so zenject factory to spawn objects.
I said it is not flexible because when adding a new entity type, I should consider it and write some extra lines to spawn them when loading.
Also, there are different repositories for each entity type. A repository keeps a collection of assets with this entity definition type (assets are SO)
In my view, if I implement a general zenject factory for all entity types and keep all assets in one repository, I can spawn different entities when loading a saved file and therefore, in the future, by adding new entity types, this system works without requiring modification
I would like to know your approaches

dusty wigeon
#

If your object are not Monobehaviour, you can even make it create them.

compact ingot
# timber flame I have implemented a save/load system. It is OK but not flexible. There are diff...

the save system i use constructs something like a persistence-prefab from a runtime instance of a prefab with specially marked components that hold the objects game-state, usually these are pure data components, it puts this compressed representation into a database with a scope in which it exists (a scene for example), when a scope is loaded, the system automatically restores the objects that were saved when it was previously destroyed. All this can also be triggered manually, for example "Store/SpawnObjectWithKey()".

fossil pollen
#

Hi!
I have an issue in my Unity Project. Though the game is low poly and the assets only consist of about 300MBs(Uncompressed), my android build turns out to be about 700MBs. I am stuck on this for a month and I just couldn't figure it out. Can anyone please help??

grizzled spear
#

If you don't start with the build report, you're kind of guessing at what it could be

modest sinew
#

so i just ran into wanting to do some static abstract methods in an interface. but thats not supported yet in unity since its using c# 9.0 and not 11.0. what could i do to work around that?

modest sinew
stuck plinth
modest sinew
#

isee, well. i guess ill try to work around it with not using those specific methods in the interface and maybe through inheritance

#

actually, ill just make a wrapper class for it instead

patent bear
earnest heron
lament salmon
#

Pretty sure they meant to reply to @fossil pollen

earnest ether
#

Anyone has any idea how I can achieve this 1st person movement https://www.youtube.com/watch?v=UOH-wzFD7qE&ab_channel=SamuelArminana

A recording I created to observe and reference mirrors edge first person view leg movement.

As you can see the legs move independent from the camera (upper spine). When an angle between the legs and spine is large enough the legs will move 90 degrees. If you continue past around this angle the legs will be clamped to the camera.

When you do an...

▶ Play video
frozen imp
#

@earnest ether Don't cross-post

earnest ether
#

I'm not sure if this is animation or code related. Maybe both?

frozen imp
#

It's a code question when you post code. In any case, pick one one channel.

earnest ether
#

I did not post code, I'm asking if anyone has any ideas. I didn't know it's illegal!

earnest ether
#

Such a warm welcome! Thanks, no need to. I'm out

shut ingot
#

Has anyone here updated facepunch steamworks and had their servers no longer advertised because heartbeat became obsolete?

worldly badger
#

Does Unity includes System.Net.WebSockets ?

grizzled spear
grizzled spear
low hamlet
#

hey yall! so im putting together a little group of programmers to challenge ourselves to do more complicated code snippets to show off in a portfolio. think of it as rapid fire demos for portfolios.

im looking for ideas that could be done reasonably in a week by a single person.

#

here are some of opur current ideas
Weekly challenges
-create your own object pool
-multithreaded algorithm (calculate pi digits?)
-implementation of a sorting algorithm
-Make 2 objects in 2 different scenes communicate

#

if you have ideas free free to just reply to this little questionaire with them

dusty wigeon
sly aurora
#

Can someone who preferably works in a professional environment suggest a course or a book that's specific to unity and teaches you advanced topics like:

Best Architecture & Practices
AI
Design Patterns
Logging

Thanks

low hamlet
dusty wigeon
dusty wigeon
dusty wigeon
low hamlet
dusty wigeon
#

If you are clever enough, you could group all those feature in a single project.

#

Also, those are not advanced topic in my opinion. They are important, but they are essentially pretty simple.

low hamlet
# dusty wigeon If you are clever enough, you could group all those feature in a single project.

that was kind of the idea, to have 1 project with a bunch of small showcaseable elements.

the whole list is full of stuff unity related.

Weekly challenges
-create your own object pool
-multithreaded algorithm (calculate pi digits?)
-implementation of a sorting algorithm
-Make 2 objects in 2 different scenes communicate
-Create a nonserializable class and serialize it in editor
-creating a proper save system ( this can be multiple)
-simple post processing effect for URP
-Procedural Terrain Generation
-make a rudementary pinball game
-Make a sine wave with cubes, then make ways to alter the wave
-create bouyancy for an object
-Make a functional turret (must have 2 axis and be able to be work in any rotation)
-2d or 3d boids algo
-generate a random noise texture (min 256x256)
-make a random number generator
-make the 3 body problem (maybe just design custom gravity first)
-wave function collapse
-make an outline shader
-non euclidiean geomretry (use stencil buffer?)
-networking stuff using unity netcode

#

its intentionally supposed to be a collage of random things that expose us to multiple facets of the unity engine from shaders to GPU code to cameras, getting us exposed to these topics.

#

some of these are basic asf like the noise txture or the pinball game

#

but using hash functiuons to make a random number generator isnt somethint that someone is going to immedaitely know how to do

#

like, from scratch i mean

dusty wigeon
#

I mean it seem pretty good. What you need more ? My advice would be to integrate them in a single project, but otherwise you already have a lot of stuff. The only issue I see is that it varies greatly in term of difficulty.

low hamlet
#

i was hoping to find someone assistance in that matter. i want them to be a variety of difficulties as the group im working with arent all at a similar level, so the differing difficulties is so they can participate in ones they feel they can take on the challenge for.

i was hoping to add even more complicated ideas that would challege those who wish to learn something thats even more difficult

#

as most of these could be done in a day or 2...

tall ferry
# low hamlet that was kind of the idea, to have 1 project with a bunch of small showcaseable ...

theres definitely a major difference in difficulty between some of these tasks. To be honest some of these are complete beginner topics. Like "implementation of a sorting algorithm" should be something you learned in your first month of coding. Then in the same list you have "networking stuff using unity netcode" which is going to be extremely complicated if you want anything more than 2 capsules moving around. Excluding the networking point, any of these could be done in an hour or maybe a few if following a tutorial with no knowledge.
While i dont want to discourage you from learning and helping others learn more, I dont think you should be continuing it in this way. For the things that aren't simple here, people will google a tutorial and then follow it exactly. That's more like homework to me instead of a fun challenge. Simferoce said a good idea about actually creating a game including these topics.

Id try to exclude details so you aren't being so specific in some cases. Like the functional turret focuses a lot on the rotation but the entire challenge can basically be solved with Transform.LookAt. I'd instead say something like "make an accurate unique turret which autofires at your character. The character can move etc". Now people can use their imagination, maybe someone makes a turret with bad aiming yet homing missiles.
The "make a random number generator" can be replaced with make a puzzle involving randomness.
These are just rough suggestions to just get the point across of something which allows imagination. Also try to consider which things would be actually used in unity. IMO these can be removed: multithreaded algorithm, sorting algorithm, random number generator,

dusty wigeon
# low hamlet i was hoping to find someone assistance in that matter. i want them to be a vari...

Putting forward a project can easily help with people with diverse capabilities and even motivation. People that have better comprehension or more motivation can easily increase the complexity of the project. Also, it is worth mentioning that leaning things in a vacuum is drastically different that actually making it. There is a reason why most people feel like school does not correctly represent what is actually being done in practice.

Having done a course specialized on Video Game, I can easily say that the best learning experience for myself was through the creating of games. You learn stuff that actually matter and you understand easily why it does. As a teacher/guide, I would create myself a mini-game and ask my student to recreate it. That would force them to focus on the coding part of creating a game as they will already have the design and the art to make it.

Then, parallels to what you see in actual Video Game industries, I would follow a sprint philosophy where I would ask my students to have specific delivery. By example:
Sprint 1: 3C
Sprint 2: Combat
Sprint 3: Gameflow (MainMenu -> Level Selection -> Game -> Level Selection)
Sprint 4: Feedback (Shader, Particle System, Sound, Animation)

low hamlet
# tall ferry theres definitely a major difference in difficulty between some of these tasks. ...

A lot of the programmers involved with this little weekly challenge event have been taking classes for programming for unity in a community college and so exposure to a lot of these concepts is unfortunately NOT covered. sorting algorithms, hash functions and creating custom random number generators, multithreading, and more just arent covered in the program we reside in. you are correct about our feelings on school not representign whats in practice. its precisely that because we are unhappy with the concepts that we should have learned much earlier on that we are forcing ourselves to go chase after now. we have games with teams and the like, but the deadlines were so tight or the resources so thin that we couldnt build anything close to what i would call a complete "tiny game".

i do plan to have multi week chains of challenges, like the gravity idea was going to be creating some custom gravity, then chaining that into orbits, and then finally into a orbit/weird gravity style microgame.

i do like the idea of doing sprints and ill see how i can integrate that into the structure of our goals.

#

for instance, im in my final year at the program. ive never heard of "the 3 Cs". googled it, and yeah, that makes sense and the process sounds correct just from my simplistic understanding (and lack of knowledge). we just are missing out on a ton of thing that developers should know, and so we want to expose ourselves to the topics. i mentioned earlier it could be useful to throw onto a portfolio, but id say thats next to irrelevant to actually going to learn the things we will need to understand in the industry.

dusty wigeon
low hamlet
dusty wigeon
# low hamlet can you list some things that are then? if i can focus our groups efforts, we ca...

I mean, if you do a game you are inevitably find yourself in situation where you need to learn X thing.

Also, you said you were not able to make a game in tight deadline, but the true is that you can easily make a game in 2-3 days. The issue is probably that you were overscoping for the time and experience you had. If I ask you to make a 2D character move, you should be able to do that in a couple of hours without even prior knowledge of what Unity is.

low hamlet
# dusty wigeon I mean, if you do a game you are inevitably find yourself in situation where you...

i definitely have had times where ive learned things to solve particular problems and learn new things to do so. in not gonna bother defending a college projects code or asset base. the group event im trying to do is provide that. give a challenge with set outcomes, and then let those who participate freely figure out how to solve them.

im just asking for help on finding some topics to incorporate in our learning process that would be interesting problems or complex topics. i have focused a large portion of my time to learning CPU, memory, and network optimisation, but a peer has done lots of work with sahders and render features. the concept is to expose us to both in a semi completive nature that doesnt require the use of building a full game every single week.

youve reiterated the "go make games" standpoint a dozen times. i understand that. ive done that myself. but some of the peers im working with havent due to work, classes, or even just confidence. im doing this so they can still sit down 2-4 times a week for an hour or 2 a day and learn topics they had no idea existed.

sly aurora
#

I know this is a big topic
but briefly how would you implement a state machine for a Player object that has many scripts each handling its own logic as follow:
PlayerInventoryManager, PlayerMovementManager, JumpAndGroundManager, FocusedItemManager, ShootingManager

tall ferry
lament salmon
#

But this might not be what you are asking, it's a bit vague.

modest sinew
#

so i was thinking of doing an ability system where a character (either player or not) requests to use an ability (if its able to use it), then a an event system handles the request and controls the ability. since i was thinking of doing the ability code in a regular (not mono-behaviour) class and have that code execute whatever the ability should do after getting the inputs it needs.
essentially like this:
Character -> Request -> Handler -> Activate the ability.

because i was thinking of doing it this way the character and the request doesnt need to know the class the ability comes from but how would i make a generic way to request abilities this way?

i was thinking maybe using scriptable objects and have them keep the info of what the ability is, but no matter what i can think of i kinda need to translate the info into the actual execution of the code. id gladly accept any suggestions either to change how it would activate the abilities or whatever it would be

grizzled spear
#

I think you're limiting yourself by not making the abilities MonoBehaviors. If you make them MonoBehaviors, then you get lifecycle events, coroutines, etc. But let's assume you have a good reason to do otherwise.
I would have an IAbility interface with some definitons like ProcessFrame, IsEnabled, etc. Then have a bunch of ability classes implement that interface: JumpAbility and FlyAbility, for example. You could then register that character's list of abilities and have your Handler loop through all of the registered IAbility instances on that character each Update() and call ProcessFrame() on each. They could determine what to do from there.

#

CorgiEngine has a similar approach that's worth looking at, easily extensible

modest sinew
modest sinew
grizzled spear
#

Check this out (from corgi)

#

You just drop those compoentnt abilities onto the character, tune the params in the inspector and they 'just work'

#

And you can write your own by making a new class that implements the interface and it works the same

#

totally self-contained and composable. It's exactly how I would approach it

modest sinew
shy cloud
#

Hello, anyone know how to get RawImage component from ImageButton prefabs?

sly aurora
#

Using the Scriptable object architecture where u put logic\data in Scriptable objects
how do u reset the values inside the Scriptable objects when u start the game again? 🙃

upbeat path
west rampart
#

Anyone know how to change the settings within an animation import prefab via code? The inputs appear to be hidden? I really didn't want my users to have to manually select "Root" or uncheck "Bake into pose" for an entire animation pack..

west rampart
#

Thanks @dusty wigeon

brisk spear
#

is there anyway to add a method here

devout hare
brisk spear
#

no, i mean to add a method into GameObject sealed class

#

and have it appear in this ui

upbeat path
#

no, that is not possible

#

sealed literally means, hands off

lucid crane
misty glade
#

Due to ... reasons .. I have to roll my own click handler. Is there any way to grab the OS click timing sensitivity? IE, duration in ms between mousedown/up to register a click?

#

If not, any guidance on best practice here?

#

(maybe something in UnityEngine.Input? I couldn't find anything in the API on a casual skim through it

#

ie: current solution is this, and I feel like it's bad since I'm enforcing my idea of click timing:

        private const float ClickDurationMax = 0.2f; // blech
        private HexPoint _startClickLocation = HexPoint.None;
        private DateTime _startedClick = DateTime.MaxValue;
        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                _startClickLocation = GetMousePosition();
                _startedClick = DateTime.UtcNow;
            }
            if (Input.GetMouseButtonUp(0))
            {
                if (DidClick())
                {
                    OnMouseClicked();
                }
                _startClickLocation = HexPoint.None;
                _startedClick = DateTime.MaxValue;
            }
        }
        private bool DidClick()
        {
            HexPoint mousePoint = GetMousePosition();
            if (mousePoint != _startClickLocation) return false;
            if (_startedClick == DateTime.MaxValue) return false;
            if ((DateTime.UtcNow - _startedClick).TotalSeconds > ClickDurationMax) return false;
            return true;
        }
dusty wigeon
# misty glade ie: current solution is this, and I feel like it's bad since I'm enforcing my id...

If you really want to try to use the OS definition of double click you can try to use https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdoubleclicktime. (Only on Windows)

That being said, it is noted that 500ms is the default value.

The number of milliseconds that may occur between the first and second clicks of a double-click. If this parameter is set to 0, the system uses the default double-click time of 500 milliseconds. If this parameter value is greater than 5000 milliseconds, the system sets the value to 5000 milliseconds.

https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setdoubleclicktime

misty glade
#

This game is built for web so i won't have access to any of that windows stuff.. I've had a heck of a time plugging into those calls in the past anyway

#

interop between unity and windows (even on windows) is like.. so fugly

dusty wigeon
#

It should not be really hard if you were on desktop.

misty glade
dusty wigeon
#

If you are on browser, you should look with each and individual browser API.

#

Any way, I do not think it really is worth.

misty glade
#

that's what a single call looks like .. it's.. kinda ugly, and I don't know my way around the API docs for windows dlls

#

yeah, I'll just.. do what I did above (which works pretty nicely for me.. but .. obviously it's crafted for "my" definition of a click)

dusty wigeon
#

It is kinda what I would expect.

misty glade
#

i'm worried users might get clicks when they don't intend to and miss clicks when they intend to

dusty wigeon
#

You could always use 500ms as it seem to be the default value

misty glade
#

Yeah, I'll try that out.. I could probably also go higher because I'm only "breaking" the click if they drag to another hex entirely, which is pretty big in this game

#

Kids'll be playing this (like 8 years old?) so it might need to be more forgiving for a click

dusty wigeon
#

0.2s seem to be a lot though.

misty glade
#

A lot..? You mean a short window?

dusty wigeon
#

It is almost the expect reaction time.

misty glade
#

Yeah, I mean, it's hard to imagine a "click" being slower than 200ms but I watch my kids (7 and 9) use the computer and even as computer-literate as they are for their age, their clicks are pretty bad

dusty wigeon
#

I believe it is also pretty near on the limit of when people start feeling that things do not react fast enough

#

At least in UX from what I remember

dusty wigeon
sand ridge
#

Hi there! I'm working with Sentis and i discovered a problem with TextureConverter class. The colors are a bit off comparing to the actuall colors of a texture when i convert it to a tensor and then back to a texture (the image appear more dark). I extracted the values to an actual texture2d and the difference is visible. Anyone knows why?

Tensor<float> input = TextureConverter.ToTensor(input_view, new TextureTransform().SetDimensions(640, 640, 3).SetCoordOrigin(CoordOrigin.BottomLeft)); 
sly grove
sly aurora
#

Using unity's scriptable objects architecture
I am making an SO that holds reference to the game object that the player is looking at

[CreateAssetMenu(menuName = "SO/FocusedItemSO")]
public class FocusedItemSO : ScriptableObject
{
    public GameObject FocusedItem;

    public void SetFocusedItem(GameObject focusedItem)
    {
        FocusedItem = focusedItem;
    }
}

However this complains if I don't have anything initially set for the GameObject FocusedItem
so i went and created an empty object and assigned it to the SO in the inspector and it works fine
but the solution seems meh
any better solution?

unreal violet
#

are you referencing theFocusedItem before you assign it to something..?

sly aurora
#

thanks

sly grove
#

Yeah - use of public fields is not recommended. You could also have your code handle the situation in which the player is not currently focusing on anything.

sturdy timber
#

Hey everyone does anyone know how to make use of mono.cecil? I want it to work on most platforms so no code will be inserted at runtime but in the editor see this post -> https://discussions.unity.com/t/does-using-mono-cecil-to-inject-code-works-on-all-platforms/882594

I know this possible since you can pretty much see it on NGO Rpc's as there is some injection going on in the background using some ILPostProccesor class. I have pretty much a similar case as how rpcs work. Any idea how i can get started?

stuck plinth
#

FWIW you might want to also check out doing code generation with a rosyln source generator or codeDOM, that can cover a lot of the use cases and it's a lot less fiddly than manipulating IL

arctic lake
#

I'm trying to addListeners to multiple buttons, and I want each listener to be different

Ex: SelectMove(0), SelectMove(1), etc.

When I try the for loop, it assigns all my buttons the same 'x' (in this case, 91, the number of moves in button Count)

But when I assign my AddListeners like I do in the comments, it works how I want it to. Am I missing something?

long ivy
#

copy x to a local variable inside the loop

arctic lake
#

okay, is there a reason why I have to do that specifically with the buttons?

#

Oh, is it because x keeps changing, so it reassigns it automatically

sly grove
#

This is a classic case

#

x goes in the lamdbas by reference, not as a copy

arctic lake
#

Ah, this is my first time experiencing that lol

#

Thanks to you both! It works how I want now

white pulsar
#

Question regarding sub-assets of ScriptableObjects.

This SO is a custom MaterialVariant solution since for reasons i CBA to explain, i'm stuck in 2021.3, trying to load the matADShroom via the assetbundle is not returning a valid material (its returning null).

Is the string name for the material the same as it's parent asset when its being bundled into an assetbundle?

hybrid belfry
#

Hi, does unity have a quick way to get the rendered size of a image's sprite, taking into account it has a preserved aspect ratio?

somber swift
hybrid belfry
long ivy
#

there isn't an exposed method, but look at UI Image's OnPopulateMesh and specifically GenerateSimpleSprite, GenerateSprite, and GenerateFilledSprite

verbal temple
#

if you knew the aspect and know the rendered height (RectTransform) couldn't you just use the aspect to calculate the missing piece of information (width in this case)?

#

height * aspect

#

or maybe I am misunderstanding something

fervent sage
#

WTF!?!?!? Did I miss something obvious? Expression on the right is 0.58... but when stepping over that line in debug accuracy is set to 0.96...
What's going on?

#

Doing this fixed the issue. Any ideas what it was?

sly grove
fervent sage
random dust
#

I suggest you split that line into multiple lines to see if the values are correct

#

Doing it all on a single line is not going to be clear

fervent sage
untold moth
#

It could as well be a class field with the same name.

fervent sage
icy smelt
#

Guys. I have a project with various structs that I generate from C header files (for interoperability).
The structs are quite big because there is no blittable array in C#, so all the array elements are inlined.
When compiling this project in IL2CPP, it takes forever to compile, and the compilation never ends.
I've tried splitting the code into several .cs files, but it did not help.
Do you have any idea what could cause IL2CPP to take forever?

#

I have tried all possible configurations (debug, release and master)

icy smelt
sage radish
#

Are you avoiding unsafe? Because if not, you should be able to use pointers to match the C structs, which you can then reinterpret as Span or NativeArray for easier use in C#.

icy smelt
#

Forever = it never compiles

#

I've mentioned the inlined arrays because I suppose this could be causing IL2CPP some trouble

sage radish
#

Do you want to continue to use inlined arrays? I thought that was an attempt at a workaround which isn't compiling with IL2CPP. If you use pointers, you don't need that workaround.

#

We can try to diagnose the problem with big inlined arrays, but if it's not necessary, we can save ourselves the trouble.

icy smelt
#

It is the fastest way I found to pass these structs back-and-forth to C

#

Because I can send them as they are to C methods

sage radish
#

How big are these structs, in bytes? And how many fields?

icy smelt
#

Something like this (C):

  bool has_warning[13];

I translate like this (C#):

 [StructLayout(LayoutKind.Sequential)]
            public struct has_warning_struct
            {
                private Byte _0;
                private Byte _1;
                private Byte _2;
                private Byte _3;
                private Byte _4;
                private Byte _5;
                private Byte _6;
                private Byte _7;
                private Byte _8;
                private Byte _9;
                private Byte _10;
                private Byte _11;
                private Byte _12;
                public Byte this[int index]
                {
                    get
                    {
                        if (index < 0 || index >= 13)
                        {
                            throw new IndexOutOfRangeException();
                        }
                        fixed (Byte* ptr = &_0)
                        {
                            return *(ptr + index);
                        }
                    }
                    set
                    {
                        if (index < 0 || index >= 13)
                        {
                            throw new IndexOutOfRangeException();
                        }
                        fixed (Byte* ptr = &_0)
                        {
                            *(ptr + index) = value;
                        }
                    }
                }
            }
#

I haven't counted, but there are really big arrays on these structs

sage radish
#

More than 1000?

icy smelt
#

The codebase is a bit complex, so I can't tell the biggest array size, unless I modify my transpiler to count it

#

There are lot of "unions" that I'm converting as well

#

I feel like it is quite complex for IL2CPP, idk

sage radish
# icy smelt Quite possible

Are they all primitive types? You can use fixed buffers for those:

public unsafe struct has_warning_struct
{
    private fixed byte has_warning[13];
    
    public byte this[int index]
    {
        get
        {
            
            if (index < 0 || index >= 13)
            {
                throw new IndexOutOfRangeException();
            }
            
            return has_warning[index];
        }
        set
        {
            if (index < 0 || index >= 13)
            {
                throw new IndexOutOfRangeException();
            }
            
            has_warning[index] = value;
        }
    }
}
icy smelt
sage radish
#

I think the number of fields is going to bog down compile time more so than the size, because IL2CPP has to collect and store metadata to ensure Reflection works for each of those fields. Fixed buffer will avoid that cost.

icy smelt
#

I will try modifying the transpiler to generate it using fixed buffers

sage radish
#

Fixed buffer only works with primitives, though, not custom structs.

icy smelt
#

Stupid question: This works with Unity, right? lol

sage radish
icy smelt
sage radish
#

You might be able to work around by using explicit struct layout. Fixed buffers get compiled as this:

#

So it overrides the size of the struct to make space for the array without needing additional fields for it.

#

You may be able to do something similar, to make custom structs work.

#

You would just need to write wrapper indexers to read it properly, like you're already doing.

icy smelt
#

Tysm. Gonna try the fixed stuff and will let you know if it works

icy smelt
#

Same thing, I guess

#

Def not working

sage radish
#

Do you recognize the conv_qtmn being from your code? IL2CPP generated truncated class names based on the originals.

icy smelt
#

No, I can't recognize it

#

But I have quite a few MSVC runtime libs in my plugins folder

#

I'm using a debug lib

#

I could try compiling it as release and see if I can get rid of most of these plugins

#

Last time I've included MSVC native plugins in my project, I remember I had to pack the MSVC runtime as well

#

But since the delay is in codegen, it might have nothing to do with these plugins

sage radish
#

I don't think IL2CPP does anything with native plugins, those will always be shared libraries loaded at runtime.

#

And you know for sure the problem is these transpiled structs?

#

It can finish building without them in the project?

icy smelt
#

The project has nothing else besides the transpiled structs

#

I've tried on a new project as well

#

Same thing

#

But the qtmn makes no sense to me. Trying to find where it comes from

sage radish
icy smelt
#

That is what it seems to me

#

Yeah

sage radish
#

You could try checking the editor log to see where it might be getting stuck, but I don't remember IL2CPP logging anything detailed there during building.

icy smelt
#

Yes, I was trying to find how to get a "verbose" output from IL2CPP

#

This is from a new project, the name changed to 0m29

[BUSY      16s] IL2CPP_CodeGen C:/Repos/TestImporter/TestImporter/Library/Bee/artifacts/il2cpp_conv_0m29.traceevents
[BUSY      26s] IL2CPP_CodeGen C:/Repos/TestImporter/TestImporter/Library/Bee/artifacts/il2cpp_conv_0m29.traceevents
[BUSY      36s] IL2CPP_CodeGen C:/Repos/TestImporter/TestImporter/Library/Bee/artifacts/il2cpp_conv_0m29.traceevents
[BUSY      46s] IL2CPP_CodeGen C:/Repos/TestImporter/TestImporter/Library/Bee/artifacts/il2cpp_conv_0m29.traceevents
[BUSY      56s] IL2CPP_CodeGen C:/Repos/TestImporter/TestImporter/Library/Bee/artifacts/il2cpp_conv_0m29.traceevents
[BUSY      66s] IL2CPP_CodeGen C:/Repos/TestImporter/TestImporter/Library/Bee/artifacts/il2cpp_conv_0m29.traceevents
[BUSY      76s] IL2CPP_CodeGen C:/Repos/TestImporter/TestImporter/Library/Bee/artifacts/il2cpp_conv_0m29.traceevents
white pulsar
#

Hello, i'm currently working on a game using Arduinos and their NFC capabilities with sensors.

We plan on using a single NFC sensor with multiple chips (we dont know how much yet). however, the basic idea is making these chips connected to ID cards.

The issue i'm having with this is that, depending on the amount of NFC chips, we may need tens, if not at least a hundred unique sprite combinations, i was thinking on making some form of algorithm for creating unique sprites based off existing "pieces" of characters (say, 10 unique body shapes, 10 unique head shapes, 10 unique hair styles, etc). and then saving these generated sprites as .png files so we can both use them in the game on the screen, and on the NFC chips

#

problem is, i dont really know how i could do this, i searched online but didnt get many results

#

I know there's the image conversion class, i assume i need to do it with that since it seems to be the easiest way and its available both in editor and runtime. appart from that, i'm stuck on how to properly execute it.

#

as a context, by "combination of pieces" the closest game i know of that does this is "Fingered!" by Edmund Mcmillen, the suspects are generated with random pieces of outfits to generate unique looks for each.

upbeat path
sage radish
#

A single Texture2D, that is to say.

white pulsar
#

indeed

#

like, take the combination of sprites renderers, and save that combo into a single texture2d

#

so that later i can save it using the image conversion class, so i can use it both ingame and as actual objects the player uses as the control to test for a condition ingame

#

the idea is more or less being a guard for a bathroom and there's a line of clients, some of them are humans and some of them are vampires, each time a new customer arrives, the player needs to find their ID (By comparing the person on the screen with the cards that they have in their hands with themselves) and scan it on the scanner, if the scanner says is a vampire, use an actual light on a light sensor to burn the vampire, otherwise, let them thru the bathroom

#

gain points by properly expelling vampires and letting humans go into the bathroom, loose points if you light a non vampire or if the vampire goes into the bathroom

#

which is why i need the generated sprites as both actual sprites ingame and stuff i can print into nfc cards

sage radish
#

The simplest approach is to spawn some GameObjects with SpriteRenderers, use a Camera and render it to a target RenderTexture and reading that back to a Texture2D. A more complex, but more optimized approach would be to draw the sprite textures directly into a RenderTexture using Graphics, GL or CommandBuffer, and avoid the Camera and game objects, but that requires some understanding of how graphics libraries work and the performance savings are basically nothing if you only need to generate these once at the start.

white pulsar
#

yeah, i like the camera approach actually

#

since this is just to avoid manually having to create 100 unique sprites

#

i havent tested camera stuff that much, i assume i can tell a camera what layer to display?

#

if so i could probably handle the rest myself

sage radish
#

Yes.

white pulsar
#

perfect

#

thanks, i'll probably come back if i need some other help, thanks for the info, appreciate it

white pulsar
#

@sage radish thank you <3

#

Works like a charm, was a bit concerned that the black where actual pixels but using the alpha channel it just shows that its transparent

misty glade
#

I'm using Input.mouseScrollDelta.y to manually do some camera zoom in/out, but touchpads are scaled different (scrolling is one unit per pixel). Is there any way to know if a physical device is .. I dunno, using a different scrolling "universe" for scrolling?

This is the effect with my mouse: https://www.youtube.com/watch?v=-QLsSNbCurM

I didn't snap a video on my macbook, but it basically zooms to the top/bottom with the tiniest little bit of scrolling on the trackpad

#

(I know I'd be able to add a configurable scroll sensitivity thing but this is for a pretty lightweight web app, it'd be nicer if it "just worked")

midnight violet
misty glade
misty glade
#

I mean, I know what a normalized vector is.. not really my problem here 🙂

#

problem is that Input.mouseScrollDelta.y is "1" for a mousewheel "click" and about 50 for a one inch scroll on macos' trackpad

midnight violet
#

So I see two easy solutions here, cap the max "speed" of your zoom or make it a fixed step per second while going up or down.

#

You could also cap the input being triggered / sec, so you do not exceed that 50 click ratio or similar

misty glade
#

hm.. that's an idea.. like "if there was any zoom upward in the last 200 ms then zoom up once"

#

it might make it sluggish if someone does want to zoom all the way out quickly, though.. like, I sorta like how it's snappy now (on my PC)

midnight violet
#

You could also smoothly lerp it to get faster the more input is coming in and smooth it to 0 with lesser. Something for you to testout.

upbeat path
#

usually with these kinds of problems I add a sensitivity slider to the game settings so users can set it themselves

misty glade
#

Yeah.. that's probably my "best" solution but .. this is gonna be a web game for kids so I can't imagine many of them are gonna dive into settings

midnight violet
#

You could do a little onboarding, are you on trackpad or using mouse too.

misty glade
#

I like the throttling approach

upbeat path
#

you'd be surprised, I find kids are more likely to dive into setting than 'adults' are

midnight violet
#

But if you want to fully automate it, the "throttling" might be the one for you.

misty glade
#

Then it just becomes a game of finding the right throttle threshhold.. like maybe even one click per 3 frames should be enough (max zoom is currently uh.. 11 clicks, i think)

#

it was kind of a pain in the ass to get the pan/tilt and position working as it is, even.. and it still needs improvement because the tilt is calculated on the Y position of the camera (and not the camera distance, as it should be - ie, the hypotenuse).. but I couldn't get that working right

midnight violet
#

Just wondering, is the new input system an option for you?

misty glade
#

method B down at the bottom

#

I'm not sure - I've never used it, but.. this is working mostly "good enough" for now so I'm probably not going to eat the learning cost of the new input system just yet

#

I dabbled with it last year and didn't get to understand it completely, just fell back on what i know

midnight violet
# misty glade I'm not sure - I've never used it, but.. this is working mostly "good enough" fo...

Ah got it. Just thought, there might be some improvements the old one is missing. And learning it is not that hard. Instead of referencing inputs directly, you just create your actions and register to them or readvalues you need. Quite easy, but I get why its weird to get in first time, had the same headaches back then. Also not guaranteeing it is solving the scroll issue, something to investigate

misty glade
#

yeah.. it might be a lot of integration/change work because I'm manually doing all the drag/mousedown/mouseup handling

#

there's hexes on the grid so a mouse click on a hex in the world is a .. discrete action

#

that might be hard to integrate with the new input system

midnight violet
#

Instead of Input.mousePosition or whatever its called, you would just use your playerAction.mousepos.ReadValue . but not gonna convince you here 😄 just a suggestion. if you stick to the current one, Id say, try some acceleration zoom the mroe the user zooms normalized maybe

misty glade
#

Yeah, I suppose I could/should do it, obviously doing mouse input manually has some accessibility concerns but.. it's one of those things (like localization) that I tend to delay until its kinda too late .. hard coded english strings everywhere

misty glade
icy smelt
#

@sage radish I managed to compile that code. It takes just 50min kekw

opal sparrow
#

Is it possible to compile Assembly-CSharp.csproj in order to get resulting Assembly-CSharp.dll for game without editor, by using an external compiler?

#

I come from C++ land and after trying to sift through info on what exactly I need for this is less than ideal

#

If I, lets say have a C++ CMake project, all I need is portable CMake and portable MinGW to compile it. CMake would be the one dispatching compilation orders, and MinGW would be the one doing unit compilation

#

What would be the correct way of phrasing this to my search engine? Coz I am lost in all this C# related stuff

#

I am also specifically asking about a standalone/portable way of handling it, since I want to be running CLI

#

So suggesting to just use an IDE is out of the question, this is not the reason why I am looking into this

untold moth
opal sparrow
#

Wouldnt that just be me taking something and building this C# project?

#

And it would result in the same output as if it was done by the editor

compact ingot
#

afaik you can compile against the engine dll in a regular (non-unity-editor) project and then drop that dll into a unity project and use it.

opal sparrow
#

I just dont know what I need to compile it from CLI and preferably from a portable folder as well (without global installers)

compact ingot
#

you just can't compile a unity project into an executable without the editor (by any practical means)

opal sparrow
#

I dont ask for that, I just need to compile the DLL

opal sparrow
#

I tried to understand all of the compatibility stuff, but I just couldnt XD

compact ingot
#

you can use any version, you must however limit your usage to the c# language version and features that unity 6 supports

#

you can always compile for standard 2.1 to be maximally compatible

opal sparrow
#

I am planning to do main development while also working in the editor

#

So that should prevent me from using anything that wont be supported outside unity

compact ingot
#

not sure what you mean by that.

opal sparrow
#

I mean I would be coding something in IDE

#

And I would have an editor opened with the project

#

And I would be relying on the editor to compile my code

#

But I also need a way to compile this resulting Assembly-CSharp.dll with my games code from CLI

#

On a server without a unity editor installed

#

This is why I am looking into external compilation

compact ingot
#

i'm not even sure if thats allowed 😉

opal sparrow
#

So, you mean that .NET SDK wont be able to compile Assembly-CSharp.csproj on its own?

compact ingot
#

i think you can't legally use the .dll without a unity install.

scenic forge
#

How do you intent on using the compiled dll? Even if you have it, you still need to have the editor to build your game.

opal sparrow
#

I am not planning to use this in any export/build pipeline of any kind

#

I understand that I still need to properly export everything

scenic forge
#

What are you using the dll for then, if not for building the game?

opal sparrow
#

I just wanted to be able to build Assembly-CSharp.csproj at any given moment

#

After any of the underlying scripts in Assets/Scripts folder were changed

#

Get the resulting DLL

#

And replace the one in the Game-Data/Managed

#

I also got rid of Plugins

#

So I am not even generating firstpass dlls anymore

#

Just the main Assembly-CSharp.dll

#

I am doing this just for a quick patchwork

#

So I wont have to launch an editor and export the entirety of the project

#

When I could just rebuild my code from the already provided project file

#

And replace resulting DLL in the already properly exported game

#

I assumed it would be easy, since Assembly-CSharp.csproj is a basic C# project

#

And I would just need to compile it somehow

opal sparrow
scenic forge
#

What's the high level goal, patching the game for faster iteration on actual devices, or something else?

opal sparrow
#

For now I was planning to just use this for faster patching

#

Later on, maybe use this compile-on-demand approach for modding as well

#

Since working with original sources and just compiling everything (changes and additions by mods) into a single Assembly-CSharp.dll is infinitely more approachable than using something that requires runtime patching (Harmony/BepInEx/etc) which most Unity based games are using nowadays

#

Yeah, it seems to be working as I want it to

#

I just need to change all .csproj references to point to DLLs found in the exported game

#

Instead of using ones provided by the editor

#

And it should allow me to recompile game's code on demand

#

Thanks for the help @compact ingot @scenic forge

hot vine
#

experiencing a strange bug with A* movement

the problem with my code is that both the player and enemy unit use the same A* pathfinding system., for some reason, the enemy opts to move diagonally while the player just sticks to cardinal directions

from the look of it, it seems the enemy crosses into the next node too early

the enemy and player here are also using identical pirate models, there's an offset somewhere i guess? but i'm not sure where

the enemy also shares print statements with the player, player triggers "player has reached next node" but the enemy never triggers this log and skips the if-statement, which means nodes aren't being dequeued properly

#

i got relevant code here but it might be a lot to sift through, mostly cause i included the grid manager for context

#

the difference between player movement and enemy movement would be player moving via mouse clicks--it also doesn't have the FindClosestNode method

plush hare
#

@spiral swift
dont post the same question in multiple channels. its annoying and against the rules

#

you might want to explain what context steering is / why you need it rather than traditional pathfinding

spiral swift
tight ether
#

i made an editor script to adjust camera layer cull distances but it has no effect neither in play mode nor in editor mode, cant find anything on google as to why it wouldnt work, i set the layer of an object to "DoNotCull" but no matter the number its not getting rendered (its very far away and visible at 4000 distance) so my camera distance is 3000 and i set this specific layer to 8000 but it does not work.

long ivy
#

"editor script" = ? Make sure this is a plain old runtime script
What is your camera far clip plane set to?

tight ether
#

3000 like i said

#

basically this, but it doesnt wor khttps://docs.unity3d.com/6000.0/Documentation/ScriptReference/Camera-layerCullDistances.html