#archived-code-advanced
1 messages · Page 25 of 1
I understand its not really used together, but I want to be able to run code, but have it not hold the frame.
The coroutines aspect I'm using to allow for multi-frame processing while Async I was just trying to use for semi-parallelisation.
you are not sure when you are accessing things on the main thread versus a background thread
Task loadTrackingData = Task.Run((() => { _trackingDataContainer = (inputTrackingData == null) ? null : JsonUtility.FromJson<SessionTrajectoryDataContainer>(inputTrackingData.text); }));
for example, here you try to use inputTrackingData.text on what you think is a background thread. if it's not the main thread, this will throw an exception
but you didn't od it right, so you ate exceptions
and you don't see them
so there are multiple cascading errors @abstract hill i am sorry
Ah okay, so it is throwing errors then. Will UniTask solve this for the purpose I am trying to do? (This being to start the code running but not hold the frame?)
void Start() {
ProcessInputs().Forget();
}
public async UniTask ProcessInputs() {
var inputTrackingDataText = inputTrackingData.text;
var inputEventDatatext = inputEventData.text;
await UniTask.SwitchToThreadPool();
// tasks are not threads.
_trackingDataContainer = JsonUtility.FromJson<SessionTrajectoryDataContainer>(inputTrackingDataText);
_eventDataContainer = JsonUtility.FromJson<SessionEventDataContainer>(inputEventDataText);
await UniTask.SwitchToMainThread();
Save();
}
here is an example with unitask
imo, you shouldn't read and write to plain object fields from other threads, but you can
@abstract hill is this hlepful?
Will UniTask solve this for the purpose I am trying to do?
yes
Ill have a quick read, thank you
plain async on unity is flawed
it won't do what you expect it to do
the way you were using coroutines is also flawed
I'm not sure I understand exactly what is happening in the code, is the await UniTask.SwitchingToThreadPool(); a stand in for the block of code below it as a task?
no
it is a real method in UniTask
because as the comment says
@abstract hill "tasks are not threads"
@abstract hill does that make sense?
it does exactly what it says
it really will "switch to the thread pool"
and then the code below it will execute on the thread pool
isn't that nice?
Oh, okay, that makes more sense then. I assume it will automatically assign the work from the JsonUtility code to a new thread and run that in parrallel then?
sort of yes
it doesn't create a new thread, and the C# thread pool threads, like most threads, runs in parallel to the main thread
Gotcha
Does the pool seperate the work evenily, or is all that is below the Switch function get processed on one thread?
the two deserializations will happen one after another on that thread pool thread. if you want to deserialize in parallel, use UniTask.WhenAll, and author a deserialize async method. however, it is best to leave it the way it is.
you are overoptimizing
trust me, if you couldn't do this right the first time
I am, sorry I just want to make sure I understand is all xD
you will not do both deserializations on separate threads correctly either
it is indeed running one after another, exactly like it is written
it isn't syntactic sugar
the reason it works the way it does is because Tasks Are Not Threads
Yeah
tasks can run on any thread, parts of tasks can run on other threads, or many threads, or no threads at all.
Last question then, since the await returns below it returns back to main, I assume this is all still happening inside a single frame still though? I can see on the git repo that there are functions to yeild and move to the nextframe, this is kind of what I am after, what would you suggest to be the way to do this?
is all still happening inside a single frame still though?
why would you assume that?
the code after the switch to the thread pool runs on the thread pool
i think you are trying to translate what you are reading into Task.Run
forget about Task.Run
forget it ever existed
just read exactly what it does
it's like english
The assumption comes from the await, SwitchToMain. since its awaiting, I am imageining that the main thread is haulting waiting for the code from the ThreadPool to run, if that is not the case then this works fine for me
why would it do that
you are on the thread pool, it deserializes, time has past
you could have rendered 1, or 100, or 0 frames since beginning to deserialize
why would the main thread halt? you didn't ask it to anywhere
someday you will understand. Tasks Are Not Threads.
you asked to switch to the main thread. await is sort of syntactic sugar
Okay thank you, this sounds like it is the solution I will just need to get my head around it a bit better.
Ill give it a go to get this working, sorry for if I'm being a bit dense xD
Thank you
you don't want to use yield
or wait for frame
you don't need to
do you see why?
i am calling SwitchToMainThread because Save() accesses data on unity objects
which you should only do on the main thread
not because i'm trying to wait
So final question then, just to make sure I have my head around this. Does the entire function operate outside of the frame or only the part below SwitchingToThreadPool?
Again sorry if I'm being a bit dense, just tyring to get my head around what you are saying and the syntax of ti
everything on the main thread runs "inside" the frame
everything that is not on the main thread runs "outside of the frame"
await UniTask.SwitchToMainThread() itself waits on the thread it is being executed on, which happens to be the thread pool.
the way it actually works is, it schedules the next part of the task to run on some other queue, and the thread that deals with SwitchToMainThread is the main thread. there is a monobehaviour that reads that queue in a "pre" Update that runs on the main thread (as any unity player loop code does)
I can't seem to build my game into a standalone player; when I try, I get a linker error (Fatal error in Unity CIL Linker). Details in this forum thread. https://forum.unity.com/threads/fatal-error-in-unity-cil-linker-failed-to-resolve-assembly-nunit-framework.1354511/ Any suggestions?
await doesn't necessarily mean there is a thread being blocked
i think you have to ticket it
however, based on this error
you accidentally referenced a test assembly / editor assembly in your runtime assemblies
Ah brilliant, I think I understand this now. Thank you!
Interesting. I hadn't considered that. Thanks for the tip, I'll check it out.
This tip worked. You just saved me days of aggravation. Thank you. (The lesson here is to double-check your asmdef's #define constraints.)
What do you suggest?
I want to create a procedural map like oxygen not included but it is 3d.
3d dungeon generator? room generator?
Delaunay triangulation graph ( Bowyer-Watson algorithm), minimum spanning tree (MST)
Suppose only place items and materials in voxels under the ground
3d tiles or is it a game that plays in 3d space?
3d tile
3d voxel game
and I would like to put some items and materials under the ground
Oxygen not included only uses 2d tile to check if an object (buildings, engines, etc.) can be placed or not in the environment, right?
It is not a tile game?
ONI uses a variation of marching squares, in 3d you’d use marching cubes. You can paint those in a 2d tilemap if you make a custom tile type that translates the 2d Info into 2.5d voxel rendering (marching cubes in a 1-tile thick plane)
I don’t know a readymade asset/package that does it out of the box
If you do it without unity’s tilemap you probably need to make a level editor too
So, in ONI, tiles are not predefined and the env is not created by concatenating them
marching cubes, OK, thanks
The way they are connected together is called marching squares, it uses a few predefined tiles and makes somewhat smooth looking connections based on a few simple rules
almost all 2d games use that in some way or other
Yes, I know marching square algorithm
but mind you it’s not pure marching squares, there is rng and some UV trickery involved too
that’s just a triangulation method
you could simply use the implementation in triangle.Net
The first tri is simply any random tri, large enough that all vertices fit into it
Elaborate it
No, it can cause problems.
If some points inside and the triangle vertices are collinear or close to collinear
a really nice implementation of it is rather complex, you can look at this one that is quite good: https://github.com/wo80/Triangle.NET/blob/f70be6a937c4c447b4cee05505d7ee2b75d68e62/src/Triangle/Mesh.cs#L548
C# / .NET version of Jonathan Shewchuk's Triangle mesh generator. - Triangle.NET/Mesh.cs at f70be6a937c4c447b4cee05505d7ee2b75d68e62 · wo80/Triangle.NET
and the code for getting the bounding triangle https://github.com/wo80/Triangle.NET/blob/f70be6a937c4c447b4cee05505d7ee2b75d68e62/src/Triangle/Meshing/Algorithm/Incremental.cs#L64
C# / .NET version of Jonathan Shewchuk's Triangle mesh generator. - Triangle.NET/Incremental.cs at f70be6a937c4c447b4cee05505d7ee2b75d68e62 · wo80/Triangle.NET
@compact ingot thanks
To implement Tile-Based Atmospherics spreading like what exists in ONI, it is not as simple as spreading some fraction of it to adjacent tiles
Fluid simulation in Tiles
Because, each tile has a capacity
its still some sort of cellular automaton (not fluid simulation at all), it just takes molecular mass + pressure (gas), conductivity (heat/germs(?)) and capacity (fluids) into account when it decides where to spread
So, it is simple, 🙂 Perfect
cellular automaton
I thought max flow algorithm
yes, very simple, but the devil is in implementing that in a way that it runs at 60fps
you probably don't need to update the sim every frame
just put it into a coroutine and update 64 x 64 tile blocks at a time... or whatever suits your game
yes
ONI is awesome. I love it
Hi, is there a way to AddComponent in an editor script? I can't believe how hard it is to just have a button that'll add a specific component for you OnInspectorGUI.
^ This was answered in #↕️┃editor-extensions
Hi guys,
I'm looking to do some CI around my project.
Here's the goal (manual steps I'm currently doing):
-Building unity project
-Use the generated DLLs
-create a unity package with those dll and a demo scene.
What's the best way to automate this process ? I don't think Unity Cloud Build has enough flexibility (I might be wrong).
I've been happy with JetBrains TeamCity. It has pretty good Unity support. I've seen others using Jenkins for Unity CI, but I don't have any experience with that. If you want something cloud based, I've seen people using GitHub Actions for bundling Unity packages (UPM packages, that is).
Thanks! I will look at those options
is it possible to create a UI padding script like the ones seen in the layoutgroup components?
if so, how could it be done?
you can use a standard rect transform to define padding
of course 😅 thanks, that saves a bunch of my time
I've been getting into fluid simulations recently and I'm interested in the different approaches to solving the simulations. I'm aware of particle based solutions as well as some other "group" of solutions that use fourier transforms/trochoidal waves to simulate fluids (via mesh deformation?) just wondering what the latter version would be called, and what other solutions are out there in terms of fluid simulation
you mean flow simulation with actual fluid dynamics or simulation of a water surface like an ocean or a river?
those would be very different
you need to define the goal of the sim
its way too expensive to do generically
so any approach is really about trickery to achieve a specific goal in a specific use case, for generic sim there are plenty of research papers but those are useless in a game
for surfaces the gerstner wave (trochoidal) is a very good approach
for fast sim of surface water flow you can use cellular automata, works in 3d too but it gets expesive quickly if you go too deep into 3d voxels
can you elaborate on this a little?
do you know what a celluar automaton is?
my understanding is that cells have rules based on how many adjacent cells are "alive", like the game of life?
but outside of that I know close to nothing
more or less, yes
so you define a rule that makes a cell behave like a water flow
it doesnt have to be binary, you can implement all kinds of stuff like viscosity, surface gradient or pressure
and if you run that sim you get something that looks similar to a liquid flowing over a surface
water in minecraft or oxygen not included works that way (probably every other game with flowing water also works like this)
A video showing off the new module for MicroSplat, which adds dynamic streams of water and lava which flow down your terrain from emission points, or can be painted onto your terrain.
Anyone can help me with Netcode? I am working on inventory system and I used ScriptableObject for individual items. So my inventory is basically List of SO. After making everything work I struggle with syncing that list with clients. I know that NetworkVariable and NetworkList exists but those don't work with SO. Is there a way to sync List of SO or do I need to switch from using SO to structs?
Yeah, I could just use List that has id and amount. But still hoped that I could use SO directly
So is there a way to sync stuff without it being NetworkVariable or NetworkList?
Your problem is having "mutable SO"
They are asset and they are static, it does not make sense to send then and replicate over wire
I used them as item database so if there is itemdrop I can just drag it into inspector and it has every info about that drop. But I guess that's excessive through network.
Does anyone know if the api AudioSampleProvider.ConsumeSampleFrames provides samples array for multiple channels in sequential(00001111) or alternate(01010101) order?
99% sure it is alternate. At least on C++ side, it is. This is the channel order L-R-C-LFE-Lextend-Rextend-Lsurround-Rsurround
Thanks, it is possible to get documentation on this?
On how to use AudioSampleProvider or ConsumeSampleFrames?
@rapid osprey On ConsumeSampleFrames please
ConsumeSampleFrames will write into your NativeArray the sample frames in alternate order. It returns how many sample frames were written into the buffer. But I suppose there is something specific you would like to know?
The frame will be buffer inside the SampleProvider at the decoder speed. So it is possible there is no samples in the SampleProvider.
Can anyone help me convert URP shader code to HDRP? Specifically I want to use TransformWorldToShadowCoord(float3) from URP - which is now EvalShadow_WorldToShadow(HDShadowData, float3, bool) but I'm not sure how I set the HDShadowData
Hi all! I have an issue I would appreciate some input on.
For our project I'm trying to improve our process in how we are dealing with/setting up dependencies between objects. For example, for our event bus / messaging system I'd like to:
- decouple the objects processing events from those objects/systems generating them (i.e.: event processors don't need to know how to register themselves, that is done for them)
- remove the burden of managing these dependencies from whoever sets these objects up in the editor (again, dependencies should be connected automatically)
- do as much of that as I can at edit/build time, not at runtime / on initialisation
As a solution I was thinking about either generating one or more ScriptableObjects per scene, or a GameObject in the scene, that serialises those dependencies between objects and automatically updates whenever something changes. However, I don't know if that would be best done from an Editor script, some kind of validation pass (like Odin Validator) or just a GameObject in the scene that updates in the editor and reacts to EditorSceneManager.sceneSaving.
Has anybody done something like this before or has some input?
this is screaming for a DI framework - I've been eyeing up https://github.com/hadashiA/VContainer recently that might be what you're looking for, though I can't say I have personal experience using this specific package yet
Hmm, interesting, I'll have a look at it. Though I'm not sure if I want to introduce to much complexity with a whole package. I'm more just intending to "bake" some dependencies at build time.
Also, looking at it, this would happening at runtime, right?
- the decoupling of processors from event sources is done by your message bus, if not, why are you using a message bus?
- dependencies can be discovered automatically by components via suitable architecture, DI frameworks is one approach. A FindObject or OnValidate can do similar things too, odin validator can check for correct setup
It all depends on how much of that stuff is facing editor users vs code users
i'd be careful with DI frameworks as they can easily solve the original problem but cause new ones (hidden complexity) that is very hard to trace and manage
in any case if you build a complex system on top of a framework all notions of stuff remaining easy to replace/change go out the window if that change isnt specifically supported by that framework
- the decoupling of processors from event sources is done by your message bus, if not, why are you using a message bus?
Yes, exactly. But additionally, I feel like processors also don't really need to know how to register themselves with the message bus. If something else collects them and adds them to a list to emit events to, that should work fine enough.
- dependencies can be discovered automatically by components via suitable architecture
Do you have a suggestion about concrete implementation starting points there? That's the one I'm leaning towards
generally patterns and frameworks that fix issues in OOP are often worse than switching to a less OOP style of coding
- on registering: this is ofc possible but wouldn't you think that this system would be irrationally complex for the little benefit it provides
- DI: i'd do this in an ad-hoc way without building a generalized system, i'd rather establish conventions and patterns for everyone to use, then when mature and proven, turn those conventions gently into a generalized system
Yeah, I feel the same way. I wish it was easier/more performant to collect objects DOTS-style without needing to use all other faff that comes with DOTS authoring.
Yes, exactly. But additionally, I feel like processors also don't really need to know how to register themselves with the message bus.
What is the process of registering a processor to your message bus? You make it sound like it requires a lot of work or dependencies that you want to avoid.
you can use DOP without DOTS, its just a principle... if you ignore the performance aspect it can be a revelation in terms of architectural flexibility
yes, though what's your reason for opposing dependency resolution at runtime?
you can certainly write your own editor scripts to bake these and assign references, but in practice it will be largely treading the same ground and writing your own DI framework on top of the Unity serialization framework and wouldn't be without its own complexities and issues
the benefit is you get to write exactly for your use-case and keep it truly simple and intuitive for your purpose, which may be preferable for your project
if you work in a large team with predictable workflows and certain issues in that workflow that are predictable, i'd maybe build the whole thing with a focus on that, facilitating that workflow better, provide checks and automation that eliminates errors (top down)... this may be easier to change than a complicated/implicit approach based on resolver/discovery logic (bottom up)
It's not really a lot of work, it's more just that if event processors are registering themselves, then it kind of also puts the burden of managing the lifetime of that registration on them, which I'd much rather have the message bus itself or another appropriate system manage.
you can make messages/registrations disposable, then the system/bus can manage lifetime and subs are forced to respect it
tbh, if you want a perfectly safe system that "fixes user error" you eventually end up with the realization that you need an interpreted language and/or sacrifice all performance
it might be good to make the system simple, accept mistakes, make them easy and quick to discover and easy to fix because the system is simple enough, the API is clear and error messages are helpful
if you have a complex system that only a few people in the team understand you will potentially create a dependency on those people for simple fixes and for improvements of the system
also if that system doesn't work close to perfectly or is a bit finnicky to set up and use, then people will hate it 😄
Hmm, you're right. I guess I'll just start simple and improve it when needed.
Thx all for the input!
can i ask what specifically you perceive as the constraint/bottleneck to your team/org's productivity?
We are quite a small indie team and are just now coming out of the prototyping phase. So, things are still very scrappy. What I noticed is that too much time gets wasted during the setup of objects/prefabs in the editor, because there are still too many things that one needs to remember to connect correctly. We already try to alleviate some of that with validation, but are not too far yet with automating setting up object structures or connections between dependencies. Main goal is to up the speed at which we are able to create content.
Is there a way to minimize the effect of lag during a coroutine? As operations sometimes go out-of-sync when fps drops, especially in an unoptimized editor scenario
I tried to use math a predict such behaviour to avoid several operations that supposed to stagger a bit gets fired during the same frame but that adds strain to the system and ripple further
what goes out of sync? What kind of operation are we talking about?
And by "lag" I assume you mean framerate hitches/drops?
Like spawn something then yield return wait for seconds 0.05 and spawn another
When fps drops, two of then might be spawned without the interval
Right now I have to write another script that handles delayed spawn which interpolates the behavior on a mirrored instance, but that just makes it lag more
I noticed is that too much time gets wasted during the setup of objects/prefabs in the editor, because there are still too many things that one needs to remember to connect correctly.
you can take an approach like
class Patrol : MonoBehaviour {
public Transform[] patrolPoints = new Transform[0];
public CharacterController characterController;
void Start() {
if (patrolPoints.length == 0) {
// setup default patrol points
var point1 = new GameObject();
var point2 = new GameObject();
point2.transform.position = transform.position + Vector3.right;
patrolPoints = new [] {point1, point2};
}
if (!characterController) {
// find component
characterController = GetComponent<CharacterController>();
}
StartCoroutine(Patrol());
}
IEnumerator Patrol() {
while (gameObject) {
// implement a patrol
characterController.Move ...
yield return null;
}
}
}
in other words do a bunch of setup in the component
for our event bus / messaging system I'd like to:
you don't need one of these
decouple the objects processing events from those objects/systems generating them (i.e.: event processors don't need to know how to register themselves, that is done for them)
really depends what game you are making. some games are coupled.
- remove the burden of managing these dependencies from whoever sets these objects up in the editor (again, dependencies should be connected automatically)
i've got bad news for you. you cannot turn someone who doesn't want to learn how to use Unity into someone who knows how to use Unity
As a solution I was thinking about either generating one or more ScriptableObjects per scene
no.
"bake" some dependencies at build time.
if you cannot drag and drop stuff into slots, you are not going to be able to use a DI framework
Whoa there, you've pinged them 6 times already
Either use one long message or turn it off after the first
@tawny otter it sounds like you are suffering from scenitis. everything you are describing sounds like "We have a bajillion scenes and it sucks." the simplest solution is do not use scenes. use prefabs instead wherever you are using scenes, and author the light 20 lines of code you need to do level loading with prefabs
And that makes 7
you could yield frames rather than seconds if your only restriction is waiting for enough update cycles, or better yield another routine that will ensure the object is created properly before continuing with the original routine - you can yield other IEnumerators in an IEnumerator and it will await as you might intuitively expect
if you want two scripts to run something at the same time
script1.Call();
script2.Call();
don't overthink this.
you cannot decouple your game the way you think you can. WaitForSeconds isn't going to "sync" ever
sounded like he's trying to do the opposite, make calls that don't happen at the same time, but will run in order with sufficient space between them
Thats what I tried to do as an alternative, as yeah, waitforseconds never comes out exact. But if theres a way to ensure it does, having the extremely computational expensive interpolation won't be needed
That could be good but sometimes frames drop by a lot during unavoidable garbage collection spike or what not
Which might result in something worse than waitforseconds. I will try that out though. Also the script1 script2 method, but that means breaking the coroutine into a lot of fragments, i tried it and its very confusing
hmm it sounds like you are in a lot of trouble
it sounds like you have two spawners you want to spawn "at the same time"
in some kind of tower defense or ARPG sort of game
is that correct?
Actually no, lets say i want to spawn like 10 things 0.05s after another
computational expensive interpolation
of what exactly?
what is your game real quick
Given a really laggy scenario, you will see different gap between each ball
hmm this might be the rare case of having trouble expressing stuff in Gamese
do you mean, "Summon 10 Skeletons over 0.5s"
You can just use FixedUpdate or simulate your own "fixed" step simulation in Update
"Summon 10 balls over 0.5s"
Yeah but it's not that simple, i have different intervals and a lot more objects that I shoved inside a coroutine
If i do fixed update method it will be even more hard code
let's try expressing what you want more accurately
There's a fun little thought experiment about how do you make a machine gun that shoots 100 bullets per second when you only have 10 frames per second.
The answer is you need to spawn 10 bullets per frame, and space them out positionally within the frame as though they were spawned 10 ms apart
So basically, I just want wait 0.05s actually be 0.05s regardless of frame drop
because right now you are doing
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
which has the chance of being off from 0.5s by time of frame*10, which is a lot if it's, e.g. 20 fps, or a whole half second
yes what i am trying to illustrate
is that the user screwed up his Gamese
this is what you need:
float timer = 0;
float interval = 0.05f;
void Update() {
timer += Time.deltaTime;
while (timer < interval) {
timer -= interval;
SpawnASkeleton();
}
}```
"Shoot 100 bullets per second" is a lot better than "Shoot 1 bullet every 1/100th of a second"
Yeah so I get the frame time passed, if something bad happens and 2 spawned at the same time, the first one will be move forward for x seconds to make up for the time elapsed
do you see @gaunt zinc ?
right you need to reposition them according to "sub-frame" timing if you want it to look good
Which means in my while loop above, you'd need to track the sub frame timing. it's not that bad
just some simple math
it's already kinda being tracked by timer
i even have a thing for this for vfx graph
it was killer for my car driving thing
Yeah! I've done the same for VFX graph as well
When it comes to bezier and AI, moving it gets pretty bad
I did a graph without it and got weird fixed timestep artifacts
even at 60 fps, spawning something moving 40 m/s is going to have huge gaps
hmm but it's still linear interpolation
you are just feeding the t into a bezier function
don't overthink it!
Maybe I can make a array [0.05, 0.05, 0.05, 0.05] and add up all the seconds infront and compare to realtimesincestartup or something
To get the time difference
no
if you want things to keep working as coroutines
you will have to create a custom yield instruction, a replacement for Time.time and Time.deltaTime, and follow a lot of rules about what context you are in - like how to coordinate this across multiple coroutines
subframe timing decoupled, implemented as a coroutine yield instruction, is very hard
much harder than what PraetorBlue is showing you
however i see that you want to keep your very expressive coroutines
I am only giving a very simple example, in reality, there will be different intervals, different calls, different events which is almost impossible to do inside a update or fixed update
aimConstraint.weight = 0f; StartCoroutine(StunLock()); StartCoroutine(SpearStorm()); animator.SetTrigger(triggerHashes[8]); animator.SetTrigger(triggerHashes[0]); yield return new WaitForSeconds(7f); animator.SetTrigger(triggerHashes[6]); animator.SetTrigger(triggerHashes[0]); animator.SetBool(triggerHashes[7], true); yield return new WaitForSeconds(0.7f); GameObject[] newImpactEffect = { impacteffectsDatabase.Items[1] }; Vector3[] newTR = { Vector3.zero }; Vector3[] newScale = { new Vector3(0.8f, 0.8f, 0.8f) }; int[] noPool = { -1 }; AdvancedWarning warningScriptAim = SpawnWarning(effectsDatabase.Items[9], textureDatabase.Items[0], textureDatabase.Items[1], textureDatabase.Items[3], 15f, 30f, 4, 4, 0.8f, baseHeight); warningScriptAim.LockToObject(transform, true, true, false, false, Vector3.zero, Vector3.zero); warningScriptAim.SetAutoFlip(0, true, true); warningScriptAim.SetAim(playerHeading, true); warningScriptAim.ShowIndication(); yield return new WaitForSeconds(0.4f); AdvancedWarning warningScript = SpawnWarning(effectsDatabase.Items[11], textureDatabase.Items[4], textureDatabase.Items[5], textureDatabase.Items[6], 15f, 30f, 4, 3, 1.5f, baseHeight); warningScript.LockToObject(playerHeading.transform, true, true, false, false, Vector3.zero, Vector3.zero); warningScript.QueueFlipBoth(0, 0.12f, 0.12f, 0.2f); warningScript.transform.localScale = new Vector3(6, 6, 6); warningScript.ShowIndication(); warningScript.SetImpactEffect(newImpactEffect, noPool, newTR, newTR, newScale); yield return new WaitForSeconds(0.3f);
the real method is probably 10 times longer than this
I don't really know how to fit it inside this
Magic numbers everywhere
xd true spagetti
this should be in code beginner or something tho
im just giving example of what is there to come
Simple answer is you'll need to refactor it and implement some of the methods suggested to decouple the logic and sequencing from framerate. yield new WaitForSeconds isn't going to cut it
i am not using interpolation of any sort but all things inside are desynced when it gets laggy
Yeah probably, coroutine is simply not accurate enough
or a structure where coroutine calls for events for something else to spawn on the same frame
I will try each of the steps you all suggested and see which one works best
Thanks again!
And yes, the true problem is the dependency on frame rate and how coroutines are handled, I probably should think of another way
Hey guys! I have a coroutine set up that turns objects red when the ray from the camera is within distance and the object is standing still, but currently the objects turn red and then return to normal after the ray is no longer pointing towards it
I just want the object to stay red once it has faded to red completely
here's my code
Can anyone assist me?
if you want it to stay red, why are you setting the colour back at all? need only call it once when the condition is met
Here is the code for the Zone object
The color is not for the zone, thats just the color of the ray line
on line 78?
if (_currentHitZone) _currentHitZone.IsHit = false;
why set this to false again if it only matters once it's been hit?
perhaps the error is somewhere else, but it looks strange to me
i don't think there is anything wrong with this code. it is pretty black and white, wrap it in a while loop like @sly grove described. you don't even use Time.delta time here, the position of the object isn't set here, however if you need to use that, extrapolate the position a little bit
it's unavoidable
the core problem is you are expressing it wrong
you want to have a certain number N per long unit of time
that's how you should be thinking about this
It's an example saying how complex each step can get so it's not ideal to put inside an update loop.
A better example would be like one of those space shooter game, but the bullet is going to make like a flower pattern
When not laggy, and each bullet is fired evenly, it will make the flower alright, but when laggy, the flower comes out distorted
Whats happening in my game, is the character will play an recorded animation clip, and it will do some sort of attacks when lets say, when it raise it's hand
When the clips get long, the attacks comes out late
Also yeah it needs to also make a pattern
you don't need to use an update loop
you can keep doing this in a coroutine
I commented out this section of code and it worked, thanks
it's pretty complicated though
Yeah i forgot you can add event in animation clip...
Might try that instead
And see how good is it
I have a question. When there are multiple sources in path finding algorithm (A star), I start from a source point and if I reach another one, set g cost to zero (reset) for this node, is it enough to find the optimal path from multi source point?
private int ComputeWeight(int g, Node node, Vector3Int direction)
{
var p = node.Point + direction; // p is a neighbor of current node
if (_sourcePointSet.Contains(p))
{
return 0;
}
//...
}
var gCost = weightFunc(currentNode.GCost, currentNode, direction);
if (_openSet.TryGetValue(neighborPoint, out var neighbor))
{
if (gCost < neighbor.GCost)
{
neighbor.GCost = gCost;
neighbor.Parent = currentNode;
_openList.UpdatePriority(neighbor, neighbor.Priority);
}
}
else
{
I'm making a custom property drawer (a lil rusty at it), and I can get the scriptable object to render, but I cannot get its name underneath, it says it is a null property
am I doing something wrong?
Top is the classes, middle is output, bottom is rendering code
and the custom property drawer is for the colourSchemeSelection class
nope, doesn't seem like you can access scriptable object properties in this way
is there some kind of special affordance for multiple cameras in Built in Render Pipeline that isn't available in URP or HDRP? specifically related to how much more performant realtime reflection probes are - if i do not use the "scriptable" features of built in render pipeline, can the same (or a lot of the same) CPU work be reused for all the cameras? clearly this is not the case for HDRP, based on the timeline, and clearly there is some CPU work done for the reflection probe, but not nearly as much as HDRP or even apparently URP
my goal is to author a local multiplayer game with split screen
i would want to use URP, and i would want to reuse all the CPU work between cameras that isn't view dependent
or, even prevent using view dependent features (like depth mapping)
Yeah, every UnityEngine.Object is the start of a new SerializedObject hierarchy https://help.vertx.xyz/programming/editor-issues/serialisation/serializedobject-how-to#objects
Makes sense
does burst work with multidimensional arrays like array[,,,] read and write. no resize
Burst doesn't work with managed reference types of any kind.
thank you
multidimensional arrays are just syntax sugar for single dimensional arrays anyway, so you can accomplish what you need with NativeArray
i use multidimensional arrays as maps within maps so if i convert them array[x,y,n,d] would be really hard to do operations on and would introduce more complex math.
have a look over https://docs.unity3d.com/Packages/com.unity.collections@2.1/manual/collection-types.html
There's lots of useful collections in there like:
https://docs.unity3d.com/Packages/com.unity.collections@2.1/api/Unity.Collections.NativeHashMap-2.html
thanks.
Is there a guide for what kinda questions belong in #💻┃code-beginner and what kinda questions belong here
Hmm not really. Tacit knowledge
I'd say #💻┃code-beginner is for questions that you know somebody already has answers to, on account of it having to do with basic features that anyone uses.
#archived-code-general Is a step above that.
#archived-code-advanced Is for more specific structural, abstract, or experimental things, I would suppose.
In theory, anyway.
ty for the info
it's funny because I was just wondering that
but I think it's a pretty common thought
Hey there, not sure where else to post this, but Unity appears to freeze on Reloading script assemblies about one out of four times. Since Unity does that step 2 times for each code change, that means I can on average change two lines of code before I have to force quit and reload Unity. I do not think this is acceptable, and I'm wondering if there are any good debugging steps to figure out WHY it does that (that don't involve just deleting packages and seeing if it's better).
Like, since it freezes ( not crashes), I can't even get to a crash log, yknow?
Hey
I have a scriptable object, where I want to be able to put a script in the inspector, I found the MonoScript type which works for the inspector.
The script I put in that slot, will always inherit from an interface 'Card_Behavior'.
Problem is that when I later, in another script, reference it, I want to call a function under the Card_Behavior interface, but it isnt marked as inheriting from Card_Behavior.
Ive tried casting the variable as Card_Behavior, but that didnt work.
I once followed a Sebastian Lauge tutorial where you could make sure, in that case, T inherited from IHeapItem.
Can you do the same for the MonoScript type in the scriptable object script?
Something like the last image.
MonoScript is not a solution for anything in your game because it lives in the UnityEditor namespace and is not available in builds.
You want to use an abstract class or interface as your field type
Oh, didnt know that
But that wouldn't show up in the inspector
Just use Card_Behavior as the field type.
sure it would
did you try it?
ye
code
and the definition of Card_Behavior?
(btw C# uses PascalCase for classes by convention)
Are you using some kind of extension for it? Interface SerializeField doesn't work for me 🤔
You can use an abstract class
Unity inspector does not support interface serialization out of box afaik
Field type has to be derived from UnityEngine.Object class to drag-drop
You can use MonoBehaviour or UnityEngine.Object to accept any type, but then you need to drag-drop exact component
So maybe use GameObject reference with GetComponent
Or abstract class derived from MonoBehaviour as Praetor suggested, whichever works better
Eh I'd never use a GameObject reference with GetComponent
always reference the component directly 😉
especially if you want type enforcement in the editor
^
True 😌
Might be really stupid but what an abstract class? 🙃
It's a class that has one or more abstract methods on it, and is itself marked abstract
Im gonna go to bed now, Ill look at it tomorrow, but thanks for the help so far
There is a game I played 12 years ago, and they had a really cool cross hair
The blue circle is where my mouse is
The + is where my gun is aiming.
It helps guide you, and I want to create something like this
Does anyone know anything about how this is done?
Use a LineRenderer
generate points on an Arc between the two points using the equation for a circle
ok we get it...
i see
oh....!
So determine the distance from ship to mouse pos, then determine the position in front of the gun the same distance, and then draw a circle line between the two points
I get it, that's what I needed
Thank you!!
yep you can think if this in terms of polar coordinates too. That will make it easier to generate the points. To wit:
- the mouse pos has a radius and a theta (angle) relative to the ship
- the ship pos has a radius and a theta (angle) relative to the ship
If you interpolate both the radius and the angle smoothly between the two, you'll get a nice smooth arc like the pictures
Suppose I have an environment similar to Minecraft. And in this environment, I have a room made of blocks. How would I determine if this room is airtight?
Is there an algo for that?
Will this work for rooms of an unknown size? Players are allowed to build their own stuff, so..
Why wouldn't it?
Dunno, just asking. Good jumping off point for googling, thank you.
Right, so I think the term I'm curious about is the "queue". If the room is an unknown size, the effectively the queue is potentially infinite. Say I have a hollow sphere, and I need to know if said sphere is airtight. How long should it continue to scan before it determines that it's not airtight?
There has to be a limit to how made nodes I check, right?
nothing is infinite
in computing
but yes if the room is extremely large, you may end up using a lot of memory to do the search.
For practical purposes you should set a limit on maximum room size
I could jobify this
Although this doesn't seem speed-limited. By what you're saying, this is memory-limited
perhaps - it would require large modifications to the algorithm - perhaps some kind of spatial partitioning
well it's both
but in a practical sense you should be able to do a DFS of a few hundred to a few thousand nodes without much trouble.
Yeah, the player would be able to partition the space by using airlocks or something.
This helps a lot. Appreciate you.
you're at the start of a very long journey
rip that person’s sanity
Start from somewhere thats air and see if it can reach all other airblocks
Hi there
does anyone know a way to calculate the angle of an area corner (let's say its a 2D plane) that's facing inside the area?
like, how do I determine if the angle is facing inside or outside an area
What is best practice for conditions in a while loop in a coroutine you will be wanting to go indefinitely unless canceled externally?
Anything like checking if your application is quitting?
If you're going to check for multiple different conditions you might as well just cache the reference to stop, or assign a bool.
Okay so i think i understand the abstract modifier, at least a basic understanding. But i dont really know what i should do with it? Yesterday you guys said to create an abstract class that derives from MonoBehaviour. I dont get how thats gonna make the behavior variable show up in the inspector?
hey guys I am using this to setup the position of a tranform to use it as shooing point, I am having a problem that when the camera starts moving or when it stops it makes a jerky movement
if(Physics.Raycast(ray,out RaycastHit raycastHit, 999f,aimColliderMask)){
Vector3 CursorAimPosition = Vector3.zero;
screenCenterPoint = new Vector2(Screen.width/2f, Screen.height/2f);
Ray ray = Camera.main.ScreenPointToRay(screenCenterPoint);
CursorAimPosition = raycastHit.point;
}
Anyone know about SQLite4Unity plugin?
Hi everyone, does anyone know if the Unity JsonUntility serialiser has a file size limit?
I am using Unity to generate a large file (over several gigs), this takes just over an hour to generate. Once I try to serilaise and save it however it the editor crashes completely.
The logs give this error:
=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
I this is potentially could be something to do with threading (I was saving on a serpate thread in the first place, but this worked for smaller files), but I have since removed the threading functions this. While I am generating a new file to test without this threading code, I just wanted to check incase there is a file size limit
Ya try it with newtonsoft?
you probably ran out of memory
json is certainly not supposed to be several gigabytes in size
if you need to serialize really large data sets you need to make sure your serializer and data format can be constructed incrementally
Ill look into seperating the file up then into chunks. And saving them that way.
You should really just look into different data formats
or make multiple files
I'd rather not have to write my own file converter as the project isn't really my roll to develop, though if there is another way to save and load files while having them convert to C# classes on load then I would be intrested to see
first it'd try if Newtonsoft JSON (also called Json.NET) has the same issue
if it does you could look at LiteDB or SQLlite to store your data in a robust way (the database file is your serialized data)
alternatively try MessagePack (essentially binary json) that could reduce the file size overall and be a lot faster
do NOT use Binary Formatter (unless you like huge files, insecure code and slowness)
Ah thank you, Ill have a look into each! ^-^
what is your application?
maybe we can talk about how to store the data for how it makes sense for you
sqlite is good but it might be too slow if this is e.g. some kind of motion capture data you are saving at 100hz
or if you are going to run out of memory trying to buffer it and write it later
Hey Guys! Im trying to find the distances between one camera and multiple objects and want the camera to turn on once the object the camera is attached to is within a certain distance between it and the any one of the multiple objects
I know we can use Vector3.Distance
Wouldn't you just use a trigger collider?
🤔
The application is about the playback of player movements of a football game using AI (its for a research project) real time playback usign the AI is too slow, so isntead we opted to generate the movement using the AI outside of the real time showcase. This way we would play the hours+ worth of tracking data, generate the movements and the for each player store the location of their bones (only the necisary ones (totalling at 29 bones per player with 22 players)). This works fine for shorter clips, but with 1 hours games at 60 frames per second (which is the framerate the AI is trained to run at) the filesize is a bit insane.
System.String has a practical limit of probably around 1-2 gigabytes
so if you're trying to store a string in memory like that, it's a bad time
you'll probably want to switch to a different JSON serializer that has streaming capabilities
like Newtonsoft JSON
so you don't have to store the entire string in memory at once
I'll give it a try
Ahh ok, I have used Newtonsoft breifly before, but only in passing, is there a perticular way that it is needing to be setup to perform this save correctly?
yes use the streaming apis
Ah okay thanks, Ill have a look
that example is for deserializing but serializing is similar (just opposite)
Here's a code snippet from one of my projects:
JsonSerializer serializer = this.serializer;
using var fs = File.OpenWrite(path);
using var gs = new GZipStream(fs, CompressionMode.Compress);
using var sw = new StreamWriter(gs);
using var jw = new JsonTextWriter(sw);
serializer.Serialize(jw, Career);```
Thank you ^-^
that sounds really cool
thank you for sharing and please post a link if you guys already have a preview of this!
there are fortunately many "fast" json formats
that you can add to your ETL pipeline
doesn't ml agents have a way for this?
@abstract hill since it is bones, you can convert the JSON to FBX animations (hard) or alembic (easier) too, besides JSON, and there are built in importers in unity. runtime alembic importing works very well. it always loads alembic files at runtime, and they can be played back at any speed and pretty robustly, whereas runtime FBX you'll have to use trilib. if you already have a good JSON workflow, you can drop in replace with BSON (a binary representation of json that json.net supports already) - bson supports streamed reads of an array-of-bson documents.
@abstract hill i direct messaged you a demo of alembic with high fidelity bones and meshes playing back in real time. it's a multi-gig file running at 60fps
to do what? reading bones?
i think keiishkii means he has a separate system that reconstructs video game type animations from live action video
and right now that system writes to a JSON format
i was thinking of imitation learning 🙂 but recording and playback of movement is another beast
That is the case, its a PFNN that works somewhat simular to motion matching with trajectory generation. The idea is to have the AI determine the movements. I'm happy to post once the paper is written properly.
Thank you, Ill have a look at your link now, I might try the quick route of using JSON.Net first and then transition to BSON. After which if my collegause are happy with me continuing to work on this, I'd like to look into your suggestion of isong Alembic
cool. in principle, the technology i shared with you in that link is remotely rendered / streamed, and the backend supports accelerators like 4xA100 machines (+a graphics capable GPU). productizing the application may be some work, but a demo with live action footage being inferred into motion directly into unity is realistic
Yeah, I'm definalty intresxted in this. Thank you
good luck out there!
Thank you ^-^
Hey, I'm trying to serialize and store a quaternion and then read it and apply it to a transform. When I'm doing this, the y axis seems to get a -90 everytime. Any idea what's happening here? I thought Quaternions aren't supposed to have problems like this. Basically, in the editor I see the object's y axis rotation as 120. But when I save and then load the quaternion, the object's rotation is now 30.
show code
I'm using a serializable version of Quaternion from a Unity answer. This is the operator overload -
public static implicit operator SQuaternion(Quaternion q)
=> new SQuaternion(q.x, q.y, q.z, q.w);
Is this an okay way to copy quaternions?
https://answers.unity.com/questions/956047/serialize-quaternion-or-vector3.html Jimmy Cushnie's answer from here. Maybe I should use the original answer instead
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
show your code that isnt working
My code's in multiple files so it's not easy to show. For now, does this answer's way of having a serializable quaternion and also the operator overloads seem correct?
Whoops, turns out the problem was the rotation set on the object in the inspector by default. Code's all fine. Thanks anyway 🙂
Hey, I face a bizzare issue. I do 'OrderBy' on list with custom Comparer, basically I just compare the positions. The point is, the OrderBy looks to behaviour different on Editor and on Build. On the Editor, it doesn't invoke Compare on the same object in list, but on build app it does. When I do
{
if (x == y)
{
Debug.LogError("Same!");
}```
In the editor I didn't receive this logs but on build they appears. Do you notice something similar or have a clue what could happen here? I'm sure that I check the same things on build and on the editor.
What does that equality operator look like?
that would imply that you have the Slot in your list twice
OrderBy will never compare the same ordinal element to itself
(assuming you haven't overridden the equality operator on that type)
Hey I am trying to get ScreenToWorldPoint(Input.mousePosition) to be same on client and server with netcode for gameobjects but for some reason whenever I change windows size of host or client it adjusts only for host. So Client gets wrong coordinated. Anybody got this issue already?
I am trying to get ScreenToWorldPoint(Input.mousePosition) to be same on client and server
Can you explain what this even means or why you would want to do it?
I am making drop option from inventory. Everything works fine on host. It drops the item under my mouse when i drag it. But on client it drops off map. I tried changing window size of host and dropping it on same spot on client and when I changed either client or host window size it kept changing
e.g. (-1790.00, 232.00, 0.00) changed to (-1377.00, 174.00, 0.00) when I dropped it on client after resizing host's window
Why is the UI replicated on either side
If you're dropping something into the world, you should simply be using that world space coordinate you dropped it to
The ui stuff should never be communicated over the network
I have my inventory attached to player prefab. Whenever I call drop it get's camera of that player and calculates world position. After that I call Rpc to spawn item with those coordinates
Are you calling the RPC with the screen space coordinates though?
Sounds like you're using screen space instead of world space
you shouldn't need to do the ScreenToWorldPoint anywhere except on the machine that the object was dropped from
Yeah. I have InventoryManager on player prefab that first gets the drop position and it uses camera attached to player dropping it. Then it calls Rpc that spawns the object
Interestingly when I debug it in update after clicking with mouse it shows correct coordinates. But I can't find anything that could change it in my get coords function
I double checked it, I have no duplicated objects in the list. I use GetComponentsInChildren to override the list. I will try to make some generic example so maybe I will be able to post it here.
I actually don't have a problem with comparison, just surprised me a difference in editor vs build. I will try to check it on some more generic case and maybe I will able to provide an example with source code. My comparation looks like this ``` public int Compare(StorageSlot x, StorageSlot y)
{
if (x == y)
{
Debug.LogError("Same!");
}
var first = x.transform.localPosition;
var second = y.transform.localPosition;
if (first.y > second.y)
{
return 1;
}
if (first.y < second.y)
{
return -1;
}
else
{
if (first.z > second.z)
{
return 1;
}
else if (first.z < second.z)
{
return -1;
}
else
{
//There should not be the case when position are equal
if (first.x > second.x)
{
return 1;
}
else if (first.x < second.x)
{
return -1;
}
else
{
return 0;
}
}
}
}```
How do I either schedule a task for the main thread or run a continuation on the main thread
I was wondering if float equality was evaluating differently depending on compilation settings. Maybe you could try comparing to within an epsilon
I guessed I need to use task factory and the unity synchronization context somehow
from what context? Are you using UniTask?
Basically I get a callback from filesystem watcher that is on the wrong thread and I want to schedule the handler on the main thread
I tried await task.delay.cinfigureawait false but that was not doing it.
I'm not using unitask
I thought I had that solved for a websocket callback in a previous project once 🤔
A lot of times I just do some cheeky thing with a ConcurrentQueue
I don't want to poll
e.g.
ConcurrentQueue<something> queue = new();
void Update() {
if (queue.TryDequeue(...)) { // do something }
}```
well something on the main thread is gonna be polling
whether its your code or someone else's
That might be true
Maybe look into UniTask if you want something cleaner
But if possible is like to use the async/await abstraction over that
yeah definitely UniTask then 😄
#💻┃code-beginner and for god's sake don't post screenshots
Can some one tell me what to do how to fix it
#854851968446365696 get your IDE configured and post your code properly
and in the right channel
would be more clear with a configured IDE
Name space {unityEngine.Rendering.player}
Like that?
Is there any way to do bindless textures in unity?
Actually there is nothing wrong with a this comparasion (previously I had a bug, when a missing returning 0, when x are equal), but what makes me wonder is that when I do "the same" check, in the editor I get nothing, but on build a have a logs from it. I did some more generic check and with this piece of code, in editor I don't receive this "Same!" log error, but in a build it appears ```using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ObjectComparationTest : MonoBehaviour
{
private void Awake()
{
List<GameObject> objects = new List<GameObject>();
for (int i = 0; i < 10; i++)
{
objects.Add(new GameObject(){name = $"obj + {i}"});
}
List<GameObject> ordered = objects.OrderBy(s => s.gameObject, new ObjectPositionComparer()).ToList();
}
}
}```
ObjectPositionComparer - looks like previous
On build I have this log which not appear on editor Same! UnityEngine.Logger:Log(LogType, Object) UnityEngine.Debug:LogError(Object) SlotPositionComparer:Compare(GameObject, GameObject) System.Linq.EnumerableSorter`2:CompareKeys(Int32, Int32) System.Linq.EnumerableSorter`1:QuickSort(Int32[], Int32, Int32) System.Linq.EnumerableSorter`1:Sort(TElement[], Int32) System.Linq.<GetEnumerator>d__1:MoveNext() System.Collections.Generic.List`1:.ctor(IEnumerable`1) System.Linq.Enumerable:ToList(IEnumerable`1) ObjectComparationTest:Awake()
Well, try doing the same test but not inside of OrderBy, but just an n^2 comparison
If it's float equality shenanigans than an early false positive or negative could change the set of future comparisons
n^2 comparation looks ok, I mean, when iterating on the same collection I eventually will get this check to be true. I was able to reproduce it on a brand new Unity Project - editor vs windows build. I can put it on github or DM to you the source code and the build itself if you wish.
Sure, github works
https://github.com/kasiula03/OrderByIssue Here you go. When you will run it in the editor you will just receive one log with amount of objects, but when you will run a build from a OrderByBugBuild in the Player.log you can find "Same!" logs. Same list but different result Editor vs Build
(only with new input system)
If not using new input system you would need to use a native plugin
i can reproduce this issue, but i'm not sure if it's an issue?
the list is sorted
it does indeed compare the same element to itself
this might be related to a stable sort feature. i'm not sure.
yeah it is, I'm not sure that I can name it as bug/issue, but it's definitely bizarre behaviour.
I would like to know what exactly cause it because it gives me a hard time to find one issue before. Basically just curiosity 🙂
I doubt they guarantee any particular implementation, provided the external result is the same and it matches the algorithmic complexity.
that said I kind of doubt it's intentional, spells like an off-by-one error
So it basically nothing specific Unity related
Might be somewhere in mono, did you try il2cpp?
Yes, my main project is in il2cpp and there was my main testing resource, the second one test project is in mono
Does anybody know when Unity gonna support .NET 6.0?
At least approximately prediction?
Hey, anyone here have a cool "Savegame" system? I'm designing a refactor for my save system, (currently using playerprefs). Anyone wanna talk design?
Yeah, I have a package for that: https://github.com/IvanMurzak/Unity-Saver
Completely free, it is open source
thanks buddy, I'll take a look through. Will probably use for inspiration, but good to know I can copy sections out of it 😉
You may just install it as package and extend classes if you need. Using UPM packages is very comfortable thing
follow up to my question yesterday. I found this way to run a task on the main thread:
// remember unity task scheduler while on main thread
private readonly TaskScheduler mts = TaskScheduler.FromCurrentSynchronizationContext();
private void OnChanged(object sender, FileSystemEventArgs e)
{
// here we are on a worker thread called from a FileSystemWatcher callback
UnityEngine.Debug.Log("outside " + System.Threading.Thread.CurrentThread.ManagedThreadId);
Task.Factory.StartNew(
() =>
{
UnityEngine.Debug.Log("inside " + System.Threading.Thread.CurrentThread.ManagedThreadId);
//now on main thread
OnFileChanged(file);
},
System.Threading.CancellationToken.None,
TaskCreationOptions.None,
mts);
}
does this look like a terrible idea? UniTask is doing something else
I am guessing very late next year
unitask allows you to easily switch between tasks running on the main thread and tasks running on the threadpool
I'm hesitant to pull it in as a dependency
why?
it seems pretty intrusive and a complex codebase
I'll have to convince my team it is worth it
It's not more intrusive than whatever you're doing now
its completely optional to use it, you can keep doing what you are doing AND use it on demand
and it is by no means complex, it basically just wraps the notion of asynchronous processes into something that could be described as a domain specific language (just like LINQ captures the notion of a data query)
and it gives you access to doing all this correctly in a very robust way where all the edge cases have been considered
its also not UniRx which would be way more intrusive as it would immediately require you to change your architecture to make good use of it
tbh, if your team doesn't see a problem with how you're describing async processes in your projects rn, you can't convince them really why UniTask would be better, maybe trying to DIY a better way (based on your specific pain points) is what is necessary to really appreciate how good it is.
What are some of the best Unity vids I should watch, especially coming from Unreal? I want to level up my 3D Unity game real quick today
check out Unity Learn for courses
Hey guys I’m looking for a Senior Unity Dev to help my studio make a transition from Unreal to Unity. Anyone know a good place to hire unity mobile devs?
Not here
You can also use System.Threading.Tasks.Task if you prefer. https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=net-7.0
We are already using System Tasks a lot
So moving to unitask would be a bigger refactor
You don't have to replace everything with UniTask
Right
Btw the solution I have for the time being is inspired by this https://thomaslevesque.com/2015/11/11/explicitly-switch-to-the-ui-thread-in-an-async-method/
Async code is a great way to keep your app’s UI responsive. You can start an async operation from the UI thread, await it without blocking the UI thread, and naturally resume on the UI thread when it’s done. This is a very powerful feature, and most of the time you don’t even need to think about it; it “just works”. However, this works only if t...
This is bit old, but there is documentation and you can do something similar as UniTask
https://github.com/modesttree/Unity3dAsyncAwaitUtil
public class AsyncExample : MonoBehaviour
{
async void Start()
{
// Unity thread
await new WaitForBackgroundThread();
// Background thread
await new WaitForSeconds(1.0f); // Or WaitForUpdate
// Unity thread again
}
}
The original blog post is deleted but you can still see from Documentation folder
Is there an alternative to bindless textures in unity, since unity doesn’t support bindless textures?
Hey, how can I recreate Fez's 3D rotation mechanic in Unity?
https://docs.unity3d.com/Packages/com.unity.shadergraph@6.9/manual/Texture-2D-Array-Asset-Node.html not sure if this what ya mean...
I need a way to sample an unknown amount of different sized textures from a compute shader
and this is the node to lookup a color in one of those textures .. note the integer parameter https://docs.unity3d.com/Packages/com.unity.shadergraph@6.9/manual/Sample-Texture-2D-Array-Node.html
I don’t use shadergraph
how about google? https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/texture2darray-sample
that requires the same sized textures and the number of textures to be known at runtime
Any help?
sorry, dunno who Fez is.
Mathematics
I hope so
does anyone know how to enable nullable reference type support in just one assembly definition of a project?
... spamming #nullable enable to every files? Can't find better way to do it
yeah its what is already going on
was hoping like a css.rsp in the asmdef folder would work but no luck
Hello guys
I have a question
I have a template class like this
public abstract class ASetChatMessage<T> : MonoBehaviour
where T : AChatMessage
{
[SerializeField] protected T chatMessage;
public Sprite Avatar => chatMessage.Avatar;
...
}
public class SetChatMessageMedia : ASetChatMessage<ChatMessageMedia>;
public class SetChatMessageText : ASetChatMessage<ChatMessageText>;
AChatMessage class is also an abstract class (public class ChatMessageMedia : AChatMessage for example)
How to do that ?
private ASetChatMessage<???> a; // How??
private SetChatMessageMedia b;
a = b // How??
a.Avatar.gameObject.SetActive(false); // How??
You can't. To make this work you would need another base, abstract class that ASetChatMessage<T> inherits from
Then you'll be able to store "any deriving generic" into that variable
private ChatMessageBase a;
private SetChatMessage b;
a = b; // now valid
ChatMessageBase a;
ASetChatMessage<ChatMessageText> b = new SetChatMessageText(); // maybe valid assignment?
a = b; // valid
Extract it to the base class
Note that this comes with the caveat that you won't be able to extract protected T chatMessage to that base class as T doesn't exist there. Shouldn't pose any problems though, if you need to do operations on it from the outside (like call a method on the base class that gets its value at some point), you can make an abstract method on the base class, and directly override it in the generic base class
Okay thank you
I think I have an idea, ill try something
Can you make a nav mesh agent travel to many objects within a navmesh using SetDestination()?
By putting it in a foreach loop and setting the.new destination position at every instance of the loop
you would wait till it reaches destination then call the SetDestination with the new Destination
No, navmesh agent only saves the next destination, not a list of next destinations, do what passerby said
can just queue up destinations in a list
Yeah, why not. Just meant NavMeshAgent component doesnt do that automatically for you
Hi, I'd like to know if someone know how to deal with scene reloading with Zenject
if I modify a script when a scene is running, context get lost and everything stop working
I think there should be some way to restart the injection process
Is it possible to know by code which device are we simulating with the device simulator ? I tried SystemInfo.deviceModel but always returns my macbook name
okay must use : UnityEngine.Device.SystemInfo
Im having an odd behavior, 2 instances of the same script with lerp, update the values of the other script with no reference to each other?
How is that possible
I'm trying to store levels in json format but they end up being around 50-1000 MB in size which is a bit of an issue, is there a better way to export a class than plain text that might compress the size somewhat, and if so where do I look?
read something about POCO, is that worth investing time into? i'm just not sure what to look for other than trying to convert it all to binary or something
50-1000mb seems a bit much
How many objects are you trying to save?
Are you sure you're doing it right?
Does the unity scene file of these levels even come anywhere near this filesize?
@wary swift i have a 3D array of tiles that contain various information, and the array might be like 500*500*50. The scene doesn't contain any of that information as I'm just creating the data with programming right now, but I'm trying to create a level editor to save and load physical maps to load into the engine later.
I'm rendering the tiles on a quad only
i turned off the "pretty text" and reduced all my variables to 2-3 letters and it shaved off a lot of file size but i still think it's not entirely viable.
An array of 50050050 would be 12.5 million elements so getting file sizes like that would make sense
Are you sure you need to store that data or can it be regenerated by a some form of random function?
Leaving json for "normal" serialization is something I'd do as well
i do need to store the data, it's just information for buildings and such that are placed tile by tile, much like a minecraft level
but there are more things i can do to cull data written a lot
though i still need to get it down a bit thats why i was asking about alternate ways to export
like hex or something idk
this is a bit new to me
for example im exporting empty tiles now and they take up as much information as a placed tile, so that should reduce size by massive margins
Simple option is just to zip your json data, that should reduce file size
yeah i did think of that but i think changes in the earlier steps is warranted first 😛
Oh okay so i cant do something like this
''' foreach (var zone in zones)
{
zoneClosestToApache = GetClosestZone(zones);
GetComponent<NavMeshAgent>().SetDestination(zoneClosestToApache.position);
}
'''
I'd look into this
And as you currently have a 500x500x50 array I assume you're familiar with chunks
Using some algorithms you only need to store the block id and the chunk id and another algorithm can place/generate your blocks at the right position
Look into alternative serialization formats than JSON, off top of my head Protobuf/MessagePack/Flatbuffers.
If you want something that resembles JSON, BSON is a lot more compact.
If you must use JSON, GZip it because it's very compressible, but that's a non insignificant overhead.
Depends on the nature of your data, you can also rearrange your data structure to make it a lot more repetitive and thus compressible
But honestly don't reinvent the wheel unless none of the mentioned solutions work for you.
Can you make a nav mesh agent travel to many objects within a navmesh using SetDestination()?
By putting it in a foreach loop and setting the.new destination position at every instance of the loop
This is the code that is suppossed to take care of that
Is this for patroling?
Not really, I have a Helicopter where i want it to automatically travel to zones I have set up in my scene and reveal them when its raycast hits the invisible zones. In a sense, im building flying AI and wanted to use a navmesh
what you can do is put your loop inside a Coroutine and then after the SetDestination use a yield WaitUntil remaniningDistance < 0.1f
for example
@scenic forge thanks, no i don't need JSON it was just the first think i knew about how to use more less. thanks i'll look into these.
So something like this
IEnumerator Fly() {
NavMeshAgent agent = GetComponent<NavMeshAgent>();
foreach (var zone in zones)
{
zoneClosestToApache = GetClosestZone(zones);
agent.SetDestination(zoneClosestToApache.position);
yield return new WaitUntil(() => agent.hasPath && agent.remainingDistance < 0.1f);
}
}
Ok, ill try this out! THanks
Yep, not possible that way
Your scene should have SceneContext. The script automatically inject needed things to any GameObject of the scene when it was loaded
hey thank you for answer. my scene already has a SceneContext game object
Maybe I didn't get a point of the question in that case
You are free to Unload and Load the scene back as many times as you need. Everything gonna be fine, until you have cross scene connections
If you have cross-scenes injections, you may need to split "that" gameobjects to dedicated scene, and never Unload it.
the case is: in the editor while developing. I'm running a scene to test it. I spot a bug, so I make a change in a script WITHOUT STOPPING THE SCENE. after saving the script, normally unity do a reload and you can continue testing the scene. the problem with zenject is that when this reload happens, injection get lost and is not triggered again
Ohh, right. You won't do that with Zenject. Zenject was designed to be executed the first one in Awake method. You should stop the game, recompile code and press "PLAY" button again
This is working except that it goes to the nearest zone and just stays there
I'm assuming because it still having that zone in the list and still thinks its the nearest zone
thank you! this is very intersting!
yep...I hoped there was some workaround...I think there it is maybe
I'm gonna try Play Mode Settings
LOL...it seems that the problem is PlayMaker now... 😄
It could also be that the new path has not yet been found. try adding a yield return null before the existing yield so the frame is skipped
your model doesn' tmake sense
flatbuffers are a good choice for you. they have good unity support. it's a lot of stuff to comprehend though
public Node CreateNode(Type type)
{
Undo.RecordObject(this, $"({GetType().Name}) Create Node");
Node node = this.CreateNodeOfType(type);
nodes.Add(node);
EditorUtility.SetDirty(this);
return node;
}
public void DeleteNode(Node node)
{
Undo.RecordObject(this, $"({GetType().Name}) Delete Node");
nodes.Remove(node);
EditorUtility.SetDirty(this);
}
```Since the `Undo.RecordObject` already marks an object as dirty, as said in the `EditorUtility.SetDirty` documentation (`If you do want to support undo, you should not call SetDirty but rather use Undo.RecordObject prior to making changes to an object, since this will both mark the object as dirty`), why is it needed that I `EditorUtility.SetDirty` after adding or removing a node from the list? This topic is somewhat confusing to me.
private IEnumerator Fly()
{
NavMeshAgent agent = GetComponent<NavMeshAgent>();
foreach (var zone in zones)
{
if(!zone.GetComponent<Zone>().hasBeenScanned)
{
Debug.Log("Moving to Zone");
zoneClosestToApache = GetClosestZone(zones);
agent.SetDestination(zoneClosestToApache.position);
yield return null;
yield return new WaitUntil(() => agent.hasPath && agent.remainingDistance < 0.1f);
}
}
}
Like this?
yes
Ok I added the if statement but ill remove it and see if it works without that
there are lots of edge cases which can occur with SetDestination so I would check out the documentation to make sure you are covering them all
Yeah even that didnt work
I would not recommend to use the Compile on a fly feature of Unity. Because you may suffer a lot with that thing.
sounds like details are leaking into the base class. Why not make an interface instead? Reading about the command pattern might be helpful for you
Thanks, i'll look into that!
Not sure if this belongs in #📱┃mobile or not. I'm trying to remove some frameworks from my iOS project with a [PostProcessBuild]. Does anybody have experience with that?
compile on a fly? what's that?
is that the thing where it compiles in the background after making changes?
Has someone here previously worked with any maps SDK? Specifically Bing Maps would be great. I've got questions that I can't find any answers to in documentations or elsewhere.
I make a change in a script WITHOUT STOPPING THE SCENE
That is
Hey guys how do I change the organizations, in plastic scm? this project is in another organization i wanna switch up
I use this code: ```c
if (microcontroller.IsOpen)
{
recievedData = microcontroller.ReadLine();
Debug.Log(recievedData);
cube.transform.eulerAngles = new Vector3(0, float.Parse(recievedData), 0);
}
to read serial data from my arduino, it works however it takes a long time (like 5 seconds or more) for it to start changing according to the value my microcontroller recieves
the variable microcontroller is a Serialport variable assigned to the correct port, with the correct baud rate
Solved, turned off plastic and turned it on again then it gave me the option to switch or create a new workspace in plastic
Hi everyone, I am running into an issue where Unity is running out of memory and crashing,
The TL;DR of what I am doing is creating files that are several gigs in size, I initially though the issue I was running into was to do with saving however it apears that its just the size of the class that is the issue.
I considered saving the class in stages, but I think that would cause alot of issues in terms of restiching the file back together at a later date for playback.
Is there a smarter way of dealing with classes several gigs in size, or is there an already implemented solution avaialble for this - I have considered saving things using SQLite, but I'd rather avoid rewriting everything I have already and getting that to work with the project if possible.
What is this "class"? Video recording or something?
Frame data for 22 characters transforms
Every bone is recorded. I know there is proberbly a better way of doing this, but for now I was just looking for an easy solution if possible
I guess you have to stream data from/to files then?
Yeah, so the setup is:
- Generate a file of movements (this is using playback data of over an hour long at 60fps)
- Record the movements and store them in a class, basically a big class of CharacterData -> FrameData -> BoneData -> Position, Rotation, Scale
- Save these to a file,
- Load them in at a later date
- Play back the file
I know this seems convoluted, but the trouble is the generation part takes so long as its using PFNN's, as such the idea was to preprocess everything, rather then generating them while playing them back. The only issue is that for times when the file spans for longer then an hour or so it starts to have issues (in this case the memory issue)
I had an issue previously about saving this data, where the string JSON string got to large, so instead I was aided in how to stream the saving of the data to and compressing it using NewtonSoft
So I was wondering, is there a simular way to work with large classes like this?
You should not treat this big data as a single class/json. You should make them small pieces so you can partially load or random access.
also how large is too large
strings can get pretty big and still parse just fine, just not recommeded since it will take longer to parse the json
Well the size is this
1.5ish hours -> 1.5h * 60m * 60s * 60f = 324,000,
Each frame I am recording 22 players each with 29 bones -> 638,
Each bone records ints transoform data, so position, rotaiton and scale (this is just an approximation but with each being a vector3 / quaternion and with is saying the 20 characters to record a vector3 (which I think is wrong but the estamate is fine)) thats still -> 3 * 20 -> being 60
On top of this each player also has some other data
But ignoring that, that means the JSON output will a minium, ignoring any {} and spaces, be a string of length 324,000 * 638 * 60
= Thats 1.2 * 10^10 characters
I agree, though this is kind of what I was asking about for the better solition, I was thinking of having a seperate file with a list of paths to the other files, where each sub file would cap at around 5mins of playtime instead.
However, I wanted to see if there was a cleaner way of dealing with this first, as that would require a bit of janky code trying to figure out what index the player is on and when to load new files and such.
I think you are looking at this the wrong way, I see no need for a large file
Do you think splitting it into smaller time segments would be fine?
The file itself doesn't have to have size limitation (other than limitation from file system format) as long as you can random access or partially stream from it. You'd have to deal with some code and overhead for paged loading, but you could minimize it with async operations.
no, I'm thinking of using a folder structure
CharacterName/Second/FrameNumber/bonedata files
one CharacterName folder per character
one Second folder per second to be recorded
one FrameNumber folder per frame of the second
26 files (one per bone) in the FrameNumber folders.
you could even be a bit clever and only write the bone data when it changes
Would that not require a file to be loaded every frame though?
Well alot of files loaded per frame
Load time, as once the file is generated and saved it would need to be played back at 60fps
well with this option you can begin playback as soon as the first set of bones is loaded and if you do your file io async or even on a different thread then you will get you 60fps playback speed
maybe use 1 file for all bones/frame so only one file is loaded/frame
maybe use a folder structure
Second/Frame/Character/bonedata file(s)
if you need all 22 characters bones/frame at the same time
This is more a DOTS approach rather than an OOP approach
btw. Converting the Vector3's and Quaternion to a binary array for saving is extremely trivial to code
might get more feedback in #archived-dots
okay after a little bit of research online
in my opinion you should adopt a motion format that (1) supports streaming, (2) is compatible with HumanIK and therefore Unity and (3) is open source. one such format is qualisys track manager's format. you probably want to output BVHs per frame - it does not support streaming, it's an ancient format, but it's the most compatible
trying to output FBX, which is the most flexible, seems the hardest
alembic unfortunately doe snot have a native workflow for bones
I use this code:
```c
if (microcontroller.IsOpen)
{
recievedData = microcontroller.ReadLine();
Debug.Log(recievedData);
cube.transform.eulerAngles = new Vector3(0, float.Parse(recievedData), 0);
}
to read serial data from my arduino, it works however it takes a long time (like 5 seconds or more) for it to start changing according to the value my microcontroller recieves
the variable microcontroller is a Serialport variable assigned to the correct port, with the correct baud rate
you can't synchronously read from the serial port on the main thread
it will behave strangely
what asset / library are you using?
not really using an asset, just System.IO.ports
well this code snippet isn't enough to tell you what's wrong
it is probably only reading 1 line from a buffer of many lines for every frame
the serial port is probably sending data much faster than 1 line per frame
true, hold on this is the script:
public string recievedData;
public GameObject cube;
SerialPort brainbox = new SerialPort("COM4", 9600);
void Start()
{
brainbox.Open();
StartCoroutine(dataFromPort());
}
IEnumerator dataFromPort()
{
if (brainbox.IsOpen)
{
recievedData = brainbox.ReadLine();
Debug.Log(recievedData);
cube.transform.eulerAngles = new Vector3(0, float.Parse(recievedData), 0);
yield return new WaitForSeconds(0f);
}
}
okay
I changed it to use a coroutine
this isn't really advanced code. it depends how much you want to learn right now
there are lots of ways to approach this problem, some make a lot more sense than others, it depends how skilled you are with unity
and what this is
Yeah I'm decent with unity although it's been a while, and this is basically a school project about serial communication, I made this as a little extra to also connect it to a pc
you will block eventually when there is no data to read, which means your problem will automatically require more work than ReadLine alone
there should always be data sent
since currently its just the value of a potentiometer constantly being transmitted
hmm
you probably want to do something like this: https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.datareceived?view=dotnet-plat-ext-6.0
then, your DataReceivedHandler will set a field to new Vector3(0, float.Parse(recievedData), 0);
it cannot set the transform directly
in an Update, set the transform's rotation to the rotation in that field
the reason it has to work this way has to do with threads, the main thread, the fact that you can't touch the Unity API from outside the main (or render) threads, etc. stuff you can learn more about online 🙂
okay thanks, I'll look into that
I keep getting an error that an object reference is required for the non static field, the error is for the variable I set the new vector3 to, it seems since it is in the datarecievedhandler it can't use global variables?
or because it is static
the handler as defined in that example is static #archived-code-general
hmm
well part of this journey is being able to figure this out, it's going to be something small
for example, the parameters used to construct the serial port object probably have to be set to enable events
Aight, so i got a bit of an issue with unity 2d. I want to make a flashlight using raycasts so in order to do this i have made a fan of raycasts and where they hit. At the moment i am doing Debug.DrawLine to represent where the cast goes, but to try and make an actual flashlight. How would i crop out/remove a section of an image on a canvas to show said area, to make the illusion of a flashlight?
Any reason you can’t use a shape/spot light?
in any case, you’d do it like the 2D lighting system does it, with render textures. The docs explain it https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@11.0/manual/Lights-2D-intro.html
In what way?
at the same time im using URP, so i want a directional light
from what i can see it just spreads out
Idk what you want to achieve , can you be more specific?
so i want a directional flashlight that casts shadows on hitting objects in a scene
from my tests before objects do not** cast shadows when it is the normal light object
as shown here
there is a URP spotlight
with shadows on
and it infact does not cast shadows
that is about as specific as i can get
good, so i found it, but how would i make it directional. As in a spotlight that doesnt point straight down (the game is top down)
in C#, if I have a list that has been initialized and populated with stuff, for example List<playableUnit> units and I copy one of the List items into another already initialized List like factionUnits.Add(units[0]), is the data I just added into factionUnits a pointer to the location in memory where that playableUnit is stored or is it a copy? Would doing something like units[0].name = "new name" apply to just that entry in the units List or would it apply for that element in the factionUnits List as well?
There is something that feels inherently cursed about having to manipulate canvas sorting order with script because messing with sibling index just makes multiple other things have a huge fit
Not an ask for help by the way I just find simulating depth with the UI to be really annoying
HOWEVER
This, this had no right to take two days straight
I never want to have to script carousels ever again
Depends if playableUnit is value type or reference type, e.g. struct vs class
its a class
so that means its a pointer
so changing the original should modify the copy
Yeah
good learning experience and epic result in the end though right
this is with default unity canvas UI?
Yuppers
Does C# contain a way to access non-generic members in a generic class?
E.g.
public class Test<T>
{
public float f;
public T t;
}```... and then access f without casting explicitly to a specific type of Test?
The context of this being the use of an ArrayList
(of which only contains two types: Test<A> and Test<B> where A and B are classes)
there's no casting necessary to access that member. you access it like you would any other field
Ah lemme expand my scenario since I think it's lacking important information
however it seems like your question is not about a generic class, but accessing the members of objects contained in an ArrayList?
Yes correct
I have an ArrayList which contains only Test<A> and Test<B> types, however I want to access non-generic members of an element in the ArrayList
Use an interface
Then cast to the interface and access the members there?
yes. or if you only need to access the interface's members use List<T> instead of ArrayList
Awesome, thanks for the good advice folks 👍
Or constrain your type to the interface if all the types passed into the method are implementing it
IList<T> can access both Lists and Arrays, but can't be used to add or remove elements from an array.
I cant find the namespace Unity.DeviceSimulator, why is this ?
i have it enabled and im using it but i cant find this particular event
i want to suscribe to it
Hi, I have a problem with my build on Linux Ubuntu.
When the game starts, the "Made with Unity" screen doesn't show up, and I got only a black screen
I'm not sure if it's a build related problem
My project use URP. I created an empty URP project for test and the game starts correctly
Hey all, Looking for a free Blur material for my UI. Asset store isn't helpful and the standard asset image effect they mention in the doc no longer exists.
I'm not an expert at shaders. so without any adjustements to the graphics pipeline, is it possible to blur via script or have a simple material? 🙂
I use this code to read data my connected arduino reads, but it takes ages before the value starts updating according to the arduino
public string recievedData;
public GameObject cube;
SerialPort brainbox = new SerialPort("COM4", 9600);
void Start()
{
brainbox.Open();
brainbox.BaudRate = 9600;
brainbox.Parity = Parity.None;
brainbox.StopBits = StopBits.One;
brainbox.DataBits = 8;
brainbox.Handshake = Handshake.None;
brainbox.RtsEnable = true;
brainbox.DtrEnable = true;
brainbox.Open();
}
IEnumerator dataFromPort()
{
if (brainbox.IsOpen)
{
recievedData = brainbox.ReadLine();
Debug.Log(recievedData);
cube.transform.eulerAngles = new Vector3(0, float.Parse(recievedData), 0);
yield return new WaitForSeconds(0f);
}
}
private void Update()
{
StartCoroutine(dataFromPort());
}
You're starting a coroutine each frame, this might impact performance. Use an infinite loop in the coroutine instead, and start it in Start.
Use yield return null; also. Might as well solve your issue
You're also calling .Open() twice on the serial port. Open it only after you set it up.
oh ok thank you
Never did Arduino with Unity or C# so I don't know if it's the computer that drives the baud rate, but if it's not, make sure to match it up with the Arduino's. I recall seeing 19200 or higher...
And if all of this doesn't solve it, try reading data without ReadLine. This might wait until it waits and end of line character \n or a terminator \0
Thanks a lot, it is quite complicated working with threading and coroutines but I'll figure it out
I've done some stuff with serial ports in the past and it's not that hard. The simplest and most versatile system is to put everything you receive in a collection (like a list or queue), and let another part of the code read the data from the collection
If you're using multiple threads (coroutines do NOT run on another thread), you can use a thread safe collection from the System.Collections.Concurrent namespace, to interact with the collection safely between threads
hello, i'm having a problem with adding an item to my list, on line 181
it says: NullReferenceException: Object reference not set to an instance of an object
what i'm missing?
presumeable pathpoints is a List which has not been initialised
hmm, how can i initialised it?
new()
No offence but you're in the wrong channel if you ask such questions
Try debugging your issue first
sorry
For Unity NullReferenceException might be the most common exception, better get used to see them, and fix them
yes i know i just confused with this one, i have no null object here but... sounds like i have to create a list temp of pathpoints and then add this list to the main list
You do have a null object here, at paths[i].PathPoints, that list is null
no, show the class that contains the variable pathPoints
no, the paths is not null
The exception says otherwise
pathPoints is null
No that's the wrong class
no
so you are missing = new() after the pathPoints declaration
Can confirm the CG shader works without a pipeline asset inside project settings.
However if i add the URP asset the CG shader will not work. The HLSL shader also does not work
what's the line of code to enable keyboard for input fields on android webgl?
can't find it anywhere
https://docs.unity3d.com/Manual/MobileKeyboard.html
also not an advanced topic
ty
oh you said webgl, which isn't exactly supported for mobile devices, so if what i sent doesn't work then there likely isn't a convenient way
there was an update a few months back that fixed the heyboard issue, just can't find the line to enable it
Hey does anyone know how unity handles textures in their raytracing pipelines?
Since bindless textures arnt supported and all
afaik this does not yet exist, according to Unity it may be available next year in 2022.3 LTS
it was introduced in the start of the year 2022.03b
yeah, but beta version. use it at your own peril
Also probably didn't need to be posted in multiple channels
Hey if you take a texture from a shader and put it in a list is it still by reference or does it copy the entire texture? What if I convert it from texture to texture2D before putting it in the list?
It’s reference type, so obviously. If you mean casting by ‘converting’ then it’s still reference. #💻┃code-beginner #archived-code-general
Ahhh ok thanks! Was confused because I Can easily have like 8-14 gigs of just textures when creating atlases, and was confused where it was all going
No recruitment here
New to unity, is there a good spot to find a good dev to be able to pay and ask questions too? @flint sage
Read #📖┃code-of-conduct . Recruiting goes on the forums or elsewhere
Oh nice, didn’t know Unity had a forum for this. Thanks!
how would y'all design a tetris-style inventory? in particular so designers can pre-populate inventories (say chests) with items in 'em?
this question just confuses me, tetris is a gameboy game to me that has no inventory
it's a pretty common thing in games, for example Diablo 1&2 or Resident Evil 4. the inventory is a grid and the items are shapes that you fit inside the grid
UI wise its just clicking and dragging things, data wise you are just keeping track of what a player owns and where it lives on that grid
thank you, yes, I'm curious if anyone has any ideas on the editor tools side, or perhaps data format side that would make it easier to design chests and things w/ items in them at various positions, rotations
There is no quick and easy way to do this, I’d suggest to not make tetris shapes, make them all rectangles, disallow rotation, store only the top left corner’s coordinate, define shapes simply as width/height in tiles. Pack shapes into loot boxes algorithmically.
But before you do that, be sure it adds something meaningful to the game and you don’t do it purely because it’s fancy. You can just have a weight/bulk value associated with items that would yield pretty much the same effect on gameplay (unless you specifically need the player to be constantly annoyed by their inventory layout)
Or you could go the ultima 7 way and abandon the grid to simulate messiness in a backpack, or you do the nested backpacks/bags thing where various bags you find have different sizes (wow style). Those would be alternative designs if you want to give people some gameplay around inventory organization that doesn’t involve bin-packing and a lot of tooling work
Shouldn't be too hard to do. Just a bunch of matrix work, though preventing resizing/rotating would probably cut down on a lot.
Make a 2D array and store the space it occupies in the item, then determine how it fits using the pivot of the item.
You'd have to calculate against the size of the inventory which could result in going over the maximum index which you'd have to account for.
on the implementation of the inventory itself I feel like I have a good grasp -- though rotation does make it more complex if I don't rely on Unity primitives. it's the design side that has be stymied. I guess I will try to come up w/ a scheme that brute force populates an inventory grid from a list ... as long as it's not too densely packed that seems like it might work
on the game design side, yes, this is a way more complex inventory, so the juice better be worth the squeeze!
Is there a way to sync GameObjects with netcode? I have array of gameobjects which represent grid of islands for easy detection on which island I am trying to build something. Each island is a gameobject that has grid for building. The issue is that Rpc cant take GameObjects as parameter and NetworkVariable doesn't take nullable types. So if there isn' a way to sync GameObjects do I have to always think about solution that involvec sync using just basic types?
EDIT: Okay, apparently the is a thing called NetworkObjectReference. I guess that answers my question
Halo, how do i know if 2 SceneManagement.Scene struct are the same?
And, related. Is it ok if i call SetActiveScene per frame? Would it skip execution if the Scene i wanna set as Active is already the Active scene?
You should profile it if the performance is concern, you could track current active scene with activeSceneChanged event
Guys, my Function is not obbeying me lol, when I assing an existing var (from outside the function) from a var (from the function), the function simply does not do this, and the existing var continues with its old value. (sorry my english btw)
I tested everything, the only thing that is wrong is the assignment
using System;
namespace Couse
{
class Program
{
static void Main(string[] args)
{
int[] vect = new int[3];
vect[0] = 2;
vect[1] = 4;
vect[2] = 5;
AddValue(vect, 6);
System.Console.WriteLine(vect[3]);
}
static void AddValue(int[] Vect, int newValue)
{
int vectSize = Vect.Length;
int[] newVect = new int[vectSize + 1];
for (int i = 0; i < vectSize; i++)
{
newVect[i] = Vect[i];
}
newVect[newVect.Length - 1] = newValue;
Vect = newVect;
}
}
}
output: Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
Doesn't look like Unity code
I'm learning C# first to use Unity
So im learning to use VS code
Cool, but this is a Unity server. Find a C# server (https://www.google.com/search?q=c%23+discord+server) and come back (to #💻┃code-beginner) when you've gotten to the Unity part.
go read up on variable scopes
you're changing a reference not a pointer
using a list will probably save you some headache. or you can look into the ref keyword
understood
thank you for your help!
Hey, I'm trying to override implicit conversion operators for a wrapper class. I can get it to go WrapperType -> underlyingValue
But I cant do the opposite, implicity set the wrappers underlying data.
public static implicit operator T(PersistantDataType<T> data) => data.mData; public static implicit operator PersistantDataType<T>(T data) { // What to put here? }
Any way to do it by modifying the object? It has to be static so I assume not eh
You are assigning variable, not part of it. You should not define operator to change the meaning of the language.
Just make property and do wrapperType.Value = 0.555f
Ok fair enough
Thought it would be cool/clean to make a type that behaves exactly like underlying type, but had methods to save/load from disk. Anyways, i'll just use a method to assign the value
ok i have problem.
the classes for a game that i am modding (legally, single player, dev approved) do not belong to a namespace.
I would like all of the game classes to be accessible to mods via a namespace (Game.Classes.[]) and not have the global env cluttered.
I have exported all of the classes, remove the code from the methods, and forwarded the types to the original via TypeForwardedTo.
Problems began to arise when I tried to compare types and (obviously) the game type was not the same as my forwarded type. Similarly problems began to arise when trying to implicitly/explicitly convert.
By referencing Assembly-CSharp all of the classes are immediately added to the global env which sucks. (global::Class == Class)
Any ideas?
I am using a custom mod loader and unity doorstop .NET 4.8 C#8.0
Can using assembly alias help you, so it won't be included in global?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/extern-alias
this only allows for 1 layer. if thats the best option ill stick with it but i was hoping for at least two layers Space.GameClass.[]
The alias is replacing global::, so it would be AliasName::Game.Classes.Something
hm. when i do somthing like this for the alias there are sum problems
Yeah I think using . would have problem
RIP multiple layers
yay it works. not 100% ideal but its much better
ill have to live with it. thanks!
Happy modding 😄
For 2D TileMaps, we have a 400x400 32bit sprite, sized map that takes like 12 seconds to load in unity. Is that normal? It does have multiple layers with animations
don't think anyone can answer that really
depends on hardware, depends on what tiles you are using
etc...
we have insanely buffed computers, its just simple 32x32 sized tiles, a map that is exactly 490x383 tiles big. And at most 1 tile animation is 5 sprites. We do have layers like water layers that are mostly covered with those 5 tile animations. These water layers are the ones in unity that are having hard times to load. Is unity known to be bad with tilemaps this size?
My assumption is that the tile map is done completely by lookups, considering that the map itself expands incredibly far in game space. So, assuming you've occupied all those cells, that's quite a lot of operations when loading up.
@regal lava I assume its whatever the built in Unity Tilemap script is
this layer is problematic cause of the animations, we have tilemaps on the same scene that have way larger info sections, but no animations that load instantly
Hello, I'm using JSON to save my game data, but I was wondering if I could stick the SaveData() method in a coroutine and only proceed once the file has been written. How would I achieve this?
Here's an example of my save code:
public class JSONSaveLoad : MonoBehaviour
{
public void SaveData()
{
SaveData save = new SaveData();
save.health = 100;
save.skill = 10f;
save.dead = false;
string jsonString = JsonUtility.ToJson(save);
File.WriteAllText(Application.persistentDataPath + "/SaveData", jsonString);
}
}
public class SaveData
{
public int health;
public float skill;
public bool dead;
}```
you have already achieved that, or you need to clarify what you want to happen and what you think is currently happening
File.WriteAllText is already blocking till the operation is complete
Physics.OverlapSphere doesn't collide with my instantiated objects. Both my prefabs have mesh renderers just like the objects that are in the scene. Anyone got a fix for this?
{
Physics.SyncTransforms();
Collider[] colliders = Physics.OverlapSphere(transform.position, 1000);
foreach (var hit in colliders)
{
string n = hit.name;
if (n.Contains("Skelly")) {
Debug.Log("rEKT");
}
}
}```
would recommend you draw a debug version of the sphere
to make sure you are colliding with what you think you are
1000 is probably too large
but yeah just draw a debug sphere
and see what you are colliding with
If I stand my player where a psawned monster is it will still collide with the player but not the monster
you should probably compare the tag
I tried rapid spawning the monster that is trying to collide with things and still on the player
instead of the name of the object
I've been pausing the game just before the if statement
and then pressing continue
and then looking at the names of collided objects
so please do the first suggestion
make sure its doing what you think it is
then move on from there
cause you have to prove your assumptions otherwise its pointless
(this is all assuming the colliders are setup properly)
yeh I just use the default colliders that come with the unity store assets
probably move this to #💻┃code-beginner
I am having a issue where the function of the code is spitting out null despite already having everything filled for it.
"spitting out"?
The State I have is giving me ArgumentException: The Object you want to instantiate is null.
owner is the Battle Controller and the instantiate its throwing is the int first
hows it being set?
or better yet
just break point into the line
and see if heroprefab exists
It is being set in the inspector and I have the hero prefab set into the battle controller
okay then breakpoint into it
check what the reference of heroPrefab is doing, like did you accidentally destroy it/set it to null etc...
Oh I think I know what the problem is
I have a obsolute code that may be causing not the hero but the job to be null
its in the static gameobject Create code
The problem is though is how I can change it
PrefabUtility.CreatePrefab( fullPath, instance ); because it says this is obsolute and wants to change it to Saveasprefab asset
hmm still seems to give me a error
ArgumentException: The Object you want to instantiate is null.
UnityEngine.Object.Instantiate[T] (T original) (at <f1212ad1dec44ce7b7147976b91869c3>:0)
InitBattleState.SpawnTestUnits () (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:33)
InitBattleState+<Init>d__1.MoveNext () (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:17)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <f1212ad1dec44ce7b7147976b91869c3>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
InitBattleState:Enter() (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:10)
StateMachine:Transition(State) (at Assets/Scripts/Common/StateMachine/StateMachine.cs:38)
StateMachine:set_CurrentState(State) (at Assets/Scripts/Common/StateMachine/StateMachine.cs:10)
StateMachine:ChangeState() (at Assets/Scripts/Common/StateMachine/StateMachine.cs:24)
BattleController:Start() (at Assets/Scripts/Controller/BattleController.cs:20)
This code is not what's mentioned in the stack trace.
Also please use our guidelines to post code, so we can see line numbers without downloading files. #854851968446365696