#archived-code-advanced
1 messages · Page 129 of 1
You can modify transforms with the job system using TransformAccessArray. It splits the work to a thread per root transform.
Oh really? Oo i was not aware of this
are their any good docs for ECS outside the unity package one ?
just curious if the community wrote some external docs
Something to note about multithreading on mobile: on PC and console, multithreading is like a free performance gain. There's basically no downside, just free hardware waiting to be used, if you can write the code to use it.
On mobile, it comes at the cost of more heat and battery drain. You'll get a performance gain, but it could mean the phone will overheat sooner and start slowing the CPU down to cool down.
thanks for this important notice
since im working on a casual game users arent expected to be pluged in
so i guess ill focus on using the single game thread
It still has its place. Its better to offload to a thread to prevent visible lag spikes every now and again.
Does anyone know what could be a reason on why this could create garbage once MeshRequets.Count is less than 1? It should leave the method, there shouldn't be any garbage. Somehow the sort changes the list in a way that it laters creates garbage, even when it's not called.
private List<TerrainConfiguration> GetCurrentRequests()
{
if(MeshRequests.Count <= 1 || _GenerationMode == GenerationMode.AsTheyCome){
return MeshRequests;
}
var currentCameras = viewSettings.GetCurrentCameras();
MeshRequests.Sort((a, b) =>
{
Vector3 posA = infiniteLands.LocalToWorldPoint(a.Position);
Vector3 posB = infiniteLands.LocalToWorldPoint(b.Position);
float distA = currentCameras.Min(a => Vector3.Distance(a.transform.position, posA));
float distB = currentCameras.Min(a => Vector3.Distance(a.transform.position, posB));
if (LoadInViewFirst)
return CompareWithVisibility(distA, distB, posA, posB);
// Default sorting by distance without visibility consideration
return _GenerationMode == GenerationMode.FarFirst ?
distB.CompareTo(distA) :
distA.CompareTo(distB);
});
return MeshRequests;
}
The lambda itself is an object that creates garbage
yeah, but if MeshRequests.Count <= 1, it shouldn't create any lambda
it's consistent 32B and I got no clue why
I've verified with the profiler
let me send a screenshot
Doesn't the profiler just give you a summary though? Like it doesn't differentiate between different calls of the same method afaik
it just tells you the number of invocations and the total amount of GC for all of them, IIRC?
Indeed, this method however is called only once per one object one time at the frame
this is the method, and on the same frame I can see mesh requests is 0 (it doesn't increase neither before or after) also verified through debug.log that it goes through that and nothing else.
Could it be that the runtime creates the lambda anyway even if it doesn't get to that point?
ILSpy could help
Or trying to move the lambda to a dedicated function for the moment.
That's what I'm starting to worry, but then it would mean that code that shouldn't be called is being called. My only guess is that when calling sort that way, something changes inside the list that makes it create that garbage
afaik Sort has no lasting effects on the list other than the rearranging of its elements
tried that, still 32B
What happens if you try this @tired fog ?
private List<TerrainConfiguration> GetCurrentRequests()
{
if(MeshRequests.Count <= 1 || _GenerationMode == GenerationMode.AsTheyCome){
return MeshRequests;
}
return GetRequestsWithLambda();
}
private List<TerrainConfiguration> GetRequestsWithLambda() {
var currentCameras = viewSettings.GetCurrentCameras();
MeshRequests.Sort((a, b) =>
{
Vector3 posA = infiniteLands.LocalToWorldPoint(a.Position);
Vector3 posB = infiniteLands.LocalToWorldPoint(b.Position);
float distA = currentCameras.Min(a => Vector3.Distance(a.transform.position, posA));
float distB = currentCameras.Min(a => Vector3.Distance(a.transform.position, posB));
if (LoadInViewFirst)
return CompareWithVisibility(distA, distB, posA, posB);
// Default sorting by distance without visibility consideration
return _GenerationMode == GenerationMode.FarFirst ?
distB.CompareTo(distA) :
distA.CompareTo(distB);
});
return MeshRequests;
}```
Also if you replace:
if(MeshRequests.Count <= 1 || _GenerationMode == GenerationMode.AsTheyCome){```
with:
```cs
if(1 == 1)``` just for a moment, does that do anything?
maybe ther's some kind of boxing happening with one of those comparisons? 🤔 Or maybe _GenerationMode is a property that does some allocation? But that doesn't show in the profiler 🤔
wtf, this seems to remove the 32B
ok yeah that seems to support my theory about the lambda being allocated at the start of the method invocation
wow
yeah, so
this bad
private List<TerrainConfiguration> GetCurrentRequests()
{
if(MeshRequests.Count <= 1 || _GenerationMode == GenerationMode.AsTheyCome){
return MeshRequests;
}
var currentCameras = viewSettings.GetCurrentCameras();
MeshRequests.Sort((a, b) => SortingList(a, b, currentCameras));
return MeshRequests;
}
this good
private List<TerrainConfiguration> GetCurrentRequests()
{
if(MeshRequests.Count <= 1 || _GenerationMode == GenerationMode.AsTheyCome){
return MeshRequests;
}
return GetRequestsWithLambda();
}
private List<TerrainConfiguration> GetRequestsWithLambda() {
var currentCameras = viewSettings.GetCurrentCameras();
MeshRequests.Sort((a, b) => SortingList(a, b, currentCameras));
return MeshRequests;
}
curious what the il difference on that is
ILSpy can tell you for sure but my theory is that the runtime allocates the lambda at the start of the method for some reason.
That feels extremely weird, I don't have ILSpy to check rn, but well, thank you for that. I guess I learnt something new
You should be able to make a new Action one time to re use if it doesnt need to capture func scope things
I made a very simplified (and pointless) version of your code here. You can see the lambda getting compiled even though the code is unreachable. If you comment out the lambda, the compiler generated Blah goes away.
C#/VB/F# compiler playground.
Ooooh, interesting! Thanks!
But I don't quite understand why this would create garbage tho
(not sure if Im doing this right)
but here for example, altough compiled and the new comparison is created, it shouldn't be called if thing is 1
C#/VB/F# compiler playground.
The way I understand it, is that once compiled, the outer method will create the object for the lambda call regardless. It doesn't yet know if the code is reachable, so has to create the object every time. It can't look ahead and decide each time.
Anybody had any success pre-allocating native memory and then assiging NativeArray's to that memory to be used in the jobs system?
How do you keep the body above the ground in a proceduraly animated creature?
oh, i never thought about that, but that assumes you only have 1 collider no?
You procedurally animate the body position too
https://i.imgur.com/DKwmJ6M.png
Not entirely sure how to go about this, but I'm building a Mesh and using Graphics to draw it because using Handles or GL Lines makes the editor cry when there's too many lines going on. So far it works alright with my custom shader, but I'm at this point where if I try to zoom out it becomes more distorted. Any idea how to solve this without having to recreate the mesh?
I had it working by increasing the thickness of the lines using the GL immediate mode so I know that would work
I'm guessing it'll have to be in the shader
I assume this is probabaly the place for this question but im making a multiplayer game and im trying to use Scriptable Objects but using NGO Scriptable Objects dont network. So I come to ask what is the solution to still using the modularity of Scriptable Objects but still be able to network them
there is #archived-networking and a unity multiplayer server pinned in there. Though this doesn't really make sense for a variety of reasons. This would be like saying "all my monobehaviours dont automatically network". They shouldnt. You define what is networked through network variables or the existing components NGO provides. This would also imply you're trying to change SO values at runtime, which you also shouldn't be doing
Instead of a lambda you can use the IComparer<T> overload to avoid allocation.
How exactly?
Need help:
I am using Motion Matching Locomotion Controller for Lower body movement (walk, run etc) and using Mecanim for Upper body. I have a knife aiming animation, my character goes into that state successfully but the animation doesn't play and my character is tilting forward/backward. What can be the issue?
IComparer creates allocation every frame
You allocate one and keep reusing it.
You don't allocate one every time you call that function, you allocate one and keep reusing the same one, similar concept to pooling.
Last time i checked, even catching was creating garbage every frame, same as it shows on the stackoverflow thread
Not sure how try catch comes into play?
It doesn't. You just create one, store it, and keep using it.
IIRC it internally allocates regardless of how you use it
The IComparer<T> overload of Sort?
Yes
If true, that would be news to me.
Well, the function overload can be written to zero alloc too, you would just basically write the lambda capture yourself.
No, this creates garbage too
I also checked the creating an object and pooling, and it creates garbage too. The benefit is that it's creating only when actually using it, so empty arrays or skiping it doesn't create garbage. Not sure if performance is affected tho
Generally, a little bit of GC is not gonna cause any issues. The overhead of releasing it is probably gonna be negligible.
As long as it doesn't happen every frame it's safe to ignore it.
yeah, i know, im gonna go with this last option since it's the most readable and 128B every so often is not that bad, since it doesn't increase or change, constant 128B is good
That's why I said "write the lambda capture yourself." That is still capturing, it's an instance method so it captures this.
If you instead use a Comparison<float> sort and do sort = SortingList once and reuse it, it would have zero alloc.
Actually if you look at the lowered C# code (eg with SharpLab https://sharplab.io/#v2:D4AQDABCCMAsDcBYAUCkBmKAmCBhFA3ihCVJiLBACID2AyjQE4AuAFAJQQC8AfBAHYBTAO4QAMgEsAzswA8E/sx4cAdAxatcNALYAHAIaNB7JMlIRipXYwkA3fc0EQFzPDoNHWLiPoA0zxQgAI05eHxUtPUNBABUaVhDTAF8gA==), it's a lot clearer why:
new List<int>().Sort(Compare)
// desugars to
new List<int>().Sort(new Comparison<int>(Compare))
And that's where the allocation comes from.
if you want to easily check if your lambda is capturing anything or not, put the static keyword in front it and see if you get errors 😄
Guys I'm pulling my hair out, no matter what I do, surfaceInput.emission is the only value that affects the output. Was this specific function deprecated? There's like zero documentation about it anywhereeee
float4 Fragment(Interpolators input) : SV_TARGET
{
float2 uv = input.uv;
float4 colorSample = SAMPLE_TEXTURE2D(_ColorMap, sampler_ColorMap, uv);
InputData lightingInput = (InputData)0;
lightingInput.positionWS = input.positionWS;
lightingInput.positionCS = input.positionCS;
lightingInput.normalWS = normalize(input.normalWS);
lightingInput.viewDirectionWS = normalize(GetCameraPositionWS() - input.positionWS);
lightingInput.shadowCoord = float4(0, 0, 0, 0);
lightingInput.fogCoord = 0;
lightingInput.vertexLighting = float3(.5, .5, .5);
lightingInput.bakedGI = float3(0, 0, 0);
lightingInput.normalizedScreenSpaceUV = input.uv;
lightingInput.shadowMask = float4(0, 0, 0, 0);
lightingInput.tangentToWorld = float3x3(1, 0, 0, 0, 1, 0, 0, 0, 1);
SurfaceData surfaceInput = (SurfaceData)0;
surfaceInput.albedo = colorSample.rgb * _ColorTint.rgb;
surfaceInput.alpha = colorSample.a * _ColorTint.a;
surfaceInput.emission = 1; // setting to 1 gives white, 0.5 gives grey, no other vars do anything.
surfaceInput.metallic = 1;
surfaceInput.occlusion = 1;
surfaceInput.smoothness = 1;
surfaceInput.specular = float3(1, 1, 1);
surfaceInput.clearCoatMask = 1;
surfaceInput.clearCoatSmoothness = 1;
surfaceInput.normalTS = float3(0, 0, 1);
//return float4(surfaceInput.albedo, surfaceInput.alpha); // This works as expected
//return float4(lightingInput.viewDirectionWS.rgb, 1);
return UniversalFragmentBlinnPhong(lightingInput, surfaceInput);
//return UniversalFragmentPBR(lightingInput, surfaceInput);
}```
Yeah static will force a check to make sure nothing gets captured. Another thing you can do is to hover over the => of a lambda and IDE will tell you what it captures, although this doesn't work for the case of .Sort(Compare).
Aaaaah, okay, that does seem to be zero alloc then! Cool!
Hello, I'm having an issue creating materials at runtime because my mesh has mutliple materials slot using the same material and I did create an array of materials with the amount of material required and the shared material is stored multiple time in the array. But when I use mesh.materials = matArrayl it seems to create an instance for each slot instead of using the shared materials.
Is there any way to fix this?
mesh.sharedMaterials = matArray sounds like what you need?
But sharedMaterials will modify the materials for all models using this mesh at once, wont' it ?
no, it only affects that renderer
OK I'll try
if you modify the material object itself, that will affect everything using it of course
a reference to a sharedmaterial != the sharedmaterial
Hm, still not working, I get two different instances for the same material. How can I make sure my two materials in my array are the same reference ?
can you share the whole bit of code?
The code is quite long because I load a lot of stuff.
My materials are created through XML files stored in StreamingAssets to allow modding
And I have a class which match the materials properties to the XML tags
This function is used after I've moved my data from my XML to my class. It then uses the class to create the material.
I store the existing materials in materialsUsed and in my XML, I have an attribute to tell if a material is a copy of another so I can use the reference instead of created a new one
I've added a debug log in the if, to check if my code does take the original reference and it does debug it so the reference should be ok
So I'm assuming there's something going on here
for (int j = 0; j < mats.Count; j++)
materials[j] = mats[j];
skinRenderer.sharedMaterials = materials;
cus this is advanced chat, debugger time
we dont do logs and guess here
that will help as you can check while debugging if references are the same via the immediate window
there's a lot going on there so it's hard to tell at a glance but yeah, it'd be good to sanity check in the debugger for example that the number of items in materialsUsed is less than the number in the array
Btw you dont need to make a new array as the managed material array is not used anymore by unity as it goes into native engine code so its a waste
Hm, never used the debugger. I'll have to look into it.
oh boy
i think that's because mats is a list but yeah, you can use SetMaterials to pass in a list directly
or SetSharedMaterials i guess
The variable mats is a List. I used mats.ToArray() but since I ended up with duplicate instances, I thought maybe the ToArray was duplicating the instance so I tried with a for loop to make sure it doesn't change
SetMaterials() is better so you can re use the same list to avoid allocating many arrays
Ah, I didn't know. I'll try.
Dont do this as it does nothing beneficial here and allocates more
Yes I know, this was only intended to be used until I found why I get two instances.
Right. If you dont make new Material instances then they are shared by those its given to.
Found my issue. Another part of my code was modifying the materials and was using .materials instead of .sharedMaterials. Now it's working as expected. Rookie mistake :x
I'm trying to make a terrain editor that takes rectangular sections of the terrain via GetHeights and SetHeights. It works fine for bulk modifying a rectangle to a new value, but I want to add in some more resolution and more shapes. Is there some sort of set of mathematic formulae I can read up on that will give me a grid of "modifiers" for something like a tapered circle? Like, a grid of floats that I would multiply with the height I want to use to smooth it off in a sort of circular mound?
Basically, given a width, height, and "softness" can I generate a grid of normalized floats that make up an arbitrary shape (or just a circle, if making brushes would be too hard I could just not) with fuzzed edges?
Also if there's some sort of library out there that can do all the matrix math for me I'd greatly appreciate it
Sounds like you want something based on signed distance fields and constructive solid geometry. (compositions of mathematical definitions of shapes) you would sample these at any grid resolution you’d like.
https://i.imgur.com/B0zsVGX.png
Any idea why my mesh is being drawn on the scene toolbar? Using Graphic's immediate draw mesh method on the editor
I assume it has to do with drawing the mesh to all viewports or something?
Yeah, think that was the issue. Can't specify the viewport with DrawNow
Does anyone know how i can debug stuff frame by frame? I have some NON Physics based movement which im running in fixed Update, In theory this script should be the only thing influencing my players position, im debug logging the results each frame, In theory Frame 6's starting position should be the same as Frame 5's Ending position, but its not (The Y has changed) and i have no idea whats influencing this change in position, Any ideas on how i can debug this its driving me crazy
Frame 5: StartingPosition = (495.00, 6.88, -10.00) Final Position = (495.00, 6.83, -10.00)
Frame 6: StartingPosition = (495.00, 6.95, -10.00) Final Position = (495.00, 6.90, -10.00)
show the code?
Also show which components are attached to the object
I would recommend, Pausing the game then use the next arrow to play it frame by frame
These are the components attached to my player & This is my movement script, this will likely just confuse you as my Movement script is fairly large
Someone else said this but this still wouldn't tell me what script/Component is causing the movement right? so im not sure what help this would be
I mean that's a lot of components. Try disabling them all one by one until you find which one is causing the issue
bisection is key
also there's networking involved here
which throws a big wrench in everything
I cant see how any of the scripts would be influencing movement, but i will give it a try, maybe disabling each of the others will give some results
In this case it shouldnt change anything, as the movement is not acting as expected client side, So its essentially not working even in singleplayer
"When you have eliminated the impossible, whatever remains, however improbable, must be the truth."
Its defo gonna be something stupid which im missing
my money's on the NetworkTransform
but it could easily be any of the movement scripts or animation
I have this very weird issue in Unity, together with visual studio code and I don't understand it. Whenever I duplicate a file in visual studio code something runs and it creates a /bin and a /obj folder with a bunch of .net 8.0 stuff in it:
I have tried everything, its driving me crazy.
Unity version 6000.0.48f1.
Ok after uninstalling all my vs code extensions its fixed :), no idea what was going on here.
Are you using the prerelease versions of C#/C# Dev Kit extension? I think the latest prerelease of one of them broke it, I just switched to release versions.
When you add a new file, it takes a moment for Unity to pick it up and add it to csproj, and I'm guessing something to do with one of the extensions seeing the file doesn't belong to a project and trying to set it up for you too eagerly.
I dont recall updating anything but visual studio code itself, maybe i accidentally did it. But removing all extensions and installing just the once vscode recommended worked for me. In on Mac btw.
Yeah I'm guessing you were using prerelease versions and one of them broke it. Installing extensions defaults to release.
Thanks good to be aware of!
You were right btw, I was doing some unnecessary syncing.
Ty
breakpoints, logs, where you include the time.framecount, my guess is there is something in the network code updating your position outside of the fixed update loop
Hello! Trying to get an example project built in Github with CI/CD. We get this error message, but it's ungoogleable?... We really need to know what it means ahah
We're using a YAML file to deploy a unity project, I can send it if needed
It appears to be a licensing issue (based on 'seat' being mentioned), how are you applying your license?
take the personal license, copypaste it into github secrets together with password and login
Could be that the license cannot be transferred so it fails with that error
tbh i have no idea how it will work for CI seeing as nothing is kept
hi
im not sure if i should ask it here or in editor extensions since its a editor code with custom inspector
i will try to simplify it
im currently making a dialog system. but since im the only programer and i have more people helping me with the project im doing a lot of custom inspector to make it more easy to edit
i have a catalog from all the characters in the game + user name + narrator + itens reference(that part is still on progress).
the catalog is a scriptable object with a static of it self (i made a simplifyed singleton basicly)
on the dialog system, i have a custom inspector to get when a character from the catalog is referenced then it colorizes, change the name to current nick names... and some more dumb stuff to easy the work.
who haves the information about it (names, colors, nick names, imagens...) is the catalog/scriptable object.
it itself has a on awake + on enable function to self put as static (becuse if its not initated my dialog custom inspector cant find the references)
the problem is:
the awake/enable funcion only plays when i CLICK the scriptable object.
i already have the same issue on the past, but recently i started learning more about editor scripts.
then i created one editor script. that on itself awake/on enable it will also initialize the awake.
yesterday it was working wonders...
today i just opened the project and realized it works the same as the scripable. i have to click to it initalize.
how can i solve this?
🫤 😅 i just spend 10m writing something that i know its dumb, but i cant solve it
this is the editor script
this is the important part on the catalog
inspectors only exist in the editor, so your design makes no sense already if you're relying on them to initialize stuff. Why are you making your SOs singletons? They can be referenced directly by scripts that need them, and if you need to make sure they don't get unloaded you can set hideFlags if necessary
the dialog system itself is not a singleton :/
currently i have 2
the catalog
and the editorbase
that suposed to start the catalogo
what does the dialog not being a singleton matter? If you have multiple GameCatalog_ScriptableObjects, your Initialize method becomes an instant source of bugs. You can use serialized fields to specify the right catalog, and they'll have OnEnable called when needed
unless there's more going on here, this looks more like you designed around an imaginary problem
i dont know if im saying it right😅
i think im making it more confuse than it sounds right now
i just have 1 catalog
i will only use 1 for the entire game
okay, let's try this another way: why isn't GameCatalog_ScriptableObject a serialized field in whatever things need it? Why does it have a public writable static field for itself?
becuse every dialog can be unique
for the tests i have like 6-7 i think
i dont want to reference it for everything on the game
thats why i try on the static thing
okay, so it's about being lazy. The most self-contained way to do this would be to put your SO in a Resources folder, change Initialize to a private static method with [RuntimeInitializeOnLoad] attribute, load your SO from resources and assign it to your static field (which you should change to a public get/private set property), and for good measure set hideFlags on that instance to prevent unloading
I would directly reference it wherever needed btw, the above is going to be more brittle. I like being explicit with dependencies
ok ok
tks
i will try it
hi, just to give an update
i had so simplify it a little, and a had to make a ping pong with the editor
but in the end it works
tks @long ivy ^-^
the phrase "had to make a ping pong with the editor" is ominous. Your original solution seemed to have a dependency on the editor so hopefully you didn't make that mistake again
I know it’s just for good measure but there’s two aspects here that should ensure it won’t unload without needing to set the flags right? First being the fact it’s in resources to begin with and second that you store a static reference to it from resources (as in it didn’t load in from a scene so it can’t ever unload from a scene).
asking just to confirm my understanding of stuff and things
no, being in resources doesn't prevent it from unloading, just prevents the asset itself (and any of its dependencies) from being stripped from a build. The static reference itself should be enough to prevent unloading, but if the intention is it never unloads then for SOs I prefer to specify this explicitly with hideFlags. For example, if I had a SO that stored some state for use between scenes, I'd make sure I used hideFlags to prevent it from being cleaned up during any scene changes because there are plausible situations where the SO gets unloaded, losing that state and causing a surprising bug
Right just realised I was going off my previously misinformed understanding of Resources, apologies
heard chef
I've never really had problems with SOs being unloaded besides sticking them into asset bundles
I mean if you have prefabs with those SOs, how exactly do you find yourself without a reference to one
unless you're making monos via constructor
if a SO is exclusively referenced by a mono in a scene that SO can be dependent on that scene being loaded
and resources can be explicitly unloaded
wouldnt the SOs become loaded with the scene though?
depends on your use of Resources.UnloadUnusedAssets. As an example, if you had MainMenu -> Loading Scene -> Game, and MainMenu puts some data into a SO for Game to use, and you used non-additive scene loading or explicitly called resources unload as some do, poof go your changes to that mutable SO
yes but if that scene is unloaded
Hello, I don't understand the point of the method Texture2D.Reinitialize. I wanted to resize my texture and the doc says to use this method but when I use it, my image loses its data?? The doc also says "This action also clears the pixel data associated with the texture from the CPU and GPU". What's the point of using this if you're goingto lose pixel data? This makes no sense to me. Could someone explain please?
It lets you reuse the managed Texture2D object rather than create a brand new one, to avoid garbage collection
Hey there. I am experiencing a strange audio ducking in my unity project. I have composed the scene entirely into two audio sources, one music and one sound effect, where it plays the sound effect on input
There is absolutely nothing in the scene besides this, and it is not hooked to audio mixers
decomposing the waveform, you can see it visually happening, and gradually gaining in volume again
Does anyone know of any unity feature that may be causing this?
this is the settings of the two sources
Turning off audio enhancements in the windows control panel fixes this
but it is strange that this is very audibly harming the audio quality, not sure how this can be fixed
Hello. I am pretty new to using Entities and DOTS, and I have been trying to convert my current game to it. It is running very badly though, even worse than before I had Entities. Since I have several scripts, I have gone ahead and put them in a Google Drive that people can look at: https://drive.google.com/drive/folders/1N2h8NGGaS8Epn_7kctV8-wozEphpojBd?usp=sharing
The idea is that it spawns ideally thousands of particles and they move around using some math. They are pairwise, which I realize is not ideal, but I figured that it would be more efficient in Entities. I have it running similarly with just Jobs and Burst, no Entities, and it runs much better.
If anyone is able to look this over and give me some suggestions, that would be greatly appreciated. Thanks. If you are going to respond to me, please @ me as I might not see the message otherwise.
!code one of these sites would be better for sharing your code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I see, but then, why is the resize method deprecated and telling us to use Reinitialize instead ? They don't do the same thing at all.
Thats not how gpu’s work, resizing would create a new resource on the gpu anyway.
Having a very peculiar issue with querying the AssetDatabase:
- I have some code conditioned on
AssetDatabase.Contains(), which passes fine. - I then get the asset path from
AssetDatabase.GetAssetPath(), which returns a valid path string - However when I run
AssetImporter.GetAtPath()on the asset path I just retrieved, it returns null, despite the asset existing and the path being valid.
Any idea what could cause GetAtPath() to return null under these circumstances?
show your code pls
Anyone know a good video course (can be paid) for intermediate / advanced C#, preferably for game dev.
Like how to write good, clean and future proof code. Info about design patterns and why/how to use them ... Probably a lot of other stuff I don't know about. Feel free to PM me.
anybody has experience with Perforce?
I do, yes
I try to merge revisions up to a certain changelist
but when I do that, it gives me an error
"integration errors: no target files in both client and branch view
what does it mean?
@ebon abyss
No clue
fantastic....
already wrote down my question...
and do you know why "revisions up to" gives back only one changelist instead of million?
I also don't understand why merge/integrate files shows me changelists way before the time I made a merge last time
what if it says "all revisions already integrated", but in practice they're not?
@ebon abyss
Not sure where you're looking for "revisions up to". If you're in the "Find" tab of P4V, make sure all the search settings are what you want. Correct workspace, correct users, etc. There are a lot of options that can get you looking at something you're not expecting.
curently I think I fucked up the entire workspace
so I just want to rollback the last few changelists
because undo didn't work as expected and just caused more errors
You'll probably need to get help from someone who can see the same workspace. This can get messy.
Is there a benefit to discarding a return value? For example _ = MethodWithNonVoidReturnType();
Rider recommends this a lot and I cant find an answer to why
you know you can google this, right?
https://softwareengineering.stackexchange.com/questions/433115/why-use-the-discard-variable-in-c
Ah shoot sorry haha, i was googling it in the context of unity and wasnt finding anything
even the documentation about discards is clear that its main purpose is to just provide the intent to ignore the return value of a method
if someone knows Perforce, is there a way to rollback 2-3 changelists (commits)? not undo them, really rollback
Anyone know if it is possible to draw Handles on top of Gizmos?
Do they take in a material? Look for a way to change the transparent sorting queue
Try Handles.zTest
Any clever ways to write lots of files without tons of GC alloc forced by file path checking as part of FileStream?
Not practical for many platforms but could do it in cpp with std::filesystem instead?
Pretty sure you could call fprint_s directly with a DLLImport
But you're bound to be spending so much time waiting on the filesystem here that GC'ing that whopping 46kb shouldn't be much of an issue
So just GC.Collect after you're done so the cost gets lumped together with what's already an expensive operation anyway.
Cant you just offload to a thread ?
Could I? That sounds like a very good idea actually, didn't consider just putting it all on a separate thread
I mean, filesystem is basically the book example of offloading to a thread.
Usually, if you are doing save system that are periodic, this is the way to go.
Nice, yeah can't believe I didn't think of that, will give it a crack. Ty
Trying to use max hits on a spherecast batch
currently writing another iteration of the code, was wondering if there's any intricacies to the whole "N * maxHits" thing
If I have two commands, both only hitting 1 collider, will the valid hits come one after another, or will they be like
valid hit, 15 invalid hits
valid hit, 15 invalid hits
I also want to make sure that
for (int x = 0; x < castCommands.Length; x++)
{
for (int y = 0; y < maxHits; y++)
{
RaycastHit hit = hits[x + y];
}
}
Is an acceptable way to access this
The results of each command will be laid out in order, so if your max hits is 16, the first 16 elements will be the results from the first command and the next 16 will be from the second command.
With that in mind, this loop won't access the data correctly.
alright, thanks for the insight on that. What's the issue with the array?
To get the correct index, you have to calculate what offset each command has in the hits array. The offset for the first command is 0. The offset for the second command is 16.
So the offset is the index of the command multiplied by max hits.
for (int x = 0; x < castCommands.Length; x++)
{
int offset = x * maxHits;
for (int y = 0; y < maxHits; y++)
{
RaycastHit hit = hits[offset + y];
}
}
OH
goddammit, that would make sense as to why stuff wasn't working before...
thank you so much
multiply x by max hits and we get the offset for the next hits, thank you so much (again, lol)
New problem: somehow those hits are all invalid?
the hit point is coming back as {nan, 0, nan} on almost all of them
int offset = x * maxHits;
RaycastHit hit = hits[offset]
Collider c = hit.collider;
for (int y = 0; y < maxHits; y++)
{
hit = hits[offset + y];
if (hit.collider == null || np.ignoredColliders.Contains(hit.collider))
continue;
if(hit.distance != 0 && hit.distance < distance)
{
Debug.Log($"Found new closest collider at {hit.distance} metres from origin", hit.collider);
distance = hit.distance;
c = hit.collider;
validHit = true;
}
}
I'm using the hit AND collider after this nested loop, so I have to assign them before the loop to use them outside of it
Can you show how you are scheduling and completing the commands?
JobHandle job = SpherecastCommand.ScheduleBatch(castCommands, hits, 1, maxHits);
job.Complete();
Should the maxHits argument be commands * maxHits or just maxHits
im also using Unitialised memory for the two native arrays
one castCommand for every spherecast I want to do,
hits length is castCommands.length * maxHits
Just maxHits
right, got it
Are you overwriting all the uninitialized data in the castCommands array?
I should be, yeah. I'll try with clear memory
I'm also adding debug rays to see if its actually casting from the right place
...It looks like its casting in the opposite direction?
so, im assigning the raycast command, then im drawing the ray from its origin, in the direction * distance, directly from that struct.
Its casting the ray in the opposite direction, so then distance on the hit is ~0, the point is reading nan/zero
so how is it even arriving at that??
is normalizing the direction somehow inverting it?
okay no its not inverting it, it IS casting in the right direction
im just so confused as to why this is doing what it is
even when i output the hit point and its like, (3, 3, 3)
the transform im moving USING that point goes back to the origin?
I FIXED IT!
I've moved everything that uses the hit retrieved via...
for (int y = 0; y < maxHits; y++)
{
hit = hits[offset + y];
// more below
so that it executes inside the for y loop
im not 100% sure why it works this way but throws a fit if I use that hit outside - maybe something to do with scope? but it works this way and that's awesome <3
what can you do, if you get this?
Error building Player: 18 errors
Building completed with a result of 'Failed' in 219 seconds (218577 ms)
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun ()
I received absolutely zero info about what these 18 errors are....
nothing in Editor.log, nothing in build errorlog
nothing anywhere...
- scroll up to see what any of the other errors are.
- click on that error and check the bottom of the console window to see the full message.
this is the full message 🙂
no other errors
there are 2 errors
error 1:
Error building Player: 18 errors
this one
this is the full message
error 2:
Building completed with a result of 'Failed' in 219 seconds (218577 ms)
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun ()
and that's all
Unity is again pretty unusable 🙂
Show what you have for this section of your console
When I get that exact error i also get the other errors above it
I already wrote that, there's no other errors
I'm using Unity for million years now
and I have never seen like this before
Error building Player: 18 errors
only this and nothing else
well me neither. I would definitely investigate all your console settings etc
default console settings
didn't modify that at all
answering questions like this one would be a good start
maybe because I try to build to an NDA console
sometimes things happen by mistake
well, I'm not in the office currently
its 8 pm here
Next time ask when you're actually at the computer and able to troubleshoot
that will be much more productive
obviously, I'm just extremely stressful and panicking
Most likely, the actual errors are getting cleared at some point during the build process, and only the result is getting to the log
probably, but is there a way to make it not get cleared?
The menu I asked to see
well, that should never clear the log during building
The second option is literally "Clear on build"
is that selected by default, when you install Unity?
its on the default menu
¯_(ツ)_/¯
whatever it was
but anyway
one click, but only from the office, and if it won't be the case, I will waste hours again
and I'm already way behind schedule
Well, what do you expect to do to fix it from here
to gather possible reasons to check tomorrow morning
and don't waste time tomorrow with researching possible solutions
Well, there you go. You've gathered reasons. Try them then
it was just 1
I'm checking in my other PC what is the default setting
@plain abyss anyway, even if its "Clear on build", that clears console only before build
not during/after that
so its 90% can't be the reason
there is pretty much nothing that hasn't already been said that anyone can say about this issue until you are physically at the device that you can troubleshoot with so idk what you are expecting to get at this point
I mean here are some people who had undetailed errors
so its not new apparently
and it has nothing to do with @plain abyss suggestion about Clear on build
so are you looking for moral reassurance that Unity is broken, or are you looking to solve the problem?
unfortunately I don't try to build to Android
you're kind
If you literally are not able to do the first step of troubleshooting then we can't really go any further. If you've been programming for a while you know that you check everything, even stuff you're certain you never touched because there are many many cases where you're wrong
i prefer "pragmatic"
I will definitely check it, but the night should be used to find lot of other things to check as well
not just the "clear on build"
I'm also pragmatic, but the working hours shouldn't be wasted with hours of googling, if this one suggestion wouldn't work
@hybrid tundra When unity is opened in batch mode (-batchmode) it should print to std out, its what my work uses for unity on our jenkins. You can use execute method to start a build (-executeMethod) or the other args defined here: https://docs.unity3d.com/6000.1/Documentation/Manual/EditorCommandLineArguments.html
Hello. I'm trying to make a simple slash hitbox detection but sometimes seems to fail. The way it's made, the slash animation has 2 events(attack window), one that start the hit detection and one that stops the hit detection. Here's some code sample: https://paste.mod.gg/qwcqwzpnqisj/0
I also tried same implementation but with kinematic rigidbody and OnCollisionEnter and it still fails sometimes to hit the target. I'm not sure what's happening but I feel that sometimes, "1-2 animation frames" are skipped even if by debugging both animation events are fired. I also tried for debugging purposes to have the slash happening all the time (without a defined window), still same miss result sometimes. Another thing would be that if I start to increase the attack speed, the issue will happen more often. Thank you!
Just do the overlapbox directly in the animation event function not in FixedUpdate
This means that if a slash window takes (4-5 animation frames), I should call that event on each frame? Is this a good practice instead of defining a window start/end?
I would venture to say that in the vast majority of games there is exactly one frame of actual attack damage.
But yes if you want it to last 4-5 frames make several events or make an event to start and stop a once-per-frame check
If you care about exact frames that your animations do damage then I wouldn't spawn colliders for that. The frame that you spawn the collider you may not even get the callback until the next frame anyway. Queries are the idea
Also if the collider spawns inside of the target, you won't get callbacks at all from Enter/Exit callbacks
I was checking right now the issue while being in "Pause". Playing frame by frame, I discovered that sometimes (because of speed I guess), 1-2 frames from animation are skipped resulting in weapon missing that hit point
Thanks, I'll give this also a try
I'm trying to stick with Physiscs.OverlapBox solution
if you change the Update Mode on your Animator component to Fixed then it should be more consistent with hitting your event on the same frame, though you'd still have issues depending on the animation speed.
If you can it might be worth just basing the collision query on a fixed point relative to the character and not the weapon? then even if your event hits too late it'd still act as a hit.
@plain abyss @sly grove @echo coral the undetailed 18 errors message was 2-3 shader errors in practice... I needed to solve them and after that the build started working (badly). I needed to revert some of my stuff and redo everything to get the build working
Are these your own shaders?
THIS, fixed my issue. I completely forgot about Animator Update Mode, and yes FixedUpdate mode on Animator works like a charm. Thank you everyone for the help!
Anybody know if there's already a class to cast the AnimationClip YAML format to? Not found anything myself, but maybe I wasn't looking in the right places. If not I'll be writing something today to do just that.
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!74 &7400000
AnimationClip:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Deserialize 1
serializedVersion: 7
m_Legacy: 0
m_Compressed: 0
m_UseHighQualityCurve: 1
m_RotationCurves: []
m_CompressedRotationCurves: []
m_EulerCurves: []
m_PositionCurves: []
m_ScaleCurves: []
m_FloatCurves: []
m_PPtrCurves: []
m_SampleRate: 60
m_WrapMode: 0
m_Bounds:
m_Center: {x: 0, y: 0, z: 0}
m_Extent: {x: 0, y: 0, z: 0}
m_ClipBindingConstant:
genericBindings: []
pptrCurveMapping: []
m_AnimationClipSettings:
serializedVersion: 2
m_AdditiveReferencePoseClip: {fileID: 0}
m_AdditiveReferencePoseTime: 0
m_StartTime: 0
m_StopTime: 1
m_OrientationOffsetY: 0
m_Level: 0
m_CycleOffset: 0
m_HasAdditiveReferencePose: 0
m_LoopTime: 1
m_LoopBlend: 0
m_LoopBlendOrientation: 0
m_LoopBlendPositionY: 0
m_LoopBlendPositionXZ: 0
m_KeepOriginalOrientation: 0
m_KeepOriginalPositionY: 1
m_KeepOriginalPositionXZ: 0
m_HeightFromFeet: 0
m_Mirror: 0
m_EditorCurves: []
m_EulerEditorCurves: []
m_HasGenericRootTransform: 0
m_HasMotionFloatCurves: 0
m_Events: []
what do you mean "cast"?
Like casting a JSON file to a native class.
99.9% sure YAML parser and the internal classes it casts to are in the C++ code, not the C#.
you mean deserializing? it already gets imported as an AnimationClip, do you need it in some other form?
m_Curve is an array of Keyframes. curve is a differrent class. There is no class that it corresponds to in C#. Animation clip itself is just a wrapper class that makes calls to the C++ part of the engine anyway. So yes, I need it in a form where I can openly access the keyframes because that's not currently possible via the current API.
m_FloatCurves:
- serializedVersion: 2
curve:
serializedVersion: 2
m_Curve:
- serializedVersion: 3
time: 0
value: 0
inSlope: 0
outSlope: 0
tangentMode: 136
weightedMode: 0
inWeight: 0.33333334
outWeight: 0.33333334
- serializedVersion: 3
time: 0.016666668
value: 0.09
inSlope: 0
outSlope: 0
tangentMode: 136
weightedMode: 0
inWeight: 0.33333334
outWeight: 0.33333334
- serializedVersion: 3
time: 0.033333335
value: 0
inSlope: 0
outSlope: 0
tangentMode: 136
weightedMode: 0
inWeight: 0.33333334
outWeight: 0.33333334
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
attribute: blendShape.vrc.v_aa
path: Body
classID: 137
script: {fileID: 0}
flags: 0
Some of these values exist within the C# reference code. m_RotationOrder is actually an enum.
what are you trying to do? access animation data from existing clips?
you can access imported animation data (like in an FBX) through ModelImporter, but idk about clips created directly in Unity itself
Yes.
The irony is the classes already exist for me to cast to in the engine's c# code.
But they're internal classes.
And because the smoothbrains over at unity corporate state that ThE tErMs Of UsE dO nOt PeRmIt YoU tO mOdIfY tHe C# cOdE it's completley fucking useless to me.
you haven't really explained why you need to do this but is it possible you could just create the data you need in a serialized AnimationCurve[] array somewhere? or do you have a workflow where you need to create it as a clip then pull the data out of that?
if you have to deserialize it manually it seems simple enough to grab some YAML parser and load the results into an AnimationCurve
I recently created 2 different tools. One uses mediapipe face landmarker, and the other uses Nvidia Broadcast ARSDK to create JSON files containing blendshape facial animation data.
NVIDIA decided to delete the MAXINE ARSDK github despite still claiming it exists in their documentation. Thankfully some nice chinese chaps gave jensen the middle finger and reuploaded it, so I was able to edit the C++ source code to allow for JSON output as well as live DATA streaming.
Unfortunately the JSON files it puts out are uh...
Humungous
What classes?
Here is an example of a class that I recreated in psuedocode
enum RotationOrder
OrderXYZ
OrderXZY
OrderYZX
OrderYXZ
OrderZXY
OrderZYX
end enum
That corresponds to the m_RotationOrder variable, but it's an internal enum, so it's not accessible or visable to us despite existing in the C# DLLs
Can’t reflection bypass that?
Apologies for not being able to share it directly, but unfortunately the sub humans at unity corporate state that ThE tErMs Of UsE dO nOt PeRmIt YoU tO mOdIfY oR rEdIsTrIbUtE tHe C# cOdE (iN eItHeR sOuRcE oR bInArY fOrM).
Probably, I just wanted to see if someone had already done it.
Sounds like nobody here has, and unfortunately unity didn't respond to my source code access inquiry so it looks like I have to do it the arbitrarily hard way.
I know from modding experience that runtime animation stuff sucksssss. Less a solution and more shared trauma
It only sucks because they won't let you modify the source.
Unreal lets you have source code access, for the low low price of sweet fuck all.
Also, before anyone decided to reply with WhY dOn't YoU uSe UnReAl EnGiNe?, pre-emptively shut up.
Your misassuming the crowd here abit
Engine source comes with enterprise licenses: https://unity.com/products/source-code
There's always one of them.
Wonder if this is the same AI chatbot for the email spam
dw you get a real person assigned if you are an enterprise customer
Lmao
Yeah they're going to give me an enterprise license
i dont make the rules
I have more chance of some rando on the internet giving me the source code than that happening.
This was the email response I recieved when I literally emailed sales about it.
I dont know if this helps but there is a way to edit animation clips in editor: https://docs.unity3d.com/ScriptReference/AnimationUtility.html
Sort of but not really. I.e. SetKeyBroken doesn't actually do anything, because it just calls SetKeyBroken_Injected.
SetKeyBroken_Injected is an external command, that again, only functions in the C++ code.
why does this matter? don't you want to just make an animation from this imported data?
I can already make an animation.
But say I implement something like Curvature Corrected Moving Average smoothing for the selected keyframes in the dope sheet or curve editor, or, I want to apply keyframe reduction using the least squares method.
I can't.
AnimationUtility.GetCurveBindings returns EditorCurveBindings, literally every single one.
What I actually need is in this class here: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Animation/AnimationWindow/CurveMenuManager.cs
This is what generates the right click options when you select curves. It's a class that get's created by the curve editors, and has all the keyframes you just selected passed to it. KeyIdentifier tells it which curve the keyframe is on, the index of each keyframe on that curve, and also the index of the curve (which corresponds to editorcurve from the yaml.
Hello. I'm trying to basically build a 'replay' system. I record positions and rotations of my gameobject to a json file.
Then, when I want to play it back, i read the positions and rotations from the json file, and try to lerp and slerp them so they are smooth.
But, what i end up with is smooth movement, until the gameobject reaches each new point. then it jitters a bit.
If I have camera follow it perfectly with no damping, you don't notice the jitter, because the jitter of the camera then matches the object.
But, i sometimes want to playback multiple recordings (on multiple objects) at the same time. Any suggestions on how to avoid the jitter?
_timer += Time.deltaTime;
float t = Mathf.Clamp01(_timer / segmentDuration);
Vector3 a = _data.positions[_currentIndex] + positionOffset;
Vector3 b = _data.positions[_currentIndex + 1] + positionOffset;
transform.position = Vector3.Lerp(a, b, t);
Quaternion offsetRot = Quaternion.Euler(eulerRotationOffset);
Quaternion qa = _data.rotations[_currentIndex] * offsetRot;
Quaternion qb = _data.rotations[_currentIndex + 1] * offsetRot;
transform.rotation = Quaternion.Slerp(qa, qb, t);
if (_timer >= segmentDuration)
{
_timer = 0f;
_currentIndex++;
if (_currentIndex >= _data.positions.Count - 1)
_isPlaying = false;
}
But as per usual with any of the actual useful classes, it's internal.
You can access internal classes with reflection IIRC.
I know, it's just tedious and I wanted to avoid it.
Quaternion offsetRot = Quaternion.Euler(eulerRotationOffset);
Smells like gimbal
I'd clarify on what you mean by jitter. If you mean it's correcting a rotation an odd way, then it's probably gimbal lock
Otherwise seems fine to me. Could try just creating animation clips and using the bicubic interpolation it provides
rotation looks good. its the position itself. as it lerps from one point to the next, its fine (in between points). But when it arrives at a point, it vibrates forward/backward.
Ah, could be overshooting in the end perhaps, then the next point is correcting that. I'd log those final values and see what's happening
ooh. that makes sense. which may be fixed by making my Vector3 a always be transform.position
Clamp your position when you change to the next node to the max value
pretty standard but I feel like that may jiggle as well if you are continuously moving it
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Vector3.MoveTowards.html
MoveTowards can be another option here, but it does it by a constant speed
Finally some good content
fun article on rotations and gimbal lock, since Unity quaternions are not immune https://ntrs.nasa.gov/citations/19770019231
anyway the original reason I came in here - I've got a setup where users should be able to import their own models for entities, buildings, etc. by specifying the file path in the XML for the definition of that entity/building/whatever. I'm trying to figure out how the hell I can force bake axis conversion at runtime - I'm able to set the mesh readable by using SerializedObject, which is necessary because I have to rebake navmeshes at runtime (both the player and NPCs can place building blueprints at virtually any time, which will modify the navmesh when completed), but I can't figure out which property corresponds to bake axis conversion.
I can't just do this via editor script - that would work for me, but I'm supporting mods and everything is set up for modders to simply work through config files + code a la Rimworld/Elin modding instead of having to make Unity projects for their mods. Trying to keep that familiar workflow in place.
tl;dr what property of Mesh actually corresponds to "bake axis conversion" if any? went through them with SerializedObject.iterator but no dice
alternatively, is there a better way of doing this? i could just provide the option to rotate the mesh when it's read as well, which would be simpler but more annoying for the user lmao
isn't that the bakeAxisConversion property of ModelImporter? which is the editor class that produces meshes from assets like FBXs - the idea of converting axes only makes sense in that context, meshes on their own are just data and don't care what order their components are in
actually yeah that's a good point...you can adjust isReadable, cooking options, etc. from the model importer, so I was thinking it'd be somewhere in the same vein? but maybe I just need to adjust the vertex data myself
how does one fix the UnityEngine.Purchasing.Security error when including the CrossPlatformValidator and GooglePlayTangle for In-App Purchasing? I'm quite confused with the AssemblyDefinition references
I have a dout i have a cube i place camera inside i use raycast to spawn the object where the ray is hit how to do that please any one explain me
that is certainly not an advanced question. but the answer is obviously if the raycast hits something you can get the hit point and use that as the location to Instantiate your object
also do not DM users for help. ask your questions and answer follow up questions in this server. i will not be helping you privately.
Sir just one thing camera is inside the cube and also child of it i try lot of things i want to spawn the game object top of the cube but it passes the cube
You need to share the actual error you got for anyone to understand...
If you don't use your own asm def's then others in packages are referenced for you automatically.
fixed it by adding an #if !UNITY_EDITOR guard before the offending code, the one that doesn't work for the UNITY_EDITOR.
actual error you got for anyone to understand
the error is vague as the editor is claiming it can't reference it. I've scoured the forums only for some people to say that the editor can't actually link it since it's a release-only code. would have been nice for unity docs to say that in the first place
Its probably because its only for ios and android but you solved it by accident by restricting it to non editor platforms
then you would do #if UNITY_IOS and #if UNITY_ANDROID
you failed to share the actual error text still and presumed because you did not understand, that we would not either.
When asking for help share the raw error
do anybody do NDA porting here?
I can't just ask my question, because its under NDA
The question is under an NDA?
You should probably go look at the NDA related forums then. And ask there if needed.
Also, it's not like NDAs are transferrable. If someone is under a different NDA you're still exactly as unable to answer it
yeah, and they don't answer for half day
not very productive way to use something like that
my issue is that there's a namespace
and I can use that only from one specific folder
and I have no idea why
there's an NDA package, and if I install that, there are samples
Could be even longer.
But it's not like you have a choice.
Wait or research yourself/ask your coworkers.
and if I import those samples
then the codes are only work from there
the namespaces I mean
but outside of the Samples folder, they can't be used
I have never seen anything like this before, and its very annoying...
Sounds like a case of assembly definitions or special folders.
yeah, but what should I do with the assembly definitions...
the assemblies are in the Library folder
You should learn about them and how they work
No, I'm not talking about assemblies. I'm talking about an assembly definition. It's. A feature in unity.
And is documented very well. Check the manual.
okay, and what should I do with the assembly definition?
Reference it in your assembly definitions. If you want to use code in that assembly. It's all in the manual. Read it up. I'm not even sure this is your case at all. It was just an assumption
I have created an assembly definition reference
and an assembly definition
also the dll was already in an assembly definition in packages
maybe its working now
I'm working with Unity like since 2010, and never ever encountered this
Assembly definitions
Every script belongs to the "nearest" assembly definition, either one in its folder, then back up to the root, and if it finds none, it belongs to Assembly-CSharp
So, if you plop one in your Assets directory, that becomes the new "default", since everything will eventually reach it. Then you can make that assembly definition reference every other runtime one in your project
so anything that doesn't have an asmdef can reach all the others
@plain abyss why did u say ur not helping me with ai or crypto and block me
i was gonna ask about public float bc i had a issieu
ur ego is insane and unmatched
Hm... perhaps there's a rule on this server about sending unsolicited DMs and publicly admitting to such is not a good idea
bro ur ego is insane bro stop caring that much
its not that serious
also ai/crypto most of the time uses a preset msg bro
no ai/crypto will msg you with "digi" as your name
do you see the irony
what
i asked somebody for help and instantly get blocked
their ego to think they will be targeted by me
And a scraper for discord id's to dm would get the ones with ! first
Well unsolicited dms aren't allowed here, so it's not exactly a reach to default to thinking it's a scam.
understandable but why dont u just.. not block and wait for a response
understand u feel like its a scam but there are 0 signs for it being a scam bc of my profile aswell
and blocking takes the same time when i send my 2nd message compared to my 1st msg
Because I don't do private tutoring either. You get blocked because I don't want to talk to someone who will just message me out of the blue
and what can be the reason not being able to add a script to a gameobject as a component, although there are no compile errors, the class name is the exact same as the script name (I copy-pasted the name from one to the other).
I'm exploding
Is the script a component? Does it implement MonoBehaviour?
yes
no special rank, legit just saw you and liked ur pfp bro
its implementing monobehavior
So, I'd suggest restarting the editor first to force a recompile
I already tried
I tried to rename both the class and the file name
also
Can you show the !code of the script that you can't add?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
nope, because its NDA
I never had issues like this
Then I can't really do anything more than say to check all the stuff you've said to check, but more thoroughly ¯_(ツ)_/¯
Maybe try deleting the Library folder while it's closed to force a re-import as well as a recompile?
after working on 4 published games, I feel like issues like this shouldn't happen
well, that would take like 2 hours waiting
so I would skip that part
Well, I can't see the code, and you won't do the only other step so there's not really anything further to try
So I guess we're done here?
I can still go crazy
@hybrid tundra older versions of unity didn't like multiple classes within one script, any chances this is the case?
it has nested classes, so...
nope, still not
even after ungrouping the classes
yeah, nested shouldnt be an issue either way
hello, anyone got experience with compute shader? i'm having a problem because my compute shader code keeps making my Unity crash, i already described my problem on Unity Disscussion: https://discussions.unity.com/t/my-computeshader-keeps-crashing-failed-to-present-d3d11-swapchain/1648319
#archived-shaders is probably where this should be asked.
Do you guys know how I can define symbols for a C native plugin (not compiled, just the plain C file) to be used when I compile my game using IL2CPP? I don't need C# script defines; I need to create a definition for my C file when Unity compiles it using IL2CPP.
Does somebody know a wrapper to access Xamarin Secure Storage on iOS or Android?
can someone describe me how assembly definitions work?
because it seems to be that I still don't understand them
Did you read the manual? If so, what part do you not understand?
All the scripts in the folder with one end up going in a single assembly (dll file) in the build.
so the assembly definition needs to be in one folder with the scripts, if they try to use namespaces defined in the assemblies?
Think of them as one layer above namespaces. An assembly can contain all kinds of code including namespaces, and are equivalent to dlls, as Praetor mentioned.
An assembly definition defines the assembly and it's properties, like references, preprocessing definitions and such. And yes, all scripts in the same or child folders of the asmdef end up in the same assembly.
okay, and what if I can't see a namespace or a class?
the dll needs to be added into an assembly definition and placed near the blind code?
You need to reference the target assembly via assembly references. Did you read the manual?
I had a hard time understanding it, just like with many other manuals
this assembly definition stuff works for one thing, but doesn't for another one
and no idea why
This is a crucial skill for developers. If you're asking in this channel, we'd expect you to read and understand the docs.
then I probably wouldn't need to ask anything here
Ok, I'll correct myself: we expect you to read the docs and being able to point to a specific thing in the documentation that you don't understand. As well as to explain why you don't understand it.
based on the documentation, I wouldn't even needed to create an assembly definition, only an assembly definition reference to refer to an another assembly
but that simply doesn't work
Share a link to the page you read that from.
To include scripts from a non-child folder in an existing assembly, create an Assembly Reference asset in the non-child folder and set it to reference the Assembly Definition asset that defines the target assembly. For example, you can combine the scripts from all the Editor folders in your project in their own assembly, no matter where those folders are located.
this is why I said I always have a hard time to understand these kind of technical English texts
I would prefer if these would be in my language
but that would never happen
Take two step back.
Create a new project from scratch and play with assembly definition. Try to reproduce the issue you are having in your other project.
I don't remember how to create dlls... I have created them back in 2010, and not within Unity
If you're talking about an Assembly Definition Reference asset, then that is probably not what you want to use. This just includes the associated scripts in the referenced assembly. I assume you're assigning a plugin there. This would just make your project code compile as part of that plugin and be unusable in the project otherwise.
You do not need to create DLL.
but based on the documentation, it is what I should use
Except if the namespace comes from a dll.
at least this is what I understand from the text
And yeah, if you have a reproducable case that you can share with us, it would make it much easier to help you.
No, it's not. What you need to use is reference the plugin in your project assembly
nope, there are like 20-30 different dlls and even more namespaces
This is where what Simferoce said is relevant.
That is not how you "constuct" a reproducable case.
You attempt to have the minimum of what is causing the issue.
I don't really have time to stuck with this issue and to make fully new projects, which are usually will be much different from my actual use-case
I have done it multiple time, it's no unusually to make a side project to test things.
Then stay stuck on your issue ?
I won't do it for you. I'm simply sharing with you attempts to fix complicated issue that I did in the past.
None of this talks about the reference asset
I do porting for console professionally, I'm not saying things for fun.
I mean I don't even know if these are in dlls or in assembly definitions... I have no experience in this at all
Find if they are in a dll or not then.
And if I click one of the links it literally tells you how to do it:
Is is a Unity library ? Usually, you have a library given by Unity for each platform.
Maybe you simply does not have it in you project.
And below there's another secion about referencing dlls
I need to use translation for this
cause I don't understand the sentences at all
What part of it? What words do you now understand?
"If two types are in different assemblies, an assembly containing a dependent type must declare a reference to the assembly containing the type upon which it depends."
what does this sentence mean?
Do you know what types are?
yes
What assemblies are?
dlls
that is really context dependent
what a reference is?
yes, I know that
Ok, then what part of that sentence is not clear?
declare a reference -> is it the creation of an assembly definition reference
No. it's what I shared on the screenshots.
@hybrid tundra In simple terms, if your code depends on something defined elsewhere, you have to tell your project where to find it by adding a reference to the assembly that contains it.
an assembly must declare a reference
then why isn't this written down instead of that nonsense sentence...
its much clearer in this way
I mean its like someone would learn math from definitions, not from examples
I never understood math only by looking at definitions
It all makes a lot of sense if you know what assemblies are.
I needed examples
aren't those dlls?
what else could an assembly be?
the language itself?
Yes and no. They are code constructs that define an "assembly" of code.
They can come in the form of a dll when compiled.
This is code-advanced...
its very abstract
its pretty advanced topic
Programming is abstract. It's the whole point of it.
I mean when I have dealt with gameplay programming, I have never needed to care with assemblies or with anything dll related
I just wrote my codes
ok, I try to figure out how this thing works...
You can visualise it as a box where you put all your C# code in. Things inside the box can reference each other, but they can't reference things from other boxes normally. You need to connect the boxes with pipes to be able to do it(one way pipes). A very rough oversimplification, but you can start with this understanding.
Then consider this an opportunity to improve as a programmer.
And a developer in general.
I understand this part, but why is that I create an assembly definition referring to the DLL I needed, and its still doesn't work?
sorry, assembly definition reference
I create an assembly definition, I refer to the assembly definition reference
You need to create an assembly definition for your code. And reference whatever you need referenced in it.
what is "for your code"?
You don't need an assembly definition reference asset. As I explained earlier it's for a different purpose entirely.
I have created the assembly definition near my code
For code in your project
Great, then reference whatever your code needs in that assembly definition.
ok maybe I will ask the chatgpt to tell me the documentation page like if I would be a 5 year old
and maybe I will understand that kind of description
already did that
this is what I'm writing
an Assembly Definition asset and an Assembly Definition Reference asset are NOT the same
already referring to the other stuff needed
Well, then it should work.
If it doesn't, you messed it up. And there's not much we can do without seeing your setup.
You should also remember that this is only gonna work for C# dlls(assuming you're referencing dlls). Platform specific stuff is often in C++ and requires extra setup if you need to access it in C#. This is a whole separate topic.
restarting Visual Studio solved half of the problems...
now other classes disappeared
unbelievable
Sometimes the project has issue, you can mostly resolve them by using:
that would be minus 2 hours
so I would try to avoid that
Also, always look if unity compiles successfully. Intellisense can be misleading .
Not really, it takes less then 1s on most project
is it normal that I created 3 assembly definition references
and I get 300 errors?
like the library creation?
Again you don't need to create assembly definition reference assets
that does not regenerate the library, it just recreates the csproj files
You need assembly definition assets
those didn't work at all
You're saying it as if you don't have 300 errors now...
It is two completly different process
Regenerate the library folder takes a lot of time
If they didn't work, then you did something wrong. Reference assets are not gonna fix that.
ok, currently I have no idea how to fix the 300 errors appeared after creating assembly definition references...
I removed the references, but I still have errors...
Try triggering assets refresh or restarting the editor.
Aside from that you'll need to read the errors and reason about what's causing them.
okay, how to figure out what stuff should I add into the assembly definition?
to refer to the other namespaces/classes, etc.?
because its not trivial
okay, now I would make this, but I have absolutely zero idea how to reproduce the issue I have
because in every other 6-7-8 other projects I was in, we have never had issues like this
we just wrote everything in one assembly and that's all
Start by trying to write in multiple assembly.
and how do you guys be calm about your upcoming deadlines?
I always feel stress, and sometimes I have moments of literal panic
By knowing what you can do/cant do.
I know I can fix pretty much any problem, it is just a question of time.
well, I had no idea there are things in Unity I still can't do
There is mutliple things I do not as well. But I know how to know about them whenever I need.
If you ask you the question "Why I do not know X", you always find the answer to X
Maybe you do not have the appropriate experience. If it is the case, what would you need to do to acquire it ?
Push back! This is where you find if you're valuable 😆
This is your realistic timeline.
I'm not management, it literally is not my job to worry about deadlines. People above me get paid five times as much to do half the work so let them do the one job they're actually supposed to do
weird thinking
I don't make the schedules. As long as I'm consistent in my output setting deadlines is someone else's problem
It's literally their job to assess everyone's capabilities and estimate deadlines for things based on that. If they set one too short and no one is falling below expected quota then they made a bad assessment and they can worry about that
While this is true, you still have to be able to measure/deal with your "quota"
That's still someone else's job, I get performance reviews, if there's no problems brought up during those I've upheld my end of the contract
How do you evaluate "your end of the contract".
I get assigned tasks with priorities
I complete tasks in order of priority
If a deadline is missed, someone didn't prioritize correctly.
At no point you have to says: It is going to take 2 weeks to do X ?
If I have to give a time table, I'm usually pretty generous. If I don't have enough information to accurately give a time table, I'll give a time table for when I'll know the full time table. Like "One week of research, then I'll give the full spec" kind of thing
I'm basically a blunt instrument that management throws at programming tasks until they break. I'm not a manager and never really try to be
@dusty wigeon I could make an example in an empty project
and it was much easier to do this in here, than in the real project...
Now you can share easily what your issue is.
in here I don't have any issue, its working here
and I do the exact same in the project
So, you know that it is possibly not an issue with Assembly Definition.
but what I have seen is that in here, I recognized, where can I see which dll contains the script
and maybe this is what I did wrongly in the project
Given that you do understand how they works.
no, its just way more complex in the real project
about what script is in what dll
and what refers to what
You should be able to find the same way you did it
You could always use if it is in the project and not a DLL
It will generate the solution for others element that you did not wrote but are present in the project.
what if you have folder A, assembly definition A in there,
folder B, assembly definition B in there to refer A
but then what do you do with all other million scripts trying to refer to folder B scripts?
If you are truly able to live like that than you are lucky. Because only a technical guy can make an estimation of a technical task. You cannot expect the management to shoulder such estimation.
Not exactly sure. I believe "other million scripts" would be in the default assembly which reference everything.
well, there are a lot which are not in assembly definitions
at all
Which would be the default assembly.
no idea
I'm saying it.
I just know that currently I have 20 errors
By defining assemblies, you can organize your code to promote modularity and reusability. Scripts in the assemblies you define for your project are no longer added to the default assemblies and can only access scripts in those other assemblies that you designate.
I understand
but now should I create assembly definitions in every single script folder?
To make it clear, its not possible for assembly definitions to have cyclical dependencies (A -> B -> A for example)
You would need to re factor code or put more in 1 in a single assembly
Do not
ok so what to do from the million scripts which tries to reach those script in one folder, which has now an assembly definition?
Those milion script should be able to access them.
Not the opposite.
I don't understand
The following works.
(Million Scripts - Default Assembly) => (Scripts) in Assembly Definition
The following works does not work.
(Scripts) in Assembly Definition => (Million Scripts - Default Assembly)
"The following works.
(Million Scripts - Default Assembly) => (Scripts) in Assembly Definition"
how?
because by default it doesn't
Default Assembly always exists
but now the default assembly scripts try to reach the defined assembly
it is Assembly-CSharp
which should work.
tell that to my Unity 😄
Tell that to yourself ...?
There is something that you are missing
Return to your example project and try
(Million Scripts - Default Assembly) => (Scripts) in Assembly Definition
vs
(Scripts) in Assembly Definition => (Million Scripts - Default Assembly)
If it works, then you know it should.
I just know there are scripts in a folder, the folder has an assembly definition
and now nothing can reach these scripts
I feel like I gave an answer to this one yesterday
You put one "project level" asmdef in your Assets folder, and anything that doesn't already belong to another one belongs to that one
then you can have that asmdef reference all the others
Mostly becuse they are in another asembly definition which does not reference this particular definition
its not working
from the example project I made
it really works
but not in the actual project
this is what I've said
Good, then modified till it does not work.
You know, there is also the possibility that what you are trying to access simply does not exists.
If you try to access something that does not exists from your working project, it should given you something similar to what you are seeing.
Yeah mostly because you are in an assembly definition that does not reference it
still have zero idea why it perfectly works in my sample project
okay, so, 2 scripts are in the same dll
but still they can't see each other
wtf
okay, now it works
don't really know why though...
I have a problem. I'm running a simulation with jobs/burst. The simulation does X steps modifying and reading from the same array. This means than multiple "threads" read ans write at the same time.
That is not a problem by default, the results are correct! However it's not deterministic, meaning that running it again will produce really similar results but not exactly the same
How can i solve something like this? I had two options:
-
make "threads" wait each other, slightly reducing performance, but ensuring that they are writing at the same time and only one writes at a time
-
store the results in between:
Execute many jobs which read from the same but write to only one array (controlled)
Pass and swap the data around from the controlled to the original
Repeat until all steps
But this feels way too slow
Mmm i guess the second option is like double-buffering which could work
it's hard to say without understanding the algorithm that's being run. Basically you need to enforce an ordering of operations and really the one way to do that in the jobs system is to chain jobs with JobHandles.
Yeah, so I'm doing erosiom simulation. Basically i schedule a job with 200000 internal loops, where each manages a single drop of water for 30 steps (a for loop in the job)
For each step i read the heightmap, calculate what sediment to move and to where and place it back to the height map.
The issue is obviously reading and writing to the same heightmap. Double buffering would help me if two droplets couldn't write to the same array index but that's not the case since each drop of water is independent
reading and writing to the same heightmap is fine so long as each execution has defined boundaries in the array that the other executions don't touch
this sounds like maybe one of those things where you touch your pixel and the 4 surrounding pixels, for example though?
But done 30 times and moving according to the terrain normal
sure sure the important thing is the data locality
which array elements does each execution touch?
their own + some adjacent ones?
Potentially all, so one execution is one drop, and inside i do 30 steps
Like
Void execute(i)
{
For 30 steps do X
}
but what is "do x"?
And their positions are random, scattered around the height map
you're traversing around the heighmap in there?
Yup
The read height, check normal direction, remove sediment , move, place sediment, Repeat
ok basically what you need to do is break this down into smaller, atomic operations
it's going to need to be like 30 job invocations rather than a single one with a loop in it
Ywah, so like double buffering?
Have you looked at any papers regarding parallelized erosion algorithms? There is no magic bullet here.
sorta yea
So read from height A write to height B, swap. The issue I'm finding is still writing to the same array. Can i overcome that with atomic operations?
To make it simpler let's start with a simpler example. Imagine you have an array that is all 0s and 1s. 0s have nothing. 1s have a droplet. Imagine the droplets always just move one pixel to the left.
You can make a job that, for each pixel, you read from the pixel to the right of it from the main array, and if there's a droplet in that pixel, you put a 1 in your pixel in a second array. If not, you put a 0.
Then, a second job depending on that first job runs, and for every pixel in the array, you read from the secondary array. If there's a 1 in the secondary array, you put a 1 in the main array. If not, you put a 0 in the main array.
Basically we separate reading from the main texture and writing to the main texture into two operations, where the writing won't happen until all the reading is done
Now we don't have to worry about atomic operations or anything, as we have formally separated out the two conflicting operations that could have a race condition (the read and the write)
If I understand the actual problem correctly you should be able to expand this technique to do the erosion algorithm. There would be 60 job executions. 30 reads, 30 writes.
Aaaah i see what you mean, so instead of writing straight away to the height map, i store the theoretical deseriable writing, and do a second job that reduces that array
yeah
that way you aren't writing to the main array and screwing up another thread's read.
Neat! I will see how to implement something like that. Thanks!
Good luck!
How could I make a VR grab system kinda like boneworks/bonelab as im trying to make a fan game but I cant seem to figure out how its so smooth and how the weapons are perfectly grabbed and such. I have a basic grab system but its pretty bland
people get paid a full time wage answering that question 😛
im not looking for directly a 1:1
maybe even just the pickup system
not the whole darn game!
yeah, people can spend a majority of their time on a project working on a specific system like that.
Your question is too vague to answer
i mean i can rephrase it
atleast are there any videos
relating to what im asking?
like e.g. each finger with rigidbody and collider to interact smoothly
or something along those lines
have you looked
cant find one
all of them are like
really really basic
like just welding or something to the hands
not even using smooth physics
that's probably mostly whats available then. You might have some luck looking for GDC videos or similar
possibly
Outside of those kinds of releases your not gonna have too much luck looking for that level of implementation advice in full
is hurricane vr asset a good place to start if i dont want to make the entire thing
its a toolkit and it seems pretty nice
How about using a optimized mesh collider that has limb extension limits to imitate it?
maybe
What's the right way to post code in this channel? Gist? Copy/paste?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ty.
I have a basically 2D game (it does have a z-axis, but that's not really important for this question)... It's sort of an asteroids clone. I wrote the script below to wrap the bullets at the edge of the screen.
https://paste.mod.gg/ipswugdhqejn/0
The instructor wants us to use a box collider that is sized automatically with some fairly inscrutable code. Is there something inherently wrong with my version?
A tool for sharing your source code with the world!
Does it work?
is that a rhetorical question?
well looks like line 26 is incorrect and this is not really advanced
Well, you're asking if there's anything wrong with it, first identify if it actually has a problem
Curious question: How is dismemberment usually done in games? In my game I have robots and I'd like to make it possible to blow predefined body parts off the robot, for instance if you take a 12 gauge and shot it in the head, the head would disintegrate and the neck would show a hole with the internals visible if you looked into the stump. I'd also like to be able to dismember already destroyed robot corpses too, but I'm not sure where to begin
You might like this re: left 4 dead 2 [cw: gore]
https://alex.vlachos.com/graphics/Vlachos-GDC10-Left4Dead2Wounds.pdf
I'm trying to build an Android AAB using Unity 6000.0.41f1 in CI with the following command:I'm trying to build an Android AAB using Unity 6000.0.41f1 in CI with the following command:
exit 1;
}
BuildScript.cs
PlayerSettings.Android.keystorePass = keystorePass;
PlayerSettings.Android.keyaliasName = keyAlias;
PlayerSettings.Android.keyaliasPass = keyPass;
However, during the CI build, Unity seems to use the wrong keystore.
The pipeline works fine with Unity 2022.3, but not with Unity 6000.0.41f1.
Has anyone experienced this issue or it's a Engine Bug ?
what exactly causes scripts to be unefficient/laggy? what should I do and not do?
Code. You should use the profiler to identify bottlenecks.
does the profiler tell you what part of the code is causing issues?
That is indeed the entire purpose of a profiler
Yes. If you need more details than it already provides, you can add custom profiler markers.
If you need even more than that, there are native profiling tools, like PIX
tbh i dont know where even to see the profiler, im rather new to coding so i thought i'd ask here because yall are going to be more knowledgeable than me
You'd get the same answer as in #💻┃code-beginner , which is probably the correct place to ask this question
If you're new it's going to be a long time before you'll have to start worrying about profiling performance problems. It's a bit too early to start solving problems that you don't have yet
and the correct order is to first learn to write code, then learn to write code that works, and only then learn to write code that's fast
I do not know what to look at 😭
true that, but im now just cleaning up code to start working on implementing stuff for the game
it was my school project that I want to continue
According to the profiler your game runs at about 4000 fps. That's not something that needs optimizing.
You need to read the manual to to learn about features you never used before.
Especially if you're asking in this channel.
Hello, anyone know how to boost GPU Level to level 4 with passtrough enabled using Meta Quest 3 and Unity?
I know there are some apps that can do it despite the documentation tell different
GPU level? What is that, an rpg?
If it's VR specific, better ask in #🥽┃virtual-reality
Can I get a Unity Cheat Sheet for application development, I'm new, starting out in Unity, but I'm a intermediate/advanced level C# programmer.
I would like to learn how to create proper scripts for PlayerMovement, GUI, etc.
i don't know about one for the whole engine but here's one diagram you should get familiar with! https://docs.unity3d.com/6000.1/Documentation/Manual/execution-order.html
Like in general C# we dont have Monobehavior
So, how do I learn these, the document doesn't teach it.
Also, like SeralizedFields, and other intialization things confuse me, and I want to get started, I've been trying to use and learn C# and Unity for a couple of weeks coming as a Java programmer.
this isn't really a subject for the advanced channel, but just check out some beginner unity tutorials? if you already know C# you should pick it up fast from there
they'll all cover the basics like that
I'll put this in #💻┃code-beginner since it seems like the content I need help with is at a beginner stage even though I'm advanced C# learner.
Thanks.
I have already, bland, generic content all over again.
unfortunately starting at the bottom of something isn't always the most fun but you kinda have to lol
maybe grab one of the sample projects and start hacking?
You can quickly glance over
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Just made a finger pose system for a hand. I want it so like it dynamically moves with the object the fingers naturally interact with, would it be possible with the pose system or is that a whole different thing like IK, i think it should be
Sounds like IK to me
but I don't know anything about your pose system
you might have a combination of the two.
yeah
basically in a nutshell the pose system just stores rotaition of each hand
and you can load them
and save them into that data hand pose
I have tried to ask it in general, but nobody replied. How to make graph with UI toolkit? Or should I use just unity ui? I would like to make nodes clickable, so I don't want to draw it with gizmos. I have created UI element in UI toolkit, but don't get how to put it in arbitrary. I can't just drug it it UI Builder
Is this the right way to do?
float currentValue = dashBar.fillAmount;
float decrement = currentValue / 3.0f;
dashBar.fillAmount = Mathf.Lerp(dashBar.fillAmount, dashBar.fillAmount - decrement, elapsedTime / _dashTime);
No. That's the "wrong lerp" (https://unity.huh.how/lerp/wrong-lerp). Also #💻┃code-beginner
Image bar;
float velocity = 1f;
float to = 0.7f;
bar.fillAmount = Mathf.MoveTowards(bar.fillAmount, Mathf.Clamp01(to), velocity * Time.deltaTime);
I'm not clamping it
just lowering the fill amount by 0.3
well, first of all, you should not read the fillAmount from the image to make any calculatons, the fill amount should be a variable in your script,
I did it with variables in the script
just to make things clear I wrote it like that
Hey there, if I get it, you're trying to make a working graph editor window in Unity with draggable nodes and everything. If yes i may have a good resource for you : Custom Dialogue System Unity by Indie Wafflus. I followed his tutorial and got it working after several hours of dev, but you can have the basics pretty quickly and then go on your own.
if you want to decrement that variable by 30% you simply do ```cs
_t -= 0.3f;
_t = Mathf.Clamp01(_t);
_bar.fillAmount = _t;
if you want to animate that change, you do what i did in the other script (in principle)
so you mean if I set the _progress to 0f then animate the fill amount to 0f?
you need to add whichever math you want
the point is the lerp doesn't help you with controlling the animation... use https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html instead
i see
AnimationCurves can be pretty fun to look into if you're looking to make animations handled by scripts. It's mostly useful if the animation
- can vary among instances
- is pretty complex
- you just want to experiment animation types from in the editor
on MoveTowards I'll have to put in a target value
but my dashbar fills up by time
the target value can be anything, including 1
Can anyone tell me what is the issue here ?
Solved it
When i call StopClient() This error occours.
ok
No, I don't wan't graph editor, I just wanted graph as UI for game
oh I got it wrong sorry
Hello!
I'm trying to build a lightweight custom Scriptable Render Pipeline (SRP) for OpenXR.
I've carefully followed all the Unity documentation I could find to build this SRP, and everything seems to work quite well overall.
I can confirm that in the editor, the rendering works perfectly.
Now there's only one remaining issue — but it's a crucial one: nothing shows up in the VR headset.
It's as if the rendering to the headset is simply not initialized.
The display stays completely dark, even without the slight variation in black you'd expect if something was rendering but broken.
In short: the rendering to the headset doesn't even start.
I have a custom Render Pipeline instance that inherits from RenderPipeline.
It calls a RenderXR function I placed in a separate file to handle XR rendering.
Here is how I call RenderXR from my pipeline instance:
foreach (Camera camera in cameras)
{
if (!camera.TryGetCullingParameters(out var cullingParameters))
{
Debug.LogWarning("[MinRP_Instance] Failed to get culling parameters for camera: " + camera.name);
continue;
}
CullingResults cullingResults = context.Cull(ref cullingParameters);
BeginCameraRendering(context, camera);
ShaderTagId shaderTagId = new ShaderTagId("SRPDefaultUnlit");
DrawingSettings drawingSettingsOpaque = new DrawingSettings(shaderTagId, new SortingSettings(camera))
{
perObjectData = PerObjectData.Lightmaps
};
DrawingSettings drawingSettingsTransparent = new DrawingSettings(shaderTagId, new SortingSettings(camera));
{
var sortingSettingsTransparent = new SortingSettings(camera) { criteria = SortingCriteria.CommonTransparent };
drawingSettingsTransparent.sortingSettings = sortingSettingsTransparent;
drawingSettingsTransparent.perObjectData = PerObjectData.Lightmaps;
}
FilteringSettings filteringSettingsOpaque = new FilteringSettings(RenderQueueRange.opaque);
FilteringSettings filteringSettingsTransparent = new FilteringSettings(RenderQueueRange.transparent);
RenderTextureDescriptor cameraRTDesc = new RenderTextureDescriptor(Screen.width, Screen.height);
XRDisplaySubsystem xrDisplay = XRGeneralSettings.Instance?.Manager?.activeLoader?.GetLoadedSubsystem<XRDisplaySubsystem>();
MinRP_XR.RenderXR(
context,
camera,
cullingResults,
drawingSettingsOpaque,
drawingSettingsTransparent,
filteringSettingsOpaque,
filteringSettingsTransparent,
settings.PostProcessMaterial,
cameraRTDesc,
xrDisplay
);
EndCameraRendering(context, camera);
Debug.Log("[MinRP_Instance] ======= EXIT XR SECTION =======");
}
Here is what my RenderXR function does :
public static void RenderXR(
ScriptableRenderContext context,
Camera camera,
CullingResults cullingResults,
DrawingSettings drawingSettingsOpaque,
DrawingSettings drawingSettingsTransparent, // conservé pour signature mais inutilisé
FilteringSettings filteringSettingsOpaque,
FilteringSettings filteringSettingsTransparent, // conservé pour signature mais inutilisé
Material postProcessMaterial, // ignoré
RenderTextureDescriptor cameraRTDesc,
XRDisplaySubsystem xrDisplay
)
{
Debug.Log("[MinRP_XR] ======== BEGIN XR RENDERING (OPAQUE ONLY) ========");
Debug.Log("[MinRP_XR] Camera: " + camera.name);
Debug.Log("[MinRP_XR] Camera position: " + camera.transform.position);
Debug.Log("[MinRP_XR] stereoEnabled: " + camera.stereoEnabled);
context.StartMultiEye(camera);
if (!camera.TryGetCullingParameters(out ScriptableCullingParameters xrCullingParams))
{
Debug.LogError("[MinRP_XR] Failed to get XR culling parameters");
return;
}
CullingResults xrCullingResults = context.Cull(ref xrCullingParams);
context.SetupCameraProperties(camera);
CommandBuffer cmdClear = CommandBufferPool.Get("Clear XR Target");
cmdClear.ClearRenderTarget(true, true, Color.black);
context.ExecuteCommandBuffer(cmdClear);
CommandBufferPool.Release(cmdClear);
context.DrawSkybox(camera);
Debug.Log("[MinRP_XR] Drawing opaque objects only");
drawingSettingsOpaque.perObjectData = PerObjectData.Lightmaps;
context.DrawRenderers(xrCullingResults, ref drawingSettingsOpaque, ref filteringSettingsOpaque);
context.StopMultiEye(camera);
context.StereoEndRender(camera);
context.Submit();
Debug.Log("[MinRP_XR] ======== END XR RENDERING (OPAQUE ONLY) ========");
}
As you can see, I make it super verbose to detect where's the problem but every step in my pipeline seams to work fine :
What did I miss ?
My last test build was the number 53 and i never succeeded to start a render in the headset.
I don't even succeeded to get an error message 😭
Please, Obi-wan Kenoby, Your are my last hope ^^
I'm writing a custom logging utility script and it appears in my stack traces. Anyone know if its possible to exclude it?
[HideInCallstack] doesn't work. This forum post talks about it, but it also doesn't work and my method is clearly in the stack.
Script:
public static class Logger
{
[HideInCallstack]
public static void LogInfo(
string message,
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0
)
{
Debug.Log(FormatLog(message, filePath, lineNumber));
}
}
Console logs:
[LoggerTest:12]: Loggy log
UnityEngine.Debug:Log (object)
Game.Core.Logging.Logger:LogInfo (string,string,int) (at Assets/Scripts/Core/Logging/Logger.cs:27)
Game.Core.Logging.LoggerTest:Log () (at Assets/Scripts/Core/Logging/LoggerTest.cs:12)
(If you ever find a way, I would be interested)
Methods marked with HideInCallstack will only be hidden when that option is enabled in the console
To hide the marked methods, click the Console menu button then select Strip logging callstack from the menu.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/HideInCallstackAttribute.html
(it should say "right click the Console tab header")
Sweet, thanks!
Hello! I need help with my code, it's giving my an ambiguity error, for reference I'm trying to add the new input system in my code.
Thanks! This is unity.
Usually it's because the same class name exists in multiple namespaces and using statements exist for both in this file.
Have a search for PlayerInputActions classes and see if there are 2+
A good example of this is System.Random and UnityEngine.Random
quick question so my scroll view works however it doesnt scroll every time i drag/try to scroll up and down it revert back to default. is there a inspector checkbox that im missing?
you have two copies of the generated C# class from your input action asset.
nevermind i figured it out LOL was a simple fix
hi
am I right that if memory usage of the game is extreme, and if Memory Profiler says textures eat the most of the memory, then it can be reduced with platform overriding of the textures with reducing max size can solve this issue, right?
Yes, if the max size is lower than the source texture resolution. The max size is just a max, so if the source texture is 512x512 and you go from a max size of 2048 to 1024, the texture will still be 512x512.
How do I do this?
How do you do what
hello i need some help. so i finish my project but it scales weirdly. how can i make the canvas and the noncanvas elements scale with the screen instead of looking weird
it seems to look ok for 1920 x 1080 but when i run my build it looks funky
nvm fixed. god i really gotta put in more effort looking at the documentations before asking when its that easy...
I'd point out that this channel is for advanced coding questions. Not beginner or ui related questions. Check the #🔎┃find-a-channel next time before posting.
A problem I often run into on projects that reach a certain scale is that my ability to refactor code to is heavily restrained by already having a lot of data (ie GameObjects configured by a designer in scenes/prefabs) that maps to the current layout of the code.
A (very simplistic) hypothetical to demonstrate the problem:
Suppose you have an 'NPC' component that stores a health variable, has a 'damage' method that reduces the health and spawns some effect when health reaches zero. Then you realize you want other kinds of objects to have 'health' and perform the same functionality, so you break out this functionality into it's own component called 'Healthable' (forgive the name...) that NPC now depends on.
But, designers on your team have already configured 10 different prefabs for different NPC types, many instances of which may or may not have overrides to NPC's health variable in scenes or prefabs they're nested inside. So a simple refactor of the code like this now requires finding all the instances of all these NPC prefabs and reapplying any overrides from the original NPC health to the Healthable's health. Nobody on your team has time to do this nor do you have a tool to do it efficiently, so you just keep the original functionality in NPC and live with duplication of code.
I find this kind of problem particularly difficult to avoid when the design is constantly evolving, making it impossible to predict from the start the code should be laid out to optimally fulfil the design.
Is this a problem anybody else feels like they run into often? If so, do you have any strategies for avoiding this kind of problem or handling it when you do?
Depending on where your at with this it might fall into a #archived-code-general question but off the bat it sounds like you'd be interested in ScriptableObjects and potentially Interfaces to help assist in some of this workflow?
I mean I imagine the same problem would arise if you have lots of data crafted by designers in the form of ScriptableObjects too. Perhaps it's somewhat easier to run automation code on data stored in assets rather than scenes/prefabs? It would naturally disallow the use of prefab overrides though. And I'm not sure interfaces would really help the problem either.
Most configuration data that gets refactored ends up in scriptable objects, and when refactoring I just keep the old and new data to port using a custom script via serialized properties, then remove the old data.
You can write an editor window to port serialized fields if you don't want to write/copy similar migration code every time, but it may be more annoying to maintain in certain cases.
It got a lot easier now you can use .boxedValue and not have to copy the whole property tree
Do you find you ever run into a similar problem with gameobjects/components?
You can still reuse code between NPC and Healthable components.
Not with my current game. Most of the configuration is in SOs. But previous games have needed refactoring tools for components, and it's not been much different, just some more annoying prefab code to deal with that once written is simple to reuse.
You can also work around this (together with SO for design config) if you make more use of type objects (pattern) and don’t create specific types for every domain concept. Keep APIs agnostic about much of what stuff means in gameplay terms. Make a strong distinction between code for systems and scripting
I would say if configuration prevents refactoring, the configuration operates on a leaky abstraction or isn’t entirely declarative
Usuage of Obselete/Readonly attribute can be useful in those case. You fallback on the old method whenever the new is not correctly defined.
2 days and monster at 17 got me successful inf recursion script 🙂
ready for that section in college when it comes🫡
can I decrease font texture atlases in a way to not lose any characters from the atlases?
because if I just decrease the atlas size, then I lose characters as well
Is this a code question? 
You can't lower atlas resolution, no. They're the size they need to be. The only thing you can do is remove characters you don't need.
sorry, I couldn't find any better channels
and can't I just make the atlas smaller and thus the characters a bit less sharp?
We're not talking bitmap fonts are we?
I'm trying to optimize memory usage currently
This is TMP right?
yes, its TMP
Yeah those aren't bitmap fonts so no. You can't lower the resolution and get a good result. They're SDF fonts, which are already optimized.
the assets taking the most place in memory are the 8K sized font atlases
that's pretty sad
8K sounds pretty big though. Is this Chinese language?
They tend to be pretty small for Latin
haven't checked it yet, but there are like 6-7 pieces of 8K textures loaded into the memory all the time
chinese or japan, yeah
and there are 12 pieces of 2K sized font atlases loaded as well
Found this anyway: https://killertee.wordpress.com/2021/04/23/optimizing-workflow-textmesh-pro-font-atlas-for-language-localization/
Has some helpful tips like sharing characters between languages. Chinese and Japanese have huge overlap so this might save you a whole atlas...
if there are empty unused "areas" in a font atlas, can I reduce dimensions to decrease the empty size?
No if it could be smaller it would be
well, its a rectangular texture, and on its right side its fully empty
like 1/3 of the texture is empty
Yeah and the next resolution down from 8192 is 4096, which is only a quarter of the area
ok and really there's no way to make the characters uglier, but the texture smaller?
Crunch compression? Dunno how well that'd work 😅
well, I only know that the memory is filled completely
and I need to reduce memory usage
and textures eat 30-40% of memory
crunch compression only reduces disk usage iirc, it gets decompressed (well, into its usual block compressd format) into graphics memory
Profile your game to see what's eating the memory
Pretty sure we're past that already