#archived-code-advanced
1 messages ยท Page 14 of 1
having just done this successfully i don' tknow, you ought to listen to me
i wouldn't start developing Tests with a capital T for something you are actively developing right now anyway
in reality, you have to work on yours and the collaborator's projects simultaneously
it's unavoidable
if you are perhaps working with someone external with their own repository, you know, that is hard
that was an error
hopefully you get to see the external source
i had my projects "polluted" this way
it was fine
but i never tried to ship in a scene
i'm not sure why i would do that
like i could ship in a demo scene, but i could also make a prefab
and if the user wanted the demo or test content or whatever
well you can drag and drop the prefab into a new scene
or do that programmatically
how are you building the "host projects"?
you mean on your local device?
are we talking about 3-5m builds? or github actions with game-ci
or something else
๐ i actually think I misunderstood the TestRunner. It actually creates a scene to run the tests. So I think I won't need the test scenes at all. And the scenes were actually not my main concern. That is solved. I am just wondering now if the addressable items I use for testing will get bundled with each host build. But if I put them in Samples I think that solves the problem
It actually creates a scene to run the tests.
yes if you are talking about the unity testing framework
it creates an empty scene, but it really depends on what you're testing if you need a scene. re: addressable items...
you should look at the addressables repo and see what they do for testing
Host projects are going to be created by my clients. They just import the package through the Package manager on any project they would like
oh i meant like, if you are doing some kind of automated building
or if you aspire to do that
like you have your own host project, which i understand is your playground for working on the package
is that built via automation? do you want the automation to run those tests?
No, we have no need for that right now
that might be helpful
the link i sent
is your goal to eventually have a publicly distributed package with some kind of proprietary / private / licensed code that gets built into unity (as opposed to a backend)?
Not yet cause we are only actively developing the package. The host project is discardable
Thanks a lot guys!
Awesome @regal olive thanks a lot. I will probably reach out ๐
Hi guys i have a question... how do i (in code) set the tiling/offset values for detail-maps?
It seems there is no keyword or i am missing something.
This is for the main material. I need something similar for the detail maps.
I need the ... well the name for the detail thing
You can set the texture name ๐
Right on the doc
So i can use: m.SetTextureOffset("_DetailAlbedoMap", xyz)?
Okay.. interesting. I will try that. I never used that before
m.SetVector("_Tiling", xyz) is what i have currently in the code - it never came to my mind to use any other method. But it has a clearer name and it makes sense i guess. So i will switch
Thank you!
No problem ๐
has anyone created a CinemachineExtension and updated the position in PostPipelineStageCallback ?
I'm having issues with the one that I created but can't figure out why
what are you trying to do?
i modified an existing one
is it possible to send in an array of compute buffers into a compute shader?
I have a user defined variable that determines how many compute buffers will be used and I cant seem to find a way to send them into the compute shader without manually writing a shader that compensates for the specified amount
why isn't the compute buffer itself an array of structs?
shouldn't it be
buffers.Select((buffer, index) =>
return new Buffer(buffer) {
bufferIndex = index
};
)
```?
do you see what i am saying @silent jungle
hey guys, when you dispatch a compute shader, does it prevent GPU / Unity from rendering new frames until the shader is done running ?
"It Depends"
on the running time of the shader I assume ?
no
interesting, must be compute buffer visualization routines then
so when you say "dispatch a compute shader"
what do you actually do? use its output for rendering?
use it on the CPU first, and then for rendering?
no, I read it back, it's data that is used by CPU later and don't use for rendering
okay
readback is async
so compute and graphics commands on modern AMD and NVIDIA GPUs run in genuine parallel
you can see this by enabling gpu profiling of a standalone player build. to profile a compute shader, you should use Nsight or PIX. if you are using the latest 2022.2 alpha, directx12 is finally released and use -force-dx12 -force-gfx-jobs native
is it a DX12 exclusive feature (the parallel graphics + compute execution) ?
it's hard for me to find an answer to this expediently online
i think it works with dx11
but i'm not 100% sure
time to profile the async code that runs that and see what actually causes the long hangs
hate profiling async code ๐ฅฒ
it doesn't prevent the GPU from rendering new frames
in any case
if you are not using the output for rendering
it slows it down.
how much it slows it down really depends on your hardware
you can't really profile it using async readback
or tools inside unity
you should probably use the 2022.2 alpha
not used for rendering
there are some visualization routines to inspect the results, hope it's them that freeze up rendering
or use Metal
need to profile visualization routines too, maybe it's them
they supposed to be very simple, but maybe
I'll update to 2022.2 as soon as it releases, this is not urgent
on 2022.1 rn
you have to test SystemInfo.supportsAsyncCompute
and yes it's definitely only directx12
oh cool, I'll test it rn, thanks โค๏ธ
oh, that's unfortunate
Currently profiling, im seing many GC.Alloc calls within the .Get method which i can not explain.
I assume the .Get method calls () => asset.InstantiateAsync().WaitForCompletion() callback... is it possible that the lambda produces some sort of closure allocation ? Any help would be great...
public class AdressableAssetsPool : UnityEngine.Pool.ObjectPool<GameObject>{
public AssetReference asset;
public AdressableAssetsPool(
AssetReference asset,
Action<GameObject> actionOnGet = null,
Action<GameObject> actionOnRelease = null,
bool collectionCheck = true,
int defaultCapacity = 100,
int maxSize = 250
) : base(() => asset.InstantiateAsync().WaitForCompletion(), actionOnGet, actionOnRelease, o => Addressables.ReleaseInstance(o), collectionCheck, defaultCapacity, maxSize) {
this.asset = asset;
}
}
yep, no support
yeah try declaring an instance method
what is going on here though
Thanks, gonna try that ^^ you just mean a method inside the class itself and remove the lambda with a method reference, right ?
Im pooling the gameobjects created via the assetreference xD
Its a wrapper class basically for some custom logic
you should only have the asset reference instantiated once, since it's a prefab, right?
then you would pool that game object
instead of instantiating from the asset reference every time
also why is it wait for completion?
pooling isn't async
i mean there are async pools if that's what you need but it wouldn't make sense to od that
Really ? Every one tells me something different which is quite funny ๐ฎ So how would it look like correctly ?
i don't know
i mean i don't really touch this stuff
i mean clearly you can profile it and it'll tell you
you can add the sampler lines to your callback
and see if instantiateasync does "gc.alloc"
however, if it's a small alloc i would chalk it up to the "do not care" column
That alloc gets called like 2500 times which generates like 500kb garbages so its actually quite big and causes a noticeable frame drop :/
I also can not make that callback a method reference since it tells me it needs to be static
Are you sure they are actual garbage not the necessary heap alloc for game objects?
I have no damn idea, even deep profiling just tells me that theres "GC.Alloc" happening... but it does not tell me what exactly causes it... but i assume that its that piece of code
Thats what happens inside the pools.Get method
It instantiates like 15 gameobjects which makes sense
and than like 2500 gc.allocs
which doesnt make sense anymore
all by calling "myPool.Get()"
Like doc said you could try profiling with https://docs.unity3d.com/ScriptReference/Profiling.Profiler.BeginSample.html
I did... the picture above is the result
Oh okay. So total memory alloc is 236kb?
I think GC alloc is just getting called internally from Instantiate?
I cropped the picture a bit wrong, but its actually about 500kb... almost 250 from the instantiate calls and other 250 misterious kb garbage from "GC.ALLOC" which could be literally anything
In that case, why isnt it listed under the Instantiate calls in the profiler ?
As you can see i already expanded the instantiate call and the gc alloc is next to it, so not sure if its really tied to that one
Ah the screenshot has confused me lol
Oh sorry, heres a clearer one
I named the profiling sample "INIT" and well... the instantiate is next to the gc.alloc so i guess those are two different ones
This is how it actually looks like
Can you provide the code you used to profile those?
So we can see what method calls are in the sampler scope
Of course, but you might laugh...
Profiler.BeginSample("INIT");
var go = pool.Get();
Profiler.EndSample();
Tada
Its literally just the pool.Get method
and it's deep profiling? ๐ค
Yes and it makes me wanna cry
But as stated above i extended the pool like this :
public class AdressableAssetsPool : UnityEngine.Pool.ObjectPool<GameObject>{
public AssetReference asset;
public AdressableAssetsPool(
AssetReference asset,
Action<GameObject> actionOnGet = null,
Action<GameObject> actionOnRelease = null,
bool collectionCheck = true,
int defaultCapacity = 100,
int maxSize = 250
) : base(() => asset.InstantiateAsync().WaitForCompletion(), actionOnGet, actionOnRelease, o => Addressables.ReleaseInstance(o), collectionCheck, defaultCapacity, maxSize) {
this.asset = asset;
}
}
And i think its a closure memory allocation ( the first lambda in the base )
closure should allocate once
Unless you are making closure from loop
The pool.get method gets called inside a loop, does this count ? xD
But the pool constructor is outside loop :0
Hmmm right
Do you pass anything to actionOnGet?
Or other way: You can use GameObject from LoadAssetAsync instead
as a prefab
https://assetstore.unity.com/packages/tools/utilities/lean-pool-35666 with addressables?
Not really, its just a empty lambda...
I meant using LoadAssetAsync to load prefab and do regular Instantiate
If you don't need reference count of addressable, that's valid approach
Maybe Addressable is allocating something for async operation
Im gonna try that next, however... if i read the docs correctly and my test example also worked correctly... than theres literally no difference between LoadAssetAsync/Instantiate and InstantiateAsync :/ Both do allocate the same amount of garbage... however im gonna try it rn
Hmmmm.
Btw is that really the right way to instantiate adressables ? I can literally only find examples with InstantiateAsync... the website actually says :
So it sounds like you should actually avoid that
I mean even if there is closure allocation it's only gonna take about few pointer size per call
Anyways it's okay to do that if you keep your original prefab's handle, not releasing it
I use the loadasync + Instantiate approach with pooling, no issues
So when i destroy the instantiated gameobject i should not release it ?
Uh that load/instantiate approach really did decrease the GC.ALLOC count
Now its just 1.4kb and not 240kb
Oh so it is addressable doing it ๐
there's a mention that addressables system has internal tracking mechanisms, that can be disabled
That's rather drastic reduce tho
Looks like, i really assume it was the Async instantiate which than allocates a AsyncHandle which is a class if im correct ๐ฎ damn
or just use the load + instantiate, which is pretty much the same
Okay thanks a lot ^^
Just a small other issue... if i do that LoadAssetAsync and Instantiate approach, what should i do if i destroy an pooled gameobject ?
Should i call Adressables.Release/ReleaseInstance ? Or just Destroy(go) ?
Basically you just keep your prefab's reference on memory, not calling Addressable.Release or anything
Since you create them with regular Instantiate, you should use regular Destroy
Alright that makes sense... thanks ๐
you release only when you no longer need that prefab (zero objects of that type left in the scene)
So it actually does not count the refereces and i need to manage that by myself, right ?
Yes, it will only count for prefab that acquired with LoadAsync
Great, thanks ! ๐
So just LoadAssetAsync, Instantiate, Destroy and once there no more instances left, Release
Is there a way to completely disable a rigidbody without removing it?
I have this rigidbody I need to parent to my character controller and need it to act as part of the parent rigidbody collision wise, marking kinematic doesn't work
thanks for responding, it looks like I misunderstood exactly how to use DrawMeshInstancedIndirect. I originally thought that you created a compute buffer with information you wanted to use per instance and this buffer would be the bufferwithargs parameter for the draw function. This lead me to believe that the size of the compute buffer directly controlled how many instances would be drawn
After alot of investigating I found that there are actually 2 (or more) compute buffers to be used with the DrawMeshInstancedIndirect; the Args buffer and the custom data itself. What I cannot find however is what each parameter in the args buffer does.
The Unity documentation states that compute buffers under the indirectarguements type requires atleast 12 bytes, but cannot seem to find solid data on what those 12 bytes are supposed to represent (the example in the DrawMeshInstancedIndirect documentation has the args buffer be a 4 int array that represents index count, instances count, index start, base vertex but that doesnt seem consistent with other examples)
I designed a solution around my flawed understanding but I realize I need more resources to fully know how to utilize DrawMeshInstancedIndirect, do you know where I can find this? I already googled and most I see are showcases of how amazing the results are :p
iirc you can disable individual components of a gameobject :
rigidbody = GetComponent<LRigidbody>();
rigidbody.enabled = false
I cant speak to how performant this is but I can imagine its neglible
No way you can just do that!!!!!
Yep, the Rigidbody class doesn't have an enabled field
ah your right
maybe try this then :
rigidbody.isKinematic = false;
rigidbody.detectCollisions = false;
Unfortunately that doesn't work as well.
Thanks for trying nonetheless.
Strange that Unity doesn't provide this sort of behavior, almost all components can be turned off.
What is expected behaviour? You want it to still collide but be part of other rigidbody?
My power went out but I am interested too so Iโll look it up soon
This article really unlocked the knowledge of how to use DrawMeshInstancedIndirect for me:
https://toqoz.fyi/thousands-of-meshes.html
not sure if this is considered beginner or advanced but what's the best practice for disconnecting the camera (or unparenting) when the player goes offscreen
can just call SetParent on its transform
camTransform.SetParent(null, true)
or you could just never have the camera parented to the player in the first place
but have a script on the Camera that has a LateUpdate method and follows the player using it when needed
Is one method better than the other
Its just a demo game for a school project but we still want to do our best and its good to know
SetParent is easier and works if the camera follows the player perfectly
having not making it a child of the player and just following the player is better if you want to do easing or if the camera does not perfectly follow the player
I cant seem to get access to it rn but I will keep trying and thank you
Yes, seems like there is no direct way, will probably just have to fake a collider
Just removing rigidbody would be better, tho
It'd break references tho, anything referencing that rigidbody will no longer do.
Wish there was an easier way but doesn't seem like it.
Yeah maybe you'd need to convert those to GameObject or your component references
And check if Rigidbody attached when you need access ๐
That's unsustainable, you'd have change a majority of your codebase to be able to do this.
And you might even come across some third party tools that you want to use but can't/don't want to modify to fit that workflow.
Seems much more straight forward to just setup a placeholder collider that fits the object.
When loading scenes additively, is there anything special I need to do to get events like OnMouseEnter to fire for objects with colliders in the subscene? When an object is in the main scene, my events fire. But when I move it to the additively loaded scene, they do not fire
(1) don't use scenes
(2) it would be really surprising if you do. do you have multiple cameras? multiple canvases? or is this physicsraycaster3d? is it the right layer?
One camera in the main (non-sub) scene. A few canvases in the main scene. All layers are default.
If I move the object with the collider/trigger in question to the main scene, my events fire. If I move it to the subscene, they dont. My desire to use multiple scenes is because this is a multiplayer game and the host has to have multiple scenes loaded in, as people could be in any one of them
Hey, so does anyone know how to cast a method?
i have this:
[SerializeField]
private string move = "Move";
//method to store
Vector2 getVal() {
return playerControls.Default.Movement.ReadValue<Vector2>();
}
public class EventTrigger<T> {
public delegate T TriggerFun();
}
//store method for later use
public void addEventTrigger<T>(string name, EventTrigger<object>.TriggerFun triggerFun) {
if (!data.Events.ContainsKey(name)) {
data.Events[name] = new Dictionary<Type, EventTrigger<object>>();
}
data.Events[name][typeof(T)] = new EventTrigger<object>((EventTrigger<object>.TriggerFun) triggerFun);
moveList.Add(name);
}
/*requires a method with an "object" return type,
but recieves a method with a "Vector2" return type*/
addEventTrigger(move, getVal);
I basically want to store a method with any return type and cast it back and call it later
Thanks in advance!
Itโs not possible. There is covariance generic modifier but it does not fit for this case.
The ones you are trying to cast is just completely different types
What is the easiest way to detect if an object (the door) is between another object (my cursor, the sphere) and the camera, and hide this door automatically.
Basically, I need to auto hide some objects when they are between my cursor and the camera.
My first thought is some raycast or spherecast type stuff
but that might not be ideal if you have a big sphere like this where perspective is gonna matter
Well the sphere cursor will actually be very small once I've updated my code, it's just an indicator to show where the camera is looking at so in the end, it should be 10 or 20 times smaller or something like that.
But for the raycast, how would that work ? Basically, it would be checking of either of the four corner of my camera rays and the center of my cursor are colliding with a gameobject?
Thereโs a bunch of ways to go depending on how you wanna balance simplicity, performance and accuracy.
A simple way would be to do a spherecast the size of the cursor from the center of the camera into the cursor. Anything it hits should be faded out.
This method would probably miss hitting some things close to the camera, but based on your example I donโt expect that would be a huge problem.
Note: I should specify that Iโd do a SphereCastAll, and use something like Layers or Tags to identify objects that should be turned off if hit
is it not possible to store a generic typed method at all?
Do i have to manually add a list for each type of method I want to store or is there some preprocessor/generics magic i can do?
One thing you can do is have a common base class for the generic and store that. But then it is your responsibility to identify how to downcast (if needed):
public class EventTrigger {
}
public class EventTrigger<T>: EventTrigger {
Has anyone worked on Vulkan gfx plugin for Unity?
Can you explain a bit about the difference between IUnityGraphicsVulkanV2 and IUnityGraphicsVulkan from the IUnityInterfaces? My understanding is that V2 is supposed to be more recent compared to legacy Vulkan, which may have better device support. But couldn't get anything concrete on that from Unity Docs or Vulkan spec.
Thanks
That could work, I'll have to try that later.
I dont get it your cursor is a physical object in 3d space ? If so just do a sphere castall from the object towards the camera and fade out anything it collides with
I didn't know about sphere casting but this is indeed an easy method to implement. I'll give it a shot. Thanks for the help ๐
I have a small but annoying problem. I have this class which is a simple serializable tuple. Nothing really complicated...
But for some reason... I am getting weird console errors
I am a total loss as for what could the problem be, since there is really not much output to the error...
These are Editor errors, not compilation errors
Probably it's CaptainType... which isn't serializable
Ew, SO. And where do you have CaptainPrefabTuple?
Are you asking me where I am using it?
Yes
Well, I wouldnt have to use them, if Dictionaries would Serialize better
It is basically a hack, to make a List<T> like a Dictionary
No I meant where is the variable that using the type ๐
Ah okay and TamaAbility is another SO I guess?
No, that is a MonoBehaviour
Oh. I see. and any Editor extension are you using?
I dont think so, no
No custom editor? hmm I think it should work
May not related but what is the warning under Tactics namespace?
So I am trying to make a tool ingame to see things like GPU, CPU, and RAM usage % in game. Would using the Unity ProfilerRecorder be the best way to go about it?
My desire to use multiple scenes is because this is a multiplayer game and the host has to have multiple scenes loaded in, as people could be in any one of them
hmm... you're in a lot of jeopardy
observe you have made a decision about how to turn the 2d area (a circle of interest in the middle of the camera) into 3d space. if you move the camera back for example, you'd want the sphere of interest to still be in the middle of the room, so it's not as simple as "a fixed distance."
cinemachine uses a spherecast to determine visibility, you can look at its source. if you're already using cinemachine, author a subclass of its preexisting visibility extension to hide and show objects instead of moving the camera
with cinemachine you'll use the target instead of a fixed distance, which will solve the main problem you have - how do i turn 2d into 3d spaces?
i think you're supposed to extend from EventBase
i'm not sure because i don't use uielements
but it looks like you are trying to make a custom event
or something that should be in a ChangeEvent
why are you using the UIElements event dispatcher for game logic?
That had nothing to do with UIElements...
no. use an asset store asset, or use a .net library for it
@hot dock it says in the error, UnityEngine.UIElements.EventDispatcherGate
Yeah, I know. But I do not know why.
Thanks! I will take a look!
2022.1
there is nothing wrong with the code in CaptainPrefabTuple
well
are you asking, does the unity editor have bugs on linux? yeah
uielements is coming up because an editor view is trying to render an inspector or something for the class
is there anything else going wrong?
like can you not see this type as an inspector field / in an array?
IUnityGraphicsVulkanV2 is for permitting multiple graphics plugins to intercept device initialization using AddInterceptInitialization. that's all. it changes the signatures of methods compared to the previous interface so it is a new API. it has no relationship to the underlying vulkan features of your device
No, that is the only error/warning I get
If the message was not there, I would think that everything works as intended
I basically want to store a method with any return type and cast it back and call it later
public void AddEventTrigger(string name, Type t, Func<object> triggerFun)
don't know why you want to do this though, because the type doesn't matter at all
you should have a EventArgs class, and it can have an int value field
or fields for the types that you will eventually use, which are extremely few
you know all the types ahead of time, so you can greatly simplify what you are doing
it'll be like, an int, a float, and maybe two ints
If I want to exclude certain dlls from build for certain targets, like exclude MyGame.Server dll from client builds and MyGame.Client dll from server builds, would I just use the includePlatforms and excludePlatforms in the asmdef for that? (sorry been away from Unity for a while and rusty as hell)
also, love that they added the dedicated server target ๐
no that would only apply for platforms with a capital P, like windows versus linux
you can use asmdefs everywhere with autoreferenced checked off, so that 100% of the code in your assets directory is covered by them
then, for example in your scripts folder, check the asmdef's box for autoreferenced
however, i would say... don't worry about it
you cannot practically toggle code like this. you can certainly use a compiler define
ah I gotcha. So I would have to manually do that for each build target
but it's a huge hassle
no the build targets are not related
the build targets and platforms have nothing to do with what you are asking for
there's no such thing as a server or a client build. i know it looks like there is in unity, but there isn't. there also isn't a file in your Assets/ folder called MyGame.Server.dll
there's an asmdef, and you're talking about DLLs that appear in the folder directory you get when you build a standalone player
I mean the resulting dlls from those asmdefs
it really depends on what your goals are. to prevent code from shipping in the client for the purposes of hiding it?
or tO mAkE tHe sErVeR bUiLd sMaLl
yeah. I'd like a separation of a few dlls that are meant only for client or server
yes but to keep it secret?
like to prevent ordinary players from being able to run their own servers or inspect that code?
or for a different reason
yeah its dedicated server code that doesn't get distributed
strict client-server arch
okay
then your best bet is to use compilation defines
#if MYGAME_SERVER
class XYZ {
}
#endif
there's a better way I just don't remember. using defines for an entire dll is not a good approach
you can simply delete it after you've built the player
scriptable build pipeline maybe? gah I don't remember
actually I think that was how I used to do it
Does define constraints work for you?
https://docs.unity3d.com/Manual/class-AssemblyDefinitionImporter.html
Unity only compiles and references a Project assembly if all of the Define Constraints are satisfied. Constraints work like the #if preprocessor directive in C#, but on the assembly level instead of the script level. Define all the symbols in the Define Constraints setting for the constraints to be satisfied.
@glad badger this means you can use a single compilation define to toggle an assembly on and off
ah actually that might have even been it. just manually changing the define depending on the target I'm building at the time
thanks folks
Yeah that will do
My game crashes, when trying to load 1000 x 1000 tilemap,
anytips on what to do?
You really need to load all that at once? Maybe some chunk system could work?
Yep, you can mark the method sealed and look for compiler errors
Sealed methods cannot be overriden, any override will now report an error
public sealed override OnServerAddPlayer
Okay next thing would be to use your IDE and find all references to this method, and go through them one by one
Anyone ever messed around with 4d arrays before
Ask your question directly
Don't ask if anyone knows XYZ, it's slower to get an answer!
No no
Your IDE's References
Not "Find this string in all files"
What code editor are you using?
Then right click on this one ^ (the function name) and select "Find all references"
can someone give me reference on how to create methods like OnClick() that are being called when certain conditions are met? (not like if(foo == true){OnClick()})
Well, looks good to me, the only reason you're not getting the log would be because the method isn't ran at all
Either in a base, or child class
No idea, I'm not familiar with that demo project, and networking altogether
Yea, towards the future, I wont be loading all at once, but for the time being, I must load all at once to see the full pictures.
Its an RNG map
is it possible to have a VR toggle?
I'm planning on making a shooter game that can be played "normally" or using a VR headset
I'm thinking its a "simple" camera and character controller switch, but does changing the camera also change the outputs from a VR headset to a Regular screen?
tilemap.placeBlock() is much slower than tilemap.setTiles()
if your tiles are < 10,000,
untested if more
holy crap. I can't believe I never knew you could mark method overrides as sealed lol I thought that was only at the class level omg
SceneManager.LoadSceneAsync still causes massive hiccups in 2021... i don't think they'll ever fix that.
How do you guys load scenes without causing hiccups? and don't tell me assetbundle ๐ข
You cannot avoid hiccups, your best bet would be turning off allowSceneActivation then hide hiccup with loading screen
ok thanks. and editor hanging during loadasync is normal?
before activation i mean
It shouldn't hang, like not responding? ๐ค
yeah for a few seconds, i guess while loading the scene
no big deal, i remember that loadsceneasync behaves differently between editor and runtime... lemme test that
Yeah maybe it's different from build
Why are SystemInfo.supportsAsyncCompute and SystemInfo.supportsGraphicsFence false in the editor in dx12 with force-gfx-jobs native and true in the player with the same settings?
how do people use graphics fences in the editor?
is the answer, "no"?
Does Device.SystemInfo.supportsGraphicsFence behave different?
Nvm
Hi, im finding shortest arc between two Vector3s, however when their dot product is -1 there's an unexpected behaviour where my character rotates 360deg, I thought this code should counterract that?
that code does nothing since you overwrite its result on the next line
but also, doesn't Quaternion.FromToRotation do exactly what you want?
no big deal i remember that
Hey gents, I never work with levels, what's the workflow for streaming in a full level, including baked lighting, and any other scene specific data?
I'm looking to stream in all assets not construct my level
Does anyone know how to add a cancellation token correctly to a async task?
private async Task StartAcceptanceTimer()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(AcceptanceTimer), cts.Token);
}
catch (TaskCanceledException ex) { }
}```
Doing it like this now, but is it normal catch the cancellation? if I don't i receive a error log in my console.
I have a timer on a server and some things can cancel this timer.
so is there no callback when the gpu has presented a frame?
seems so basic
how does IssuePluginEvent know which graphics buffer it was executed against?
it appears to be running immediately and not when a graphics command buffer is executed
does this make sense?
I found this which is where stuff like where OnMouseDown seems to get fired:
And the trail seems to go dead here:
I can't seem to find source for RaycastTry but it seems likely that it is only doing the raytracing in the container scene and not in the subscene. So I'm wondering if I need to add a camera to the subscene and switch the player to that camera after the subscene loads in...
Anyone had any experience with mouse events on colliders and multiple scenes?
can you use the modern event system?
I can give it a shot. Do you know if it works on colliders across scenes?
What framework do managed plugins need to be? <TargetFramework>net6.0</TargetFramework>
netstandard2.1
<TargetFramework>2.1</TargetFramework> Correct?
No, what I wrote is exact text
thansk
No problem
Any idea how to dotnet generate a 2.1 proj?
You mean command line? dotnet build? dotnet publish?
Commandline
like iirc dotnet publish -o outputpath
then you get dll
Just trying to generate the inital project with 2.1
Don't want to fuck around trying to scope the libs after switching from 6.0
Oh you mean how to create 2.1 project for first time
dotnet new classlib --framework "netstandard2.1" -o MyLibrary
Something like that
Dope thank you.
Hmmm... Unity is picking it up as a managed plugin, but I cant access it. Any ideas?
Is there a linker that auto connects with VS code? Or do I have to add the lib to my vs project as well?
IDE? you probably needs to regenerate csproj
i don't know because i don't use scenes ๐ฆ
Did it in Unity no luck.
Oh ffs
Plugins are now includeded wihtout having to import...
Is this new? Or am I missing something.
I have no using statements but I can access the plugin.
using statements are not imports, you can always access stuff with fully qualified names
they might have just removed the namespace on it
I should be able to state what namespace I want.
if you want stuff in a namespace you have you manually wrap it in a
namespace Name { // your code here }
Fuck, it looks like I have to restart VS each time I rebuild the plugin.
if i am editing things alot, will just use a asmdef instead of compiling my own dll
Also if you're using vs code there is reload command..
rider is pretty good at detecting the changes and reloading it as well
I'm getting tempted to get one
i work on multiple platforms, so made sense to use one that works on all of them
VS code is supposed to be that cross-platform IDE ๐ข
am also familiar with the other jetbrains ide's make heavy use of CLion, GoLand and PyCharm too
I'm up for any IDE but Eclipse family
ONE final question regarding plugins, is it safe for a plugin to use Newtonsoft from nuget? OR is there another way I would do this?
What would be the proper way to use libs in my own lib for unity?
unless you are distributing it as a package that can get complicated
Unity package manager lets you use com.unity.nuget.newtonsoft-json@3.0 as a dependency
otherwise i am not sure, if everything you need can be built into the dll its self it should be fine
but if it needs depednencies from elsewhere it can get more complicated
So just scope to the specific version?
don't know off hand, would need to test
i have seen it get ugly with other plugins before, where they included there dependencies as dlls that might clash with other things
So what would be the proper way to reference the unity version?
Download the lib from com.unity.nuget.newtonsoft-json@3.0?
So the workflow I did is
- My .net plugin reference Json.NET from NuGet to build dll
- Use Unity Package one for editor and runtime
Interesting I'll try it out, thanks!
I have an advanced issue. Whenever I have an event defined in my code for OnCharacterControllerHit(), unity allocates 80 B of garbage EVERY FRAME. Whenever I comment it out, the allocation goes away. Is there any way to avoid this GC.Alloc? Or is this unavoidable when scripting within OnCharacterControllerHit()?
got more details
what kind of event, like a C# event, a UnityEvent, just a unity message?
Can you share the code that you have added inside the OnCharacterControllerHit callback?
also the code invoking the event as well as subscriptions
yeah one sec
void OnControllerColliderHit(ControllerColliderHit hit) { if (hit.gameObject.CompareTag("Bomb")) { var bomb = hit.gameObject.GetComponent<BombBehaviour>(); if (bomb != null) { bomb.InitializeBombKick(gameObject); } } }
well right off the bat GetComponent allocates
CompareTag is also costly, switching over to layers is the way to go if you're concerned about performance here
a nice trick i have used before is cache both the collider and the component to a field on first hit
then on other hits, i first compare colliders if they are the same i use the component reference i already have
if not equal, then i save the new collider to the field and get the new component
have done this alot for raycasts that fire often, so i am not paying the full cost for a lot of hits to the same object
how is OnControllerColliderHit being invoked?
I use deep profile and it says that the method that is allocating the 80 B is CharacterController.Move_Injected()
it is being invoked when it the player runs into anything
no like how by what
and specifically only calls the GetComponent when it collides with a "Bomb"
Does GetComponent allocate? It should be just lookup
i dont believe it does
and it shouldnt be called every frame anyway
Especially when the player is standing still, because then OnCharacterControllerHit() is not being invoked
really
would think that should be a struct
but yeah that could be a allocation unless they keep mutating the same one
I wouldn't expect any optimization at the point they're using reflection ๐
actully never used unitys own CharacterController always just rolled my own
guess stuff like Collision is also a class and so other unity messages act like this
does feel like it should all be structs thought
To be fair they contains some lots of info to be struct
in the case of ControllerColliderHIt mostly references to stuff that already exists
and a few vectors
guessing a reference is like 8 bytes
each vector3 would be 12
think i rather copy that much data then deal with that in gc
#archived-code-advanced message
same amount there you go ๐ @green ether
so the napkin math more or less proves it
really not sure how it can be avoided outside of not using the CharacterController
Yeah only way would be not using that callback
though i am really not familar with CharacterController
I don't really use it too. It's too specific to be generic and too generic to be specific XD
its a bit of work to make your own, but should be able to keep the allocs low to non on update
since we got all the NonAlloc raycast calls
Unity default characterController pretty much suck ass! Only useful for testing ๐ฅ
Please do not use gay in a derogatory way.
ok
Does it actually effect your performance, tho?
I mean not really but i dont want 80 B allocations every frame
isn't something like that on mobile just bad?
Also with 100 players in a game that means that there would be 8000 B per frame
it adds up
Well you wouldn't load 100 players at the same moment with physics.. are you?
GetComponent will allocate in the editor even if the result is null, because null can be a fake Unity Object in the editor for UnityEngine.Object types.
If you're checking the result of GetComponent with null you should use TryGetComponent instead
Adding to the above, CompareTag wont resulted in heap allocation anyway
Well Generation-based GC is pretty optimized I believe
also would worry about it when its a issue
oh shit actually good advice
doesnt help my gc.alloc problem but is still helpful
need like a the more you know gif for that one
never knew TryGetComponent acted different memory wise
and i been using unity for a long long time
is there a better way to CompareTag() as well?
CompareTag is the best way to do it.
if you compare tags manually you inherit the cost of allocating the .tag string on the C# side.
(It also doesn't perform any checking whether the tag exists)
i tend to not use tags at all
same
in stuff like my raycasts i will get component for a interface type
its there for convenience only
and do little trick to cache the result, along with its collider so i can do a comparison instead of getting component everytime
only get component again on a change of what is hit
Is there guidance on OnMouseEnter() style events that don't require an interface to be implemented versus IPointerEnterHandler.OnPointerEnter()? I believe the latter is the only that works with the new input system? I was not clear from the docs
though will totally be swapping for TryGetComponent now that i learned about that extra detial of it
the interface way is the newer way
it ties into the same event system UI uses
its not related to legacy or new inputs system at all
Ah. The interface doesn't seem to work with colliders though yeah? Or perhaps it's because of my additive scene loading, which I'm kind of needing to use due to a Mirror networking consideration
it does just needs more setup
you need a EventSystem if you have a canvas you should already have one
and the camera that sees the collider would need a PhysicsRaycaster on it
Okay yeah, have that, though it's in the "base" scene and not the additive scene. Let me add the raycaster and see what happens
wont matter what scene the EventSystem is in
just make sure you only got 1
the Raycaster goes on the camera you are clicking from
there are 3 kinds a Graphic one for UI, a Physics and a Physics2d
Hmm, my only concern with the component based filter is that you'd have to have specific components for every element of would-be tag and changing/managing components may be more if a chore than say.. switching a string tag or enum.
@orchid marsh GetComponent works on interface types
Which brings enum to the table with custom types to differentiate, which works.
for example i got a IDamageable iterface
Never said it didn't.
anything that can receive damage implements it
lets me not care about the exact component, just if it has the feature i need
if im not mistaken there are no physics associated with CharacterController()
For instance, you no longer want said object to be a part of a group... with tags, your simply change it's value. With interface, you're going to need to removed said component and have variations without the specific interface to avoid being picked up by try get component.
They use something like SweepTest. it's just not Rigidbody.
Assuming you're now wanting to place the specified object into a different category that's not to be addressed with this function
ok, thats interesting
can someone explain to me how 100 players each allocating 80 B of garbage every frame isn't bad? Not trying to be sassy i just want to understand why its not a big a deal as i think it is?
is that a real usecase though?
If you find people changing tags for object, then it is very much applicable.
we more questioned, if its worth the amount of work to make your own character controller
@orchid marsh was in context to AltTabbed
What's the context?
Not that it's not bad, but in generational GC newly creates objects are likely to be GC'd quick
have never really found myself modifying tags at runtime, really if its categories i think i would just end up maintaining collections of them
its to each there own, multiple ways to skin a cat
i do not know, but there is a #archived-networking room, your question might not scroll off the screen before someone sees it if put there
sorry, context is that each player will have OnCharacterControllerHit() defined
Every frame is a concern. Should be aware though that stack is very fast (if applicable), pooling is memory efficient (avoids garbage collection) and that being a big deal or not it's relative to hardware - it's a big deal for potato computers or cheap mobile devices.
which is whats causing the 80 B per frame
I found a simlar document online that talks about OnCharacterContorllerHit() allocating 80 B per frame
from 2 years ago
its a unity message that is doing the allocations pretty hard to avoid
I mean yeah thats what I'm saying
I don't know what giving OnCharacterControllerHit() a definition would start causing 80 B to be allocated
just weird
why would it make sense for that to happen but not the same thing happening for OnCollisionEnter()
for unity messages, it does not call them unless defined
or OnTriggerEnter()
OnTriggerEnter just passes Collider
Well the hit from cc is a class type with some actual allocations.
Not sure about OnCollisionEnter, I think they would allocate too
i think OnCollisionXXX has the same issues
might be less memory
OnTrigger is passing a reference to something that already exists
I'm assuming Collision from OnCollisionXX just references other stuff (important data likely on the RB - thus requires an RB hitting it)
Collision contains a lot of data about that collision though
not just things on a rb or collider
contains mostly reference types though
ah its like all getters
When I say that there are things on the rb I'm referring to it not having to possibly manage/allocate any data itself.
ok I'm actually starting to understand why
very interesting.
So what I assume is occuring is the ControllerColliderHit class is being passed int OnControllerColliderHit() every frame, which explains why CharacterController.Move_Injected() is allocating 80 B of garbage every frame
sorry
is there any way to get OnCollisionEnter() to work with a character controller?
Have an rb on a child object with collider at it's level or below. Parent would have the Character Controller.
The way I used to have it coded was that OnCollisionEnter() was defined on the "Bomb" objects that were kicked around, and it would work fine. But when I switched over to a character controller, it stopped working
you are not going to like the normal way of makign a character controller from scratch
:(
more lots of short capsule or raycasts in the direction of movmement
so you can early out and not move, if they hit something
I feel like theres gotta be anotehr way aroudn this
would unity hate it if I put another collider on
just for fun ๐ ๐
Any ideas why GetWindow would be returning null on a Editor window?
var tempWindow = (ConfirmWindow<Category>)EditorWindow.GetWindow(typeof(ConfirmWindow<Category>), false, $"Delete ");
I doubt you can create a generic window
It took some hacking but I got it...
Could someone please help me figure out how to formulate this. Given a float x, I need to determine if the object is facing up or down.
Face From To
Down -450 -270
Up -270 -90
Down -90 90
Up 90 270
Down 270 450
(please mind the formatting - I know there is a simple solution to this, but it makes my brain hurt)
Looks like a negative sine wave
Where a period between [0, 360]
Would have it changing states (slopes) at```cs
000-090 (down)
090-270 (up)
270-360 (down)
It'd be the negative sign wave
Where pi would have been 180
pi/2 at 90
and 3pi/2 at 270
2pi at 360
I would use Mathf.Repeat and an if (switch case if you want sides too)
bool isUp = ((int)Mathf.Abs(x + 90) / 180 + 1) % 2 == 0;```
bool isUp = Mathf.Repeat(x + 90, 360) > 180;
For reference
What were not told is if 90 is up or down
As the example had it with both ranges but did not state whether it was inclusive or exclusive.
Thank you. I am trying to follow along but this problem makes me feel really dumb haha. The Mathf.Repeat seems to work. The IDE complains when I try to assign -1 * (Mathf.Abs(x - 90) / 180 % 2); to bool
result == 0, Edited.
Hey guys, I would appreciate it if someone could tell me how to detect edges using raycasts like in Marvel's Spider-Man (Web-Zip) and Batman Arkham (Grappling Gun) games, I've been strugling with it for a very long time.
Thanks.
-sin is just cosin
thanks, but i've already done it
i used 3 raycasts
first one casts from the camera
second one casts up from the first ray's hit point
third one casts down from the second ray's hit point and with a little bit of forward offset
and i used a capsul overlap to check if the ledge is suitable for the player
i suck at explaining, sorry
yea
alot
still struggling
it's saying that the ledge is not vertical but it is
that's true
it is?
How to use GetComponent dynamically.
Instead of writing ``` webSocketMenuServer.GetComponent<MenuServer>().rq_tcpid();
I can write something like
webSocketMenuServer.GetComponent(scriptName).rq_tcpid();
GetComponent has an overload that isn't generic, and that expects a Type argument.
Better solution, make the scripts you want to access implement an interface, and GetComponent that interface instead.
It'll return the first attached type implementing said interface.
To be honest I didn't really understand your solution
You're in #archived-code-advanced, expect advanced answers
Do you know what an interface is?
Yes I know
Alright so GetComponent can take interface types GetComponent<IMyInterface>(), and it'll return the first script that implements the interface.
So the proposal would be to make all scripts that are supposed to be fetched with that GetComponent, implement this interface, so one GetComponent can get different scripts
Hello so I am working on a first person script and I got everything to work 100% of the time but jumping. What happens is whenever I slid and jump my character flies into the sky (3-D btw). I have changed the gravity to -30 -20 and -10 but whenever I got to 0 or 10 I drift into the sky. I checked the code and even replaced the code many times now to see if it was the problem but it doesn't seem to be the issue. It has to do something with how the code works with gravity but I don't know. Any Ideas? (going to get code)
this is everything to do with jumping and gravity
I think
Also read #854851968446365696
my bad
Hey I have a function that takes TerrainData and sets large arrays of data to ComputeBuffers (data about grass positions), it takes around 16ms, and is a one time thing (only called once, when chunk is generated). What is the best way to call that function and wait for it to finish without making the game stutter?
Could it be turned into an IJob? I haven't worked with the job system, so I want to ask first
ok i will look into trying that
what exactly takes 16ms ? generating the points, or just copying alone ?
dont know for sure, but good point, i'll check it out
if copying it to the gpu is the bottleneck, then this wont help i think???
parallelization (Jobs) would help with generation
but for copying a simple async routine (async or coro) would work
and data would need to be split into chunks too
yes that i know, but i haven't worked with jobs or coroutines ever (i am coming from c++ ๐ ) so i have to look up the implementation
but does copying to the gpu memory halt everything else?
like i mean in rendering
also, if you only need some point field on the gpu for geometry shader stage, you can take a look at tessellation stage
I use that to render grass fields
for the initial setup I was also sending point distributions into the shader
yeah i am rendering grass, but heard geometry shaders are a nono
what is the performance like? i am doing very fine with DrawMeshInstancedIndirect ๐
yeah, I heard that too, until I came across a talk by Ghost of Tsushima devs
they use it extensively
I'd say performance is great, but I haven't actually tried to run it on a mediocre device
I might look into it in the future, thanks for the info
what are you working on?
that requires grass
But if but Ghost of Tsushima runs on consoles, I'd imagine you can make performance good
Yeah, makes sense
Hi I needed some way to run unity functions in Editor script, from another thread.
ok so I think I figured out drawmeshIndrect well enough and got some results, but I encountered something that I cant wrap my head around; I have 3 meshes that are being drawn :
for (int i = 0; i < LODMeshes.Length; i++){
MeshMat.SetBuffer("_ChunkData",LODBuffers[i]);
MeshMat.SetColor("color", colors[i]);
Graphics.DrawMeshInstancedIndirect(LODMeshes[i], 0, MeshMat, MeshBounds, ArgsBuffer, i * 5 * 4);
}
But only the last batch gets rendered to the screen, after some investigating, I found that if I only do one draw call of a particular buffer and mesh, it renders correctly, but when I have it in this for loop it does not
I need some way to run the getData () function inside the socket events, but socket events are handled on a different thread.
and note, this is an editor script
you can use unitask to easily run code on the main thread
This is the full code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hmm
don't know about that , let me search
will that work in editor script ?
in the edit mode
oh yeah, you were trying to create an http server a while ago right?
yes
yeah
alright let me test it
it really depends what your goals are
it's automating the editor remotely right?
through a web interface?
Doing it like this, with the same material, will draw all the meshes with the same value for color and chunkdata. Maybe using materialpropertyblocks will fix your issue
it's quite challenging to use async / await in an editor script
Thanks, I just saw that would be an issue haha, a hacky solution for now is just create duplicate material objects for each draw call
MaterialPropertyBlock exist for this specific case, it is more efficient than using different materials and they are easy to use, you should check that. Good luck!
Hello, i have a really advanced question. How would i be able to create runtime modifiable language/script or whatever. Basically i want a text file that you can type in stuff like Cube1 : Cube { position = new Vector3(0, 0, 0)} and so the game reads the file and for example gets the position of the cube1 and instantiates it in the position given in the text file. I'm looking for resources so i could start on this, i haven't really found anything useful on the internet (or i just can't look properly)
Also i forgot to tell you that the text file should be accessible in the built version of the game so when i build the game others can modify the text file
If you just want to place objects and set their properties, that's basically the same thing as loading in a save file. There are plenty of resources for that.
I know. It's basically the same thing as loading in a save file.
Also forgot to mention the fact that the object count should be based on how many objects are in the text file so if there's Cube1 and Cube2 there's 2 cubes spawned but if there's a 100 of them then a 100 gets spawned each using their own position
I have done savefiles but i don't really know of generating multiple objects with multiple properties that would probably be lists in unity i think
you can use moonsharp
it's robust
the text file would be a lua script
Is there a way to disable the profiling of a specific code block?
So to add to the topic i want like a text based map editor so there can be Cube1 : Cube { position = new Vector3(0, 0, 0); scale = //define my scale etc.} Cube2 : Cube { position = new Vector3(10, 4, 1); scale = //define my scale etc.}
you would author a "header", "preamble" or similar "library" for lua that would add things like a "cube" for your player to use in their lua scripts
@unborn vessel https://github.com/moonsharp-devs/moonsharp here it is, it's free. good luck out there!
There are plenty of tutorials also for saving and loading level data, you'll only need the loading part of that
a full scripting language would be overkill if you don't need actual scripting
what do you mean?
I've heard of it but can it access c# scripts? Since the Cube that it's inheriting from has all the values that the textmap is setting and also all the functions.
Yeah that looks like just some config file can be done with json or yaml
i kind of want to just turf this patient
can it access c# scripts?
sure
My sockets send methods are allocating garbage, so i whant to just ignore them at the profiler, is there a way to do it? (this is until i create my own native udp socket implementation of course)
Okay, i have enough resources for now so i'll try looking into it.
ignore them at the profiler
are you saying you have Deep Profiler turned on?
what do you mean ignore them at the profiler? the unity profiler? it will not create a span (technical term for a "Begin Sample" "End Sample" pair) unless deep profiling is turned on or you explicitly sample it
the better question would be why do people jump to recreating all of unity for 0 users
why not just edit in unity
for 1 user, you
yes, it's for multiple projects like controlling the editor through a phone etc
Yea i have deep profilling on, and i whant to disable the profilling of a specific code block.
hmm let me check
Well the point is i want the built game to be moddable and second of all, if no players play the game or something it will be a great learning experience etc.
do anybody knows how to fix this error
i get this error while building the project into apk
you can't do that no
CommandInvokationFailure: Gradle build failed.
C:\Program Files\Java\jdk1.8.0_77\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2020.3.21f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-6.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"
stderr[
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
try restarting your computer
ok i will try
When singularity comes we will create Unity that runs on Unity
Like PyPy
You gave me an idea. Why write a game engine in C++ when you can write one in Unity?
Yeah i know how those things work. That was fully a joke, why would i create a game engine inside unity.
Using a game engine like unity is really good too because you skip like 5-10 years of learning programming in languages like C++ and another ~5 years of the engine development
It uses Mono for the C# stuff right?
Sorry Unity admins to be going off-topic of Unity but before i'm trying to write a game engine i'd rather make a simple Asteroids style game in Raylib or something to learn the basics of C++
Yeah, this is so so annoying.
That might be part of the reason while I usually end up scrapping my interfaces (๐ข) and trying to accomplish the same goal with abstract classes. Not the same though.
From someone on Unity Answers:
"By definition serialization of an interface makes no sense because serialization is storing the state of the data of an object and Interfaces have no data.
Similarly, "inspecting" an interface makes no sense because the inspector displays the data, which an interface does not have.
If you have sub-classes that share data you should use an abstract parent class. You can use custom inspector inheritance to share inspectors."
They actually raise some fair points lol. Oh well.
Still would be nice, just for designers working in Unity at least.
Just for like restricting what can be assigned to a slot, and nothing more.
Haven't tried myself but I think you would be able to work around with custom inspector like
[OnlyAccept(typeof(IMyInterface))] public MonoBehaviour component
Probably
I'm going with DI Container ๐
It's not like it's unspecified behavior. It's a non-bevahior xD
Yes precisely. It really does remind me of how Unity is continually behind C#. And not just on newer features but fundamental ones like interfaces as well.
does anyone know how I fix this? I got these build errors when trying to build my project to webGL
I'm getting a warning saying "ShadowMap RenderTexture requested without a depth buffer. Changing to a 16 bit depth buffer." and render textures are not clearing themselves every frame. I'm using the custom material blit found here https://github.com/Cyanilux/URP_BlitRenderFeature/blob/master/Blit.cs. Has anyone here had a similar problem?
NVM found the solution, you just have to make a new URP renderer for cameras making render textures
This is a little bit hacky but it's what I have to do in order to get generic properties working in my window,
TL;DR I want to deconstruct a object with reflection then reconstruct it back with some data without using generics
I take a object break it down to it's properties, then collecting the data generically then I want to reconstruct it into it's original type:
public void Set(Data dataObject)
{
data = dataObject;
var propertyInfos = dataObject.GetType().GetProperties();
genericLabelObjects = new GenericLabelObject[propertyInfos.Length];
for (int i = 0; i < propertyInfos.Length; i++)
{
if (propertyInfos[i].GetIndexParameters().Length == 0)
{
genericLabelObjects[i] = new GenericLabelObject(propertyInfos[i].Name, null, propertyInfos[i].PropertyType.Name);
}
}
}
Lets say I pass my Set a public class Item : Data this Set function takes all the properties and puts them into a custom label, from there I can edit them, what would you guys do to get the data in the GenericLabelObject back into a Item object? Can you see a good solution to setting the data back into the Item?
Same way through reflection with PropertyInfo.SetValue?
Iterate through the properties of the original Data then set the values with the keys?
How would I be able to say it's an Item?
Without Generics?
You can get specific property by the name
You are already have property name, type wouldn't matter
This is for the object itself, not the properties.
And isn't he getting the type in the dataObject.GetType()?
Are you asking how to get a new instance of Item?
I need to pass a new instance of the passing type.
Serialize.SetJson<Item>(data)
Item In this case being what I'm trying to construct.
If I pass my Set a Foo then Serialize.SetJson<Foo>(data)
I'm just looking to re construct my original Data back into the type I passed initially.
Without using generics.
Well you need a Type at least then you can use Activator.CreateInstance
I don't think I can pass it typeof can I?
Serialize.SetJson<data.GetType()>(data) Shouldnt this work?
No that's not how generic would work ๐
You can pass typeof(Item) to Activator.CreateInstance if that's what you're asking
I didn't think I could, testing.
I'm using an asset UniStorm with URP URP 13.1.8 on 2022.1.16f and I get this error
error CS1503: Argument 1: cannot convert from 'UnityEngine.Rendering.Universal.RenderTargetHandle' to 'UnityEngine.Rendering.RTHandle'
error CS1503: Argument 2: cannot convert from 'UnityEngine.Rendering.Universal.RenderTargetHandle' to 'UnityEngine.Rendering.RTHandle'
The line is
copyDepthPass.Setup(RenderTargetHandle.CameraTarget, RenderTargetHandle.CameraTarget);```
full function:
```csharp
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
if (!settings.isEnabled)
return;
// UniStormAtmosphericFog Pass
fogPass.settings = settings;
fogPass.Setup(renderer.cameraColorTarget); //, renderer.cameraDepth);
renderer.EnqueuePass(fogPass);
// CopyDepth Pass
if (Application.isEditor && !Application.isPlaying) return;
copyDepthPass.Setup(RenderTargetHandle.CameraTarget, RenderTargetHandle.CameraTarget);
renderer.EnqueuePass(copyDepthPass);
}
simply changing it to RTHandle. does not work it tells me it doesn't exist in the current context. I think maybe because it has to be setup/initialized?
Not sure if this is considered advanced, can move if needed.
I joined the developers discord and there was someone who asked a month ago with no response.
Thoughts on this: newInstancePropteries[i].SetValue(newInstance, Convert.ChangeType(genericLabelObjects[i].value, newInstancePropteries[i].GetType()) );
I'm not seeing how I can get past the dynamic casting:
InvalidCastException: Invalid cast from 'System.String' to 'System.Reflection.RuntimePropertyInfo'.
All my values in my constructed data are strings
cos of zero differs in that it usually starts at 1 without offset.
Where -sin is that of the sine wave but with a negative slope.
where -sin would be equal to sin(x + pi).
cos would be that of sin(x + pi/2)
What do you mean by dynamic casting? You sound like trying to deserialize string to specific type
Ah I see where you got wrong idea. newInstancePropteries[i].GetType() is type of PropertyInfo
Is there a better way?
for (int i = 0; i < newInstancePropteries.Length; i++)
{
if (newInstancePropteries[i].PropertyType == typeof(uint))
{
uint n;
uint.TryParse(genericLabelObjects[i].value, out n);
newInstancePropteries[i].SetValue(newInstance, n);
}
else
{
newInstancePropteries[i].SetValue(newInstance, genericLabelObjects[i].value);
}
}
You should use PropertyType yeah
Convert.ChangeType should work too
Thanks mate!
for (int i = 0; i < newInstancePropteries.Length; i++)
{
newInstancePropteries[i].SetValue(newInstance, Convert.ChangeType(genericLabelObjects[i].value, newInstancePropteries[i].PropertyType));
}
lol
no i hear you ๐ it's a good idea
might as well do it with moonsharp
i think you should use 2021 LTS
there are 0 new features for you in 2022 for URP
otherwise you can fix this yourself using RTHandleProperties
i don't have my editor open so i don't kow exactly what it's called
?
as in a pipeline asset
Don't cross post
lol discord mod wannabe
i see...
@gilded shuttle Don't whine if someone calls you out. There's no crossposting here, #๐โcode-of-conduct
Hello Im getting this erro Deterministic compilation failed. You can disable Deterministic builds in Player Settings Library\PackageCache\com.unity.multiplayer-hlapi@1.0.4\Editor\Tools\Weaver\AssemblyInfo.cs(22,28): error CS8357: The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation
does anyone know how to solve it ?
var webSocketMenuServer = GameObject.FindWithTag("WebSocketMenuServer");
webSocketMenuServer.GetComponent<MenuServer>().Invoke("rq_tcpid", 0);
I try to call a function using a string name
but it doesn't seem to work
Can anyone see why this isn't removing the object?
public static void DeleteItem<T>(T data, Path path)
{
if (DataStore.HasFile(path))
{
var dataCollection = Deserialize<T>.GetJson(path);
dataCollection.Remove(data);
var json = JsonConvert.SerializeObject(dataCollection);
File.WriteAllText(DataStore.GetFilePath(path), json);
}
}
You need to pass it a delegate.
You googled it?
yes it said that I should do sth with multiplayer HLAP but didnt find it only found multiplayer HLAPI but then it said that I should click up to date but cannot find it
Or even:
public static void DeleteItem<T>(T data, Path path)
{
var dataCollection = new HashSet<T>();
if (DataStore.HasFile(path))
{
dataCollection.UnionWith(Deserialize<T>.GetJson(path));
dataCollection.Remove(data);
var json = JsonConvert.SerializeObject(dataCollection);
File.WriteAllText(DataStore.GetFilePath(path), json);
}
}
It tells you the error mate: You can disable Deterministic builds in Player Settings
what is player settings
Did you google it?
is it the only way?
Unless you want to use reflection , yes.
@chilly nymph thanks fixed it ๐
What is data? Reference type I guess?
Did you implement IEquatable<T> or override Equals?
what type is T, if its a reference type it will not work since the identity will not be the same
For a .Remove()?
Yes
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove?view=net-6.0
If type T implements the IEquatable<T> generic interface, the equality comparer is the Equals method of that interface; otherwise, the default equality comparer is Object.Equals.
Just got back, sorry I don't see what you mean.
So.. if T data is reference type list.Remove would try to find element to remove with reference equality
Isn't that just a comparitive?
I understand what's going on. That's not the issue, I'm just looking for a way to reference in the proper way.
.Convert for this again?
So it's not going to remove anything because there is no same data in there
Deserialize<T>.GetJson(path) so then .Convert this?
No, if deserialization works then why would you Convert
It's just not removing because list checks reference equality as in
It cannot compare your data and list's elements
Because there is no equality check logic given
so it just trying to check with "pointer address"
public static void DeleteItem<T>(T data, Path path)
{
var dataCollection = new HashSet<T>();
if (DataStore.HasFile(path))
{
dataCollection.UnionWith(Deserialize<T>.GetJson(path));
dataCollection.Remove(data);
var json = JsonConvert.SerializeObject(dataCollection);
File.WriteAllText(DataStore.GetFilePath(path), json);
}
}
.Remove would handle the check,
No, the elements in dataCollection is newly created
data is already created before you call DeleteItem
They are not same element
Ah.
Sorry I was being a retard, I understand, what's the best way to get a reference to the data?
So since you are doing serialization you cannot 'recover' actual reference to data
But for this use case you can implement IEquatable<T> or override object.Equals
you would have to make sure your type has its own way to test equality
To provide custom equality check
does not do the same thing, but other approach would be pass a delegate in as a selector
that way you can choose a field or something to select on
or you could constrain the data to just structs
so its not a reference in the first place
Or, you can perform PopulateObject to your original data
So your original data get overwritten, instead of creating new objects
What about construct the set again but with out the data I don't want? It's heavy...
^^ That may work.
Thanks lads
to me its kinda weird a remove function is Deserialize and doing a Serilize
would think Deserialize would happen eariler and you just hold on to the data in memory and modify it as needed
Yeah just piping in the logic will move it over.
It needs to deserialize the original json to remove what it needs, I don't keep this in memory. .
where does the object you are removing come from?
Json
from the same json?
It desseralizes the data then I need to remove an element then write back to json.
turn off deterministic compilation in your player settings
The item comes from the json.
from the same json file?
then why are you deserialize, to find the object to remove, then doing a deserialize again to do the remove
He's asking where the data is coming from
dataCollection.UnionWith(Deserialize<T>.GetJson(path));
if you need to remove a field from json, you can read it as a JObject, delete the field, then write it back
you do not need to interact with strong typing at all
i am asking where data comes from
I still need a reference to the data I need to delete.
I guess I could construct my data as a JObject.
But it's pretty much the same thing.
Why? ๐
well if it came from the same place you are trying to remove it from, you are doing way more work then required
and making it a more complicated issue then it is
How so?
if its something you constructed yourself, then that is different
It's a CRUD system
This is a delete function.
๐
I need to be able to delete data.
because of the reference equality and it not having the same identiy
if you want the comparison to be by value, you will need to tell it how to compare equality or will need to not use a reference type
like use structs instead
since its not working because the exact instance of data you are passing in does not exist in that hashset
Yeah I was just being a dumbass, was thinking I could get a free Remove out of the collection.
I understand now.
If you use C# record type and it gives you free Equality check ๐
Not sure it will work well with Unity, tho
if the type contains a id, you could also just compare on that
I was orignially thinking that but in terms of what the full system needs its not that easy.
I'm leveraging the union, otherwise I would. I'll figure something out. Thanks guys!
well define what you count as equal
Pointers
but you don't, based on your problems
Dude, the problem was understood like 10 min ago.
C# isn't my native language, as soon as Cath said pointers I understood.
We're way passed what you're tyring to explain. ๐
๐
Jobject has remove, thabks for the advice gents!
This is a double post from shaders as well. I'm trying to work out an idea for a skybox around a tiny planet. I've been stuck on it for a while. Has anyone done something similar or have an idea that I could try? Thanks.
is it common for tilemap state around a tilemap position to be stored as a string representation of binary?
No
"string representation of binary"? Sure, it's common enough to save all sorts of things as bit flags. But what do you mean about the string part, literally "00111100"? It would defeat the point if you saved that as a string
If you wanted to transfer that as a string for human-in-the-middle reasons you could use hex ("3C") , or if you had a whole bunch of it, base64
I've been studying roguelikes and procedural map generation lately. Cellular automata is next on my list after I'm done with these tutorials https://youtu.be/szOq1HSWtm0
In this episode, he's taking an approach that I am at first a little skeptical of... but maybe it's fine. I'm not sure yet.
Learn how to procedurally generate a 2D dungeon in Unity using Random Walk and Binary Space Partitioning algorithms! In this tutorial we will use unity Tilemaps to create single and multi room dungeons connected by corridors using Corridors First and Rooms first approaches.
Resources
https://github.com/SunnyValleyStudio/Unity_2D_Proecdural_Dun...
He's looking at all the tilepositions around the current tile in a foreach loop, and building a string representation of 1=floor 0=not a floor
Just at a glance there's some bizarre stuff going on as far as I'm concerned. A hashset of bitmasks that is used as a helper is weird as hell
These things should just be enums, which has the added benefit that you can't just come along and directly modify it from anywhere
Right, I was like... surely there's a more standard way of doing this..
is it for performance reasons or what?
Yes, for performance reasons. Strings are immutable, so any time you operate on a string that will allocate a new string
right so his approach is actually not performant
so in this foreach loop (presumably 9 directions) that's 9-ish strings being created and thrown away. Small, but if that's used often enough it'll contribute to GC
to his defense, the algo only runs once when the scene loads, so... yeah
It should all just be enum flags and literal bit operations. But I presume he didn't want to teach binary logic?
he did mention powers of 2 for the binary positions but hasn't used the concept yet
Or maybe he wanted it to be able to scale out to not be binary, and eventually just have any letter represent a different tile type
which is also weird to me, but less bad than just doing what should be a traditional bitmask
I'll finish the video series but at this point I am going to hold off on typing every line manually like I have been doing since the start.
I'm trying to understand all of the code without just downloading it from GitHub.
I've made a few changes along the way
If you're learning I think it's fine to just view most things as experiences to pick up, not even correct experiences, just as long as you're doing something that you think about, you're learning
yeah, I have compiled a list of like 10-15 videos on this subject that I thought were really good, really advanced. Prim's algo, MSTs, A*, Random Walk, Cellular Automata, and more.
If you want an overview of how it might work if you had an actual bitmask, which could be a single byte I have a little overview that should be familiar enough if you're doing similar things: https://help.vertx.xyz/info/bitmasks
bitwise operators
This is the most disgusting thing I've written in a long time:
public static void DeleteItem<T>(T data, Path path)
{
var obj = JsonConvert.SerializeObject(data);
JObject remove = JObject.Parse(obj);
using (StreamReader file = File.OpenText(DataStore.GetFilePath(path)))
{
string json = file.ReadToEnd();
JArray array = JArray.Parse(json);
JToken token= new JObject();
foreach (var item in array)
{
if (JToken.DeepEquals(remove, item))
{
token = item;
}
}
array.Remove(token);
}
}
Please tell me there's a better way.
hey guys, both the other chats are super dead tonight. was wondering if you knew a way to disable the physics of a box collider but still get the collision detection for it. Basically I built an in house renderer to draw close objects, medium objects, and far objects but my camera seems to skip anywhere from 45 degrees to 90 degrees sometimes randomly. My assumption currently is that I'm colliding with an object and getting thrown.
also should say my detection box for drawing is a very large box collider
Trigger or Layermask https://docs.unity3d.com/ScriptReference/LayerMask.html
awesome thanks, ill check it out
maybe the question is why.
like the simple alternative would be just save the whole object later back to disk
instead of dynamically trying to update it like that
cause theres no benefit from doing this
"like the simple alternative would be just save the whole object later back to disk" I'm saving it to disk there.
How so?
What are you talking about mate. This is how I have to do it. ๐
i mean over the way i mentioned
What way did you mention?
or the normal way
just save the whole object
and override the json
instead of trying to take sections
It's a delete function mate.
I need to grab the item to delete from the json.
no thats backwards thinking
I don't have any references to any data.
why would you need to do that
Because I need to get the object from json.
No it's not.
It's getting the data, then deleting the specific object from that data.
then what do you do with that data?
What does it matter?
cause that changes why this is necessary or not
This is a delete item function.
Thanks.
Since a native array is a struct, does passing it by value breaks it?๐ค
I'm getting an error saying that I'm trying to access a disposed array. Trying to figure out wether it's due to passing it into another method or because I misunderstand the lifetime of an array retrieved with async GPU access...
I'm guessing you've tried to reference it and are getting that error?
it kinda depends on when the other method runs i guess?
cause passing it by value doesn't copy it
since its a native array
when one gets disposed every one of them dies
What's the exact error?
ObjectDisposedException: The UNKNOWN_OBJECT_TYPE has been deallocated, it is not allowed to access it Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckReadAndThrowNoEarlyOut (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle handle) (at <823fb226a3f9439cb41fdcb61f9c86a1>:0)
Unity.Collections.NativeArray`1[T].CheckElementReadAccess (System.Int32 index) (at <823fb226a3f9439cb41fdcb61f9c86a1>:0)
Unity.Collections.NativeArray`1[T].get_Item (System.Int32 index) (at <823fb226a3f9439cb41fdcb61f9c86a1>:0)
BuilderGods.Terrain.EdgePathGenerator.GeneratePath (System.Int32 firstNodeIndex, Unity.Collections.NativeArray`1[T] edgeInfoArray, System.Collections.Generic.List`1[T] remainingNodes, System.Boolean looping, System.Threading.CancellationToken ct) (at Assets/Scripts/TerrainSystems/EdgePathGenerator.cs:138)
Added a bit of callstack for context.
From the look in the debugger it seems to have the same pointer and other properties before and after passing it to the method, so I'd assume that copying it is not the issue. It's probably something with Async gpu access and me trying to process several arrays at the same time.๐ค
but the problem is never whether its the same
its whether or not it gets disposed during its access lifetime
Yeah, that's what I'm wondering. When would it be disposed? Does it only exist for 1 frame?
depends on whats managing the resource
Hmm... Async gpu acess?
I'll try to copy the data into a regular array right when I get it.
Seems like it was it.
I guess the issue is that I was passing it into an async task. It was probably being disposed on the next frame which caused the issue.
Native collections should always be manually disposed. Presumably what allocated it is disposing it?
Depending on the type of allocation there's also rules on how long the allocation can live for
yeah, async gpu readback result exists for just one frame, need to copy the entire result on the same frame you get it
in the WebRTC, the video receive sample is setting the raw image's texure all the time. That is taking a lot of resources and may not work with 4K. Is there a better way to do it?
you can try finishing the experimental/directrender branch on github. the work is not done
That is taking a lot of resources
it's more nuanced than that