#archived-code-advanced
1 messages · Page 62 of 1
are u sure that 5/6th one is centered?
also if the sprites were wrong it'd show up when the camera wasn't following
could you check this one?
to be honest I don't think the sprites need to match the transform
are u moving the player with the same method? this one looks more clear as to the desync
since the sprite has a bobbing effect
so it's intentional
like the player bobs it's head when walking
my main theory is it's just something to do with the camera follow for some reason
well yes it is the camera following the transform, which is not aligned exactly with the sprite
but that shouldn't cause stutter
since the transform is moving smoothly
the sprite animation should look the same whether the transform is moving or not
that last one slowed down at some part
the camera and transform moving might be fine, but its just the animation isnt lined up. That 1 frame of desync is whats causing it
remember you arent seeing the transform on screen, u are seeing the visual
but the animation is meant to be moving up and down as part of it's walking animation
look at the frames where the red cross is moving and the animation is not, or vice versa. thats the desync im talking about
i could test this by removing the animation all together
yea try, i suspect itll be smooth
if its not, ill be more confused lol but that'd just mean the follow is somehow not on the transform properly. The transform should always be on the same part of your screen.
You can even disable the sprite and just use the red cross, the red cross alone should look smooth but that relies on drawing lines so that should be in the same place your character moves
ah ha
still appears
it's for sure something to do with cinemachine and not the animation
It could actually be because of MovePosition not happening instantly.. let me try something
honestly i have no clue at this point
I tried messing with the cinemachine update settings but nothing changes
idk if u saw as well but even with camera follow in the first half of the video, the transform is still not perfectly aligned
then its just especially worse with follow

i don't get it
I'm only drawing the debug rays in my fixed update
oh wait
I'm drawing them before my rb.move position
oh thatd definitely affect it.. i shouldve realized that
i moved the debug draw to after i do my rb.move position
so now the debug draw definitely comes after it translates, but it that makes sense
what paramaters are u using for those lines?
i just wanna make sure its using the actual transform, because its kinda bouncing even when the camera isnt following
{
if (CurrentAction != null)
{
CurrentAction.FixedUpdate(this);
}
else
{
PlayAnimation("idle");
}
// Draw debug point at character's position
Debug.DrawRay(transform.position, Vector3.up, Color.red);
Debug.DrawRay(transform.position, Vector3.down, Color.red);
Debug.DrawRay(transform.position, Vector3.left, Color.red);
Debug.DrawRay(transform.position, Vector3.right, Color.red);
}
this is when ur camera isnt following
oh my, I built it, and something strange is happening
yea sorry i got no clue because of this video and i gotta sleep. Someone smarter might be able to help but in that vid u can see the horizontal line shifts while the vertical one doesnt.. which doesnt make sense to me
its working? honestly its possible that the editor is just slowing it down
that was with my animation back in
anyways, I'll shelve this for now I guess, thanks for the help
I guess the last thing u can try at least is manually adjusting the position just to make sure it's not some weird shenanigan with MovePosition. Even in update to see if the camera can just align with the transform properly
Im on mobile now but that looks way smoother
I turned cinemachine's X and Y dampening on the transposer to 0
Ohh, guess this wasnt such an advanced issue after all lol
Well at least its solved lol
guess not 
i can finally resume coding
that was going to bother me so much if I didn't get it fixed
not to be mean but remember the article i send earlier afaik they talk about that and other issues that might occur
Apparently you had other issues, my bad
But im glad you figured it out, i would go crazy and just trash the project for a few days
it didn't though 😉
wot
i mean that kinda would fix it tho since it smoothes it out the dampening
weird it does in 3D
is all good though lol
2D is wonky i guess
am just teasing
yeah still
wondering how it didnt fix it in 2D
when it does in 3D
and the article is made for 2D and 3D

