#archived-code-advanced
1 messages · Page 169 of 1
in any case, i'm not going to refactor this now but this is all really great feedback, thanks all.. geniuses, the lot of ya.
As long as it was informative and helpful, I'm happy
More knowledge = better programmers = better games
(I should add implementation 'worth it' considerations aside, the discussion was excellent)
on the linq perf stuff
It's one part of working in a team that I miss - I'm capable of doing all this crap myself but sometimes I don't even look at a solution that I've done and question it, and having someone else be like "yo why didn't you use SortedList" is like 🤯
lmao yeah
lol
i think it's close
i think it's probably making new textures every frame
And actually I didn't know about the LINQ performance issues.. I was starting to move towards more LINQ use because the syntax is finally growing on me
because honestly looping through a big grid a bunch of times... doesn't matter
making new textures every frame would be quite expensive yeah
since you're also paying the cost of a gpu<->cpu transition
to create the texture resource etc
That's all true, but the cpu is getting burned up real good with a naieve implementation
going back to this 👆 - I think the bottom 2 lines "look" better than the top 8
it does matter
(unless that is the gpu texture translation that is incurring the cost)
Is that code trying to look for a completed mission matching an ID, and then remove it if it exists?
yeah
it is only an issue (in your project) if you can show concrete proof that it is. So i would take this overzealous "unity .net is bad" advice in here with a metric ton of salt
I mean, that's fair, but it's helpful to have these things rattling around in my head so once i DO begin performance profiling I can keep an eye out for it.. I'm certainly not going to waste any time profiling now
or going really deep in it - I still try to write the client in as performant a way as possible (ie - minimal Update() stuff)
linq is great
Only thing I would say about that is I wouldn't profile once it's 'too late' i.e. the entire project is coupled together and slow etc. Easier to fix the problems when they are right in front of you.
i develop a lot of games and
but again you know your current project context / scope better than I do
Note - no profiling subtask. Look at all those glorious "dones" 🙂 🙂 🙂
truthfully, i've never had the kind of problem where getting rid of linq helped
if it was bad, it is just either impossible in all cases or a unity limitation
I suspect this is engineering purist stuff to some degree vs practical reality in a good chunk of situations
the last time i've had a performance issue, it was vfx graph giant quads with alpha
Yeah, and also, again these data structures I'm working with (for this feature) are tiny - 4 items
but it doesn't make either opinion wrong, it's all context dependent
also you will never get to "as fast as possible" as that would be way too much work, and using standard OOP is already the primary issue (once you get to actual optimization).
where it just needed to paint like 10,000 quads over each other
There's no way I would even consider changing it if the structure will remain that small
It depends on the problem -- you may have just run into scenarios where the scale wasn't large enough for the impact to actually matter
again unless it's an academic exercise
Which is completely valid
performance doesn't matter until it does
There are an innumerable number of situations like that
what's the problem with OOP?
I'm also a little biased, a lot of the code I write is written with the intention of being shared across all games where I work. It's a lot of "library"-like code, so I try to optimize for all potential uses
it is very wasteful when it comes to its utilization of the CPU cache & pipeline, most CPU cycles are wasted on waiting for data. At least the way it encourages you to model your problem makes it very easy to be wasteful.
well I think there is a difference between writing it that way at the start and refactoring
If you're at the outset and it's 3 points of work vs 5 points hey have at it
but if you have to rewrite stuff for something that doesn't matter, idk
I have my own generic game object pool that uses an approach I haven't seen elsewhere
It makes use of Transform.hierarchyCapacity and retrieves objects from the end of the list to maximize performance
Since internally each root transform has its own buffer of transforms, it's like a List<T>
So setting that to the number of children you expect it to have will improve things since it won't have to resize constantly
(removing from the end of a list doesn't require any reordering or resizing, it's basically just changing the count value)
yeah anything to do with pooling and instantiations / destructors is probably worth making performant 10/10x
It's open source for anyone interested https://github.com/NewBloodInteractive/com.newblood.core/blob/master/Runtime/GameObjectPool.cs
Sorry, so explain this - whenever you (instead of) Instantiate you grab a gameobject from the container, and same for Destroy?
The idea is that you never actually call Destroy, you instead call pool.Return(obj)
But yes
Imagine a gun shooting bullets
aand Rent() instead
Yeah
cool
Yeah, of course.. I haven't really gotten into object pooling yet (my games are UI games and so far I haven't needed to mass-instantiate anything)
but I'm familiar with the concept.. cool implementation
Do you ... make a container for each type of object you're working with? or is it a pool that holds any generic kind of gameobject
indeed
The intention is that you'd have one pool per type of object
I have heard Jason Weimann talk about that concept
but not saying that negates the novelty of your library/ solution etc
Ah I see - the pool has the prefab as a member
was just talking about pooling as a more general concept
You can use it for multiple types of objects, there's no restriction on it or anything, but it's not what it was specifically designed for
The pool can also be scoped
neat
using (var pool = new GameObjectPool(prefab))
{
// use pool
}
// pool has now been destroyed
So .. open question for y'all.. (thinking about this after seeing this lib).. I implemented my own "BigDecimal" (maybe it's better termed an IdleDecimal - really designed for low-precision but arbitrarily large numbers in idle games). Is that the kind of thing that I ought to clean up and publish as an open source thing?
It meets my requirements now but I've realized that it's .. starting to get pretty full featured
How does it compare to the built-in BigInteger?
It's... different
sure go for it
Probably not as good, but it contains some idle-game-specific stuff like some custom string formats
there are a lot of people who have issues with this in the idle games community
this is "arbitrarily large" - ie, it can support any number up to .. uh... well, i can't math this, but it's large
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335.
decimal mantissa, integer exponent
so...
79,228,162,514,264,337,593,543,950,335 x 10 ^ 2,147,483,647
it also does the whole naming thing if you wanted to go that route:
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I think I can currently handle "correct" naming for anything up to 1e999
I'm trying to get the file from private github repo using token. Tried with UnityWebRequest and HttpWebRequest, both return null or 404 Not Found (or Forbidden), any recomendations?
Here is the code i used:
link = new UnityWebRequest();
link.downloadHandler = new DownloadHandlerAudioClip("https://api.github.com/repos/<user>/<repo>/contents/<file>.ogg",AudioType.OGGVORBIS);
link.SetRequestHeader("Authorization","token <my_token>");
link.SetRequestHeader("User-Agent","<user>");
link.SetRequestHeader("Accept","application/vnd.github.v3.raw");
link.SendWebRequest();
try the same in postman and see what github says
How do I use the parent constraint component to make the character not be able to rotate on the x and y axis?
ParentConstraint won't make them unable to rotate, it will instead cause them to rotate with their parent as if they were a child object
oh
If you want to prevent them from rotating at all, then you want RotationConstraint
Okay, thanks, will try tmr and say it works or not
^
ah
i guess haha
Is there a way to tell the job system to begin working on a particular task immediately without awaiting its completion with .Complete? I schedule a certain job, but it seems like it wants to wait until the end of the frame to actually start running it. It's one of the only jobs actually running, so the rest of the time is just idle, would really like to have it begin running ASAP in the frame
Nope, Schedule adds it to a queue so either the job threads are already busy or Unity doesn't end up looking at the queue until the end of the frame here
There's no way to start the job immediately because of how jobs fundamentally work
They're a bunch of background threads that all constantly try to grab functions from a queue to execute
The .NET thread pool is similar, if you want an idea of what that looks like check this out: https://source.dot.net/#System.Private.CoreLib/PortableThreadPool.WorkerThread.cs
The threads are all running that function constantly until it manages to "steal" work from the queue, and it will then execute that work and then resume attempting to "steal" from the queue
I don't necessarily need to start it immediately, but I'd like to at least hint to the system that there's something that needs to be done so it doesn't idle for the 10ms it takes to complete the frame
as it's literally all idle time until it starts
That's the thing, it's not necessarily idling -- those threads are probably busy with other work queued up elsewhere
I'm not aware of any kind of priority system for jobs
Job threads are shared with the rest of the engine (afaik) so all kinds of other work could have been queued up before yours
looks idle to me
Then chances are something is telling them to wait before attempting to dequeue
Either way I don't think there's a way to hint at them to continue
k thanks
"manually kick off the batched jobs" so how do
So the queue is only inspected after update
JobHandle.ScheduleBatchedJobs() looks like
So there is an API to force it
By default jobs are only put on a local queue when using Job Schedule functions, this actually makes them available to the worker threads to execute them.
So I guess it's important to note that this will affect all currently queued jobs
Not just yours
Probably won't matter, but worth knowing
all good, this is exactly what I needed I believne
I didn't know about this API either, so it's handy to know
So... thanks for asking about it lmao
If ya wanna ask about job threading and burst, pop into DOTS channel itself.
I can answer most questions but I never check outside that channel
didn't know the Job system was considered DOTS
since it wasn't a Burst-spcefic question
It is. DOTS is a coding system built directly onto of Jobs and Burst. There is no use to Burst outside Jobs and there is no DOTS without the Job system.
Yeah it's part of DOTS but isn't necessarily DOTS-specific
I guess you could say it's a foundational feature
It exists because DOTS needed it, but it has uses beyond that
Yea. I do non-critical image processing with a job chain although I really should convert it to a compute shader
i think you should carefully read the docs
it's telling you what the issue is. if it's 404, the path is invalid. if it's 403, you used the wrong token
How do I add an event to a button?
With public void SetText(string Text) gives error Argument 1: cannot convert from 'void' to 'UnityEngine.Events.UnityAction'
You want to add an assignable event in the inspector?
Or you want to subscribe an event exposed by a button?
The code you're showing wouldn't cause that error, it must be coming from elsewhere. The error will tell you the line.
Hahah. Job system and documentation. Been a joke for years and still is.
You want to add a listener, here's an example: https://answers.unity.com/questions/938496/buttononclickaddlistener.html
If I'm understanding the question
I managed to fix it this, thanks
Hey, so I got a reflection question.
There is an internal method that takes an internal delegate. I want to create a method with the same signature that calls it, but can't figure out how to parse my delegate in to the internal one.
// Internal...
internal delegate void ExecuteHandler(string arg1, int arg2);
internal static void CreateButton(float arg1, ExecuteHandler arg2) { .. }
// My Public...
public delegate void ExecuteHandler(string arg1, int arg2);
public static void CreateButton(float arg1, ExecuteHandler arg2)
{
var createButtonInfo = type.GetMethod(...);
var internalArg2 = // Something to convert from the public one to the internal one....
createButtonInfo.Invoke(null, new object[] {arg1, internalArg2 });
}
you ok with wrapping it into lambda?
delegate void A(float a, float b);
delegate void B(float a, float b);
static void Main(string[] args)
{
B b = Get;
Accept(new A(b));
}
static void Get(float a, float b) { }
static void Accept(A del) { }
id look into avoiding reflection, but if necessary you can always use activator and pass existing delegate as a ctor arg
does anyone have any experience with the new ScriptableRenderPass api that uses RTHandle instead of RenderTargetHandle?
Just looking for a quick sanity check before I expand my scriptable object usage. I have some unit tests for movement rules in my grid based game. I've changed how the regualr movement processor works so it now makes more sense to test it through the processor rather than manually testing each rule seperate of it. Since non of this needs a scene to function, I figured it would make sense to change the processor from a monobehaviour to a scriptable object. The processor also references a grid factory, which is also a monobehaviour but only references prefabs and SO's.
Would it be a good idea to make both the processor and factory SO's? I normally only use SO's for strategies, and really hate getting into the clash with them and monobehaviours when an SO needs to reference a monobehaviour.
SOs are just serialized and automatically created instances independent of any scene. There is nothing that makes them good or bad on principle. If their semantics make sense to you for your use-case use them without reservations.
There isn't, and like any other method they have ups and down sides. One of SO's being their struggles at referencing scene objects, which comes up a lot when you build stuff around monobehaviours. This forces it to become more of an all in approach unless you can docouple it all really well. That's why I'm trying to see if this seems like a good limited use case so I'm not plunged head first into a SO based architecture.
Hence, if the semantics make sense to you. If you need to reference instantiated MonoBehaviours they probably aren’t that useful in that situation.
Which makes sense only should nothing else be put to the same scrutanty of also changing to a scriptable object, which then brings things to the more abstract question of what should and shouldn't be a monobehaviour?
Then again you can just have a proxy in a scene to pass the references to a SO
How would that work?
MonoBehaviour with a reference to the SO. Which on awake calls init on the SO and passes it’s context as argument
You could call that a strategy by injection
Or reverse proxy
Or YourNameHere
Ah. That makes more sense than my current solution for another instance of this happening where the thing managing it just hands it's entire game object to any rule with a Constructor method and lets it figure out what, if anything, it needs from there. Should keep that in mind for disambiguating calls like that in general, thinking about it.
Wait! This is the bridge pattern, isn't it?!
It’s just a simple piece of glue code to make SO connect to Scene
Fairly unity specific
Well yes but I just realised the bridge pattern for my constructor situation. A part of the reason I have so much pain referencing the scene is I tend to use SO's for stragies, meaning they'll all have the same interface but likely want different specific things to use. Instead of trying to directly hand them something to please them all a 'bridge' can be made to talk to the specifics of any one script and the scripts outside it.
Well this has been helpful for how I think about this. Thanks.
Suddenly it doesn't seem as railroading to use.
I am doing stuff with internal Unity editor code, so reflection is required. I tried using an activator but it threw a exception that there wasn't a constructor that took a delegate as a argument.
Which type are you trying to construct?
A internal delegate
If you have a function matching its signature, get the MethodInfo for it and use CreateDelegate with the Type
I guess more accurately I want to convert a delegate that matches the signature of an internal delegate, to that delegate
(it is a parameter of an internal method that I wish to invoke)
yourDelegate.MethodInfo.CreateDelegate(typeOfExecuteHandler)
(this will only work for delegates around static methods, note)
It is giving a method arguments are incompatible exception
I will say thia again SO's are there to hold DATA that is all. They dont need to reference scene object or anything. They HOLD data that is it. Anything more is outside the intendet use of a SO
static readonly Type s_ExecuteHandler = Type.GetType("UnityEditor.WindowAction+ExecuteHandler, UnityEditor");
static Delegate WrapExecuteHandler(ExecuteHandler handler)
{
ExecuteHandler invoke = handler.Invoke;
return Delegate.CreateDelegate(s_ExecuteHandler, handler, invoke.Method);
}
try that
And if that works, here's something a bit more generic:
static Delegate Wrap(Delegate d, Type target)
{
return Delegate.CreateDelegate(target, d, d.GetType().GetMethod("Invoke"));
}
Yeah that works, I bet some of the others would work too... I forgot that my mirror delegate was taking my mirror WindowAction class instead of the UnityEditor one... oops
The others might work but the last one I posted using Delegate.CreateDelegate is the only one that will work "properly"
(i.e., the only one that will handle instance delegates instead of only static ones)
Yeah, works for me, thank you!
No problem
I got another reflection question, easer this time though. I have an array of an internal class, but it is an object[] array and I can't set a field to it. Is there a nice way to convert it to an array of the internal type?
You can do object[] array = (object[])Array.CreateInstance(realItemType, count);
Thanks I just thought of that too. It is working now!
(I then had to iterate over them and assign the elements)
or you can do Array array = Array.CreateInstance(realItemType, count); and use array.SetValue(value, index);
but object[] is more convenient
though for an int[] array I'm not sure if object[] works
similarly for any other value type
It seems you can't assign it to a field
I mean specifically using it here
Actually I think I misunderstood you, were you doing field.SetValue(target, array)?
I believe you have to do field.SetValue(target, new object[] { array })
That is only for methods
Haha, it is working now 👍
But anyway, when using CreateInstance it should assign properly
Hey Zombie, we were talking about disabling domain reload (and scene reload?) yesterday and I've been looking through the doc about that.
But I'm not sure where to start, i.e. what's there to do to make it work as intended.
Are there examples I didn't find yet? lol
Or is it just clearing statics
Thanks for your help, I got it working! 😄
https://i.imgur.com/YODPlrE.gif
Awesome!
It essentially just boils down to manually clearing statics when play mode starts, yes
What about scriptable objects?
What about 'em?
There's not really anything special you need to do other than clearing static fields
Are they cleared "normally"?
Alright
So if I had no static fields, I could switch it w/o any problems?
Yeah
Np!
And is it enough to disable domain reloading or should I also consider disabling scene reloading?
And static fields with a reference of gameobjects do not need to be cleared right? As they stay the same anyway
It would be a good idea to still clear them
How are they reassigned then?
Could someone help me with I2 localize tool?
So, I am getting a key to my string from my spreadsheet. I am translating from English to Arabic language. String is saving on TextMeshPro - Text (Ui).
I want to use color tags on text. But when there is a method "ApplyRTLFix()" calling from the script. It is bugging out my text and giving me weird symbols
You need {[PopulationDistinct]} population. Increase <color=#AEE204>{[ServiceType]}</color> population cap by {[PopulationNeeded]}
أنت بحاجة إلى {[PopulationDistinct]} من السكان. زيادة <color = # AEE204> {[ServiceType]} </color> الحد الأقصى للسكان بمقدار {[PopulationNeeded]}
The same way they were assigned to begin with
I'm trying to spawn "cells" exponentially. Currently, I hit a freeze at about 2^15 or 2^16 cells. I'm using normal GameObjects and a custom implementation of the Unity ObjectPool.
Sounds like a fuckload of objects
Use the debugger your code is probably still chugging along
Ueah if each cell out of the 65536 objects has a mono and update loop I would freeze too. You need a multithreade entity component system at this point
Yep, will do that properly
Yeah it grinds at half of that. However it's never really running an update, but there is a trigger detection.
I can't say for sure what the heaviest hitter is. Debugger to the rescue.
Till then I'm happy watching my experiment go rogue and escape the "hatches" every now and then
This is after giving them a 70% chance to die and a general trigger check that stops them from reproducing if they get too close or connect with the corral wall. Well that doesn't really work lol.
Changes to code are causing huge problems and errors. I get this warning in visualstudio: "Background analysis of asset and meta files has been disabled, because this project seems too large."
So some (not all) changes are not propagating to meta files, causing big problems with the game.
googling this error gives me exactly one result, where the issue was unresolved
Is it possible to create an action with a nullable/optional generic parameter?
I want to call a unity event that sometimes will have a value to pass and sometimes not
An action, as in the delegate type Action? For nullable, you can do with it, Action<T?>.
For the optional param, you need to define your own delegate
Something like public delegate void MyDelegate<T>(T value = default)
An action as in UnityAction, that I can assign a callback in the editor to
Assuming UnityEvent, as UnityAction is also a delegate.
You'll have to make a custom inspector for it to appear.
Not sure if it'll like the generic argument either
Yes, sorry for mixing them up, I meant UnityEvent
it doesn't, won't even load the script lol
But it's alright, I guess I figured out a way
Ah, so you would need to inherit it and pass the type to the base class, which makes one subclass for each type you need. Pretty convoluted.
public class DerivedEvent : BaseEvent<Rigidbody> { }
Like Reflection, avoid unless it's the last resort solution
Interesting, though, thanks for sharing
now console doesn't reurtn null, and it downloads file with 404 error (not found)
specifically:
{
"message": "Not Found",
"documentation_url": "https://docs.github.com/rest"
}
yes
i'm using this path: https://api.github.com/repos/<user>/<repo>/contents/<file>.ogg
even without file it returns Not Found
Can you log the complete path before it's sent?
it is same as typed
by the way, it works with public repo, which is different by the some symbols in the name, but path is the same
tried to get the repo info with https://api.github.com/repos/<user>/<repo>, but there is still an error
How tf do I open a windows form through unity? I was told to use System.Windows.Forms, but it doesn't exist
Is it possible to not render something close to camera?
im not looking for camera's clipping plane since it applies to the complete camera render. I just want it for one object.
Any clues?
Alternatively, I would like to send a notification through window's notification system
No idea then..
Use a collider lol
Make a separate camera for the object and set it to only one layer with the object in it?
That only tracks collision with your special object
i want to avoid multi camera setup since i'm already using SRP and its a big headache using multiple cameras
custom shaders
oh yes good idea!
how do i deal with opaque objects this way?
luckily the ones i'm dealing with aren't opaque, but i'm just curious
why make life easy when there's a complicated way lol
opaque can still be clipped or you can do dithering to do some fading
Hi, I have been looking for hours and I can't find anything about how to use shaders to only render an object when looking at it through another object. Does anyone know of any sources that could explain how to do this?
colliders are a very bad idea for this because it would put the load on cpu way too much (for higher object count) whereas handling it on a shader is very efficient for something like this
forgot this. I can't even access public repo from my account smh
thanks! i'll look into the opaque clipping.
only thing i'm worried is about zwrite. but i'll test it out first
Do the objects you want to clip have colliders already?
What about zwrite?
Like this:
Does anyone know how write defaults works behind the scenes? It doesn't seem to be working as expected
with animations that do not have a position keyframe, position is being forced to 0,0,0 every frame with write defaults off.
Have you looked at using the stencil buffer? https://docs.unity3d.com/Manual/SL-Stencil.html
Looking for a little help here. My team's project is using Photon Self-Hosted servers to run our multiplayer game. We're not allowing players to be MasterClients, and instead we're going with a dedicated server. The way we've achieved this so far, is that when a player makes a request to create a game, we have a plug-in that intercepts that request, and starts an instance of the game on the server. What we need to do next, is find a way for that plug-in to pass information to the instance of the game. For example, sending a string to the game to let it know what PhotonRoom to join and take over. Obviously I can't call methods in the code in the game's build from outside of the game. Is there a native way to achieve this.
There is a Photon discord for questions such as these.
This isn't a Photon question. I've already handled the Photon part of it. I'm asking is there a way to communicate into a Unity game from outside of of the game.
Is your plugin in a different process? If so use sockets to do the inter process communication
you can also pass few arguments to unity while starting the unity instance if you have control over the instance starting logic.
And in unity, you can read the arguments using Environment.GetCommandLineArgs()
Yes, it is. I was coming up short when looking for documentation on how to do it via Windows Sockets.
I'll give the CommandLineArguments a shot.
Thank you!
Well... If you're using Photon you should be able to communicate via the room.
Oh, you're talking about the server instance, gotcha
Idk if this is the right chatroom to ask this. But has anyone experience using ubuntu to store unity servers
cause upon running my server.x86_64 thingy
./Server
it runs it and closes it after a while
and prints "Aborted"
and sometimes "Aborted (core dump)"
in URP you can use the Render Objects render feature (experimental) to do this kind of thing
is there anyone here willing to help me with some advanced code, even if it is a paying tutoring session? It involves basically completely altering unity's timing system. I had someone help me a bit, but I am just in a situation where I think in order for me to understand it I need it explained in a slightly different way. I also plan on releasing the code to the community for free to assist anyone and everyone who wants to replicate the behavior of the old gaming platforms. (if so pls message me so I can be sure to see the response, tyvm)
I'd like to make all the enemies in my game make decisions, move, etc. on a fixed hertz -- so like every second they can evaluate their situation then make a new move, spend the remaining time performing the action, then wait for the next "tick" to make the next decision. Does anyone have any recommendations for how best to set something like this up?
I had the same issue
You have to add that library
Idk how tho, i’m stuck with that tbh
It was something like Add Refrenences or something, but I don’t have that option sadly
For Unity you don't have that option yeah, however you can directly drag the DLL anywhere into your Assets, and of it's compatible, Unity will happily load it
Then, add the using directive in your code and you're good to go
Just remember that not all DLLs are cross platform. So if you're developing something cross platform, you might run into issues
I haven't ever made an ai that could be called somewhat complex
But I think coroutines might work nice here?
When your character decides to do something
It can call a coroutine for that action
which can take as long as it needs to
For intersecting collisions, should be using triggers or collisions?
Specifically, I want to highlight the closest object being intersected.
Alright so the cell code I was making becomes slower when there are about 2^15 cell game objects in the hierarchy. Usually having an object pool is better to manage instantiate/destroy calls, which I checked visibly without needing the profiler.
now if I continue using GameObjects I will have to restrict spawns to somewhere around 3000.
Make that 2^14 yikes
At this point it might be better to use one of the Graphics.DrawMeshInstanced() variants instead of having the overhead of so many gameobjects
dots might also be good to use
will look into this immediately
however I do need the cells to know what's going on around them – if they hit the corral wall they should stop entirely, and if they hit other cells, they stop temporarily till some die out
Is there a cheaper way to do the following? https://gitlab.com/Vivraan/GermBomb/-/blob/main/Assets/GermBomb/Germ/GermCell.cs
Note that I'll probably restrict access to this later on
unsure, I'm not really a guru in any of this xD
From the profiler, the hardest hitting factors are: Other, Scripts, Physics, and GC, from most to least.
There's no way to determine what's taking a long time based on the info you gave
Is this a Game of Life kind of thing?
Graphics.DrawMeshInstancedIndirect uses compute shader, and you have a single "mother" object. It's probably possible to code in some collision logic into either the shader, or just the "mother" object. Though you want to avoid any "ifs" in a shader
Yep, that used to be the classical way to get performance earlier. I need to read more about this.
But I am short on time, sadly.
Don't use dotween if you have that many
not exactly, it's meant to be something incredibly dumb
the cells will do their thing and your job is to kill them by dropping sanitiser
yikes, true, DOTween takes up a hefty chunk
Remove that log
I feel really dumb already lmao
Oh cool, Google has a Game of Life easter egg
https://www.google.com/search?q=game+of+life
Also figure out what's doing that allocation and remove it if you can
how is it triggered? 😬
most definitely the object pool
Just removing that log made the thing smoother lmao
It just starts simulating in the background and you can pause it and place new cells
I'm also scaling up the cells so they fill the space faster xD, taking less cells
nah it's still sometimes grinding
Are these cells on a grid?
nope, I gave up that idea quickly
so the simulation lasts a lot longer without grinding down now since I added a null check
Why?
It wasn't aesthetically pleasing to look at, and while the possibility of managing a grid algorithmically is probably the solution here, the sheer feel of cells multiplying naturalistically felt more alluring.
wholly unsure how to reproduce this run lemme check
this is of course considering that I have a limit to how many objects I can spawn, and the prototype is meant to be 3D
Is it possible to make a custom world in blender and then use a grid system in unity to destroy blocks of that map, and build on that map with the blocks you obtain from breaking the blocks?
Cause I havent been able to find a single tutorial on this
Yes, I've played this when I was a lot younger!
You want to pre-empt general cases first, then consider if you can make it better by making it specific. Usually, the answer is no.
Just say minecraft lol
If you mean displacing those blocks, you can do that pretty easily. If you're using Blender, you'll just need to make sure that block is a separate object. Which I guess isn't good practice. Let me think again...
Well, I was thinking of like that animal crossing terrain but the grid system like minecraft
Better done with tweens I'm guessing but I'm not so sure.
This is the terrain im sorta going for but then being able to mine and place land on a grid like minecraft is what im trying to do
Also I saw you mention what separates a good system from a bad one. The answer is, you'd usually want to use as many metrics as possible, such as cohesion and coupling to figure out whether you've designed something in the best possible manner, but strictly speaking the considerations of performance will have to come first.
In such a case the better option would be to start with the specific case. I believe if it's designed well enough you can adapt it to a generic case more smoothly. Care must be taken t do this early or with a system which is as decoupled as you can muster, or you will face complications later on.
Making them all separate objects would be terrible for performance
Repetitive spawning sequences perhaps, those things are much heavier with a timeline.
I have just found this but Im not so sure if its really useful for terrain https://m.youtube.com/watch?v=Cdcn6uK9gPo
🌍 Get the Game Courses Bundle 3x1! https://game.courses/code-monkey-bundle/
📝 POLYGON Fantasy Pack https://assetstore.unity.com/packages/3d/environments/fantasy/polygon-fantasy-kingdom-low-poly-3d-art-by-synty-164532?aid=1101l96nj&pubref=housebuildsystem
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=Cdcn6uK9gPo...
Im also thinking of making a custom height map for my terrain
But if I want caves or more than 90 degree inclines, I would need to learn how to make a 3D heightmap
There's some limitations to performance that you may encounter with a timeline in that case, from my understanding.
Yes, I have used Timeline in my development. Have you used Tweening packages before?
I guess I'm a bit biased towards tweens atm but I find great utility in Timelines!
This is a really cool use case! I'll study it at some point.
I'm thinking along the lines of procedurally generating a wave of enemies. A timeline in my experience can help you set up a fixed wave.
I apologise if I am not making enough sense, I'm just trying to work through my own problem atm.
True, it's more or less related to certain use cases where you might use the Animator. Timelines are far more generic in that sense.
Is there a way to wrote own int.myFunction() function without making it a Myfunction(int) format function?
I think that would be called an extension, and can be done
Extension methods yeah
ah thnx
Okay so I was thinking about how to represent the cells in a more abstract way and I thought "how complex is it to determine which cells are in contact with each other?" Naively I could think it's an O(n^2) lookup but there should be more efficient ways to do this. Obviously all we need to know is if the centres of those cells are closer to each other than their diameter. For not having them exceed bounds, just do a similar check.
This collection of points could in practice be a graph, and we could essentially connect them based on whether their spheres are "touching" or not. I think if we disconnect all cells which touch, we can consider them "obstructed" since we can't reach tem in a graph traversal. Only traversible nodes/cells are "fecund" and can reproduce.
Now the loop would essentially be:
- Start with a single cell
- Randomly assign two positions for its children and remove the first cell's point. Obviously you don't want these to touch so they should be slightly fardher away than a cell's maximum diameter.
- Determine which cells are touching and assign edges as needed.
- Repeat.
To make sure the simulation keeps running, cells have a 99% chance of dying at the end of a few seconds, which frees up space.
Okay one immediate problem is that the graph will be super dense if we take all non-touching cells. Doing the opposite means we'll have clusters of cells touching each other, and unconnected cells will be fecund. Changes some details.
Are there any good write ups or guides on AI troop formations?
Quadtree?
I will get myself some docs and begin reading posthaste. Hopefully there are some implementations I can use readily.
Boids, flocking behavior.
did any of you know ml-agents
if yes how do i request a observation on the start of the episode?
Should probably be asking in #archived-machine-learning
thanks
I think the basis for a quad tree's partitioning is the number of points it can contain. In my case I'll require the condition to be whether points touch or not. Can this be done?
Maybe if I keep the max node count at 2...
Did you have an idea?
I'm simply too smoothbrained but you might be looking for voxel based stuff.
look into BVH
Well, its not exactly voxel
For some reason it just stops and the timer never starts when it reaches the first point
Its a similar system to animal crossings building system
it seems like a problem with the navmesh but it doesn't let me make a new navmesh because when I hit bake it doesn't do anything
Ah, no, I can't afford to instantiate points and check spatially, I would rather have the checks done logically. But I'm considering a spatial alternative which involves GPU instancing.
The point of a quadtree is that you can find nodes in a given area, this means you only have a few neighbours to consider instead of 100s
I'll try using a quadtree to partition the generated points. Can I run this with instanced meshes?
Quadtree has nothing to do with meshes, it's just data points
What you insert is up to you
can someone explain why this isn't working?
maybe start by reading the error messages. But basically what you're doing is a bit of an abuse of the ternary operator
TransparencyImage.color = transparent ? Color.white : new Color(1, 1, 1, 0);``` is the right way
Ofcourse I read it and I googled it but I can't seem to find the right way to do it
(note that I changed your 255s to 1s because color uses 0-1)
Thanks!
is there a hook/callback to be notified by unity when a frame finished rendering when using camera.render()?
I'm rendering a camera to a RenderTexture and want to do stuff to the texture when the render is complete
A callback? I don't think it's asynchronous
myCam.Render();
// any code here will happen after rendering is completed
hmm that's not what I'm observing
why wont this move the player
kehfjsubehvsutfgvdghv^%^&@*@%%@^jbfhc
... not sure I understand what you mean
?
i am a pro coderr
.5hgjjb9tugjkjhpogukcnkhobcjjuh365476763r6irk;gvnhg
script to hack
<@&502884371011731486> annoying spammer
yeah the camera.render() seems to be asynchronous
like, if I have a custom render pass, I can add a hook to a readback when the pass is complete
I'm using this as a callback for now, but I think it's inneficient, as it will probably copy the texture back from the gpu
!warn 842485498907983903 Don't spam this discord.
Matthew2009#6363 has been warned.
also if you call camera.render() too often (like, at each update() iteration), you will end up with 50+ frames in flight
(of course depends on the target framerate)
Well according to https://docs.unity3d.com/ScriptReference/Camera.Render.html
The camera will send OnPreCull, OnPreRender and OnPostRender to any scripts attached, and render any eventual image filters.
So you can probably use those
but the receiving script needs to be on the same GameObject as the camera I'd guess
(also is your name a reference to Neuromancer? I just finished that book yesterday)
yes it is! 😄
Might be worth asking in #archived-hdrp
awesome! thank you
Hey guys, I have been trying to understand a few things about state machines.
Should I have different state machines for movement and for attacking/casting abilities?
Where should the logic the individual state use live (updating move controller, changing animations etc.)
- Maybe. Depends on your desired behavior. A simple state machine can only be in one state at a time. Can you move and attack at the same time?
- Depends. SOme implementations simply put each state in a separate method, some get complicated and use different objects to control each state.
What are some practical use cases for Jobs in a non-ECS context? I'm playing around with Jobs for the first time today and it seems most of the kinds of things I try to throw at it are much slower.
I used jobs for a factorio-style fluid simulation in my factory builder game. Basically anything you can write as an extremely parallel process can gain benefits from being job-i-fied.
The fluid simulation in question is like:
Given the current quantity and velocty of flow of fluid in all the pipes in the game, calculate the new quantity and flow velocity of fluids for each pipe for the next simulation tick.
You could imagine doing something similar for, let's say, navigation for a large number of AI characters
So traditional game loop stuff is unlikely to work well within the context of jobs, outside of ECS?
you basically replace what would normally be a big for loop over a large amount of data with a job that runs the each part of the loop in parallel
It definitely sounds like a tool with a very specific use-case right now
In both cases you need to write things in a way that one result doesn't depend on the next
Or at least, you need to identify and clearly delineate those dependencies and isolate/avoid them as much as possible
because every dependency means a whole lot of serial processing and orchestration that needs to be done, which slows things down
There are a lot of problems that are not easy to parallelize. Those problems can't be solved well with the job system
But there's also a lot of common things that can be parallelized that would benefit from Jobs
Right, I'm struggling to think of many in the context of my own game. If the players had been setup in some sort of ECS way, I could imagine iterating over each of them with Jobs, executing the movement for each player all at once.
Of course, given that I've coded everything in OOP-land, the uses are less
This seems like the best clue to where I should be looking in my codebase
Yep - or any object which you have a large number of that has an Update or FixedUpdate
Hi, is there a way to make it so the backface of a mesh (which usually isn't rendered) render a color/texture different that the mesh's color/texture? For example, if the camera moved inside the mesh, or the mesh had a whole in it, you could see the special color.
You could do that either using a custom shader, or just use a normal shader, give your mesh internal geometry, and UV map it appropriately
Hi, I want to use Prefabs (MonoBehaviour) as an alternative to scriptable objects due to prefab variants inheritance and hierarchy. Is there any caveats in reading uninstantiated prefabs? These would be in fact readonly resources in my application. Thank you
The only thing I think is that none of the lifecycle methods will run (Awake, Start, OnEnable, etc...)
Yes that would be fine since they would only be data containers. What I am wondering is all the craze about scriptableobjects then, given prefab are so much more powerful. I doubt the memory difference makes a substantial on modern hardware.
Honestly I guess not much. A slightly cleaner UI in the editor (without extraneous GameObject stuff), a bit less memory usage
Other things you can do with SOs:
- embed multiple SOs in a single asset file
- CreateAssetMenu (does this work somehow with prefabs? The workflow may be a bit weirder)
In https://gitlab.com/Vivraan/GermBomb/-/blob/main/Assets/GermBomb/Germ/GermCell.cs, I try to reuse DOTween Sequences once they get completed (I perform a null-coalescing assignment to prevent DOTween from exceeding maximum allotted tweens and sequences), but I am not able to get the sequence to run again.
Another reason for going with SO is the data duplication.
If you have a mono behaviour which serializes 1mb of data.
If you clone that 1000 times, you get 1gb of additional duplicate data.
But if you put that in a scriptable object and then reference that Scriptable object in mono behaviour and then clone the mono behaviour gameobject, only the reference to the Scriptable object is cloned
Its just a work flow change which can help some cases to avoid bloated memory
Pretty sure you're comparing 2 different things, you can still just reference a prefab without instnatiating it and thus without duplicating memory
Um no i don't think you got my point here.
You can still refer it, but when you clone it the data is duplicated. I pretty specifically said clone 1000 times.
You won't clone 1000 times just to read :)
I should also note that in a build, prefabs are stored compressed in memory and when you first load them they will "bloat" up to the size of a full game object
I'm not sure if unloading them will free that up
But then that's the same with a scriptable object, you can clone it and still have the data duplicated
Just don't clone lmao
btw could anyone help me understand if I am doing this right? I have also used .SetAutoKill(false) for this.
Using the FBX SDK in the unity engine (not the editor), I can create and export an fbx scene with a root bone. But when I add a child bone to the root bone, it doesn't seem to get registered properly - the Blender importer complains with "KeyError: bpy_prop_collection[key]: key 'child-bone' not found". 🤔 The code doesn't look wrong...
var skeletonAttribute = FbxSkeleton.Create(scene, "child-bone");
skeletonAttribute.SetSkeletonType(FbxSkeleton.EType.eLimbNode);
var childBone = FbxNode.Create(scene, "child-bone");
childBone.SetNodeAttribute(skeletonAttribute);
childBone.LclTranslation.Set(new FbxDouble3(0, -5, 0));
childBone.LclRotation.Set(new FbxDouble3(0, -0, -0));
childBone.LclScaling.Set(new FbxDouble3(0, 0, 0));
rootBone.AddChild(childBone);
I'm asking here because #archived-code-general is a bit busy:
So if we take this C# code
public class PlatformTest : MonoBehaviour
{
[SerializeField] private SpriteRenderer sprite;
public bool canInvite;
void Start()
{
sprite.color = Color.magenta;
Activities.canInvite(CanInvite);
}
void Update()
{
sprite.color = canInvite ? Color.green : Color.blue;
}
void CanInvite(bool value) => canInvite = value;
}
If I assigned sprite.color from CanInvite instead of the value type canInvite the game would crash
A little backstory: Activities.canInvite is a native function (running Swift actually). I'm curious if anyone knows what limitations sprite.color could pose, which makes it so the game crashes, and why those limitation aren't on the canInvite bool?
I'd assume that's because you're trying to access unity api (Sprite.color) from a different thread. Native functions are usually called from a separate thread. Setting a value type in your code is allowed though.
Could use a main thread dispatcher or similar technique.
I was about to ask if C# had that
No, but you can look up an implementation on google or make your own.
I think there's a decent one on github.
I already have UniTask, do you know if I can use that to aid me?
Perhaps. Not sure. Main thread dispatcher should be a really small simple script.
I found one that uses the update function
@untold moth thanks! Moving it to the main thread worked 😄
Dispatching to the main thread can be extremely simple btw: https://github.com/NewBloodInteractive/com.newblood.core/blob/master/Runtime/MainThread.cs
With this you can just do MainThread.Send or MainThread.Post
Using the synchronization context makes things really easy
that looks better than what I found 😄
I thrive on simplicity 
I spend more time than I probably should cutting things down to be as small as possible
Makes it easy to share the knowledge around
Plus it's less code to maintain
I had a thought. I don't know if you've coded in React before, but I was thinking of a useEffect style "destructor" function, where you curry a function, and the last function runs on the main thread. something like
SomeAsync(() => {
//this runs in a random thread
return () => {
// this runs on the main thread
}
})
If you use async/await, you can use a custom awaitable to hop between threads
eg
// stuff
await new SwitchToMainThread();
// stuff
await new SwitchToBackgroundThread();
// stuff
You just need to write an awaitable that dispatches the continuation
oh nice!
public struct ContinueOnMainThread : INotifyCompletion
{
public bool IsCompleted => MainThread.Instance == Thread.CurrentThread;
public ContinueOnMainThread GetAwaiter()
{
return this;
}
public void OnCompleted(Action continuation)
{
MainThread.Post(state => ((Action)state).Invoke(), continuation);
}
public void GetResult()
{
}
}
Simple implementation
await new ContinueOnMainThread();
bam
Daaaamn that looks nice
does csharp have a bool object?
Not sure what you mean
class Boolean vs struct bool (or whatever)
bool is just an alias for it
They're the same thing
typeof(bool) == typeof(Boolean)
Unlike Java's dumb system where primitives end up allocating because stuff like Integer is a class
Basically there is no reason to use System.Boolean instead of bool in C#
but value types aren't considered objects, right?
Value types in .NET have two representations
Boxed and unboxed
object o = true; will give you a boxed boolean
and then you can unbox it with (bool)o
basically, I can't send or post a bool?
You could also just capture a bool:
bool someBool = true;
MainThread.Post(_ =>
{
// you can use someBool here
}, null);

and yeah, SynchronizationContext doesn't use generics
time to file PR's
It's basically the "core" type for synchronization in .NET
There's not really a way that it could use generics that would be useful
You can build a type like a Dispatcher on top of it though
having state be the same type as state, I'd argue that's pretty handy
Right but it would complicate SynchronizationContext itself, which is a low-level type
It's meant for building higher-level stuff on top of
So it's deliberately kept simple
I see
You could totally write a generic Send/Post in the MainThread class though
In this example I passed the continuation as the parameter to the callback instead of capturing it because it avoids allocating a delegate
I could have written MainThread.Post(_ => continuation(), null); but it'd be less efficient
Using the null trick works like a charm btw, thanks!
time to file a PR with that as overload
Send = "queue it up to run on the main thread and wait for it to be called"
Post = "queue it up to run on the main thread and forget about it"
So Post is like "just run this on the main thread whenever, but don't make me wait for it to happen"
Nope. Asset reference gets copied with instantiation.
Same is the case with any asset like texture, sprite etc.
Whereas Send is for when you need something to run on the main thread, and the code after the Send needs to wait for that to happen
Oh because Post takes an async func?
Nah it still takes a synchronous function, it just dispatches it asynchronously
interesting 
MainThread.Post(function, null);
Debug.Log("This message will appear immediately");
MainThread.Send(function, null);
Debug.Log("This message won't appear until after 'function' has run");
This might make it clearer
can you elaborate why that difference might matter in a bool => MainThread.Post/Send context?
Let's say you are running code on a background thread, and that thread belongs to the thread pool, so when it finishes executing its code it can return to the pool and perform more work queued up there
If you used Send, you would be holding onto that thread even though you're done with it
Post would allow that thread to go back and do its own thing while you wait to run on the main thread
In the case of Send, maybe you're generating texture or mesh data on a background thread, but you need to jump onto the main thread for a moment to create a Texture2D or something, so you would use Send to make sure you have that Texture2D before you continue
I must confess, I'm using two different threading systems, so I don't even know which thread is doing what (That's a side-effect of me trying to write a wrapper around a Swift only iOS feature)
Basically it's just a matter of when you need things to complete
Ahh that makes total sense!
so in the context of single expression functions, it doesn't really matter?
Most of the time, no
thanks for the explanation 😄
Another example
await new ContinueOnMainThread(); just simplifies writing code like that
Is there an advantage when wrinting cs Texture2D texture = null; instead of just cs Texture2D texture;I don't see the difference since the type of the var is already declared
In this case it's just to make the compiler shut up
Because it will complain about using texture before it's assigned
Because it doesn't know that texture will be assigned by your callback when you use it
Since it doesn't have knowledge of the semantics of the Send method
Also, here's an example of ContinueOnBackgroundThread, a companion type for ContinueOnMainThread:
public struct ContinueOnBackgroundThread : INotifyCompletion
{
public bool IsCompleted => Thread.CurrentThread.IsThreadPoolThread;
public ContinueOnBackgroundThread GetAwaiter()
{
return this;
}
public void OnCompleted(Action continuation)
{
ThreadPool.QueueUserWorkItem(state => ((Action)state).Invoke(), continuation);
}
public void GetResult()
{
}
}
Next step: entitlements in the unity player

I wanted to say that it doesn't look like my dylib is being transferred over, but it's in the Plugins folder of my build
Hello, how to stop async functions? (when game stops, they do not)
not an expert but i've got the impression they're not safe to use in unity without the "plumbing" to adapt them because of the way unity handles threads (?), but for example UniTask is one add-on that has done some of that work
Pass a cancellationtoken
It's because (unlike coroutines) tasks are not bound to the lifetime of an object
And thus keep running as long as the domain isn't reloaded
Thank you for answers!
unitask makes threads not run on separate threads and thus allows its tasks to use the unity api. it also allows you to switch easily between execution on the mainthread and a separate thread in the same task, while providing an API with semantics that make it much more obvious what is happening and supposed to happen in a game-loop driven environment.
threading issues? couldn't be me
Does anyone has an idea on how to align the birds face to the stepstone direction? We are using dotween plugin and i am not used working with it. The bird can only walk along the stepstones and all we want to do right now is it to face the directions its walking to
are the stones 1 mesh, or is each stone it's own mesh?
Ehm they are just textures but beneath the stone lies a path block which it walks on, was kinda about to share the next picture but i got distracted, here is the path its walking:
Right, yeah, that's good. I was gonna suggest the best way would be a spline or something to follow
Each of this path blocks is rotated by a certain degree and my idea was, if we just give the character the same y rotation coordinate, it should always be aligned with the path
Problematic is that i didn't started this project but i got assigned to it during practical project in university
I wouldn't use DOTween for this mechanic. Have the points in a list/array, and set the next point you're running towards as the rotation to look at
Technically yes, but as i said the guy who created this game did use dotween so we just kinda have to adapt :/
I was just double checking, the y coordinates for the character and the path block are not facing the same direction when i equal those
You want to look at the block, not use the block rotation
Well i guess i just found a solution 🤔
well, gotta have to take my break, i'll try to be back at 1pm
Generally, i’d rewrite something before spending even more time dealing with the fallout of an ill conceived system.
I tried doing some code signing, as per:
https://docs.unity3d.com/2021.2/Documentation/Manual/macos-building-notarization.html#signing-identity
but I get this error when I try and open my dev after codesigning
Since my DOTween related question went unanswered, what's the best place to ask it?
re-link it, I didn't see it.. might be able to help
you could use .IsActive() instead of ?/?? and maybe set .IsRecycleable explicity.
Got it, let me try those
have you changed the defaults in DOTween settings?
let me check that out as well
so I enable that there?
does that switch mean I can leave the pooling to DOTween?
yes, no manual pooling required
do I set autokill to true within the code then?
autokill is generally useful to be on as a default so you dont have to worry about it for the more common fire-and-forget type of tweens that are recreated each time you use them
also mind that a tween will never update its configuration... whatever values you set when its created will always be used
I'll profile it to check if there's more allocations being shoved out
does killing the tween make sure the tween is available for recycling?
anyway let me check that for myself with the profiler
no, it's just not rampantly reproducing like earlier
In the earlier case, I was not performing a ??= so the sequence would be created anew whenever a cell was retrieved from the object pool.
DOTween wants you to use its own api for checks like this
it has these .Target and .Id properties you are supposed to use for controlling tween lifetime in addition to using handles. But if you use handles, its probably best to use the DOTween api for liveness checks too.
Okay I got the lifecycle of the germ cell constructs to last for some time in the last run.
you can also check the source code... its not that complicated a system
Okay, I'll give it a shot, although it's really smooth now thanks to the pooling.
After using this line of code:
Error shows up and says:UnityException: Create can only be called from the main thread. I want to attach cancelation token and pass it as second argument of .Run function. how can I use cancelationtokensource without using Task.Run()? or how to fix it?
just await GetTextu.....; is not problem
Ok kinda fixed my error and found a solution, but now the character model is always turned around wrong. From this perspective, she should like the other way around
The single code snippet that kinda made it work
dotweenSequence.Join(transform.DOLookAt(finalPath[i].position, .1f, AxisConstraint.Y, Vector3.up));
Also note that any nested Tweener/Sequence needs to be fully created before adding it to a Sequence, because after that it will be locked.
Not sure having it in a sequence will work how you want? You can't change the values of a tween in a sequence once it starts?
I guess it's not possible after trying a few things, could it be that the character model is just on the wrong side?
wrong side of..?
Idk maybe its loaded the opposite direction 😅
I guess the reproduction algo is not working for some reason. I'll get back to it later but I think OnTriggerExit is not doing its job properly.
It was lol
yo a math question
A 3d vector is not the most compact way of encoding a direction, right?
Because it also encodes a length (norm) info
Hi all, I could not find a specific channel for unit tests, so I hope I can write here
If you represent a direction with two rotations along two designated axis, then you only need 2 real numbers to represent it in a 3d space
I have some PlayMode tests that works correctly if I run them one-by-one, but if I run all the tests, some fails. I think there is some "refuse" of previous loaded scene. What is the best practice about scene load/unload in Test Framework?
kynda but I want to automaticaly change game display to for example 3
@broken socket
I am makeing a multiplayer game and every player have his camera and I made that every camera is rendering to special display for example player with id 3 will have his camera render to display 3 and now I just need to set game display to 3 as well
Never mind I fixed it
depends if it's a 3D direction
what about a bool3?
(probably bool6 is better)
why would you spend 6 bytes on a single bit thing? 😵💫
Are there any disadvantages to using terrain tessellation for dynamic LOD?
Hi all, I've been searching but can't find it. I'm making a 3d space game and I want to draw orbit lines. They need to have a fixed width (independent on distance from camera), a bit like Gizmos or Debug.DrawLines work
what's the best way to do this?
do the orbit lines depend on a physics simulation or are they just circular?
this will probably solve what you need
https://www.codinblack.com/how-to-draw-lines-circles-or-anything-else-using-linerenderer/
Vectorsity or Shapes or Linefy (all paid Assets)... you can do what they do on your own, but thats the "best" way if you want to not worry about it anymore
I’m trying to make the rainbow 6 shooting holes in walls mechanic but I don’t know how to cut the holes into walls. What should I be using to do that?
One strategy would be to brute-force the effect using boolean operations. Another way would be to use a pre-baked fragmented mesh. One more way you could attempt that is by using shader magic (think portals). 😉
I would be curious to learn of any other ways as well.
Have you had a look at Unity’s LineRenderer? There is also a TrailRenderer, which I used in AR to draw a line where the user walked.
Ah, I’ve just noticed others have already shared the same… 😋
OHH ok so for large amounts of data, does ComputeBuffer.SetData take awhile? turns out that profiler says its taking quite a long time(deep profiler says its taking 41ms by itself)
Profile it in a build, might be multiple orders of magnitude faster there (il2cpp)
true but for now, im making something for editor/play mode only atm
is there anything really that I can do for my current case?
That is extremely long. Are you sure that's right?
hang on broke something
I shovel 16k x 8k R8G8B8A8 textures back and forth from CPU to GPU and back to CPU regularly. And it takes maybe 10ms one way.
I highly doubt your compute buffers are 4x2M ints
lemme rebuild it and ill see how large it is
I also desperately need to continue looking into memory, as for larger models untity can take 25 gigs of ram easily while building my thing
Jesus. This a full game?
are you baking the raytrace? Or real time computing?
ok correction, unity RESERVES 20 gigs of ram
but if I do something to refresh like going into play mode, its reserved memory will drop to about 5
real time ideally but
there are several parts of this where it uses loads more memory than I feel it should and I have litterally no clue why
Welp, that's the wonders of debugging. Time to find out why eh.
ive been trying but memory anything confuses me so much
maybe you are accidentially allocating large blocks of memory or copying stuff multiple times without realizing it
ok so the data im uplloading to GPU is 1.587 million entries of a list of a struct, where the struct is size of 80 bytes
maybe, but I dont know how to know
Oh boy
this is a compressed wide bounding volume hierarchy for a mesh of 12.7 million total triangles
And there's your problem
either round that mesh down or cut it apart
And please dont be the twitter meme.
and unity has reserved 22 gigs of ram
and if I go into and out of playmode or do something to update something, itll drop down to like 5-7
?
Also this mesh is used as a benchmark, so its this big for a reason unforunately
Ya know the twitter meme where some guy is asking for advice on how to budget. 10 bucks on food, 10 bucks on toys, 10,000 on candles. When recommended to buy less candles, they say no. Ya know that image.
lol
havent seen it, but while I see what you mean
this meshes point is to be intensive, its a benchmark
unity please stop using 22 gigs of ram...
you dont need it anymore...
you never needed it
Check if ya render textures to be sure they've all been disposed / released properly. Make sure you use the using statement on unmanaged assets. And maybe even call garbage for completion of major steps
Otherwise yea, that's roughly to be expected for something that large
ok so I went into play mode, and memory used on my PC by unity dropped from 22 gigs to 4
close unity and reopen, how much memory is it using?
if it continuous increases, ya got a memory leak
it doesnt
that I know of at least
again going into play mode calls something that frees up like 18 gigs of ram
well then, this problem is fairly deep. Start cutting / commenting out sections of your compute shader code calling (CPU render chain side) sections to see how it affects the memory usage
This aint something talking to a rando on discord is gonna solve. This is hours of debugging and trial and error ahead.
fair
oh wait the massive memory usage is from scripts I use in editor mode(which I still say never uses the 22 gigs of ram unity reserves)
Can anyone recommend me tutorials for time loops? like in We Went Back
Like coding a time loop? Physics rollback?
How does tasks effect memory use/reservation?
C# async tasks?
yes
this doesnt mention the memory usage/memory reserving as a result of async tasks?
Im wondering if my moving the previously sequential building into tasks means it reserves a lot more memory reserved, as it may be reserving the memory for EVERYTHING at once, instead of being able to resuse space?
Tasks aren't unmanaged, where did you hear that?
Random google. I dont use tasks, prefer unity's job system
Tasks and Jobs serve different purposes, so they're not really comparable
Didnt really look too closely at the stack overflow comment chain
Well to some degree you can run asynchronous code with jobs, but they can only last for up to... 4 frames?
but yeah, different purposes
Either way, tasks aren't "unmanaged" in any sense, so either that stack overflow commenter was wrong, or you may have misinterpreted them
Basically yeah. Tasks are designed for async code, Jobs are designed for parallelizing synchronous code
It's SO, probably both
Long-running jobs are almost always a bad idea because you'll starve the job thread pool
You typically want them to be short and complete within a few frames
Yes, I am looking for a tutorial for coding a time loop with physics rollback like you go through a room and through doorway into same room all reset. ...but without reloading. There is respawn and teleportation, but resetting scene isn't what I am looking for; more like load changed scene without long loading.
this is something that cannot be stated often enough
Does anyone know why it is that any time I do a capsulecast or anything like that, it won't return any collisions if the capsule starts on the surface of another mesh??
3D physics casts won't detect any collider that they are overlapping at the start of the cast
But why?
it should detect other colliders that it doesn't overlap at the start though
Because that's how it works
¯_(ツ)_/¯
If you want to know about the start position, you can use Physics.OverlapXXX instead
But does that work with meshes?
I just want to be able to move a transform based player without clipping through walls or the floor
But I have a bunch of extra stuff I need to add
also if you are using a capsuleCast or whatever it should work fine since you wouldn't be starting overlapping something if your code works right
That's the thing, I do that and it will detect the first collision, then just clip through because it starts on the surface of the other collider
why is it starting on the surface of another collider?
that would mean that you clipped into something on the previous frame
I have it capsule cast the velocity, then move the distance of the cast
yep - sounds typical
So if it collides, it will move as far as it can so it ends on the surface of the mesh it collided with
Then the next frame, it ignores that mesh because the surfaces are touching and clips through
That's why the default CharacterController has a "skin width"
How does that work?
😐
I've tried that too
How small an amount?
Because if the Time.deltaTime or the velocity is too low, the distance will be too small and the subtraction will make it negative, making the player float or not move at all.
And if it's too small, it just clips through anyways
Well, obviously clamp the distance to 0
This is stupid
I used Physics.ComputePenetration to check for overlap before casting, and it returns no overlap
Try drawing debug gizmos to make sure that you cast in the right place and direction.
float distance = Vector3.Magnitude(direction) * Time.deltaTime;
RaycastHit hit = rigidbody.SweepTestAll(Vector3.Normalize(direction), distance);
distance = hit.distance;
transform.position += Vector3.Normalize(direction) * distance;
i need to know which exact UnityEngine.Object throws serialization depth limit warnings, anyone has a working solution?
Doesn't it select it if you click on the error?
no
is this ok or is pattern matching a no-no for anything UnityEngine?
any of your classes could be doing that. look for circular references
ok thanks
that wasnt the question, i found the issue in a plugin and fixed it, but i would still like to know the answer.
are you asking why it happens?
i would assume it's the inspector itself giving the error
no i asked what i initially asked
what a json utility? did you read the question?
you asked what's throwing the depth limit warning
zombie knows everything maybe they can help you
lol
sometimes warning/error messages can have a context object attached to them, but I'm not sure in this case
I was just looking through the engine to see how that error is reported
it doesn't look like it attaches one
okay so, what you could try
- Create a custom logger a la https://docs.unity3d.com/ScriptReference/Logger.html
- Check if the message begins with
"Serialization depth limit"
- If it does, do
Selection.activeObject = context;
then whenever you get that error, the editor should select the offending object
If there's no context passed then that variable will be null
if they pass a context
If they pass a context, then selecting the log (in the console) should already select the object
You don't assign unityLogger
you assign unityLogger.logHandler
i mean if you want to do magic youd substitude the default one
That's exactly what that does
alright, i still think it wont work for the reason Navi said
it simply doesnt pass any ctx
yes, it depends on if they pass a context or not
it should know what it is deserializing right? there must be a serious reason it doesnt have a context?
Chances are, it's too deep in teh serialization library that it's impossible to find out the gameobject reference from that point
For what it's worth, inspecting the code
It does actually appear to assign the value in the C++ related to the context object
So it might pass one
ill try the logger path later
You got the cpp source?
no
Unity ships with PDB files
So you can see the internal structures etc, useful for debugging stuff like this
I wish had a source license, there'd be so many trivial problems I could solve for stuff I work on
Surely there's a suspicion of what is causing it. Something surely changed recently to cause it?
Most of the time when you see it it's a class serialized in itself
I also thought that the error had a small stacktrace of sorts mentioning what class caused it, but maybe that only happens under certain circumstances
Yes it has problem is that you can have 100 objects with that problem, but the error throws only on couple of them
I wanted to understand why, to isolate the objects on which it specifically throws and analyze why they do and other dont
But there is no ctx so i just had to use the nuclear option
I would restructure the code to avoid it happening entirely tbh
You could send the structure and we can speculate on the why if that helps 😄
Its what i did, but its a plugin, i made a commit, nuked it, saw it didnt break anything, so this particular issue is resolved
but i had this exact question pop up over the years a lot
You could try and see if ISerializationCallbackReceiver is invoked in-between these objects
and not just around the whole grouping of them
hm add a logging point? clever
Yeah, if the error is in between one of the logs then you're good. If it's before or after then sadly I have no nice answer
that will work most likely, thanks
Hi!
I have a dilemma. I have a RuntimeInitializeOnLoadMethod where I load up managers dynamically and set stuff up. This works fine and I would not like to change this. But I would like to disable this when running play mode tests. Is there any way to check if the unit test framework was the the one that launched the app?
dumb solution - static bool
It doesn't look like there's an API for what you want, at least from a cursory glance
can somebody can help me with multiplayer netcode
Hmmm..... I mean sure I can just flip a bool manually, but this actual init scrip is in a package so I can't actually edit it
#archived-networking is probably what you want
which package contains the method?
My own... But it is included with git URL so I "can't" edit it locally
You can clone the repository into the Packages directory
Which will allow you to do that
So you have Project/Packages/com.whatever.mypackage
..... Besides the point
But I guess I could do some checks if it is in the editor
The package manager will load it from there instead of the git URL, and there's a setting in preferences to generate a csproj for it so you can edit it in VS
Yeah it's not ideal, just offering a potential workaround
I know that but I want others to be able to use it
I really wish Unity would let you browse packages sources on their site
It's annoying as hell to have to download them via node or the editor itself to look through it
Oh yeah... Or just put it on GH
I wanna see how the test framework initializes to see if there's a way
this is a valid architectural issue, which unity should resolve
Okay so, as a hack
It looks like you can reflect into EditModeRunner.RunningTests, a boolean field
I'm not seeing a public API for this anywhere yet
I also don't know if that will be set when your init method runs
Which load type does it have?
Yeah ....
I think the default
The default is AfterSceneLoad I think, so that should be fine
Let me check
where you could potentially compile with a define, and strip out the attribute if the define is present
That's a possibility too
Before scene load
Could use it to set a static boolean that causes the init method to not run
BeforeSceneLoad and AfterSceneLoad should be fine I think
OnSubsystemRegistration might be too early
Good luck, if you find a solution I'm interested in hearing about it
How can I loop through all areas enclosed with wall tiles in my 2d tilemap?
run flood fill on all tiles, each time flood fill cant grow - its an area, if more cells are left in the open set - you have more areas, in the end you will have a list of areas
I tried to look into flood fill but its too confusing for me xD
well, make it not confusing
its the most basic interaction you can have with a graph
Breadth First Search is basically flood fill
hi, someone is using "TEST SCENES" in automated tests?
@odd mesa there is no job posting here. See #📖┃code-of-conduct . Also no non-Unity discussion.
Sorry my bad
Hope am forgiven
You have been told this before. Next time is a warning
Test Framework Error : The type or namespace name 'Core' could not be found. when trying to unity testing
why?
and how to fix it?
Add a reference to it in the asmdef of the test project
hi guys, I need to go deeper in my project with asynchronous coding, been playing with async await and Tasks mixed with coroutines but i think this is a mess... i was taking a look to the UniTask asset... seems quite good for this purpose.. do you recommend it?
How can I fix thatt? I need cancelation token to stop it
What does GetTexture do?
As the error says, you're calling a Unity API from a non-main thread
So I'm assuming GetTexture does new Texture2D somewhere, or something similar
That's because SendWebRequest doesn't return an awaitable type
You shouldn't be using Task.Run here btw
Task.Run will run the code on a background thread
So you can't use the Unity API there (eg, material, mainTexture, UnityWebRequest, etc)
so, how can I fix that?
I want to get textures from server and I also want it to be stopped after game finishes
Give me a sec and I'll write up an example of one solution you can use
thank you
public static Task<AsyncOperation> AsTask(this UnityWebRequestAsyncOperation operation)
{
var tcs = new TaskCompletionSource<AsyncOperation>();
operation.completed += op => tcs.SetResult(op);
return tcs.Task;
}
So, you can implement an extension method like this
and then you can do await request.SendWebRequest().AsTask();
Thank you, I will try that wait
SendWebRequest/sendTextureRequest
do they need both?
I'm not sure what you mean
You might want to look at UniTask then, it offers support for this stuff
Okay, thank you!
are these things different from Unity Jobs system?
Can I do the same thing with Jobs
?
The jobs system has a different purpose
Jobs aren't designed for async stuff like downloading files or loading data, they're for parallelizing synchronous operations like heavy math processing
Great, thank you
VS doesnot recognize namespace I imported.
Closing and opening didnt work
what's the problem?
Same root folder fixedbut..
i have a very annoying bug related to spawning some gameobject. just want to confirm if its really a bug or something wrong on my end.
i have a gameobject i'm spawning using Instantiate(cloningObject,position,rotation,parent). no rigidbody involved.
the parent gameobject is a root gameobject at Vector3.zero local position Vector3.zero local euler rotation.
the rotation is absolutely fine. but the object position is for some weird reason spawned at my camera.
i have tried to debug the position. using Debug.LogError and enabling pause on error.
I print transform.localPosition and transform.position for the gameobject. they appear to be same and correct position as i intend them to be.
but in inspector the position value seems to be different, and is same as the position of camera
of course the position in game view is also wrong
can somebody please explain this weird situation? :))
unity 2021.2.12f1
Ok, so I have this code running in Update() to work as a player controller (I want to simulate collisions manually so I can do some extra stuff later). this code works perfectly when run frame-by-frame (even for thousands of frames). But the second I unpause play mode, the player clips straight through the floor. I have no idea why and I desperately need help, I have been pulling my hair out over this for hours.
rotY += Input.GetAxis("Mouse X") * sensitivity;
rotX += -Input.GetAxis("Mouse Y") * sensitivity;
rotX = Mathf.Clamp(rotX, minX, maxX);
transform.eulerAngles = new Vector3(0, rotY, 0);
cameraTransform.eulerAngles = new Vector3(rotX, rotY, 0);
Vector3 direction = Vector3.zero;
if(Input.GetKey("w") &! Input.GetKey("s")) {
direction += transform.forward * speed;
} else if(Input.GetKey("s") &! Input.GetKey("w")) {
direction -= transform.forward * speed;
}
if(Input.GetKey("a") &! Input.GetKey("d")) {
direction -= transform.right * speed;
} else if(Input.GetKey("d") &! Input.GetKey("a")) {
direction += transform.right * speed;
}
if(isGrounded) {
gravitySpeed = 0;
} else {
gravitySpeed += gravityAcceleration;
}
direction += Vector3.down * gravitySpeed;
float distance = Vector3.Magnitude(direction) + 1f;
RaycastHit[] hits = rigidbody.SweepTestAll(Vector3.Normalize(direction), distance);
if(hits.Length >= 1) {
distance = hits[0].distance;
}
transform.position += Vector3.Normalize(direction) * (distance - 1f);
Question: would it be easier to make a time loop OR make an infinite room situation where leave and then are in a new instance of it? Are there any tutorials for time loop? ...resetting room but having changes be made on each iteration
what's a time loop?
time loop like you just did a level and get to the end but then when you pass the end portal \ door \ walkway, you are back at the start. Sorta like respawn with level reset, but... there are three versions: 1. Full Reset, 2. Reset with dead bodies, 3. Reset with changes
Many ways to do it:
- Make different versions of the same level
- Use DontDestroyOnLoad to allow certain objects to persist between reloading the scene
- Have code that "prepares" the scene in some way when it loads, i.e. by reading some persistent data and placing objects or changing things in some way (e.g. opening a door that was normally closed)
until you show your code, its very hard to tell.
also a note to you that Debug.Break() or 'Pause on Error' dont pause immediately because its impossible to do so without freezing unity editor, and it happens at end of frame.
make sure there's no code modifying your spawned object's position in that same frame after you spawn it
I've thought of different versions of the same level, but I do not want the game to get too heavy if I keep remaking the same level. Even if all in the same scene, it loads\unloads and teleport. Was thinking of an array of select level to go between for loadi--- oh! That's it. Could just move everything back to their initial position after X happens. Triggers with array positioning.
Hey guys, I just wanted to ask. What is the exact difference between Singletons and UnityEvents
and the difference between UnityEvents and UnityAction
They are completely different concepts
I've started getting this error about generics in burst, but I'm sure we haven't had a problem with generics before, is the issue something else?
System.TypeInitializationException: The type initializer for 'VoxelEngine.Core.ChunkBuilderUtils.Build_000068CB$BurstDirectCall' threw an exception. ---> System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal method 'VoxelEngine.Core.ChunkBuilderUtils::Build$BurstManaged' parameter 'contextMaterialMap': Generic types cannot be marshaled.
the function is defined as so:
[AOT.MonoPInvokeCallback(typeof(Action<ChunkCache, ChunkBuildStats, UnsafeHashMap<int, ChunkBuilder.MeshBuilderContextContainer>, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, UnsafeHashMap<int3, BlockMeshData>, UnsafeHashMap<int3, UnsafeList<ThreadSafeMeshCopy.MeshData>>, ChunkSnapshotBlockAccessor, float3, bool>))]
public static unsafe void Build(
ref ChunkCache chunkCache,
ref ChunkBuildStats stats,
ref UnsafeHashMap<int, ChunkBuilder.MeshBuilderContextContainer> contextMaterialMap,
MeshBuilderContext<PositionOnlyVertexData>* colliderContext,
MeshBuilderContext<PositionOnlyVertexData>* shadowContext,
MeshBuilderContext<PositionAndNormalVertexData>* waterContext,
MeshBuilderContext<PositionNormalUvVertexData>* contextLOD1,
MeshBuilderContext<PositionNormalUvVertexData>* contextLOD2,
in UnsafeHashMap<int3, BlockMeshData> cubesMap,
in UnsafeHashMap<int3, UnsafeList<ThreadSafeMeshCopy.MeshData>> decorationsMap,
in ChunkSnapshotBlockAccessor blockAccessor,
in float3 groupOffset,
bool tempEnableLodCubes)
To understand UnityEvent read this: https://forum.unity.com/threads/unityevent-where-have-you-been-all-my-life.321103/
UnityAction is just a delegate type - it means a function with no parameters and no return value
And Singleton just means "something that there is exactly one of"
Hmm I see, better check that link out
What do you think about scriptableobjects + unityevents architexture
architecture
```c
how does c# know that this is comment // hei have a nice day
people that that its very powerul
It's not great because the main benefit of UnityEvent is you can set it up in the inspector, and you can't reference scene objects from a ScriptableObject inspector
Now ScriptableObjects + C# events? That's pretty swell
I see
It's a complicated subject. https://course.ccs.neu.edu/cs3650/ssl/TEXT-CD/Content/COD3e/CDSections/CD2.12.pdf
I took a whole class in college about compilers, there's a bunch of steps involved
damm cant they just use if stement if find(//) return 0;
just skip
Does anyone know if you can control Aura Sync or other manufacturers' device colours (sort of like wallpaper engine can) in Unity?
Found no libraries that actually explained how they work
You can do anything you want in Unity, but most likely it will involve either Process.Start to run a separate program, or calling out to a native windows function
A native windows function?
can u read and edit memory in unity?
Reading and editing memory may as well be the entire definition of programming
Someone told me you can't access the memory from unity
They're either dead wrong or they meant something very specific that they didn't explain
Okay so controlling it is possible, but does anyone you have any resources that they could share or something? :)
how old are u? u know so much
You'd have to look up the specific thing you want to control and how its programming interface is set up
31
Oh okay, so there is no universal solution :/ But thank you for helping!
nice! unity says Start is used for Initialization. but "Initialization gives a variable an initial value at the point when it is created" how is it Initialization if u are not giving it value at the point when it is created`?
is num1 created and asigned value before num2?
It's a place to initialize things. Awake actually runs earlier than Start and is probably more appropriate for a field like that one
¯_(ツ)_/¯
what about num1
The thing is Unity has some special stuff like copying serialized values (e.g. ones from the inspector) into fields, which will happen after field initializers run but before Awake or Start run
what about it?
does it run before Awake

