#archived-code-advanced
1 messages · Page 111 of 1
Yes? I'm not exactly sure what you're rendering though
roads like cities skylines
"spline generated geometry" I guess one mesh?
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
Ideally I think you'd modify one existing mesh
(for a single road at least)
You're talking about when you're editing the road and it's changing yeah?
yeah
Ideally you don't create a new mesh each frame for that
well its very complicated to re-adjust uvs when manipulating the same one
so i just start again
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
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
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
No drawbacks except GPU memory consumption. Use compressed texture formats. And for even bigger texture container you can use texture arrays.
Upon some manual calculations, it's really not that much memory used
Surpsingly
Anyway consider compressed texture formats. More free GPU memory and faster shaders (less memory to read = bigger throughput)
Not sure how accurate this thing is, but it gives a rough estimate https://toolstud.io/photo/filesize.php?imagewidth=16384&imageheight=128
Obviously all images are compressed differently
This calculator is set up for 16384x128 texture. It is small. Try 16K x 16K
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
Just keep in mind that some compression algorithms like PVRTC on iOS will only use square textures so 16k x 128 might end up taking the space of 16k x 16k. I think PC compressions should be fine with any power of two textures though
Not planning on any ios development but couldn't I choose compression algo in Unity?
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
You can but not all devices support the newer algorithms. Now that I looked at it, it seems PVRTC is only used for older iOS so doesn't seem to be a problem for you anywyas
You can choose, but some of the best in terms of quality/memory algos might require you to have width = height and also a power of 2. Just consider it a standard and try to follow the rule.
Yeah it's not hard to pack in square aspect ratio honestly just to be safe
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
Wdym
My idea was to stich them at game startup into a single atlas, then use in a shared material to enable instancing
If you generate them procedurally (combining existing textures for example), then it doesn't matter but if you import them from somewhere else, closer to square would be more pleasent to work with
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 🙏
What are you guys using to establish this connection. Some code would be benefical to checkout
Well, it’s a big project, and showing you some code won’t really help. I’m looking for ideas or clues since I’ve run out of them…
You do you. I guess, connecting to the server is not a big chunk of code. But letting people guess for whatever might not be the best start to get help 😄
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;
}
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
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
Okay, so its also happens on editor, not as often as in build
Yes
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?
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();
}
}
But the error occurs randomly or everytime you start the application a second time?
On editor it's randomly, on build, everytime
It works if I'm staying on the same computer as well
So your application serves as server and client at the same time, do I get this right from your NetworkManager.IsServer check?
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 😅
Not really 😄
Maybe its just me 😄
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 ?
Ah, okay, that makes sense now 🙂
And your App 1 is running constantly while you get the error when reconnecting?
Yes
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?
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 ?
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
Wdym by "launch WebServer.exe"? Are you launching it programmatically from App 1?
Yes
Here's the code
Make sure that the WebServer is being terminated or reset properly when your unity server shuts down.
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
Synchronicity? #archived-code-general message
👀
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
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?
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.
Thanks, there are several sources and sinks and a bunch of pipes. I would like to convert it to a DAG graph. Clearly, the directions should be from sources towards sinks and then by getting a topological sort for it, I can calculate the flow amount for each pipe and finally for each sink
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.
Appreciated but this way is time consuming, isn't? I thought finding DAG is more efficient.
It is like cellular automata.
Have you played oxygen not included? I guess they have used your approach to model and simulate their pipes
Do you know any refs or links or even keywords so that I can dive deeper into it, thanks
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...
recommend using kruskal's algorithm
Kruskal doesn’t work on directed graphs. In fact MSTs are not really meaningful for directed graphs. It was simply meant as a starting off point for defining a cycle breaking heuristic.
not a code question. Do not cross post
I don't get it. You said I should use pressure model and now you introduce an algorithm to find a DAG from a bidirectional graph
Anyone know netcode for gameobjects can take a look at #archived-code-general ?
i suggested the BFS search in by first answer, that is still a straight forward (recommended) first option you can try. I did not suggest any other algorithm, just gave you starting points of what you can look at to figure out what heuristic you want to use for breaking cycles.
Does anyone know a better alternative to marching cubes or surface nets alghoritims?
Some interesting info here: https://www.reddit.com/r/VoxelGameDev/comments/pklhuo/i_wish_i_found_surface_nets_sooner/ (dunno if that's helpful or not but it's a pretty specific question)
The "best" algorithm usually depends on the context of utilization.
How do you define better?
Right, performance would be most important however the simpler the algorithm the easier for me it is to extend it with other stuff
I will take a look at this
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;
}
Your onChanged lambda captures the variable i, not the current value of i. By the time that action is called, i has changed.
interesting. Do you know how to make it capture the current value?
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.
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 ;)
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.
i'm also just guessing but it looks like it's just treating it as a regular old pointer so maybe that's just the fixed address unity puts that string at when it creates the heap?
Hey! How could I make a mouse sensivity slider, or atleast 3 buttons for sensivity?
do not cross post
okay
don't crosspost
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..
When I create a C# script, how do I stop it from reloading the domain every time? It kills productivity immensely.
buy Hot Reload
it's free unless you have a pro license
No? It only has free 30 day trial
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.
did they change it back? That was how it originally released, then they went with a free for personal edition https://discussions.unity.com/t/hot-reload-edit-code-without-compiling/906893/61
I've been using it for many months (via github package link) so maybe I'm grandfathered into the old model
yeah, it's Feb 2023, they changed it back
yep you're right, pricing changes. Should still be free for personal + Unity 2022 though, with no more updates https://discussions.unity.com/t/hot-reload-edit-code-without-compiling/906893/525
I'll have to buy it next time it's on sale, it has some quirks but definitely a productivity booster
I managed to integrate the Roslyn compiler into a Unity game and do 'live' game coding (using C# as script):
I use Unity 6, so I'll have to pay for this plugin soon
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?
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?
nvm, i think i figured it out. should've used '$' in the path to my interface instead of a '.'
java sucks so bad... lol
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?
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)
I'm trying to do something pretty simple
- Allocate a 2gb persistent memory arena via Malloc
- 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?
How to reproduce: 1. Download and open the attached project 2. Enter Play mode 3. Observe the console window Expected outcome: No er...
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?
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
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
I'm on 2022.3.5f1 for what it's worth
that is the first thing you should change. 2022.3 was not stable until at least patch version .11
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
you can host the json file on the same server that you host your WebGL build then use UnityWebRequest to load it
but this force me to have a backend server with rest api no ?
no. You need a server to host the WebGl build anyway, that server can host the json file, no rest API required
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.
I have no idea what you mean by local repo, we are talkiing about web servers here
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
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...
Can't really guess if we don't knwo what method is throwing that
tbh I have never used relative paths with WebRequest, you would need to test it. If I doesnt work you can do it via javascript
because Unity does not use MS .Net
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
It seems to mix some parts of MS's stuff, since simply replacing the assembly does the job without any visible consequences...
Unity uses roslyn to compile, and as such some compiler level features are available
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) ...
But that exception might as well come from the runtime mono libraries, and not from System.Runtime.Loader
Seems like it's not implemented in mono https://github.com/dotnet/android/issues/7763
(yes that repo is xamarin, which is effectively mono)
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.
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
Do you mean 'live c# coding'?
Yeah
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...
Idk what video you're talking about
But there's also things that let you execute C# in your game as well
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.
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.
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
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:
- the fact that their
Matrix4x4type has methods for creating TRS matrices, but not for deconstructing. - 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.
- gut feeling
I would guess so as well, if anything, to ensure serialization <-> deserialization is idempotent
NavMesh didn't work due to both NavMesh.CalculatePath being extremely bizarre and nonfunctional despite everyone in the company looking it over 😭 and because the player wouldn't always be perfectly on the mesh
No specific shape, laid out in a space station in most intersections and in long hallways. No weights as I've yet to learn about A* past knowing it exists
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
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.)
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)
Random note: due to the unification of entities and GOs—where each GO will have its own entity representation—they're unifying the Entity transform system to align with the internal GO representation. So when that work happens (hopefully we'll learn more at Unite) it should hopefully become very obvious how it's all set up as the Entity transform should alias to it directly.
That sounds like exactly what I need. This isn't a huge priority in the overall project but if we do come back to it this sounds like what I'd need
Maybe I'll mess around at home and see if I can get something working
Thanks ^^
neat!
Unfortunately it still happens even up through 2022.3.34f1+
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
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?
Have you looked into doing a flood fill algorithm?
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)
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)
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?
Nah, I just did a "get all hexes in range" (poor man flood fill - plus it's something I had already written) and then did my A* to each hex in that range (since we're talking N=30 or so) and then colorized based on distance, it worked great
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
beautiful
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?
Less is better, but it is something you should profile. Also, it is worth nothing that LOD culling is made per camera.
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.
But surely this isnt a 1 - 1 trade, I should be able to disproportionally trade, Small amount of performance on CPU for larger performance gain in gpu
It depends on many factor. So not really.
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
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
<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
Relatively few. A block only has a state if some unique behavior is attached to it. If that behavior is very complex, a block gets its own entity (yet another different thing)
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
MC isn't infinite - but it's very very large
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
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
Also wondering, if you only have like 5 units, if you need to destroy them at all. Why not just disable them or even use addressables in that case?
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
anyone know what's the currently best CI/CD solution for unity android / IOS? Except Unity Cloud Build
the C# reference will stay valid as long as you have any references to it, it'll just throw a MissingReferenceException if you try to do anything unity-related to it, but that said definitely don't build anything that relies on keeping destroyed instances around for any reason haha
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?
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
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
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
exists a way to check if player is clicking when pointerenter?
No, it's done with the IPointerClickHandler.OnPointerClick method
Hm.. good point. I was thinking that some of the data points might change during gameplay (ie, "identity color" might be different if the unit is powered up or whatever) but so far.. this is probably the better idea
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
(note hex highlighting for mouseover)
(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)
Since raycast-blocking UI objects trigger the EventSystem, it can be checked by the
EventSystem.IsPointerOverGameObject boolean.
Use with EventSystem.current.
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
Not sure what you mean by iterating through them, since it's just a boolean. Yes, you can get a List from the EventSystem: refer to this
EventSystem.current.RaycastAll(eventData, results);
cool, will try this out.. should be what I was looking for, thanks
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.
What kind of restrictions you talking about? Are you using FABRIK or something else?
I'm using the fabrik algorithm yeah, and I'm talking about rotation restrictions between nodes, as marked by the yellow lines
I see yellow lines but I have no clue what they are supposed to represent. What you need those constraints for?
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
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
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#
https://github.com/mintyleaf/ufabrik
XMR:
48S22unhWmxHgwk6Rco5Wc6C4riPGg3rNNKx3WFsVxVQ3BjQRuu8Tq22uQNWJvnVSYPL5kKge1towDmHqDPhwb4qVcmLHVb
ETH:
0x41505ceD17519012827C43C5e0DBFd0Ddd5C789E
BTC:
bc1qtee9l2yjdk4qr8ecrmkk0mxycejndt2d62m8ja
00:00 intro
00:21 basic FABRIK explanation
02:09 engine debates
02:18 basic FABRIK implementation
05:05 basic ...
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#
would you recommend using unity's in-built animation and rigging system for procedural animation, or doing it directly from scripts?
I have very little knowledge about unitys animation and rigging stuff but I assume procedural animations rely quite heavily on custom code
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
https://www.youtube.com/watch?v=qqOAzn05fvk I watched this video
Woha! We are going deeper. With the last episode of mine, I demonstrated how to use inverse kinematics if the script is already set up for you. But many of you want to look under the hood and want to have a deeper understanding of it.
I will use the FABRIK IK Algorithm that is used in Roblox for example. We will go step by step through the code....
So you're using DitzelGames' FastIK package?
yes, I followed along with the code used in the video
Does it help if you move the pole object towards one of the sides?
last time I tried it didn't help, but I'll upload another clip of me trying again
If not - you may need to seek out a more sophisticated IK solution. Perhaps using Unity's own 2D animation package which is a little more feature rich
Although honestly I'm not sure how to specify a preference of bones to move first
I'll try it out, thank you
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
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
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?
<@&502884371011731486> job posting spam
linked the collab message here already too
#💻┃code-beginner message
and i guess now they wanna DM me too..
Sure, you can do that.
!kick 692295716575510528 don't return if you intend to rule-break by spamming the server. We have no job-posting channel.
muratslmn was kicked.
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.
How would I call them, like so they happen inside the gameloop?
But is there any issue with the approach that you mentioned?
just that it feels wrong to imagine systems as entities themselves with system components. gimmicky kindof
you can plug into unity's update loop without using monobehaviours
Well, in the end you'll need an entry point from one of the unity callbacks of course.
what do I look up to figure out how to do that?
i don't know where the entry of the program is
Just don't think of components/gameObjects as entities.
PlayerLoopSystem[] playerLoopSystems = playerLoop.subSystemList;
playerLoopSystems[5].updateDelegate += CustomUpdate;
playerLoop.subSystemList = playerLoopSystems;```
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
Yeah, that's an option as well I guess.
Though it might be a bit confusing if you introduce new devs to the project.
I haven't read much of the conversation. All I heard is that you wanted to call the update loop in a custom way
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.
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
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
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
currently only using this: https://blog.s-schoener.com/2023-08-16-why-your-unity-project-is-slow/
Believe it varies depending on system as well as project :/
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?
Is it possible to disable domain reload when creating a new script?
you can disable automatic compilation
Is it the Auto Refresh?
yes
it works if you make the script in your IDE
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
4 seconds is nothing in unity
you should worry when you regularly get more than 30 seconds.
ScreenCapture.CaptureScreenshotToRenderTexture will write to the render texture the color buffer at the end of the final blit.
it will not cause a second rendering
I appreciate the double-check. The CPU pressure doubling the clock time of the SRP function must be coming from elsewhere.
Thanks!
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?
It must be some other audio effect. I just built a soft clipper.
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.
You want to use prim's to do what? What's the actual question
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.
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.
does anybody knows how NetworkLists work? Im using Netcode and I want the client to be able to change a list
#archived-networking or the unity multiplayer server in there. There are also docs for this
Hello everyone
. 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
Dont think this don't really an advanced issue but I'd probably start with this
https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html
Have the object in the world, when you collide, make a UI object and lerp it towards the coin counter
I was using matrix for rotation, so I thought this can be an advanced issue
also I tried WorldToScreenPoint, but it sends the object somewhere in the sky
@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).
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
it kind of looks like the world space/screen space rings are completely separate, there's a frame before and the screen space ring doesn't have the slightly yellow fresnel of the world space ones?
Is unity 6 clr ready? I have unity6 but not updated tho can anyone confirm?
so I have to create another camera that only renders rings and the player?
somehow I got it to work
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?
Pls if am publishing a game on steam for the first time using unity engine do I need to pay
yes
steam is $100
you do know google exists?
No
well, next time you have simple to answer questions, use it
which planet are you from again?
good plan, try google earth
no, google them
Which google will i use
any one of them, they all interlink
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
you are asking about Godot on a Unity server?
also this is a code channel please use the correct channel for Unity related questions
Why are always angry
It is a question
And should have said it in a polite way
Anyway let me move to godot
@dreamy basin Don't post off-topic. Read #📖┃code-of-conduct
Steam is the one that charges, not Unity or Godot.
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
You could get the frustum planes, calculate the corners from those, then do ray-triangle intersection for the sides of the frustum?
Actually not sure if you need to get the frustum planes, you can calculate corners something like this:
https://discussions.unity.com/t/calculate-camera-frustum-intersection-with-plane/148346#:~:text=the camera frustum%3F-,To get the ray of each corner you can simply use,.,-Ray bottomLeft %3D camera
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
Actually, just saw that cam has a CalculateFrustrumCorners method
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 🤦♂️
lol
Though you can find a ray-triangle intersection implementation online
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;
}
What do you need this for btw?
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
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?
its called a ternary operator
Oh thank you thank you
if true, then the first int is used. if false, then the second one is used
Just in case: this is hardly an advanced question. Probably a beginner question even.
Oh, sorry, never heard of this before to be honest!
Anything syntax related would be a beginner question.
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.
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
From the looks of it, you have encountered an error during garbage collection and it is trying to access an uninitialized memory source. You might be able to see if there are any null or invalid pointers in the source code that could be causing the ACCESS_VIOLATION
At a guess you have something in Managed Memory pointing to something in Unmanaged Memory which has not been released. Are you using ECS or Unsafe code?
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 🤔
Shader stuff will not be in managed memory so not considered by the GC
Oh, then I guess there is more than one bug which causes the AVE
most likely to be your Burst/Jobs stuff
Ok
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
Well, the good of it is that I can program in C# instead of C++, which I find more comfortable with
the problem is, you are effectively writing C++ without knowing it and it's pitfalls
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.
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.
Hmm.. for debug purposes, try rendering it with an Image component instead of SpriteRenderer? What happens?
Assuming that's a screen space overlay canvas? In this case it's not rendered by the camera. Maybe try using a screen space camera canvas?
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
What was the issue?
Image works but SpriteRenderer didnt?
(Im assuming that _renderer was a SpriteRenderer)
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
Got it working by changing the render mode of the canvas
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!
not without a custom editor.
was hoping i could avoid that. thanks for calrification
or using Odin or something like that
i will give odin a shot
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
What are you trying to achieve?
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.
what is slopeRotation though
Let's me get the angle of the slope to determine how much sonic should accelerate or decelerate
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
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;
}
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
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;
if you're actually using a rigidbody here, you'll get acceleration from the slope automatically - but I thought you were doing a home-grown solution
it's a kinematic rigidbody so yeah it's home-grown
velocity won't do anytthing then
oh unless it's a 2d rigidbody
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
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...
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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.
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...
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.
Ohh that's a good idea! I didn't think about that. But with this solution, will the application of force be continuous? When going from one state to another, won't we feel that the application of force has been interrupted for a short moment because of the change of state? I'm inclined to say no, as I use AddForce with VelocityChange, but I'd rather be sure.
The change of state is made on 1 frame hence making it continuous.
There is no moment where you are no longer in state.
Yes, I agree about the inheritance, I had something like that when I was trying to apply another solution to my problem
Yes, I really want to add extra functionality based on the character's state. That's why I want a defined state. And it will make my code cleaner.
Ok undesstood, I wasn't sure about that 1 frame . Thank you for the clarification. And since we're never outside a state as you say, your previous statement makes more sense.
Thank you very much for your help, @dusty wigeon . I'm going to try and implement what you've just suggested. 😁
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)
I don't think so. Are TComp1 and TComp2 used by Group<>, or they are unused and only there for ICondition<>?
what does time.deltatime do?
Yeah, they are found/gotten inside of Group<> and then a method invokes a method in ICondition and passes it to the method as arguments.
!docs
This is not a question suitable to #archived-code-advanced
sorry
I was going to suggest if TComp1/TComp2 weren't used, then add a non generic ICondition, but welp.
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()
foreach doesn't allocate for arrays or lists iirc
I have a function that takes an IEnumerator<T> instead of a concrete Array or List
Span?
And that does seem to be allocating, even if the concrete type is one of those
Does Span<T> allocate if I call GetEnumerator?
Have you considered IReadonlyList<T> instead?
Let me test it then
and not using foreach
I can try that
Saying that it's weird is like C# Stockholm Syndrome, plenty of other PLs have the ability to pass around a slice
C# has span
Right, let me try that
:/
it works
Great, without copying?
array implements that interface
Oh great
why would it copy
Not talking about passing around a span, talking about doing GetEnumerator manually and then iterating over it
I'm just using a foreach which invokes it automatically, I was just referring to the thing that's actually allocating
Ah sorry got confused then 😅
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 :/
Can't you just start your for loop at the place you want?
what's wrong with seeing the whole array
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
Just create a struct which contains the list and the length?
YOu could use System.Range no?
var slice1 = array[2..^3];
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.
keep reading
Yeah, this looks promising
Oh this is interesting
I didn't know C# added this... it's been a while...
Dudes that develops his game, please add udpate
This would be great if I could make it polymorphic on the backing collection
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
Yes the issue is getting an IReadOnlyList
A bunch of these probably have to do with that the runtime is still net fx
Let me read the docs because other than calling Take() I didn't find a way to specify a range
How so
ArraySegment<T> is the closest thing I've found
I read somewhere that GetEnumerator won't allocate if the underlying type is concrete, but not sure
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?
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)
I didn't bother implementing IEnumerator but should work as Praetor posted
Or did you have it somewhere?
I think we both whipped them up lol
Nice
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!
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
Why does that not work?
Compiler complains about the argument type
Oh
I misread the error
What's the actual error?
/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
Whats the up and downside of NonAlloc versions? Just curious, why its not always using nonalloc
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
But the physics methods are actually doing this behind the scene, as they might not know, how big the array is. Or are they just passing a huge array to get around this?
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
Ah, okay. Got it. Interesting topic I had not touched yet. Thanks for clarification 🙂
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
the question, to me, seemed more like a "why ever use OverlapSphere when OverlapSphereNonAlloc exists"
instead of NonAlloc vs physics messages
Oh if that's the question, the only answer to me seems to be convenience
Would be there an implementation of slang ( formerly known as spark) for shader graph/ neural rendering
https://developer.nvidia.com/blog/differentiable-slang-example-applications/
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.
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
I usually prefer to manually unload and load entity, but you can easily use Newtonsoft Json to simply deserialized on an already created object effectively removing any "translation step".
https://www.newtonsoft.com/JSON/help/html/PopulateObject.htm
If your object are not Monobehaviour, you can even make it create them.
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()".
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??
Anyone ?
Some basic suggestions like make sure dev mode is off, enable texture compression, etc. But I would probably start by inspecting the build to see what's taking up space: https://docs.unity3d.com/Packages/com.unity.build-report-inspector@0.1/manual/index.html
If you don't start with the build report, you're kind of guessing at what it could be
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?
Check the size of the code.
essentially what i wanted was to have some static methods in the interface
there isn't much of answer except "wait" unfortunately 😔 you could maybe look into code generation depending on what you're trying to do
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
Not always, but quite often this is caused by textures. What are your compression settings and are you using power of 2/multiple of 4 dimensions?
Hmm, is it related to my issue ?
Pretty sure they meant to reply to @fossil pollen
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...
@earnest ether Don't cross-post
I'm not sure if this is animation or code related. Maybe both?
It's a code question when you post code. In any case, pick one one channel.
I did not post code, I'm asking if anyone has any ideas. I didn't know it's illegal!
Read #📖┃code-of-conduct
Such a warm welcome! Thanks, no need to. I'm out
Has anyone here updated facepunch steamworks and had their servers no longer advertised because heartbeat became obsolete?
Does Unity includes System.Net.WebSockets ?
Sorry - replied to the wrong person
Some basic suggestions like make sure dev mode is off, enable texture compression, etc. But I would probably start by inspecting the build to see what's taking up space: https://docs.unity3d.com/Packages/com.unity.build-report-inspector@0.1/manual/index.html
If you don't start with the build report, you're kind of guessing at what it could be
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
What you describe range from a couple of minutes to a couple of hours. Nothing really worth showing off to anybody.
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
thanks, its supposed to be a collage of semi-to-advanced things. i came to ask for more advanced topics precisesly to find to some better ideas.
From experience, and I do work in a professional environment, the best you can get is by following official Unity course and Unity EBook. The rest should be standard C#/coding reference.
Link to the EBook please?
I do not think what you are describing are particularly good element for a portfolio. If you are making game, you should have game in your portfolio.
im a college student trying to help showcase other college students into advanced topics by giving them weekly challenges to grow.
I was also reccommended by a couple of my contacts nearby that micro projects showing off a particular exploration would showcase a comprehension and good usage of common ro advanced topics.
Do that in a concrete context, not an abstract one.
By example,
- Make them create a pong game were you need to make communication between scene.
- Make them create a simple space ship game were you ask them to do pooling for their projectile.
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.
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
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.
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...
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,
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)
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.
In practice, hash functions, sorting algorithms, custom random number and even multithreading are not used though.
can you list some things that are then? if i can focus our groups efforts, we can apply them in the appropriate ways.
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.
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.
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
this isnt really an advanced issue at all, but you should probably specify what you mean or what you're hoping to achieve. its not really clear what you'd want to use a state machine for. these seem like completely unrelated scripts rather than states you'd be in.
What I do is have a centralized component on the character that runs the states. Each state has a mask that defines which bodyparts it occupies.
This way you can, for example, not reload your gun while simultaneously using your hands to open a door, but you can reload while kicking/breaching a door.
But this might not be what you are asking, it's a bit vague.
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
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
yeah true, i was debating if i needed the ability to be a component or not which was the reasoning behind it not being monobehaviour. but you are right then i would have access to all of that which probably would make it easier
thanks, ill have a look at this
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
nice, thank you so much this is gonna help a lot 
Hello, anyone know how to get RawImage component from ImageButton prefabs?
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? 🙃
in a build they reset automatically, SO's are immutable in a build. In the Editor you need to reset them manually
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..
Thanks @dusty wigeon
Make a script with a method and attach it to the object. #💻┃code-beginner
no, i mean to add a method into GameObject sealed class
and have it appear in this ui
You can do extension methods but I don’t think they’ll appear as unity events
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;
}
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
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
It should not be really hard if you were on desktop.
If you are on browser, you should look with each and individual browser API.
Any way, I do not think it really is worth.
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)
It is kinda what I would expect.
i'm worried users might get clicks when they don't intend to and miss clicks when they intend to
You could always use 500ms as it seem to be the default value
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
0.2s seem to be a lot though.
A lot..? You mean a short window?
It is almost the expect reaction time.
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
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
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));
Probably different color spaces (linear vs gamma)
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?
are you referencing theFocusedItem before you assign it to something..?
meant to reply
Yeah..
forgot about that actually
I will make a method to fetch the item instead of referencing the property and it should work
thanks
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.
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?
i don't think it's officially documented but you should be able to make use of cecil from editor assemblies, NGO is open source so looking at how they use it there might be a good starting point
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
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?
copy x to a local variable inside the loop
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
Lambda variable capture
This is a classic case
x goes in the lamdbas by reference, not as a copy
Ah, this is my first time experiencing that lol
Thanks to you both! It works how I want now
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?
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?
Can you elaborate on that? I'm having hard time understanding what exactly you mean.
Yeah, so if I have an Image, say 150x200 and its scaled on a canvas so that it is no longer its native size, how could I get the rendered size, considering it uses the Preserve Aspect image option. (Using the RectTransform, doesn't account for the preserved aspect obviously)
there isn't an exposed method, but look at UI Image's OnPopulateMesh and specifically GenerateSimpleSprite, GenerateSprite, and GenerateFilledSprite
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
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?
Is it not just a matter of before and after that assignment?
No. It sets to 0 above it so it's 0 the frame before. Stepping over I see the value change
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
I did so in the watch, all seemed correct
Having it pinned in the watch tab is a bit sus. We don't know what you have pinned there. Does it have the same value in "local"?
It could as well be a class field with the same name.
I hovered over it to see the Vale as well and I couldn't see anywhere else a similar variable used. I thought to check that as well
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)
Could Unity NativeArray work?
I don't know if it is blittable. I mean, if it works with interoperability
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#.
I'm using unsafe. I mean, the code is working properly and compiles on Mono. It just takes forever to compile with IL2CPP
Forever = it never compiles
I've mentioned the inlined arrays because I suppose this could be causing IL2CPP some trouble
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.
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
How big are these structs, in bytes? And how many fields?
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
More than 1000?
Quite possible
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
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;
}
}
}
Now you got me, I did not know Unity accepts these
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.
I will try modifying the transpiler to generate it using fixed buffers
Fixed buffer only works with primitives, though, not custom structs.
Stupid question: This works with Unity, right? lol
Yes, I've used it in Unity and with IL2CPP.
Ah, well, that might be an issue, but I can check it at transpile time
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.
Tysm. Gonna try the fixed stuff and will let you know if it works
But at least the code is a bit tidier now 😌
Do you recognize the conv_qtmn being from your code? IL2CPP generated truncated class names based on the originals.
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
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?
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
I think that part might be random and only conv is the truncated start of a class name.
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.
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
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.
this is extremely simple, it's just pixel manipulation in an image. Imagine you were doing it in a image editing program
You can just piece together multiple sprite renderers to get this look. You may need to be a bit creative with placing certain items, but this is how most 2D games would do something like this. That's most likely how this game does it. But it sounds like you don't just want to render it on screen, you want a single image of everything composited together, is that right?
A single Texture2D, that is to say.
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
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.
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
Yes.
perfect
thanks, i'll probably come back if i need some other help, thanks for the info, appreciate it
@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
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")
can you use a normalized value probably?
https://docs.unity3d.com/ScriptReference/Input-mouseScrollDelta.html This just says "it will need to be adjusted".. What do you mean by a normalized value..?
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
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
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)
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.
usually with these kinds of problems I add a sensitivity slider to the game settings so users can set it themselves
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
You could do a little onboarding, are you on trackpad or using mouse too.
I like the throttling approach
you'd be surprised, I find kids are more likely to dive into setting than 'adults' are
But if you want to fully automate it, the "throttling" might be the one for you.
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
Just wondering, is the new input system an option for you?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
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
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
I am quite sure at some point, you just get the mouseposition, right? thats the only part that would change
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
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
the zoom/tilt is already accelerated/blended with cinemachine
@sage radish I managed to compile that code. It takes just 50min 
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
It is more unity related stuff, rather than C#, as it has it's own compilation toolchain. And they don't reveal how it works internally, unless you have an enterprise license. If you're asking about a regular C# build(not unity related), it should be pretty simple with just dot net sdk I think.
I mean, since I already have .csproj in the root of my project in order to compile DLL output for the resulting game
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
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.
That is precisely what I am aiming at
I just dont know what I need to compile it from CLI and preferably from a portable folder as well (without global installers)
you just can't compile a unity project into an executable without the editor (by any practical means)
the .NET sdk
I dont ask for that, I just need to compile the DLL
Which version should I use? If I target latest Unity 6 version
I tried to understand all of the compatibility stuff, but I just couldnt XD
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
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
not sure what you mean by that.
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
i'm not even sure if thats allowed 😉
So, you mean that .NET SDK wont be able to compile Assembly-CSharp.csproj on its own?
i think you can't legally use the .dll without a unity install.
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.
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
What are you using the dll for then, if not for building the game?
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
Soooo... you say .NET SDK is the answer to the above?
What's the high level goal, patching the game for faster iteration on actual devices, or something else?
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
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
@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
alr thanks
Sorry!
Either way, by that I mean having the enemy movement happen through detecting the player and obstacles and assigning weights accordingly to choose a direction. Using this rather than baking in navmesh to also avoid other enemies and try to create different movement patterns
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.
"editor script" = ? Make sure this is a plain old runtime script
What is your camera far clip plane set to?
