#archived-code-advanced

1 messages · Page 169 of 1

nocturne elm
#

Don't want you to do anything really.. The suggestion and psuedo code is more than sufficient and appreciated

misty glade
#

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.

final steeple
#

As long as it was informative and helpful, I'm happy

#

More knowledge = better programmers = better games

nocturne elm
#

(I should add implementation 'worth it' considerations aside, the discussion was excellent)

#

on the linq perf stuff

misty glade
#

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 🤯

final steeple
#

lmao yeah

undone coral
#

i think it's close

#

i think it's probably making new textures every frame

misty glade
#

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

undone coral
#

because honestly looping through a big grid a bunch of times... doesn't matter

final steeple
#

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

nocturne elm
#

That's all true, but the cpu is getting burned up real good with a naieve implementation

misty glade
#

going back to this 👆 - I think the bottom 2 lines "look" better than the top 8

nocturne elm
#

it does matter

#

(unless that is the gpu texture translation that is incurring the cost)

final steeple
#

Is that code trying to look for a completed mission matching an ID, and then remove it if it exists?

misty glade
#

yeah

compact ingot
misty glade
#

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)

undone coral
#

linq is great

nocturne elm
#

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.

undone coral
#

i develop a lot of games and

nocturne elm
#

but again you know your current project context / scope better than I do

misty glade
#

Note - no profiling subtask. Look at all those glorious "dones" 🙂 🙂 🙂

undone coral
#

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

nocturne elm
#

I suspect this is engineering purist stuff to some degree vs practical reality in a good chunk of situations

undone coral
#

the last time i've had a performance issue, it was vfx graph giant quads with alpha

misty glade
#

Yeah, and also, again these data structures I'm working with (for this feature) are tiny - 4 items

nocturne elm
#

but it doesn't make either opinion wrong, it's all context dependent

compact ingot
#

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).

undone coral
#

where it just needed to paint like 10,000 quads over each other

nocturne elm
#

There's no way I would even consider changing it if the structure will remain that small

final steeple
nocturne elm
#

again unless it's an academic exercise

final steeple
#

Which is completely valid

nocturne elm
#

performance doesn't matter until it does

final steeple
#

There are an innumerable number of situations like that

final steeple
#

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

compact ingot
# proud gust what's the problem with OOP?

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.

nocturne elm
#

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

final steeple
#

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

final steeple
nocturne elm
#

yeah anything to do with pooling and instantiations / destructors is probably worth making performant 10/10x

final steeple
misty glade
#

Sorry, so explain this - whenever you (instead of) Instantiate you grab a gameobject from the container, and same for Destroy?

final steeple
#

The idea is that you never actually call Destroy, you instead call pool.Return(obj)

#

But yes

proud gust
#

Imagine a gun shooting bullets

misty glade
#

aand Rent() instead

final steeple
#

Yeah

misty glade
#

cool

proud gust
#

You dont want to instantiate a bullet every shot

#

So you use object pooling

misty glade
#

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

proud gust
#

indeed

final steeple
nocturne elm
#

I have heard Jason Weimann talk about that concept

#

but not saying that negates the novelty of your library/ solution etc

misty glade
#

Ah I see - the pool has the prefab as a member

nocturne elm
#

was just talking about pooling as a more general concept

final steeple
#

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

misty glade
#

neat

final steeple
#
using (var pool = new GameObjectPool(prefab))
{
    // use pool
}

// pool has now been destroyed
misty glade
#

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

final steeple
#

How does it compare to the built-in BigInteger?

misty glade
#

It's... different

misty glade
#

Probably not as good, but it contains some idle-game-specific stuff like some custom string formats

undone coral
#

there are a lot of people who have issues with this in the idle games community

final steeple
#

There's also the decimal type

#

Which is 128-bit

misty glade
#

this is "arbitrarily large" - ie, it can support any number up to .. uh... well, i can't math this, but it's large

final steeple
#

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.