prolly just unity beeing unity
glad you fixed it
i will remember the dampening setting if i go to do my 2D minigame for my game should i have that issue
are static constructors safe if the first time the class is referenced is from a mono's awake?
Safe in what sense?
You might want to use https://docs.unity3d.com/ScriptReference/InitializeOnLoadAttribute.html
A static constructor is always guaranteed to be called before any static function or instance of the class is used, but the InitializeOnLoad attribute ensures that it is called as the editor launches.
I noticed that trying to set the destination of a nav mesh agent when not on a nav mesh only prints an error message, and it doesn't actualy throw an exception that can be handled
@untold moth Worried about the constructor being called outside of the main thread. I'm not sure if it is a valid concern. MSDN says static constructors are called the first time the class is referenced.
I read a fairly old thread claiming unity's serialization/deserialization process is done outside of the main thread. I don't think this is a concern since the class itself is static and no instances reside inside a scene, therefore I believe it isn't part of unity's serialization process at all?
If it isn't, then would calling it from awake basically guarantee that it's called from the main thread?
is that supposed to happen?
shouldn't it just throw a simple exception like everything else
You could also try to use https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.FindClosestEdge.html
Not everythings throw an exception...
Depends on how things are made.
Some return status code.
java has ruined me I guess
C and C++ do status codes, rust does monads, and C# does what ever it wants
That has nothing to do with C#. It's a Unity API
Where else does unity use status codes to indicate an error?
UnityWebRequest
Yeah makes sense
I am not saying that it should be an exception, only that I expected it to be an exception like everything else
Suppose in a voxel based game, there are some items, grasses, flowers, etc. which are not voxel. They can be placed on top of voxels. Now, should I keep their ids in the corresponding elements of 3d array or just for example group id for each type is enough? I think I just want to know if a voxel is occupied or not or for example if characters can pass through it or not. I keep all items in dictionary somewhere else.
It is worth mentioning that pure voxels are stored in 3d array with their ids
For a fps game with item spawns for 2-8 players should i use unity networking services or like photon or other stuff? just for close people so
If you've already the data structure for the voxels, might as well just keep everything together and expand it into a larger data container for what each voxel may contain. Not exactly sure if a dictionary would be needed for your use case then.
If it's a small project, you can stick with unity's networking resources. Only problem is prediction/interpolation functionality is still being developed, so you'll end up with a heavier client authoritative type of game, and usually you don't want that in a quicker base game like a FPS.
kk ty
Fishnet and mirror are alternatives to a networking library, but they do not offer hosting services like photon.
unless you want to implement your own client prediction and server reconciliation, of course :p
Use whatever you feel is the best as it will probably won't matter and you would not perceive the difference nor get to the edge of each one of them. Personally, I like Network for GameObject.
There is actually a large tutorial for implementing the prediction using unity's library on youtube somewhere, but it expands like 40 videos long and no one has time for that.
Prediction of what ? Movement ? This is like 4 line of code in most network environment.
Really? Looked rather intensive for what I was looking into
The issue, is that it can become complex if you want to be perfect. Most people can get away with just offseting with the latency.
well, you have to do client-side prediction, then replay the user's inputs if it turns out that the server disagrees with what you did
i guess you can settle for client-side prediction without any reconciliation
if the server disagrees, you just get snapped to wherever it said you should be, and that's it
You do not have to reconcile. (Like you said)
At least, not for a small game.
Made on a corner.
I should keep them in a dictionary. They have some extra data like object itself for non-voxels, etc.
Non-voxels like items, vegatations, trees, buildings
Would probably be easier for loading them instead of checking each independent voxel, so perhaps you can do both. Only problem beyond a large lookup table is how you're populating it with the clusters and unloading it all.
For my voxel project I kinda just stuffed all the info into each voxel index of my grid
I think it's fine for it to be called outside the main thread. Unless you're accessing some unity API in it. Which would probably be bad regardless of what thread it is called from.
I also don't think that it would be called outside the main thread, but you should test if you want to know for sure.🤔
If you're predicting anything in a networked environment, then reconciliation is absolutely crucial. You really can't do prediction without it
Skipping the rollback phase is going to prevent the client from properly synchronizing. Snapping positions if they differ will not work since the client is predicting into the future.
That is totally false, I worked on a project (FPS) with multiple thousand of user and we do not have reconciliation. But, I can say this project is not made for competitive shooter, but more casual play style and it works just fine. In my opinion, this is what most people here are looking for. The only prediction part we do is latency offset.
But why? Why not take the extra few hours to properly implement rollback if you're already trying to do prediction? It's just lazy.
You're undoubtedly going to experience nasty jittering and teleports when they go out of sync
It is not an extra hours. Properly implementing rollback means resimulating the whole physics which is not something we can do in the budget server we have.
The server doesn't rollback.
And, you do not experience nasty jittering nor teleport.
gonna go ahead and doubt that
Pretty sure this is how you would reconcile.
Network packet can be lost, or slowed.
not an issue
And anyway, you wouldnt able to do this on a switch.
Nintendo Switch
why not?
Because we hardly have enough power to run the game...
Imagine resimulating the whole thing.
Which means resimulating multiple frame in one.
I mean, you do you
I'm not the one that made the decision anyway.
Just sounds lazy
I'm trying my best to not be an asshole and tell other people their business, but it's just difficult to watch.
If you have a low enough tickrate, you can probably get it down to 2-3 resimulations per tick. If you're just resimulating the local player, that's basically nothing.
I do not think this is particularly lazy. The solution we currently have does the job for the target market and the budget allocate to the game. It can reach a higher range of console by not having to do heavy calculation that would not matter to the public we are targeting.
So how does that work?
If your client is predicting tick 100 and tick 95 comes in, are we now just reset to tick 95?
Prediction without rollback is basically one giant contradiction and is going to screw with your lag compensation and hit resolution among many other things.
It is even simpler then that. If the receive position of the client is too far then what his actually position, lerp him back to the server position.
This is not made to be perfect. It cost nothing, and most of the time it does nothing.
This is a tradeoff between performance, quality and budget.
So how are you dealing with raycasts over a network?
When the clients shoot each other
Is it just whatever the server is seeing?
Pretty much. The other player are being offset by latency which balance a bit this.
There is definitely issue with the hit detection, but as I said, this is not a competitive game which means that this is acceptable for most of the player.
People (As with low budget / Single Developer) that are making an FPS, does not need Client or Server Reconciliation to make a game. People are still gonna play your game and enjoy it same if you do not have perfect networking.
Completely disagree with that last part. Many people will throw a shit fit towards the developers if their clientside shots aren't registering.
I'm not looking to start a fight, so that's where I'll end the critique.
What people say and what people do is completely two separate world. Take micro-transaction by example.
You have the right to have your opinion, the only thing that I suggest that you consider is how other project are successful same if they have a weak networking. Personally, I would not advice people to invest resources in doing server reconciliation as there is other solution that works and is easier to implement. There so much to be done in a game that would be more important than strong networking.
Sorry, but if your game has weak networking that leads to shitty hit resolution, then I'm absolutely going to call it out. It's not an opinion. It's a fact that your team is taking shortcuts.
I fail to believe that rolling back and re-applying inputs is so massively heavy on the CPU that it leads to something unplayable. If that's the case, then lower the simulation rate to something appropriate for a switch.
I'm going to say this in the nicest way possible, but your network guys have no clue what they're doing.
That's about where I'm going to end this conversation, because it's just going in circles.
btw for the hit resolution on the server, don't use latency. Let each client tell the server which state they're looking at, and the interpolation alpha. Server can rebuild the client's view based on that. You'll get much more accurate detection.
And no, this doesn't open up cheating any more than someone installing an aimbot on their client.
anyways best of luck to you man
sorry for being an asshole
❤️
why is this script able to turn off the light but not turn it on?
@old hazelprobably because you're disabling the gameobject
if I had to guess
this also isn't an advanced question
what could i use as an alternative to UnsafeList?
im basically looking for an array version of the UnsafeList - an unsafe collection that lets me write to an arbitrary place in the list
(i have an IJobParallelFor that wants to write to this collection)
What's wrong with NativeArray?
main problem is that burst doesn't want me to have nested native collections
in another job i have a NativeArray<UnsafeList>
which is fine
but NativeArray<NativeArray> it doesnt like
im generating terrain with marching cubes and each chunk needs to know about its neighboring chunk's information in order to build its own mesh
could be thinking about this problem wrong idk
that would technically work but it seems kinda wasteful
compared to if i could get some sort of unsafe array sorta thing
the only problem im having with unsafelist is that even if you set its capacity to say 100 for example it doesnt let you access list[50] unless you actually add that many elements to the list
which you can imagine is a problem when youre using parallel jobs
If you know the number in advance why not just a flat nativearray
you want a 2D array basically, but under the hood those are just 1D arrays with a little clever indexing math
For example - let's say you want 10 arrays with 100 elements each.
That's the same as 1 array with 1000 elements and you reserve 0-99 for the first thread, 100-199 for the second thread, etc..
is there a performant way to join two nativearrays together like that
WHy would you need to join anything together?
each chunk's voxel data is generated in a native array (with a persistent allocation) then an abritrary amount of time later, its mesh is built using that native array. so if you're saying i should just be using a single native array for multiple chunks, i would need to combine them together before sending them to the mesh building job
It's a single array, what is to be combined?
1 chunk has 1 array of voxel data, however it must take into account the data of adjacent chunks while building the mesh
I'm saying put all of the data into one array. Not one array per chunk.
that wouldnt work cuz the world is infinite
my code works
the problem is that i need to do a seemingly pointless initialization of an UnsafeList by looping through 4096 elements adding empty data before sending it to the job
why not?
You obviously wouldn't have the whole world in memory at once
obviously you will have to do a little management of your array - assigning chunks to swaths of indices for example
comes with the territory of manual memory management
well it WOULD work but the problem is that i'd have to be doing a lot of shifting stuff around on the main thread
which is what i want to avoid for performance reasons if possible
im comfortable using the unsafe stuff if it means avoiding that because this a very performance heavy part of the game
Only on the order of the number of loaded chunks, which is what - less than 50?
well 50 was just an example
but in the actual game each chunk is 16^3 voxels and there are 10^3 chunks
1000 chunks loaded simultaneously?
I'm imagining minecraft here - at worst there'd be around 256 chunks loaded at once in Minecraft
Ok but your chunks are smaller than minecraft chunks
minecraft chunks have 65k blocks
it's really the same, your system is just more granular
yeah basically
oh wtf
i solved the issue
turns out its possible to access the unsafelist.length and actually change it by hand?
so i just set it equal to the capacity i needed
now it functions identically to an array
🙂
Anyone experienced with multitouch? I'm using the "new" input system and have callbacks set up for primary touch position and touch1 position. Sometimes when I start dragging with 2 fingers, and then lift one of them I end up in a state where neither of my callbacks is getting called anymore? Did anyone experience this? Is there a way to use multitouch in the new system like the old one? by just examining touches and how many there are each frame?
I’ve often found Multitouch gestures with inputsystem to be cantankerous like you describe. Recently it seems that Fingers (asset) figured out how to deal with it (it used to have similar issues). You might find hints what they did in their changelog/source. personally I’ve only ever managed to fix it by detecting and handling all the weird cases.
@compact ingot thanks, I'm debugging now, and if not for the fact that everything works correctly using controller/keyboard I'd start changing my gameplay logic cause the touch inputs are putting my code in impossible states. I think I'm going to have a go of rewriting it with the "enhancedtouch" have you tried that? I just found some tutorial for it allegedly handling multitouch.
I’ve once made a Multitouch gesture library which was not fun to do beyond the basic proof of concept, eventually I abandoned it in favor of better/maintained/commercial libraries
Well Fingers is only $10, but on the other hand it does a million things I don't need, all I need is a documented touch api that works reliably 😦
What do you need specifically? The core/value of fingers is not the 50 example components, it’s the gesture ‚engine‘
Well, I already have a simple "gesture" recognition in place, but I started having bugs with my input c# events the moment I added multitouch support. I guess I must be making some assumptions about how the new input touch works, I added primary / touch1 actions for position and press. And it all just behaves "weird" for example I would expect one of my motion callbacks to always log something when a finger is on screen, but with some lifting single fingers while keeping other on screen I get into situations where none of my callback fires... things like that..
Can confirm, I’ve experienced that too. Don’t know a fix.
(ugh, found a bug ( in my code) I was calling a callback on press ended/cancelled for each of the configured touches, and fireing an event, where I should have been doing that only when all fingers stopped touching... it's still a mess, and I should still rewrite it, but it's good enough and I'm having a sort of premiere of my free game in two weeks : ) anyway, thanks for the support @compact ingot for future reference you've since got and used the Fingers asset and can recommend it?
Yes, it’s a good asset that has not yet failed me.
That's what I did 🙃
Unfortunately, I could not find the cause.
Although I did find out the issue was due to the pathfinding code I was using.
I'm trying to create a Civilization-esque system where the player can select a unit and move it to a different cell. Previously, I was using the A* algorithm which took 2 cells and tried to find a path between them. But then I also wanted to show all the possible cells where the selected unit could move, and for that I had to use Breadth First Search. So, I ditched A* and just used BFS for pathfinding as well.
The issue does not occur anymore. (But I still don't know why it was happening before).
Anyway, Thanks for the help @scenic forge @dusty wigeon @bleak citrus @compact ingot @sly grove
you may want to look at Dijkstra's Algorithm (if just for reference), this captures the idea of checking all paths and then selecting the best one (without any heuristic like in A*). An intermediate dataset in that algorithm is your "all available paths" info.
whats the best way to save and load scenes
save everything in the scene as it is, all the changes, movements, traps or whatever, and then load it with a button in the previous scene
Anyone knows how to tweak OnDrag pointer event sensitivity? I am implementing IDragHandler and it seems like when I press button and move mouse, the OnDrag is not triggered immediately, I have to be a certain distance from the original pointer position to trigger and in my case for some reason the distance is quite long so it feels like there is a lag.
Save the particular data you care about and then load and recreate the scene from it
Saving the "entire scene" isn't really a thing nor would it be efficient.
it's a very broad question
especially if you're talking about changes relative to the original scene
e.g. recording that a specific enemy from the original scene is now standing in a different position
i imagine it's a lot simpler to just make a big list of every enemy that's currently in the scene and recording that information
I intially put this in the talk chat but it it's gotten a bit lost so thought i would put it here too. don't know if anyone can help me but I've been banging my head for hours trying to fix this to no avail, When clean building my game that uses Firebase. i get a duplicate class error, I've tried the Android resovler to delete, resolve and force resolve the libraries however that didn't work, I've also tried uninstalling the Firebase SDK and re installing it through the package manager and then as assets but both of those still resulted in this error, any help would be appreciated
okay
try deleting android dependencies again. Use the resolver to delete, then go to Assets/Plugins/Android and delete any extras there since it misses some sometimes which will cause that type of error. Then search you project for the mentioned artifact. Maybe it snuck into a folder it shouldn't have, and that would cause an issue like you see
Thanks for the reply! okay so i used the resolver to delete again and those files are still there, so am i right in thinking it's okay to delete them completely? I also used the project search bar to search for them and that's the only location those files appear to be in
yes, those two jetbrains files
Is there any activity revolving exporting to webGPU?
so delete them then force resolve and try clean build again?
my guy i cannot thank you enough, I can't believe that's all it was, honestly been at this for 2 days straight trying to fix it. You've no idea how much your help there meant to me
Who codes gtag fan games
Not me
I need help with setting up my assemblies.
I have a tests assembly, where I included Main (the assembly where I have all the code), and UnityEngine.TestRunner
I now also need to include the newtonsoft assembly, but I cant find it in the editor. How do I add it?
it doesnt find it in the test
but it does on the play mode assembly
found it
Hello! I have a problem with credentials in WebGL requests.
I have Set-Cookie .AspNetCore.Identity.Application=CfDJ8KibhKtdp... in one request and "credentials" set to "include" (127.0.0.1:10203/ns/login)
And in the later request to the (127.0.0.1:10203/ns/projects) I see no cookies set and "credentials" is set to "include" too
I don't see anything related to credentials in the Headers, if it needs to be there
In Unity there appears to be no Set-Cookies either
What should I do to make cookie be set in the (127.0.0.1:10203/ns/projects) reqeust?
hey: is it uncommon to make use of allocator.persistent at all? im Disposing the nativearray when OnDestroy() is called. i can find only 4 google pages for "allocator.persistent" and most of them are dealing with bugs. so i thought of recreating the transformaccssessarray every time im using it, but where is the sense of recreating the entire array every frame to move my transforms like this: transforms[] -> nativearray-> setting the transforms ? wouldnt this cause even more overhead/garbage, or will just refernce the original items of the original array? i mean its ok as long as i am not using any other jobs, or physics events that interact with the gameObjects moved by the transformaccsessarray. this is the warning which is most likely caused by a bug, or incompatible package: ````Internal: JobTempAlloc has allocations that are more than the maximum lifespan of 4 frames old - this is not allowed and likely a leak
okParallel-for-transform jobs allow you to perform the same independent operation for each position, rotation and scale of all the transforms passed into the job. it doesnt say that its multithreaded so i guess i just use asnyc, or playerloop to move my transforms and calculate their positions inside a job
If you're going to use the same size array every frame there's no sense in deallocating and reallocating it over and over again
The job system is indeed multithreaded when circumstances allow.
Hello i am trying to save settings with PLayer Prefs and i am starting off with a toggle (to mute volume) how do i do that???
SetInt 0 1
How do i do that?
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
Series Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53vRrMuPBkNNZUmnl1jCHcHs
Grab the Project files and Utilities at https://unitycodemonkey.com/video.php?v=donIirlj074
Learn the simplest way for Saving a...
Thank you i shall watch this
no i mean the ijobparallelfortransform.
since gameObject/transform is not a simple datatypes or non-blitable.. https://www.ibm.com/docs/en/tivoli-netcoolimpact/6.1.1.5?topic=types-simple-data i cant quite remember
it is multithreaded
but it does it per root object, so if all your objects are children of one object it will happen all on the same worker thread
yeah, normally you can't change gameobject fields safely in jobs but Unity built a special way for transforms which is why IJobParallelForTransform exists
ok. thank you. can transformaccessarrays be public? ```you should not access global (i.e. static) stuff from jobs, as it would introduce race conditions.
you should put a NativeArray inside the job and use that
i'm not sure what you mean
public and static mean two different things
yea sry i mixed up global and public
https://pastesite.org/view/05379732 this is how im using it to transform my objects. but why would this cause memoryleaks? ill try to use the memoryprofiler lets see
is this your only job?
even if its the only job, the warning is still thrown
To Debug, run app with -diag-job-temp-memory-leak-validation cmd line argument. This will output the callstacks of the leaked allocations. so where can i see the leaked allocations? in the debugger?
well then it's probably an internal Unity leak
or check the profiler and see if that job is taking too long (over four frames)
warning says internal (only thrown if this job is fired), but the problem is that physics events will cause crahes (like physics.overlapsphere). but let me check the profiler
void Update()
{
var job = new carJob
{
deltaTime = Time.deltaTime,
playerPosition=playerPosition,
playerVec=playerVec,
startPos=startPos
};
JobHandle jobHandle = job.Schedule(transformArray);
}
I've just noticed the last line
you are setting it to a local variable
which means the LateUpdate is not force completing the job
which could cause the job to go over four mainthread frames, if the main thread is running fast
remove the JobHandle so its not a local variable
and try again
ok let me try
ok i think i have to recreate this in a test scene... im not sure why its saying 750 instances. i only got 300 transforms that im moving. now im kinda confused
yeah, SystemAPI.ManagedAPI.GetSingleton(), i think is the syntax
I believe this is available in Entities 1.0 and not in 0.51
do you have a reference to the entity that contains the component?
ah
For managed components, put 'this.' in front to use GetSingleton<T>(ComponentSystemBase)
so in a class system you can do that for 0.51
or do it through an Entity query
I was about to say "what kind of unholy things are they doing in there, to require this. to be used", but then I saw that it was an extension method
i think this is a bug. i actually have another job float timer=0f; void Update(){ if(timer<1f){ timer+=Time.deltaTime; } else{ timer=0; var commands = new NativeArray<OverlapSphereCommand>(1, Allocator.TempJob); var results = new NativeArray<ColliderHit>(3, Allocator.TempJob); commands[0] = new OverlapSphereCommand(centerObject.transform.position, 10f, QueryParameters.Default); OverlapSphereCommand.ScheduleBatch(commands, results, 1, 3).Complete(); if(results.Length>0){ foreach (var hit in results) { if(hit.instanceID==0)return; Debug.Log(hit.collider.name); } } commands.Dispose(); results.Dispose(); } } but that really dont make any sense at all. the memory leak-warning is only thrown if both jobs are running. (even if theres no interaction at all). ill try overlapboxcommand, i really dont know what to do from here, besides recreating this in a testscene. can Profilermarker help to find the source of evil here?
foreach (var hit in results)
{
if(hit.instanceID==0)return;
Debug.Log(hit.collider.name);
}
......................
.........
........
see the issue
Yes
var entity = GetSingletonEntity<SceneManager>();
? what do you mean?
it doesnt matter if i use break instead
ahhhh
Thanks this one works for me
that makes sense, but the editor is still crashing 😭 and the leak-warning is still thrown
I see that NativeArray<T> implements IDisposable, meaning you should be using them in using () statements to ensure disposal whatever happens (even if you return early)
you could do that in this case since they complete in the same function and it's TempJob
but you don't need to dispose for Temp. Also persistent unless you need to (like in destroy)
If you were using Entities then you'd use the World Allocator instead of TempJob
then you wouldnt need to dispose then either
thats why you don't really see a lot of people use using, at least i don't
like this using NativeArray<OverlapSphereCommand> commands = new NativeArray<OverlapSphereCommand>(1, Allocator.TempJob); instead of var commands = new NativeArray<OverlapSphereCommand>(1, Allocator.TempJob); but this is the actuall snippet provided by unity https://docs.unity3d.com/2022.2/Documentation/ScriptReference/OverlapSphereCommand.html
and i cant modify the commands-nativearray if im doing soCannot modify members of 'commands' because it is a 'using variable' https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects the using(...)-field in the given example is also just readonly
I'm trying to understand GOAP. I have problems with building an action graph and solving it. I've watched 2 videos explaining that on a script similar to this https://github.com/sploreg/goap/blob/master/Assets/Standard Assets/Scripts/AI/GOAP/GoapPlanner.cs but I dont understand it. Also I would like to use a*, and this one doesnt.
doesnt unity has its own ai-system now`?
what system? i need to learn this anyway
its called unity-ai but its still in beta. not sure if that includes a GOAP-like systhem for statemachines
heres a complete series https://learn.unity.com/project/goal-driven-behaviour?uv=2021.3&courseId=5dd851beedbc2a1bf7b72bed
In this project you will learn about the Goal-Orientated Action Planning (GOAP) architecture used to create intelligent agents that can set goals and plan at achieving them. Unlike Finite State Machines, actions and states are uncoupled, making for a very flexible system. You will build a GOAP system from the ground up and implement it in a si...
thanks i'll check it out
yeah wait a minute i've watched those.
but why implement your own a* systhem? navmeshagent is super performant
not for movement but for action graph
ah
this one here looks awesome and its actually up to date https://github.com/crashkonijn/GOAP
it does, thanks
Hey everyone, how can I prevent breaking on exceptions while debugging in Rider?
In my main project, I have a tool installed which always throws when exiting play mode and I would like to ignore it.
In visual studio, that would be break on exception. (Given that you did not place a break point yourself). I guess there is the same in Rider.
Can you suggest me a good way to handle it?
In my voxel game, there are some rivers, they flow gradually. I have to update voxels and generate chunk mesh in every step but it is time consuming.
A simple way is not to regenerate chunk mesh in every step.
Another option is to regenerate meshes just when they get visible.
or create different meshes for water voxels completely separate from other voxels.
Chunk = Water mesh + Main mesh
hi. does LateUpdate happen after render call?
look at this test
output
why is LateUpdate executing one frame later?
according to docs, LateUpdate has to happen before rendering
https://docs.unity3d.com/Manual/ExecutionOrder.html
I think you perhaps are just missing when start is called in the scenario you are creating, as it's not the first frame I suspect you're instancing, in which case start may not run when you think it is
so you're saying if I instantiate on, say, Update, then the Start will happen right there and not according to the execution order document anymore?
I'm instantiating it on LateUpdate btw
tho not instantiate. I enable it then
changed it to this for better testing
this is the result when I enable the Test1 on Update
if you do this with an object already in the scene, you should just get framecount = 1 for both messages.
oh just saw that last part u put
nah Test1 is not enabled at first. I shouldve mentioned that lol my bad
this is the result when I enable the Test1 on LateUpdate
this is weird... seems like Start happens in the same frame as when the component is being enabled. this is not according to the docs ...
either that or im missing something very important here
The docs do not show start or awake in the update loop, they just say:
For objects that are part of a scene asset, the Start function is called on all scripts before Update, etc is called for any of them. Naturally, this cannot be enforced when you instantiate an object during gameplay.
C# Discord
they do at this doc https://docs.unity3d.com/Manual/ExecutionOrder.html
those arent in the player loop and also
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html
Start is called on the frame when a script is enabled just before any of the Update methods are called the first time.
oh good point. the bold arrow is the main loop, huh?
it all makes sense then
thanks a lot
Hi, I have communication via SerialPort (consoleApp works fine) but if I put into unity event "DataReceived" not fired although serialBuffer have data
{
this.m_SerialPort = new SerialPort();
this.m_SerialPort.PortName = this.m_COMPort;
this.m_SerialPort.BaudRate = 9600;
this.m_SerialPort.DataBits = 8;
this.m_SerialPort.StopBits = StopBits.One;
this.m_SerialPort.Parity = Parity.None;
this.m_SerialPort.Handshake = Handshake.RequestToSend;
this.m_SerialPort.DtrEnable = true;
this.m_SerialPort.RtsEnable = true;
this.m_SerialPort.ReadTimeout = 0;
this.m_SerialPort.WriteTimeout = -1;
this.m_SerialPort.DataReceived += this.DataReceivedHandler;
this.m_SerialPort.Open();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
print("přijem!");
SerialPort lSerialPort = (SerialPort)sender;
byte[] lBuffer = new byte[lSerialPort.BytesToRead];
lSerialPort.Read(lBuffer, 0, lBuffer.Length);
this.m_Command.AddToBuffer(lBuffer);
}```
Or if it won't be better to simply create a coroutine that checks the buffer and reads and not rely on the event?
is having everything in one item class the norm ?, I plan to have 3 kind of item, these 3 doesnt share many things so my current code have a lot of empty return. easy to code but quite ugly
I'd imagine that you're doing something wrong if you end up with empty override methods. Or even more so if they're interface/abstract class implementations.
yes actually considering using interface but "this cant be the right way". tutorials usually use this architecture, and I havent find proper one
I mean, you'd usually have a base class with the common functions, then the subclasses only override stuff they need to override.
for more context, i have item that can only be placed on floor, on a surface, and normal item
these 3 basically only share inventory icon but if i want to check an item i couldnt check the right class
havent figure it out other than mark it with a string then check the string then check any of 3
I'm sure items have at least some other common properties. Either way, that doesn't sound like an advanced question.
If you need a code review, share your code in #archived-code-general
true i guess, cannot find stuff i want so i put it here my bad
i want to convert a patrol/chase/attack state machine into GOAP. There should be actions like MoveToPoint, DealDamage. I dont get how i would set goals, preconditions and effects. Let's say an agent only wants to patrol. What would the sequence look like? The picture is how I would do it. But the SetTargetPoint action should be later reused for finding what to chase, for example. If i make a lot of set point actions then the amount of states also increases and it just seems wrong.
i want to convert a patrol/chase/attack state machine into GOAP
why? what value are you hoping to get out of goap? it sounds like what you want is predefined states with scripted behavior, which you can represent in your goap but it's going to be awkward compared to using a state machine which is designed to handle exactly that
so i can understand how it works and make it more complex later
'when does it make sense to use this?' is an important part of understanding tools
trying to use a hammer to screw in a nail will teach you something but it's not how i'd recommend learning
okay what should i start with then? it's not about having state machine as a base, it's just a simple example
you mean like what is something you can make that would have a use case for goap?
you're saying goap is super specialized, but i think it just allows for more complex ai behaviour
I don't know if it's super specialized, but it's about planning and the actions you are trying to plan don't really require any planning
what plan is required for following a patrol route? the plan is just...follow the route
same for something like 'chase target'
goap is essentially a pathfinding algorithm that can include things other than pathfinding nodes, which is cool! but if all you need is pathfinding in the world, and not across a set of actions/outcomes, goap is way overkill
often it makes sense to do both -- you want your mobs to have heavily scripted patrol paths, target acquisition, etc. so that the player can predict and interact with those things
but maybe once your ai is in the combat state, it can switch to a goap planner with some interesting goals
what those can be and how interesting they are will depend a lot on the environment you are building in your game though
there's a reason goap isn't super popular used all the time everywhere despite how cool it is
hmm, that's an interesting-sounding idea. I don't know very much about "GOAP" myself
i should really just read about it lol
it's very cool but ultimately having things in your game act in unpredictable ways is often not what you want
in most cases it ends up being cleaner (and more performant)to just script a few different 'plans' and select one versus doing that in realtime all over the place
you need a fairly complex environment before it becomes worth it to let your agents come up with their own plans and at that point it becomes difficult to do important stuff like...balance your game, because your main tool for doing that is changing the environment itself, which is a lot of work
this is a good talk on how they used in in Shadow of Mordor, where maybe it was overkill but the results were good:
https://www.youtube.com/watch?v=gm7K68663rA
In this 2015 GDC talk, AI Programmers Chris Conway, Peter Higley and Eric Jacopin revisit the Goal-Oriented Action Planning method of game AI programming to see how it's held up for the last 10 years, and how it influenced the AI of Middle Earth: Shadow of Mordor and Tomb Radier.
GDC talks cover a range of developmental topics including game de...
i'm working on an AI for a survival horror game
it's a good resource for seeing what kinds of goals/actions make sense and all that
i do want to start moving towards more complex interactions than "investigate the most interesting sound/sight"
ah yeah, that's a potentially good fit because that kind of game is a lot about the environment
first time i made ai i had 100 lines of hard readable code and only later i switched to behaviour tree, which was painful, because i didnt know what it is then. I just dont want to make it even more complex and repeat the same thing. but maybe you're right i should first try to lay out some logic and only then separately apply goap to what i want.
writing and rewriting stuff is just a big part of learning and i suggest embracing it
the important thing is having clear goals so that you can tell whether that time was well spent, what improved/didn't, etc.
I specifically want to introduce memories, where the enemy remembers the results of encounters
for example, if you throw a rock to distract it, and it finds nothing after investigating the "rock falling" noise, it should gradually start ignoring the noise
oh shadow of mordor totally does that but i donno if it has anything to do with goap really
ah not quite in the same way
that's also probably not GOAP anyway
it sounds like "goal-oriented" really kicks in when you have complex chains of logic
like, the enemy wants to trap the player, so the enemy starts barricading doors and stuff
yeah, do you want your ai to come up with and execute complex multi-step plans? but in a lot of cases i feel like you may as well just script a 'barricading room' state
especially because for goap to be useful, you kind of want a complex environment? but the more complex your environment is, the more frequently plans will be invalidated and need to be replanned
one thing I want to tackle first is "cutting off" the player
ultimately you kind of want your ai to be predictable because otherwise the game is too hard
player goes into room with two exits -> go to the other exit
haha
i can't remember how to do the math for intercepting a projectile
see a lot of stealth games intentionally prevent mobs from being mean like that
god knows how i'm gonna do this one
depends on the vibe you are going for
i feel like i need to calculate how far the player could possibly be from the starting location at different times
and then find a spot the enemy can reach at the same time (or sooner)
but it can be very easy to put a lot of work into making the player's life miserable and then succeeding and being like 'shit'
lol
unless i have some way to clearly know that that zombie is flanking around to cut me off, i am going to call bullshit when it happens
I'm going for an Alien: Isolation vibe, so I do want the enemy to be very threatening and a little unpredictable
it's one enemy, not 100 dudes
oh nice, ok yeah
i figure I can slap a big dial on the AI that controls how likely it is to be "weird"
i really like goap for that case then
it also means that I can spend a lot of resources on the AI
since there's just One Of Them
since the environment won't actually be that dynamic and the player hopefully has enough bandwidth to actually understand this one individual and how they behave
yeah good stuff
i bet A:I cheats though
i doubt they are calculating the timing for the alien to cut you off or whatever
they just decide whether it will and then let it reach where it needs to go, physics be damned
much easier
lol, yeah
i really like the idea of 'manipulating' the enemy in a way that goap kind of allows though
like let me steal someone's weapon and then startle them so they go grab another nearby weapon which i have booby trapped
it opens up some interesting interactions which make the player feel clever but of course you can just script those
yeah
definitely deep in #archived-game-design territory now though i suppose
the platonic ideal is that your enemies have a bunch of little behaviors that all mesh together properly
to OP's question
Need some advice/opinion:
What's a good role title in a job ad for a person that would do a lot of rendering optimisation, shader fine-tuning, asset pipeline optimisation, and general URP wizardry?
"Tech Art" feels too vague (and some on the pure programming skew see "art" and feel mismatched)
"Rendering Engineer" maybe, but some people seem to get confused by the term "engineer".
Graphics engineer?🤔
Proficiency with urp render pipeline, shaders and experience in game optimization?🤔
Technical artist isn't vague. What you described is the definition of a Technical Artist afaik. Good plus for any team imo.
if you want the title to be descriptive enough so people that aren't qualified would not even read the description, you could just make it Rendering Optimizations Engineer
but be mindful, that'll reduce the applications by a shitton amount
If you think this is not an advanced position, write 'Designer - Unity (URP Shaders)'
Any Problem in this code? why rotation of laser is so wrong?
Are you sure it's an advanced question?
Also check the code sharing guidelines:
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
yes if it's something i can fix i'm ready to listen
First share the code properly. Because it appears as a text file on mobile.
Not sure what you're trying to reflect here. The first argument needs to be a direction vector afaik.
Vector2.Reflect(hitInfo.point, hitInfo.normal);
Hit point is a position, not a direction

You could get that answer in #💻┃code-beginner to be honest...
If you can't solve a problem it doesn't meant it's an advanced issue.
sorry i couldn't calculate the complexity of the problem
Well, if you're a beginner, it's very unlikely that the issue is gonna be advanced. Either way, it's better to start from the beginner channel and if people tell you that it's too advanced go up the channels.

Need a bit of EMERGENCY help. I modified a script and saved it. Unity started to do it's Importing thing to recompile; but it got hung up and it's not progressing. Is there ANYTHING I can do to force it to stop or something? I don't want to "kill" Unity because I'll lose all my scene work.
Don't cross post please
Was a reason for it.
Where's the #code-god?
i am having a vary frusterating issue with my code
may anyone help please
it is a lot
please ping if you can help
paid only
Also, don't cross post.
You don't need to ask to ask, just post the problem. Also this discord isn't really for one on one support.
whicth one is for support
All of them, it just depends on the topic of the problem #🔎┃find-a-channel
Question. Is there an extension or IDE that has a sub tabbing system. So in VS I can pin script tabs. And with a setting I can have unpinned scripts on the line bellow. Which I would like is if I click a different pinned tab it has it's own unpinned tab bar/update the second script bar that is there.
Hi guys,
I'm using Python Scripting 7.0.0 package and I'd like to get auto complete for Unity classes in IDE (Ryder) while writing python code.
My closest finding so far is this repo: https://github.com/gtalarico/ironpython-stubs
Using this I may can generate python stub files from the C# classes.
Haven't started to play with it yet; I thought it's better to ask first whether there's an existing solution. Even an official one, or whether someone in the community already managed to generate the stub files.
Does anyone know if it is possible to pass a array of positions, instead of matrices when using gpu instancing (fixed scale/rotation). Cant find any examples online, thanks a lot
Good morning, any one knows how to further compress TextAssets to reduce build size? I have around 30mb in texts assets (.csv) with levels in different languages (its a word game)
30mb is the compressed size in a build
i have tried different compression softwares to try compress them beforehand but the resulting size is very similar... i guess im looking for magic 😆
Maybe look at different ways of storing your text. Im unsure of why u are using csv, especially since you say there are different languages.
Do you have localization and i18n?
Different compression software's wont really do much
its a list with all the levels (each level is 2-10 words) there are around 30k levels in each file
one file for each language
would there be a better way of storing it thatn a csv? i already minified the files
From what I saw online unity does have a localization package, although I have no clue how it is because I've never used it. That might be able to help with your issue
It does say you need csv or some other format for it though..
thanks i already know it, but it wont help for this issue, the game is already correcly localized, im just trying to reduce build size
without implementing download of content
Im not entirely sure, I havent ever compared different file sizes. Your csv might be bloated if theres some formatting inside
But that's more so if u are opening it in excel or converting
i already stripped all unnecessary info from the files, its just a lot of content.
thanks for the help, i will continue looking to optimize other areas of the game first.
Yea unfortunately there may be a certain point where it's just too much data to compress unless you write some custom compression
Goodluck still, maybe someone else knows some black magic function for you
Can someone analyze my crash log file? I dunno where the problem is
I couldn't find that option in Rider but thanks for the suggestion
Hmm, I would like to ignore exceptions though. Run | Stop On Exception isn't the same as enabling breakpoint debugging.
Just make sure there is no break point on exception.
but I don't get a breakpoints dialog when I enable breakpoint debugging
I have all exceptions disabled here
In visual studio, there is a window like that
If this is the case, then it is not what I was suggesting.
I have a world that i am procedurally generating
and it looks like this
Now in am stuck on how to do pathfinding in the this dynamic world
everytime a different world is generated
it is created using this tilesets. I am not able to figure out how i would do pathfinding in this scenario
isn't that just the AI Navigation package now
but yeah, you can totally bake a navmesh at runtime
havent used it for a long time, youre probably right
If movement is grid-based, you can create some simple graph and use any pathfinding algorithm. If the movement is free, then probably it's better to use NavMesh as suggested above.
Can confirm that the AI.Navigation package has support for dynamic navmesh generation
^ Yeh AI.Navigation package should help you out
I found a project I had that generated tiles and then created a navmesh from it
using Unity.AI.Navigation;
public class NavMeshManager : MonoBehaviour
{
private void Awake()
{
GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
//<I set the scale and position here to fit the map I generated>
floor.AddComponent<NavMeshSurface>();
UpdateNavMesh();
}
public void UpdateNavMesh()
{
surface.BuildNavMesh();
}
}```
Hey guys! I want to ask if there is anyone who does coding for a living. Is it possible? Is it worth it? I would like to leave my current job and live on my reserved money for 5-6 months, and create some games that make my CV attractive to employers. But are there any employers out there that are willing to pay a living cost for my coding and unity experience and desire?
Of course there are. Like any other job.
Though, I wouldn't quit your job while learning. You don't know how much time will take you to learn enough to get a job. And the job hunting itself can take some time.
You wouldn't be able to create "some" games in just 5-6 months
Maybe 1 would be possible if its a 2D game.
But that won't be a such a big feat to put in your CV i guess
Also what's the reason u wanna quit
What is it that coding job can offer that your current job dosent?
From my experience (I do not have a lot), Video Game Industries as a programmer can be tricky to get in. There is a lot of "self taught" programmer, but with the except of a few, most of them accomplish nothing that is worth considering.
In my opinion, if you really want to get into video game, you should consider certification (1 - 2 years). Those certification helps build a portfolio while also acquiring a variety of skills that are directly applicable. Where I work, 3/4 of the people that has been judge qualified enough have done those certification. I feel like video game education has evolved these past years and the quality of education you can get is now higher.
Note: Multiple bachelors and master has applied, and with the exception of 2, none were qualified. Lack in understanding of video game concept was one of the reason why. (They were not able to find the closest point in list. )
whether you can get a job depends a lot on your location, game studios are swamped in applications of clueless people (everyone applies to every job offer disregarding any requirements) so to actually get even an interview you need to have a believable resume and can demonstrate competence in a screening call within minutes, this is difficult to fake. Its considerably easier to land a unity job at a mobile studio over a AAA job doing C++ in an in-house engine. Best/most predictable path is an internship and practicing by making challenging projects in the meantime. Most of what studios are looking for in skills is not the easy stuff that is fun to do. They want you to be able to connect your work with that of others, deal with integrations and pipeline issues, tools and conceptual things that are part of operating/releasing games. You are often left alone in understaffed teams, so being able to pivot quickly between problems and having strong fundamentals is key. Anyone can implement gameplay features. Few can do it performantly, fewer still can do it productively in a team running a live game.
How can I call managed functions from Burst compiled code?
I tried using FunctionPointer<>, but the function which points to must also have the BurstCompile attribute
Hey, so I'm new to the whole DOTS scheme. I'm reading the documentation, but I would also like some starter guidance from someone.
I want to make a game where you have up to millions of individual "Bricks", lego block style bricks. Like the game Blockland. Would it benefit me to have each brick as an Entity?
The tutorial of DOTS says that if you are making a Minecraft game, probably you don't want each block be an entity because the overhead would be unnecessary.
I guess the same applies to bricks.
Thanks! I would suppose then, that entities is not the way to go. Is there anything you could forsee entities helping optimize in relation to the "brick engine"?
I'm sorry, but my knowledge of ECS is very limited to forsee anything actually haha
For DOTS and ECS questions there's the #1062393052863414313
Currently my work is great. But I feel like I am not good enough to keep working with CFDs. And I feel like this is because the lack of study of physics and chemistry. I know I am antitalent in physics and chemistry stuff and I don't even like it. I hate calculating Pressures (dynamic pressure, absolute pressure, pressure, gauge pressure, vacuum pressure, total pressure, Static pressure), I feel like for this I would need highschool and I am burning out slowly because it is just Way too much on me who knows nothing about physics and chemistry.
I want to start programming. I loved programming from the first Time I wrote out "hello world".
And also I love video games. And I love programming games. Once I was ín a 5 week long camp, it was in Bratislava, and Ive worked together with 1 programmer, 2 graphics designer, and 1 team leader. It was great working in a team and I loved it so much. I would love it even after 10 yrs if I had the chance to work ín a team As a programmer and create fun little(or big) games
I need some help with UnityEvent...
I'm invoking a UnityEvent<string>, and I want to use that string value to update an UI element.
I've added an event listener to my UI element so I can call a function to update the value on the UI element to my UnityEvent string value.
But for some reason the value stays empty, so it throws an error because the string is empty
I think you need to use the dynamic version.
When configuring a UnityEvent in the Inspector there are two types of function calls that are supported:
Static calls are preconfigured calls, with preconfigured values that are set in the UI
. This means that when the callback is invoked, the target function is invoked with the argument that has been entered into the UI.
Dynamic calls are invoked using an argument that is sent from code, and this is bound to the type of UnityEvent that is being invoked. The UI filters the callbacks and only shows the dynamic calls that are valid for the UnityEvent.
Oh wow, I have no idea how to implement this, I'll look into it. Thanks!
`[Serializable]
public class StringEvent : UnityEvent <string> {}`
StringEvent is not even recognized in the IDE
The documentation is a bit outdated. You no longer need to define a derived class, you can serialize UnityEvent<T> directly
Which networking system should i use if i just want players to spawn and be able to shoot weapons and kill eachother in unity? for few players too
The easiest and fastest one?
Yeah I actually tried to use this
https://docs.unity3d.com/ScriptReference/Events.UnityEvent_1.html
But I couldn't get it to work
Here
k ty
you know best tutorial or smth? but dw ill just use any
How to re-write attribute like UNET's [Command] ? I tried with sample Debug attribute to log class name and method name but it doesn't work, when I google, I see attributes isn't be called when method called instantly but so how UNET can do it? When I call some method with Command attribute, it works 😳
Any example for that?
[Debug]
void SomeMethod(){}
And called like
SomeMethod();
But it didn't work, Debug attribute is not triggered
if stuff doesn't work out, you'll come to hate it. game industry is often really toxic.
when doing new Class<T>(script) (script is of type T) why would it assign the base class of whatever is passed in?
Why can I not convert a custom type into a variable of type System.object? (An enum or a class, for example)
And by extension, are System.object types not serializable?
How to create procedurally hexagon grid.
You've been here long enough to know the drill, easily Googleable non-question
why would what assign the base class to what?
as in when I then go to use that class why would it be Class<BaseClass> instead of Class<Script>
There's nothing to convert, as all types already derive from System.Object.
Serializing object is tricky because there's generally no way to know what type the object actually is when deserializing
what do you mean by this?
Can you share a concrete example?
A shame 
thx
public class Example<T>
{
public T script;
public Example(T script)
{
this.script = script;
}
}
something along the lines of: new Example<T>(GetComponent<ScriptType>())
Can you show me your example with concrete types? @hoary bane
It's unclear in your example what is a placeholder and what is a generic type parameter etc
for example you would never do new Example<T>(GetComponent<ScriptType>())
You would have to do
new Example<SomeConcreteType>(GetComponent<ScriptType>())
Or rather
new Example(GetComponent<ScriptType>()) and the "T" would be inferred from the parameter type
public void Method<T>(T script)
{
this.AddScript(new Example<T>(script));
}
you may be confusing the T from your method with the T from your class definition
they are independent generic type parameters
again this isn't a concrete example though
i have this grid, but how do i only spawn for example some trees togheter or only water at the right side.
Hello! Does Unity have a callback at the start of the build process, which would let me insert my own custom build step into the pipeline? I’m hoping to bake some data down, per GameObject. But it would only be safe to do so right before I standalone build is made.
I could make this build step a manual process, that’s kicked off from a menu item. But it would be nice (and less error prone) to always run it as part of the build pipeline.
IProcessSceneWithReport or IPreprocessBuildWithReport could be a way.
Thanks! I’ll check those out
Having trouble finding the Scene version. I assume it’s the same, but you get a callback for each scene, during the build process?
Nevermind found it. Man, google did not want to show that result for some reason. :p
hey guys I wonder if anyone can give me an input on what I want to do. I have a glove that has been setup with arduino and when it moves, I want to be able to "grab" using the unity VR xr controller, anyone can give me an insight on how I can do it?
I am already able to send the signal from the arduino to unity but I dont know how to make it so that this signal will trigger the grab
I have 2 questions.
-
How can I change the window title during Runtime? Like "GameName (Not Responding)". I want to do some sort of cool trick if it's possible.
-
How to create software gore? I want the UI and controls to be messed up in all sorts of ways, while also adding glitchy movies and pictures
is there a way to check sum my entire game while it is running
it will be about or below one gb, I want to run a checksum or similar on it to prevent cheating in competitive modes
This wont disable cheating in competitive game...
There is numerous way to cheat that does not include the modification of the source code:
- Packet Modification
- GPU Man in the Middle
- Modification of shared library (DLL)
Also, you would not be able to checksum the memory of your game.
The only way I see that a sort of checksum could be useful is after loading an asset. It would be an easy way to prevent the least competent/motivate hacker to cheat, but it would not prevent them entirely.
hmm, I am not too worried about cheating as i plan to have modded and unmodded mp. I just need to detect if a game is modded or otherwise altered
on it to prevent cheating in competitive modes
yes, i dont want people using mods in the normal servers
This is all about how you "load" mods.
If you load a mod, then refuse the access to the server.
Well i am not sure about how the mods will be loaded
I plan to have it on steam and oculus
steam has workshop but oculus not so much
oculus has a crap policy on modding
I fear that my game wont ever make it on the oculus store if say i put a folder in the game files where you can drag in various mods and the game will load them
If I use C++/CLI stuff like System::String^ to build DLL that I will use in my Unity game, will the game work if I build it for Linux?
If the DLL has been build for Linux. (Which is not a .dll but .o or .a)
okay, but Ive read that C++/CLI is not supported on linux. does that mean that i cant build it ON linux or FOR linux?
If C++/CLI cannot be build on Linux, then no. It won't work.
If you want to prevent cheating in a multiplayer scenario, you need a server-authoritative simulation
there is no other way.
See through wall
I am aiming for peer to peer
maybe ill cross that bridge when i come to it
The host can have authority
if he wants to cheat, nothing will prevent that
If host doesn't have authority, then anyone can cheat at will
like GTA V
it is a ping pong game
so the host was gonna have authority over the ball
and the players 2-4 will have their balls set according to the physics the host has calculated
but i need to know if the host is using mods or cheating
so i wanted to verify the files of the game with a check sum
you're gonna ban players for cheating on a p2p game?
so the host can have a mods tag in the host list
no
ah
If you want vanilla, you can know ahead of time if it is modded or vanilla
so how could i detect if it is modded
the host needs to specify that when he's starting the server
trying to stealthily detect this is pointless
but what if he doesnt
you need to understand the term "never trust the client".
anyone can modify the client
your checksums will do nothing against someone whose going to make cheats/mods for your game
and actively wants to avoid it
you're fighting an impossible problem
the meta headsets automatically detect the beat saber clients that are modded and display a popup
then what do i do
You can't do anything. If people want to cheat, they're going to cheat.
especially in a p2p scenario where players are the server
alright, thx
Payday 2 marks people as cheaters based on the mods they have installed
but again, nothing preventing someone from making it undetectable
save yourself the time and just let each client broadcast which mods they're using.
you can build it into the game so they don't have a choice.
you can attempt to detect modded clients by making your client send a specific key to the server, if that key does not match what is supposed to be sent then you know its modded. This will deter some individuals but if an attacker knows what they're doing and really wants to mod, this will not stop them at all. Itll only really stop people who dont know what they're doing, but might as well stop them too rather than not use anything.
If you've heard of the game, osrs tried to implement this and literally the same day it got implemented, people found what the key was.
I was planning on open sourcing my game
and having a separate lobby list for modded/cheating
The open source version will have a different key
maybe i can change the key every update
this would also prevent out of date clients
Why is it so problematic if the host is running mods?
this is p2p so im not sure how well relay will like keys
Each client should be able to just ignore it
I want to have a rank system
is there any reason you want to open source it as well?
thatll just let people know which areas arent protected against packets
you're underestimating the amount of people that just go around fucking with other people for the sake of being bored
idk
i dont wanna use server infrastructure because of cost
you can very easily run hundreds of your pong instance on a single VPS
for like $20 a month
its possible to open source some things yet keep your key secret. But also updating your key every update wont change anything
maybe i can just go p2p with no rank system, if the game sees some success and revenue i can transfer
vps?
I wouldnt take away the rank system entirely because of hackers possibly existing
could i use the unity gaming services or do they not offer vps
it would probably be more expensive
OVH is so cheap because they hardly manage anything
they just spin up a box and give you SSH
I would be transferring 3 vector3 transforms, 3 euler rotations, and a handful of various other values with each update
You could probably also pay by the hour/hardware used per month
that's pretty inexpensive
uhhh how hard is that to implement
Im still a bit new to mp
completely depends on your linux knowledge
0
how much more expensive would unity gaming services be?
no idea
would vps be the same as multiplay
I know nothing about unity's services
ah ok
a VPS is just a computer sitting inside a datacenter
oh
im not sure im advanced enough to design packet infrastructure
ill probably look into multiplay for now
thanks for your help guys :)
I made an A* algorithm that finds the player in a 2D space and placed it on my enemies. The problem is that my 2D space is side view and I can't completely use this A* because the enemies will fly instead of walking, taking the shortest path. I want them to walk. I think the easier way out would be to change the heuristic function for the path generator to stay closer to the ground. I tried to take every position and go to the lowest tile that is above ground and somewhat works (this is the green path). In the image bellow Player's location is the green circle and the red circle are the enemies. With the A* it will take the red path. If I try the solution above it will take the green path. I want to make it go the yellow path or something that feels more natural than the green path. Any package or asset will not be helpful, I want to make my own. Any ideas?
How are you generating the path?
Using this in A*
{
return Math.Abs(targetX - x) + Math.Abs(targetY - y);
} ```
this is heuristic function
Well yes. Everything else is basic A*
check whether the cell underneath is ground (or whatever the enemy can walk)
I did just that and I got the green path
is yes, then explore it, no then mark it unwalkable
It needs full knowledge of what is a floor/ceiling/wall
Ah. I have to do that when I explore. I did not think of that.
So basically mark everything that is not walkable as wall?
Like, once you know where your floors and walls lie, you can just run the A* algorithm against that
against those lines
someone with more knowledge on pathfinding might have a much better answer than me
i realize checking the cell underneath is not working since the character may jump
Right now, you could definitely try a steering behavior with gravity and such
instead of just forcing the position
that way he's forced to fall down
how about have a heuristic to give you a lower score if you are close to ground
I could see that failing in different levels
maybe some exponential function that can give a significant different between different height
honestly pulling your AI down with gravity and recalculating on an interval would probably solve this
assuming gravity is a thing in your game
yes, i believe gravity is a easier way rather than path finding
I will try to play with it a little
like I said, you'll probably want a steering behavior. So a rigidbody is probably the best for this
then you can give it a brain, raycast infront, check if it needs to jump, etc
you should probably also include some state data like waypoints hit, so that it knows where it's been and doesn't try to reverse
I don't know if this is the right place, but I need an undo operation to work for both destroying an object and also the data structure for keeping track of the position of those objects.
public void RemoveTileAt(Vector2Int pos)
{
GameObject tile = _tileGrid.GetTileAt(pos);
if (tile == null)
{
return;
}
RemoveTilePieceAt(tile);
#if UNITY_EDITOR
Undo.DestroyObjectImmediate(tile);
#else
DestroyImmediate(tile);
#endif
Undo.RecordObject(gameObject, "Undo Tile Grid Remove");
_tileGrid.RemoveTileAt(pos);
}
The intended behaviour is that when I remove a tile, the game object is removed, and the tile grid no longer keeps track of the position of that tile. And when I hit undo, the game object is back to where it was, and the tile grid is keeping track of the position of that tile again
As of now, when I hit undo, the game object is back to where it was, but the tile grid no longer keeps track of the position of that tile again
you need stack
The _tileGrid is a serializable class.
Isn't Unity's Undo the stack?
idk unity have undo system, first time to hear that
Okay, so I found the issue. It turns out I should be passing in this into RecordObject, and not gameObject. Looks like passing in the gameObject is trimming out the information I care about.
Hi guys! A little new here but does anyone have any good places to start on how to design a CutsceneManager for a game? So far I've broken the system of the manager down and have a queue of CutsceneSteps which can extend to stuff like dialogue and switching the camera.
I'm also trying to make a custom editor tool inside of the inspector where u select the type of step that is needed and it would give you a list of variables to fill up (e.g. Camera if needing to switch camera, or TextAsset if its a dialogue step) if anyone has any information on how to start something like this would really appreciate it! 🙏
I'm getting periodic GC.Collect tasks that are taking 120ms periodically, how do I go about debugging memory or finding out what is creating so much garbage?
the profiler shows you all memory allocations, and corresponding GC events, look through your code and eliminate the worst offenders
I'm using dots so hopefully it'll give me enough info to narrow it down x_x and thanks, I don't know why I didn't think to just look at memory allocation in the profiler
You need to modify the neighbor to include tiles that are in the air.
I would look on how Timeline and Sequence are doing it. Then base on that, you can take whatever you like.
https://docs.unity3d.com/Packages/com.unity.sequences@2.1/manual/index.html
https://docs.unity3d.com/Packages/com.unity.timeline@1.2/manual/index.html
Have you looked at Timeline, and if so do you have a list of features it's missing that you need?
Otherwise it's hard to answer without knowing why the existing tools don't work for you.
There are packages, but you can make this by hand.
Right now (I think) you're treating it like a top down map. All you need to do is check which direction you can move from each tile. So you can go down the wall, or maybe diagonally down if you can steer while falling, but you can only go across or up if you're near a floor.
That will give you a collection of tiles (or nodes) and connections.
Then you run normal A* and you should get the yellow path.
If you want to, you can then weight going upwards or jumping to be more expensive than going across the ground, so they'll prefer to walk.
(And can vary that to make enemies that prefer to fly, walk on the ceiling etc.)
That's a tiny amount of data, you should be fine to try anything that looks easy to use. It should fit into the free offerings for most services.
If your game grows, you can always change to something else later.
Better to make it easier on yourself and get a working project, instead of trying to plan too much and never get finished.
"Good enough is good enough."
And if you decide to change later, you'll know why you need to and understand what you're doing. So it's not wasted work.
Totally. It would also let you test more easily.
It's not all or nothing, you can have the host act like server + client. So p2p is basically the same code as a hosted server.
As people said, you can't verify if the host is cheating.
But for a physics game like ping pong, you can have the clients also calculate the ball.
When the host sends updates, the clients check if they agree.
The host and clients won't perfectly agree, because of slight delays, but it should be close.
When the host sends a reasonable update, the clients can match to it so they stay similar enough.
If they disagree, the client should disconnect. Pretend it's a time out or something.
You won't know if it was the host or client cheating, but it stops the cheaters playing with others who don't have the same mods.
(And there's always more ways to cheat, always.)
(Cheating or stopping cheaters is always a question of "is it worth the effort?")
You'd set up... uh, I think it calls them peripherals, for the glove. Then trigger the grab interaction.
There's a lot of different ways people structure their VR projects, so I'd need to see details to help more.
But there should be tutorials showing this.
Noooo!
You want to look into "voxels"
Basically, you would group all the similar bricks together into a shape, and treat it as one "object" (but can still make it look like connected bricks) - so the road could be one big rectangle instead of ten thousand bricks.
Then you can update at runtime to build or change them.
I do. And I hire junior developers.
The industry is super hard to get into, especially that first job. There's so many people who want in. I'll spend probably a year before most juniors will be contributing more to my project than they're costing me in teaching/reviewing/planning. And then maybe another year before I can give them a complex task without monitoring it.
I'm hiring a junior to teach, not because of how good they already are.
So the best thing you can show is that you can learn and adapt to how other people want to work.
You need a portfolio, showing nice clear examples of the work you think you're best at.
And showing your overall skills.
Often I'll see an example and ask "oh, have you done much with maps and procedural generation?" or whatever, so you want to show the range of what you've done.
If you can, show team projects, even if it's just a side project you make with other people here. Clearly state what part you worked on - showing you worked in a team is a good thing, I want to see you saying when others did the work. It shows I can believe you about the things you say you did.
But focus on one nice, easy to show visually, example that you'll try to get in front of people.
And don't quit your job!
Write code to do those calculations you don't like doing. Put that onto your resume!
I already had 20 years experience and was team lead of enterprise systems development.
It took me years to get a good job. "No industry experience"
You will be competing with people who've gone to university AND already have a portfolio of group work from their courses.
So start making games.
Build a portfolio and start applying.
But keep your job because even if you're really good it could easily take 5+ years to get that first real break.
I was planning on doing that, I just wasn't sure the best way to handle separate brick data. I want to be able to have separate events, properties, and interactions, as well as rendering. I wasn't sure that each chunk should really be a GameObject, I thought that perhaps chunks could benefit from being Entities somehow. By the way, if you're looking for a developer, I could use a job. I've been programming professionally for around 6 years now, and have experience with various teams and projects, even commercial Steam products for both Unity and Unreal.
I'm not sure if each chunk should be a game object, it depends on your programming knowledge.
I mean, the answer is you shouldn't use game objects.
But it's better to use them and get it working, learn about your project and what your needs are, etc. rather than over complicating things and getting stuck.
But I'd try to find a good voxel engine, because it should have already solved this for you.
Unfortunately not unless you're in Sydney, Australia.
I don't have any remote roles available at the moment :/
Worked 40 hrs straight, currently in zombie mode. I could really do with a good mid or senior unity workhorse who can hit the ground running, if anyone happens to have a recommendation.
(The company culture is good. My team are leaving on time or working maybe an extra hour or two.)
Ah, shoot. Had to try.
Anyways, yeah I don't think I want to use GameObjects for sure. I was thinking that chunks could be entities, I though they could be useful. I wondered if ECS would help process chunks faster, and allow them to be in and render in-scene with less overhead. I was also planning on using the Job System + Burst for mesh generation. The last time I wrote a "brick engine" like this, I multithreaded it with normal System.Threading methods, but I think it might be more efficient to just use Jobs + Burst this time.
You miss every shot you don't take! It would be silly not to ask!
I've been thinking that more and more lately ^
If nothing else, I might just reduce myself to hyper-casual apps for a while.
Sounds sensible.
I haven't actually used Unity's ECS, but any large scale voxel system would probably want to run on a "data oriented tech stack" or whatever the non-unity name for that is.
But I've never done it myself, and don't know if it's "nice to have" or absolutely necessary.
I've experimented with ECS, but I never had a solid reason to get deeper into it until now. My basic implementation was the Lorenz attractor displayed with entities. It performed decently.
I would like to show people that Unity is capable of greatness and abundance. Many onlookers have the idea that Unity is bad, and slow, and for beginners, and that saddens me because I know better.
Gotta find a way to earn and maintain "industry experience", yeah.
If hyper casual games work for that, it might be the way. Do the deep dive projects as a side hobby.
But work on the stuff you want to do, at least enough to show in a portfolio, so you can keep applying for those roles.
Yeah, I need to update my portfolio site soon, it's becoming a tad dated
I cheat. I leave my portfolio clearly unfinished, so that I can bullet point list topics and skills "that I still need to add"
Let's me at least mention them, even if I don't have a demonstration. They can always ask about it at an interview.
And they're not hiring me for professional website design.
Games dev is so broad, we could spend years on a portfolio and not cover the right topics. And they're not going to dig through looking for your work.
You really just want a good first impression, and maybe highlight a few key skills.
https://youtu.be/Yl4a-1FtXqQ I once came up with this cool voxel meshing method that pre-cached the voxel edge case meshes ahead of time so it didn't have to calculate what it needed to be based on its neighbors, and it was faster than any other voxel method i'd implemented before. Unfortunately, and to this day I'm still sad about this, I lost it all in a drive issue before I managed to back it up..
Representing layered 3D noise with meshed voxels using the Job System + Burst Compilation.
The voxels are pre-computed on program start up and sent into a cache where vertices can be copied from an index assigned from their neighbor combination state rather than recomputed.
FPS: Frames Per Second
CPS: Chunks Per Second
CPU: I7-4790T @ 3.6 GHZ
Yeah, I like the video a lot lol
https://youtu.be/DsNMvN0MICI This was my next best voxel implementation, but it could've been far more optimized. I was too excited not to present it.
I'm working on a little 3D falling sand game, it's rendered with a raymarching compute shader! Thoughts? Raytracing needs optimized still, but it's coming along great, I think!
Interested in my projects? Join my Discord server! https://discord.gg/7TSkHTnrsr
Music from https://freemusicarchive.org/music/zight/single/number-one-edm-instrumental/
Nice!
Have you seen Petr Minarik's work on water for Space Engineers? I think you'd be interested.
I haven't, but you're right, I would be
How would I go about assigning different materials/shaders and physics materials to different voxel faces in a procedural mesh?
You wouldn’t. That’s terrible for performance. Best to have a unified material and custom handler for the material (same for physics)
Oof
you could for example encode your physics material into vertex colors or a splatmap together with the shader data
And your shader can paint it differently depending on the angle. So you could have grass on the top and rocks on the side and bottom, letting you make terrain from the one voxel block.
But I think you'd normally use a different voxel for something substantially different. Like grass vs sand.
For something like lego you could probably use raymarching so the voxels can just be cubes, but you still render the knobbly bits or hollow insides.
Can allocate and deallocate a native array with Allocator.Temp in a loop exhaust all memory or is it reused inside the same frame?
If you deallocate it should be available immediately (I believe...)
Also, if the array uses value types and is a local variable in a method, it can stay on the stack and is automagically freed when the method exits.
building games with c++ using sdl good idea?
i cant find any docu talk about how deallocate work
and i believe the function provided in Unity.Collections.LowLevel.UnsafeUtility is warpper of function in stdlib.h with the same name
it's not a bad idea, it's just a big undertaking
interesting, maybe if the ball misaligns a certain number of times instead of once in order to give some leniency on people with poor connections
sweet! thanks :)
thanks man, this makes it a lot less stressful
actively hiring? I have a few industry-related questions relating to the current market demand of certain positions. Can I DM you?
I'm trying to make smart fleeing. The problem right now is finding a point that takes longest path to get to from the threat and shortest from the agent. I'm following the first reply here https://gamedev.stackexchange.com/questions/43947/pathfinding-for-fleeing. Calculating heuristic cost using pathfinding however freezes the game.
We recently did a hiring push, so I don't think we're acting hiring at the moment. But if someone amazing comes along we'd certainly take a look.
I can try and answer questions. But things can be so different from one company to the next, I'm not sure how useful the answers are.
Everyone is welcome to DM, I love talking game dev.
Is it freezing, or just going so slowly it seems to have frozen?
There's a few different ways to approach this, mostly depending on how important fleeing is to your game.
A* is pretty fast and shouldn't be lagging you. But if you're calculating the path from the enemy to every square that you check then you'll be calculating WAY more paths.
You can use node weights to cache a value of how safe it is, and pre calculate dead ends.
You obviously can't pre calculate enemy positions, but you can calculate it, store it in the node weights, and update occasionally.
Once that's set up you can use normal a* pathfinding, or better yet, a least cost walk, to pick your path.
DM'd you. You might have to accept it.
Hello everyone, I'm doing a project in unity 3D in which checking if the player is touching the ground or not is very important, besides being able to go up and down ramps is essential. I would need the help of a non-profit who has done a complex groundcheck system to help me with it. Thank you
that sounds like a complete beginner topic unless you have any extra details to add
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=c3iEl5AwUF8
Let's look at 3 different methods for doing a Ground Check which is a necessity if you're making a Platformer.
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials https://www.yout...
I made a mistake there and fixed it, now it gives good results on low depth. Yes I am calculating a path from each square, so this doesnt seem like a good solution. I want it to be important but idk if i can make it. Do you mean calculating node weighs before the game starts or dynamically, either way how would i do it? Now i want to move to second reply in that threat and add minmaxing, but right now idk how.
You can calculate the dead end costs once. If your levels are always the same you could save it into your project.
You would have to calculate the cost of being near enemies during gameplay.
There's different ways you can do it, but as one example imagine if you store the cost of enemies in the node, and every time you calculate you set the cost for the cell the enemies are in to 10
Then any cells connected to those gets set to 9. Any connected to those gets set to 8, and so on.
You can even show it visually by colouring the nodes. Helps you see where the AI will want to move.
And you don't have to calculate it every frame.
It will get out of date as enemies move, but will be accurate enough that it will still give similar results as long as you recalculate before the enemies move too far.
i experimented with that a little. setting cost around the enemy is kinda redundant cause the algorithm already takes care of that. But setting cost of nodes where enemy is going based on velocity works nicely
I want to create ItemProperties component with unity ECS 1.0.8, but it can't store string properties. Which alternative I can use for this?
Use FixedString64
Or whatever fits your size
Let me try, thanks in advance
Is this a good place to ask DOTS questions? It looks like the #archived-dots channel has been archived. Can’t find a replacement for it.
I’m wondering if Unity has said anything about adding support for chunk DynamicBuffers in the future. Chunk components are great, but there’s a lot you can’t do with them.
there’s #1062393052863414313 where you can make a thread. but here is also a decent place too
I saw them mention that, but I couldn’t figure out how to find or access the forum. Where do you go to see those?
uh in #1062393052863414313
it’s 4 channels below this one lol you might have the tab collapsed
You have to enable it in the Browse Channels menu, at the top of the channel list.
I’m in the iOS app. Might be different. Thank you both for the help - going to dig for those settings…
Do you guys have a “forums” tab in your channel list?
No
You can also just click on it 👉 #1062393052863414313
does anyone have any ideas on how to make the CutsceneStep variables appear in the CutsceneTrigger class instead of just an instance?
Hey-o, so I am doing some mesh generation with jobs, I am generating it and need to do some 'post processing' on it (like bending it). I was wondering if it would be faster to do the generation and modification in the same job, so only loop over the vertices once, or would it be faster to have two jobs, one to generate, and after that is finished, a second job that modifies the mesh? This would be 2 loops over the vertices, but each would be doing less, but also one would have to wait for the other to finish first.
Hey o so I am doing some mesh generation
does the unity parallel jobs system work in editor scripts?
Hi everyone. I have the following code:
Collider2D collider;
[SerializeField] private LayerMask layer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
collider = Physics2D.OverlapCircle(transform.position, 0.5f, layer);
if(collider != null)
{
Destroy(gameObject);
}
}
There's an object that moves to the object that should be destroyed, which is in the layer of the "layer" parameter of overlapCircle. When the object reaches the position of the object that should be destroyed, the object does not destroy, why is this happening and how do I fix it?
may be a beginner/general question but I post it here for lack of solutions in code-beginner and general
The code is ok (algthough, its not recomended to call a variable just "collider", idk how it didn't warn you about it)
Now, are you 100% they are touching?
yes, they are touching with a lerp function
I dont remember if this is necesary but, maybe, one of the two objects has to have a rigidbody
So, give it a try
both have a rigidbody
And you are sure the layers in the layermask match that of the object, right?
yes
i tried adding the destroy script in object 1, with the layer of object 2 as parameter, and the only one that gets destroyed is object 2. In object 2 the layer parameter value is the layer of the object 1
Is the object containing this script a child of another object?
im i missing any configuration on the components?
both objects are childs of another object
And does this same object have a rigidbody?
i mean each one has its own different parent
no
Then, its the other one that has the rigidbody and the collider?
no, any of the parents have a rigidbody
Thats not ideal
You say they are touching through a lerp?
Are you moving them through code instead of physics?
im using vector3.lerp in object 1 to approach object 2
Did you freeze the position and rotation of every objects rigidbody?
yes
How can I boost my mesh generation algorithm using burst?
i also tried moving them manually with the mouse and the same happens
Look, the code is ok, it has to be something outside of the code
Do you want to share your screen on a vc?
sorry i don't know what a vc is
Voice chat, but, never mind, there are no voice chats rooms in this server xD
you want a screenshot?
Emm sure, unfold the whole hierarchy and select the object with the script
Get the inspector too
ok im doing it
And do another one with the target object selected
Wait, none of them get destroyed? or only one of them does?
try to set 1 of them to "is trigger" in collider
In fact, I wouldn't use physics for a chess game unless you really want it xD
You could use this to get the distance between the two objects and destroy them once they are close enough
only one of them does, the black pawn
And yo uwant both of them to get destroyed?
The problem is that, the first one that touches the other is the one thats going to get destroyed
And once it is destroyed, they cant destroy the other
does that depends on which object is the one that moves to the other?
I have no idea
I don't know if it even matters, they are both touching at the same time
I guess it has to do with the priority in execution of their scripts, which, idk how to check
In any case, if you want to keep the physics, add a bool that tells the script if that piece can destoy objects or not
didn't you say one of them touches the other first?
And add it to the if statement for if the collider != nul
I meant the one UNITY considers the first xD
They are technically both touching eachother at the same time
But unity's mind goes one thing at a time
ok i'll do that, I just wanted to make clear why is this happening
thanks for you help
You are welcome
. Hello does someone know how can be fixed "Memory leak" in this code, thx
Script creates texture from current obj's material and sends it to other obj's material ,
Can i somehow clean RAM garbage after 10-20 method calls? because when i change scene i suppose it clears ram somehow.
Every call takes up to 10mb ram, and speed of how fast method called doesn't matter, at about 100 call App runs out of ram and crash.
public GameObject Car_itself;
public void Create_Texture() // Creates Texture from one Material then Send it to Other Material
{
Material This_Object_mat = this.GetComponent<MeshRenderer>().sharedMaterial;
This_Object_mat.SetColor("_Color", Random.ColorHSV(0, 1, 0, 0.6f, 0.5f, 1, 1, 1)); // This Object's Material
RenderTexture buffer = new RenderTexture(
1024,
1024,
0,
RenderTextureFormat.ARGBFloat,
RenderTextureReadWrite.sRGB
);
Texture2D texture = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false);
Material material = GetComponent<MeshRenderer>().sharedMaterial;
Graphics.Blit(null, buffer, material);
RenderTexture.active = buffer;
Graphics.CopyTexture(buffer, texture);
Material Target_Material = Car_itself.GetComponent<MeshRenderer>().sharedMaterial; // Target Object's Material
Target_Material.SetTexture("_MainTex", texture);
}
It's clearing memory in the scene reload because loading a scene automatically called Resources.UnloadUnusedAssets()
You can call that manually, but you can expect there to be a stutter when you do because it's not cheap.
It would be better to manually destroy the textures you're using
Or better yet, reuse them. Unity has a built-in RenderTexture pool through RenderTexture.GetTemporary and RenderTexture.ReleaseTemporary
Also, I don't see why you need to create the Texture2D and copy to it. You can assign a RenderTexture as a material texture just fine.
i already tried to assign a RenderTexture but it dont work correct and every thing messed up. i'll Show in second
how can i destroy texture, like that? it doesn't help unfortunately
if (buffer != null)
{
buffer.Release();
Destroy(buffer);
}
You would have to destroy both the RenderTexture and Texture2D
And of course you would have to create the old textures, not the new ones you just created in the method
No reason not to use RenderTexture.GetTemporary here instead of creating one
And no reason not to just create the Texture2D once, assign it to the material once, and then copy to it whenever you need to update it.
every prefab has own component that creates Texture, when Button pressed method calls, so i suppose i can't use RenderTexture.GetTemporary
i'll try you methods now
this with
Target_Material.SetTexture("_MainTex", RenderTexture);
instead
Target_Material.SetTexture("_MainTex", texture);
aye
hello i can't understand , will this 2 codes have same impact on ram Memory
Texture2D Huge_Texture;
void create_SomeNumber()
{
Huge_Texture = new Texture2D(2048, 2048, TextureFormat.RGBAFloat, false);
}
private void OnDisable()
{
Resources.UnloadAsset(Huge_Texture);
}
and
void create_SomeNumber()
{
Texture2D Huge_Texture = new Texture2D(2048, 2048, TextureFormat.RGBAFloat, false);
}
is it not destroy /clean itself after method ended?
You probably need to release the reference to the texture to actually clear it.
Also, Resources.Unload is probably pair with Resources.Load. I do not think it actually does anything in your case.
hello, i have a question. I did an elastic bed o Unity with this code, but the raycast always send me "No he dado a nada". The raycast dont hit the colliders
ok i got it
/
and will this "Huge_Texture" be unloaded /released from memory after methods is finished?
void create_SomeNumber()
{
Texture2D Huge_Texture = new Texture2D(2048, 2048, TextureFormat.RGBAFloat, false);
}
No. It's a Unity Object, which are not unloaded unless destroyed or Resources.UnloadUnusedAssets is called and it's not referenced anymore.
Resources.UnloadAsset only works with assets saved on disk, not objects created at runtime.
i see, is this release memmory
Texture2D Huge_Texture;
void create_Huge_Texture()
{
Huge_Texture = new Texture2D(2048, 2048, TextureFormat.RGBAFloat, false);
}
private void OnDisable()
{
Destroy(Huge_Texture);
}
yes 1 time,
thx ,i'll try now all advices you told
StandingObjectPos = StandingObject.transform.position;
Vector3 LastStandingObjectRot = StandingObjectRot;
StandingObjectRot = StandingObject.transform.eulerAngles;
Distance = Quaternion.Angle(Quaternion.Euler(StandingObjectRot), Quaternion.Euler(LastStandingObjectRot));
Vector3 RotChange = StandingObjectRot - LastStandingObjectRot;
Vector3 PosChange = StandingObjectPos - LastStandingObjectPos;
transform.position += PosChange;
transform.RotateAround(StandingObject.transform.position, RotChange, Distance);```
I have a basic script here that checks the object the player is standing on's movement and rotation change since the last frame and changes the players position and relative rotation to match, similar to if the player was parented to it. It works fine for the positioning and mostly fine for the rotation, but there's 2 main issues. One is when any of the axi goes over 360 or below 0 the player snaps to an unexpected nearby position. Also, it matches normally when rotating the object around one axis, but moves oddly when multiple are changed. I'm guessing it's due to the distance being calculated wrong or the the rotations being compared wrong since they're Vector3s. Anyone know how I'd go about fixing this?
and because i've send and assigned texture to other material, is it possible to release that sanded to material texture too. or i can just
private void OnDisable()
{
Destroy(TARGET_Oject.GetComponent<MeshRenderer>().sharedMaterial);
}
The material only has a reference to it, no copy is made. Destroying the material does not destroy the texture it references.
But it removes the reference, so next time Resources.UnloadUnusedAssets is called, the texture will be destroyed.
if this whole script and i do like this at "OnDisable()" will it be almost fully released from ram? thx again for help , been struggling for week, searching info
public GameObject Car_itself;
RenderTexture buffer;
Texture2D texture;
public void Create_Texture() // Creates Texture from one Material then Send it to Other Material
{
Material This_Object_mat = this.GetComponent<MeshRenderer>().sharedMaterial;
This_Object_mat.SetColor("_Color", Random.ColorHSV(0, 1, 0, 0.6f, 0.5f, 1, 1, 1)); // This Object's Material
buffer = new RenderTexture(
1024,
1024,
0,
RenderTextureFormat.ARGBFloat,
RenderTextureReadWrite.sRGB
);
texture = new Texture2D(1024, 1024, TextureFormat.RGBAFloat, false);
Material material = GetComponent<MeshRenderer>().sharedMaterial;
Graphics.Blit(null, buffer, material);
RenderTexture.active = buffer;
Graphics.CopyTexture(buffer, texture);
Material Target_Material = Car_itself.GetComponent<MeshRenderer>().sharedMaterial; // Target Object's Material
Target_Material.SetTexture("_MainTex", texture);
}
private void OnDisable()
{
buffer.Release();
Destroy(buffer);
Destroy(texture);
}
and as second but expensive solution is Resources.UnloadUnusedAssets
and unfortunately a RenderTexture as a material texture doesn't work for some reason.it would be way faster and performant than Graphics.CopyTexture
From the video you sent, it seemed like you were copying the texture a lot more than just once. Is that not the case anymore?
yes but method called from different prefab's component ,as soon as gameObject enabled method call and assign new texture to childs obj material
if i have 10 prefabs, and setActive 1 by 1 , in total i will create 10 textures
so i need to clear previous one
If you're only calling Create_Texture() once for each script instance, then this should work. It's not necessary to call RenderTexture.Release() before destroying it.
And I'm assuming the scripts are being disabled or destroyed at some point, not just accumulating until scene reload.
From the look of this code, you should be able to destroy the RenderTexture immediately after CopyTexture and not keep a reference to it.
But then, there's no reason why you shouldn't use RenderTexture.GetTemporary and RenderTexture.ReleaseTemporary instead.
It'll be faster because it means every script instance reuses the same instance, since they all use the same texture settings.
i've read about RenderTexture.GetTemporary and there was said that it life only for 2-3 second is it right
For a couple of frames, yeah. But you're only using for less than a millisecond, to call Blit on it and then copy the data off it into a Texture2D.
After the copy, there's no connection between the RenderTexture and the Texture2D, so since you're not using the RenderTexture anywhere else, it can be disposed.
Can't see/understand where to put RenderTexture.GetTemporary 🫥
i'll search some info about it
you would use it in multipass post process effects for example, say you were doing bloom you would get a temporary render texture to blit it for the threshold pass, and then get a temp render texture for the blur passes