misty glade
#

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:

#

I think I can currently handle "correct" naming for anything up to 1e999

winter schooner
#

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();
misty glade
#

try the same in postman and see what github says

regal olive
#

How do I use the parent constraint component to make the character not be able to rotate on the x and y axis?

final steeple
#

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

regal olive
#

oh

final steeple
#

If you want to prevent them from rotating at all, then you want RotationConstraint

regal olive
#

Ill look into that

#

eh still doesnt work

winter schooner
misty glade
#

tmr?

#

tomorrow? or something else

proud gust
#

^

misty glade
#

ah

proud gust
#

i guess haha

warm python
#

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

final steeple
#

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 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

warm python
#

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

final steeple
#

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

warm python
#

looks idle to me

final steeple
#

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

warm python
#

k thanks

final steeple
#

Yep, there we go

#

From Joachim himself:

warm python
#

"manually kick off the batched jobs" so how do

final steeple
#

So the queue is only inspected after update

#

JobHandle.ScheduleBatchedJobs() looks like

#

So there is an API to force it

warm python
#

excellent

#

cheers!

final steeple
#

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

warm python
#

all good, this is exactly what I needed I believne

final steeple
#

I didn't know about this API either, so it's handy to know

#

So... thanks for asking about it lmao

dusk bone
#

I can answer most questions but I never check outside that channel

warm python
#

didn't know the Job system was considered DOTS

#

since it wasn't a Burst-spcefic question

dusk bone
final steeple
#

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

dusk bone
#

Yea. I do non-critical image processing with a job chain although I really should convert it to a compute shader

undone coral
undone coral
random goblet
#

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'

kindred tusk
#

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.

dusk bone
unkempt nova
random goblet
urban warren
#

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 });
}
plucky laurel
#

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

drifting galleon
#

does anyone have any experience with the new ScriptableRenderPass api that uses RTHandle instead of RenderTargetHandle?

final kindle
#

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.

compact ingot
final kindle
# compact ingot SOs are just serialized and automatically created instances independent of any s...

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.

compact ingot
final kindle
compact ingot
#

Then again you can just have a proxy in a scene to pass the references to a SO

compact ingot
#

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

final kindle
#

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?!

compact ingot
#

It’s just a simple piece of glue code to make SO connect to Scene

#

Fairly unity specific

final kindle
#

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.

urban warren
final steeple
#

Which type are you trying to construct?

urban warren
#

A internal delegate

final steeple
#

If you have a function matching its signature, get the MethodInfo for it and use CreateDelegate with the Type

urban warren
#

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)

final steeple
#

yourDelegate.MethodInfo.CreateDelegate(typeOfExecuteHandler)

#

(this will only work for delegates around static methods, note)

urban warren
livid kraken
#

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

final steeple
#

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"));
}
urban warren
final steeple
#

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)

urban warren
#

Yeah, works for me, thank you!

final steeple
#

No problem

urban warren
#

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?

final steeple
#

You can do object[] array = (object[])Array.CreateInstance(realItemType, count);

urban warren
#

(I then had to iterate over them and assign the elements)

final steeple
#

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

urban warren
final steeple
final steeple
#

I believe you have to do field.SetValue(target, new object[] { array })

urban warren
final steeple
#

Actually no brain fart

#

Yeah lol

urban warren
#

Haha, it is working now 👍

final steeple
#

But anyway, when using CreateInstance it should assign properly

proud gust
#

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

urban warren
final steeple
proud gust
#

What about scriptable objects?

final steeple
#

What about 'em?

#

There's not really anything special you need to do other than clearing static fields

proud gust
#

Are they cleared "normally"?

#

Alright

#

So if I had no static fields, I could switch it w/o any problems?

final steeple
#

Yeah

proud gust
#

Cool

#

Thanks!

final steeple
#

Np!

proud gust
#

And is it enough to disable domain reloading or should I also consider disabling scene reloading?

final steeple
#

You can disable both

#

Domain reloading is the biggest one though

proud gust
#

And static fields with a reference of gameobjects do not need to be cleared right? As they stay the same anyway

final steeple
#

It would be a good idea to still clear them

proud gust
#

How are they reassigned then?

pine bone
#

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]}

final steeple
regal olive
#

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.

sly grove
#

Use the debugger your code is probably still chugging along

livid kraken
regal olive
regal olive
#

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.

hallow elk
#

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

proud gust
#

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

fresh salmon
#

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)

proud gust
#

An action as in UnityAction, that I can assign a callback in the editor to

fresh salmon
#

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

proud gust
#

Yes, sorry for mixing them up, I meant UnityEvent

proud gust
#

But it's alright, I guess I figured out a way

fresh salmon
#

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

proud gust
#

Interesting, though, thanks for sharing

winter schooner
winter schooner
proud gust
#

Then your path must be incorrect

#

Did you follow githubs rest api doc?

winter schooner
#

yes

#

even without file it returns Not Found

proud gust
#

Can you log the complete path before it's sent?

winter schooner
#

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

valid flame
#

How tf do I open a windows form through unity? I was told to use System.Windows.Forms, but it doesn't exist

reef wren
#

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?

valid flame
#

Alternatively, I would like to send a notification through window's notification system

valid flame
proud gust
#

That only tracks collision with your special object

reef wren
reef wren
# humble onyx 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

proud gust
#

why make life easy when there's a complicated way lol

humble onyx
fast falcon
#

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?

reef wren
winter schooner
reef wren
proud gust
misty sierra
#

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.

long ivy
hazy epoch
#

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.

kindred tusk
hazy epoch
tough tulip
#

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()

hazy epoch
kindred tusk
#

Oh, you're talking about the server instance, gotcha

livid talon
#

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)"

compact ingot
languid isle
#

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)

rugged pollen
#

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?

quiet bolt
#

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

fresh salmon
#

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

quiet bolt
#

Ayo I didn’t know that was possible

#

I’ll try that out, thank you so much!

lucid girder
#

Just remember that not all DLLs are cross platform. So if you're developing something cross platform, you might run into issues

quiet bolt
#

yeah true, hence system.windows.form hmm

#

but it works like a charm though

atomic void
#

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

arctic robin
#

For intersecting collisions, should be using triggers or collisions?
Specifically, I want to highlight the closest object being intersected.

regal olive
#

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

lucid girder
#

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

regal olive
lucid girder
#

unsure, I'm not really a guru in any of this xD

regal olive
#

From the profiler, the hardest hitting factors are: Other, Scripts, Physics, and GC, from most to least.

flint sage
#

There's no way to determine what's taking a long time based on the info you gave

sage radish
lucid girder
#

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

regal olive
#

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.

flint sage
#

Don't use dotween if you have that many

regal olive
regal olive
lucid girder
#

might have some helpful code

flint sage
#

Remove that log

regal olive
sage radish
flint sage
#

Also figure out what's doing that allocation and remove it if you can

regal olive
#

Just removing that log made the thing smoother lmao

sage radish
regal olive
#

I'm also scaling up the cells so they fill the space faster xD, taking less cells

#

nah it's still sometimes grinding

sage radish
#

Are these cells on a grid?

regal olive
#

so the simulation lasts a lot longer without grinding down now since I added a null check

sage radish
regal olive
# sage radish 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.

regal olive
regal olive
#

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.

regal olive
#

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.

regal olive
#

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

#

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.

earnest crest
#

Is there a way to wrote own int.myFunction() function without making it a Myfunction(int) format function?

craggy spear
#

I think that would be called an extension, and can be done

flint sage
#

Extension methods yeah

earnest crest
#

ah thnx

regal olive
#

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:

  1. Start with a single cell
  2. 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.
  3. Determine which cells are touching and assign edges as needed.
  4. 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.

tawdry perch
#

Are there any good write ups or guides on AI troop formations?

regal olive
# flint sage Quadtree?

I will get myself some docs and begin reading posthaste. Hopefully there are some implementations I can use readily.

untold moth
final dome
#

did any of you know ml-agents
if yes how do i request a observation on the start of the episode?

final dome
#

thanks

regal olive
# flint sage Quadtree?

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...

regal olive
plucky laurel
#

look into BVH

regal olive
#

Well, its not exactly voxel

regal flax
regal olive
regal flax
#

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

regal olive
flint sage
regal olive
#

I'll try using a quadtree to partition the generated points. Can I run this with instanced meshes?

flint sage
#

Quadtree has nothing to do with meshes, it's just data points

#

What you insert is up to you

hybrid plover
#

can someone explain why this isn't working?

sly grove
#
TransparencyImage.color = transparent ? Color.white : new Color(1, 1, 1, 0);``` is the right way
hybrid plover
sly grove
#

(note that I changed your 255s to 1s because color uses 0-1)

hybrid plover
#

Thanks!

idle latch
#

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

sly grove
#

A callback? I don't think it's asynchronous

#
myCam.Render();
// any code here will happen after rendering is completed
idle latch
#

hmm that's not what I'm observing

mellow wolf
#

why wont this move the player

kehfjsubehvsutfgvdghv^%^&@*@%%@^jbfhc

idle latch
#

... not sure I understand what you mean

mellow wolf
#

?

#

i am a pro coderr

#

.5hgjjb9tugjkjhpogukcnkhobcjjuh365476763r6irk;gvnhg

#

script to hack

sly grove
#

<@&502884371011731486> annoying spammer

mellow wolf
#

Sory

#

ill stop

idle latch
#

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

humble leaf
#

!warn 842485498907983903 Don't spam this discord.

thorn flintBOT
#

dynoSuccess Matthew2009#6363 has been warned.

idle latch
#

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)

sly grove
#

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)

idle latch
#

I'm using HDRP (sorry, should have stated that before)

#

so the OnPostRender is gone 😦

sly grove
idle latch
#

awesome! thank you

cold pivot
#

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.)

sly grove
supple crest
#

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.

sly grove
# supple crest What are some practical use cases for Jobs in a non-ECS context? I'm playing aro...

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

supple crest
#

So traditional game loop stuff is unlikely to work well within the context of jobs, outside of ECS?

sly grove
#

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

supple crest
#

It definitely sounds like a tool with a very specific use-case right now

sly grove
#

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

supple crest
#

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

supple crest
sly grove
fast falcon
#

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.

sly grove
#

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

vernal solar
#

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

sly grove
vernal solar
#

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.

sly grove
#

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)
regal olive
tough tulip
#

Its just a work flow change which can help some cases to avoid bloated memory

flint sage
#

Pretty sure you're comparing 2 different things, you can still just reference a prefab without instnatiating it and thus without duplicating memory

tough tulip
final steeple
#

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

flint sage
regal olive
#

Just don't clone lmao

regal olive
civic talon
#

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);
modest sparrow
#

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?

untold moth
modest sparrow
#

OHHHH

#

That actually makes sense yeah

untold moth
#

Could use a main thread dispatcher or similar technique.

modest sparrow
#

I was about to ask if C# had that

untold moth
#

No, but you can look up an implementation on google or make your own.

#

I think there's a decent one on github.

modest sparrow
#

I already have UniTask, do you know if I can use that to aid me?

untold moth
modest sparrow
#

I found one that uses the update function

#

@untold moth thanks! Moving it to the main thread worked 😄

final steeple
#

With this you can just do MainThread.Send or MainThread.Post

#

Using the synchronization context makes things really easy

modest sparrow
#

that looks better than what I found 😄

final steeple
#

I thrive on simplicity picardy

#

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

modest sparrow
#

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
  }
})
final steeple
#

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

modest sparrow
#

oh nice!

final steeple
# modest sparrow 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

fresh salmon
#

Daaaamn that looks nice

modest sparrow
#

does csharp have a bool object?

final steeple
#

Not sure what you mean

modest sparrow
#

class Boolean vs struct bool (or whatever)

final steeple
#

System.Boolean

#

It's a struct

modest sparrow
#

thanks!

#

oh

final steeple
#

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#

modest sparrow
#

but value types aren't considered objects, right?

final steeple
#

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

modest sparrow
#

basically, I can't send or post a bool?

final steeple
#

You can

#
MainThread.Post(state =>
{
    bool value = (bool)state;
}, someBool);
modest sparrow
#

OHHHH

#

Post doesn't use generics

final steeple
#

You could also just capture a bool:

bool someBool = true;

MainThread.Post(_ =>
{
    // you can use someBool here
}, null);
modest sparrow
final steeple
#

and yeah, SynchronizationContext doesn't use generics

modest sparrow
#

time to file PR's

final steeple
#

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

modest sparrow
#

having state be the same type as state, I'd argue that's pretty handy

final steeple
#

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

modest sparrow
#

I see

final steeple
#

You could totally write a generic Send/Post in the MainThread class though

final steeple
#

I could have written MainThread.Post(_ => continuation(), null); but it'd be less efficient

modest sparrow
#

Using the null trick works like a charm btw, thanks!

final steeple
#

np

#

Also for future reference, since it can be confusing

modest sparrow
#

time to file a PR with that as overload

final steeple
#

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"

tough tulip
final steeple
#

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

modest sparrow
#

Oh because Post takes an async func?

final steeple
#

Nah it still takes a synchronous function, it just dispatches it asynchronously

modest sparrow
#

interesting naruhodone

final steeple
#
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

modest sparrow
#

can you elaborate why that difference might matter in a bool => MainThread.Post/Send context?

final steeple
#

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

modest sparrow
#

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)

final steeple
#

Basically it's just a matter of when you need things to complete

modest sparrow
#

so in the context of single expression functions, it doesn't really matter?

final steeple
#

Most of the time, no

modest sparrow
#

thanks for the explanation 😄

final steeple
#

Another example

#

await new ContinueOnMainThread(); just simplifies writing code like that

somber hedge
#

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

final steeple
#

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()
    {
    }
}
somber hedge
#

Oh I had some errors like that it could help me

#

thx

modest sparrow
#

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

cloud crag
#

Hello, how to stop async functions? (when game stops, they do not)

gilded wing
#

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

flint sage
#

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

cloud crag
#

Thank you for answers!

compact ingot
modest sparrow
#

threading issues? couldn't be me

still glade
#

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

craggy spear
still glade
#

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:

craggy spear
#

Right, yeah, that's good. I was gonna suggest the best way would be a spline or something to follow

still glade
#

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

craggy spear
#

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

still glade
#

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

craggy spear
#

You want to look at the block, not use the block rotation

still glade
#

Well i guess i just found a solution 🤔

#

well, gotta have to take my break, i'll try to be back at 1pm

compact ingot
modest sparrow
regal olive
#

Since my DOTween related question went unanswered, what's the best place to ask it?

craggy spear
#

re-link it, I didn't see it.. might be able to help

compact ingot
compact ingot
regal olive
#

so I enable that there?

#

does that switch mean I can leave the pooling to DOTween?

compact ingot
#

your recycle tweens is off

#

so you have to set it explicitly

compact ingot
regal olive
#

do I set autokill to true within the code then?

compact ingot
#

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

regal olive
#

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?

compact ingot
#

it should

#

at least from my understanding

regal olive
#

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.

compact ingot
#

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.

regal olive
#

Okay I got the lifecycle of the germ cell constructs to last for some time in the last run.

compact ingot
#

you can also check the source code... its not that complicated a system

regal olive
#

Okay, I'll give it a shot, although it's really smooth now thanks to the pooling.

cloud crag
#

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

still glade
#

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));
craggy spear
#

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?

still glade
#

I guess it's not possible after trying a few things, could it be that the character model is just on the wrong side?

craggy spear
#

wrong side of..?

still glade
#

Idk maybe its loaded the opposite direction 😅

regal olive
still glade
rotund dagger
#

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

steep robin
#

Hi all, I could not find a specific channel for unit tests, so I hope I can write here

rotund dagger
#

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

steep robin
#

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?

sweet walrus
#

Does anyone know how to change this with script

#

If yes tag me pls

sweet walrus
#

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

modest sparrow
#

what about a bool3?

#

(probably bool6 is better)

#

why would you spend 6 bytes on a single bit thing? 😵‍💫

tulip fox
#

Are there any disadvantages to using terrain tessellation for dynamic LOD?

wintry wind
#

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?

cedar ledge
compact ingot
lyric copper
#

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?

civic talon
#

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.

civic talon
honest hull
#

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)

compact ingot
honest hull
#

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?

dusk bone
honest hull
#

hang on broke something

dusk bone
#

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

honest hull
#

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

dusk bone
#

Jesus. This a full game?

honest hull
#

no

#

custom compute shader based raytracer

dusk bone
#

are you baking the raytrace? Or real time computing?

honest hull
#

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

dusk bone
#

Welp, that's the wonders of debugging. Time to find out why eh.

honest hull
#

ive been trying but memory anything confuses me so much

compact ingot
#

maybe you are accidentially allocating large blocks of memory or copying stuff multiple times without realizing it

honest hull
#

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

dusk bone
#

Oh boy

honest hull
#

this is a compressed wide bounding volume hierarchy for a mesh of 12.7 million total triangles

dusk bone
#

And there's your problem

#

either round that mesh down or cut it apart

#

And please dont be the twitter meme.

honest hull
#

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

dusk bone
#

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.

honest hull
#

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

dusk bone
#

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

honest hull
#

ok so I went into play mode, and memory used on my PC by unity dropped from 22 gigs to 4

dusk bone
#

close unity and reopen, how much memory is it using?

#

if it continuous increases, ya got a memory leak

honest hull
#

it doesnt

#

that I know of at least
again going into play mode calls something that frees up like 18 gigs of ram

dusk bone
#

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.

honest hull
#

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)

pliant ridge
#

Can anyone recommend me tutorials for time loops? like in We Went Back

dusk bone
honest hull
#

How does tasks effect memory use/reservation?

dusk bone
honest hull
#

yes

honest hull
#

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?

final steeple
dusk bone
final steeple
#

Tasks and Jobs serve different purposes, so they're not really comparable

dusk bone
#

Didnt really look too closely at the stack overflow comment chain

sly grove
#

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

final steeple
#

Either way, tasks aren't "unmanaged" in any sense, so either that stack overflow commenter was wrong, or you may have misinterpreted them

final steeple
final steeple
#

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

pliant ridge
# dusk bone Like coding a time loop? Physics rollback?

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.

compact ingot
fast falcon
#

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??

sly grove
fast falcon
#

But why?

sly grove
#

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

fast falcon
sly grove
#

it works with Mesh_Colliders_

#

sure

fast falcon
#

I just want to be able to move a transform based player without clipping through walls or the floor

sly grove
#

use CharacterController

#

it does that for you

fast falcon
#

But I have a bunch of extra stuff I need to add

sly grove
#

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

fast falcon
#

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

sly grove
#

why is it starting on the surface of another collider?

#

that would mean that you clipped into something on the previous frame

fast falcon
#

I have it capsule cast the velocity, then move the distance of the cast

sly grove
#

yep - sounds typical

fast falcon
#

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

sly grove
#

That's why the default CharacterController has a "skin width"

fast falcon
#

How does that work?

sly grove
#

take the distance of the cast

#

and subtract a small amount

fast falcon
#

😐

#

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

sly grove
fast falcon
#

This is stupid

#

I used Physics.ComputePenetration to check for overlap before casting, and it returns no overlap

sly grove
#

maybe the problem is something different then

#

maybe share your code?

untold moth
#

Try drawing debug gizmos to make sure that you cast in the right place and direction.

fast falcon
# sly grove maybe share your code?
float distance = Vector3.Magnitude(direction) * Time.deltaTime;
RaycastHit hit = rigidbody.SweepTestAll(Vector3.Normalize(direction), distance);

distance = hit.distance;

transform.position += Vector3.Normalize(direction) * distance;
plucky laurel
#

i need to know which exact UnityEngine.Object throws serialization depth limit warnings, anyone has a working solution?

flint sage
#

Doesn't it select it if you click on the error?

plucky laurel
#

no

cedar ledge
#

is this ok or is pattern matching a no-no for anything UnityEngine?

cedar ledge
final steeple
#

is null isn't safe with a Unity object

#

You have to do == null

cedar ledge
#

ok thanks

plucky laurel
cedar ledge
#

are you asking why it happens?

#

i would assume it's the inspector itself giving the error

plucky laurel
#

no i asked what i initially asked

cedar ledge
plucky laurel
#

what a json utility? did you read the question?

cedar ledge
#

you asked what's throwing the depth limit warning

#

zombie knows everything maybe they can help you

final steeple
#

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

#
  1. Check if the message begins with "Serialization depth limit"
#
  1. If it does, do Selection.activeObject = context;
#

then whenever you get that error, the editor should select the offending object

flint sage
#

If there's no context passed then that variable will be null

final steeple
#

if they pass a context

plucky laurel
#

Debug.unityLogger is readonly

#

i could inject ofc

flint sage
#

If they pass a context, then selecting the log (in the console) should already select the object

plucky laurel
#

yeah

#

this is so dumb 😄

final steeple
#

you assign unityLogger.logHandler

plucky laurel
#

i mean if you want to do magic youd substitude the default one

final steeple
#

That's exactly what that does

plucky laurel
#

alright, i still think it wont work for the reason Navi said

#

it simply doesnt pass any ctx

final steeple
#

yes, it depends on if they pass a context or not

plucky laurel
#

it should know what it is deserializing right? there must be a serious reason it doesnt have a context?

flint sage
#

Chances are, it's too deep in teh serialization library that it's impossible to find out the gameobject reference from that point

final steeple
#

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

plucky laurel
#

ill try the logger path later

final steeple
#

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

flint sage
#

Ah right, I never bother with that 😛

#

I just use the reference source

austere jewel
#

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

plucky laurel
#

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

austere jewel
#

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 😄

plucky laurel
#

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

austere jewel
#

You could try and see if ISerializationCallbackReceiver is invoked in-between these objects

#

and not just around the whole grouping of them

plucky laurel
#

hm add a logging point? clever

austere jewel
#

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

plucky laurel
#

that will work most likely, thanks

ocean igloo
#

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?

plucky laurel
#

dumb solution - static bool

final steeple
#

It doesn't look like there's an API for what you want, at least from a cursory glance

prime moth
#

can somebody can help me with multiplayer netcode

ocean igloo
#

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

final steeple
#

which package contains the method?

ocean igloo
#

My own... But it is included with git URL so I "can't" edit it locally

final steeple
#

You can clone the repository into the Packages directory

#

Which will allow you to do that

#

So you have Project/Packages/com.whatever.mypackage

ocean igloo
#

..... Besides the point
But I guess I could do some checks if it is in the editor

final steeple
#

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

ocean igloo
#

I know that but I want others to be able to use it

final steeple
#

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

ocean igloo
#

Oh yeah... Or just put it on GH

final steeple
#

I wanna see how the test framework initializes to see if there's a way

plucky laurel
#

this is a valid architectural issue, which unity should resolve

final steeple
#

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

ocean igloo
#

Perfect

#

I'm not afraid of reflection

final steeple
#

I also don't know if that will be set when your init method runs

#

Which load type does it have?

ocean igloo
#

Yeah ....
I think the default

final steeple
#

The default is AfterSceneLoad I think, so that should be fine

ocean igloo
#

Let me check

plucky laurel
#

where you could potentially compile with a define, and strip out the attribute if the define is present

final steeple
#

That's a possibility too

ocean igloo
#

Before scene load

final steeple
#

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

ocean igloo
#

But I was planning on that as wellblobmeltcry

#

Okay thanks for the help. Will look into both

final steeple
#

Good luck, if you find a solution I'm interested in hearing about it

ocean igloo
#

The define and the reflection

gleaming dagger
#

How can I loop through all areas enclosed with wall tiles in my 2d tilemap?

plucky laurel
#

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

gleaming dagger
plucky laurel
#

well, make it not confusing

#

its the most basic interaction you can have with a graph

#

Breadth First Search is basically flood fill

steep robin
#

hi, someone is using "TEST SCENES" in automated tests?

austere jewel
austere jewel
#

You have been told this before. Next time is a warning

serene sparrow
#

Test Framework Error : The type or namespace name 'Core' could not be found. when trying to unity testing

#

why?

#

and how to fix it?

compact ingot
stuck onyx
#

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?

cloud crag
#

How can I fix thatt? I need cancelation token to stop it

final steeple
#

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

cloud crag
#

After I moved Task.Run(.... in start, error has gone but

#

this doesnot work

final steeple
#

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)

cloud crag
#

so, how can I fix that?

#

I want to get textures from server and I also want it to be stopped after game finishes

final steeple
#

Give me a sec and I'll write up an example of one solution you can use

cloud crag
#

thank you

final steeple
#
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();

cloud crag
#

Thank you, I will try that wait

#

SendWebRequest/sendTextureRequest

#

do they need both?

final steeple
#

I'm not sure what you mean

cloud crag
#

Oh, Im wrong

#

nothing

#

It didn't work (if I did it correctly)

final steeple
#

You might want to look at UniTask then, it offers support for this stuff

cloud crag
#

Okay, thank you!

final steeple
cloud crag
#

are these things different from Unity Jobs system?

#

Can I do the same thing with Jobs

#

?

final steeple
#

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

cloud crag
#

VS doesnot recognize namespace I imported.
Closing and opening didnt work

#

what's the problem?

#

Same root folder fixedbut..

reef wren
#

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

fast falcon
#

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);
pliant ridge
#

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

pliant ridge
#

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

sly grove
tough tulip
pliant ridge
#

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.

thick spire
#

Hey guys, I just wanted to ask. What is the exact difference between Singletons and UnityEvents

#

and the difference between UnityEvents and UnityAction

sly grove
umbral trail
#

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)
sly grove
#

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"

thick spire
#

Hmm I see, better check that link out

thick spire
#

architecture

regal olive
#

```c
how does c# know that this is comment // hei have a nice day

thick spire
#

people that that its very powerul

sly grove
#

Now ScriptableObjects + C# events? That's pretty swell

sly grove
regal olive
sly grove
#

no

#

what would "return 0" mean

regal olive
#

just skip

steady stirrup
#

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

sly grove
steady stirrup
#

A native windows function?

regal olive
sly grove
regal olive
sly grove
#

They're either dead wrong or they meant something very specific that they didn't explain

steady stirrup
#

Okay so controlling it is possible, but does anyone you have any resources that they could share or something? :)

regal olive
sly grove
sly grove
steady stirrup
regal olive
# sly grove 31

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?

sly grove
#

It's a place to initialize things. Awake actually runs earlier than Start and is probably more appropriate for a field like that one

#

¯_(ツ)_/¯

regal olive
#

what about num1

sly grove
#

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

sly grove
regal olive
#

does it run before Awake

sly grove
#

the field initializer runs before Awake, yes

#

but so does deserialization