#archived-code-advanced
1 messages · Page 118 of 1
It's 2025, time to learn how to make screenshots https://screenshot.help/
That said, are there no errors in the console? Did the project compile at all?
Is your scene in the build profile scene list of your platform?
Yes sir
Bro Discord is banned in our country
And do you get any errors?
It's a company computer so if I get an SS it will be difficult to transfer it to my phone.
You are printing something about "Task". Is that really a task or do you just call it task? Is the object destroyed when the scene is loaded?
Nope.
It works fine in the editor.
by the way the text changes are not working
textmesh does not change or image slider does not change
I think there is a compile error in Unity 6.
Text changes?
Xx.settext("")
Thats not visible anywhere in the screens.
Again, are you sure, your build scene list for the target platform is set correctly?
confirm that your code is running on the main thread. It's possible your sign in api isn't 1:1 with the editor and runs on a second thread in a build, which would cause LoadScene to throw an exception
would be good, to see, if you just disabled error logs and only get the normal dbeug logs in your console. You can hook into application errors and just print them to a textfield to see, what happens. And for research, could you try to remove the space in the mainmenu 1 name?
I changed its name and tried it on an empty scene.
I will look at the main thread
makes sense
here's another idea, let me try it from a different phone
same
when I tried yesterday, print(“Starting scene loading...”); this was not entering either
StartCoroutine is also not thread safe and would throw. You need to show more context around this method (ideally with a paste site) at this point
yes a threading issue. Your GoogleSignIn.DefaultInstance.SignIn().ContinueWith( line should be using ContinueWithOnMainThread instead
I remember I tried that too. I will try again immediately thank you
also you said it worked in the editor but I don't see how, you're using a mobile API. I assume It's not actually running in the editor and userid isn't blank
for editor is userid "admin"
yes so you're never actually calling this method in the editor, you're calling StartCoroutine(LoadScene2Seconds()); instead and bypassing all the task stuff
otherwise it would have blown up a lot earlier
for local builds you might consider disabling il2cpp and using the mono backend on Android instead; it'll build faster and save you time (disable script profiling as well, if enabled)
this is a very good idea, it will speed up my work thank you very much
worked!
do you have crypto wallet for a coffee gift
no thanks, not necessary
Hello I'm trying to recreate Super Monkey Ball Controller. In my first iteration I was rotating the level based on its pivot point but it's wrong.
In Super Monkey Ball, the level pivot point is the monkey position. I tried with transform.RotateAroundbut I need a better control over the rotation not just adding degrees.
Do you have any idea ?
What do you mean by better control over the rotation? You have total control over the rotation already
I would calculate the entire transform matrix for the world every frame (or every physics update, really)
rather than trying to modify the transform matrix from the last frame
that sounds much more annoying
You could also just tilt the camera, change the gravity vector and use a custom skybox shader that ignores the tilt.
hi
is there anyone
i have asked to help about ScriptableObject and i have that error again
so the game cant recognise it
so i cant clone styles to car
What error?
you need to explain your problem if you want help
yes
i have writed this too see what error is and it give me this errors code:
public static bool StyleIsBought(LockedContent obj, int index)
{
if (obj == null)
{
Debug.LogError("LockedContent obj is null");
return false;
}
if (obj.Car == null)
{
Debug.LogError("Car is null in LockedContent");
return false;
}
if (obj.Car.AvailibleStyles == null || index < 0 || index >= obj.Car.AvailibleStyles.Count)
{
Debug.LogError("AvailibleStyles is null or index is out of range");
return false;
}
if (obj.Car.AvailibleStyles[index]?.Styles == null)
{
Debug.LogError("Styles is null at index " + index);
return false;
}
return PlayerPrefs.HasKey(string.Format("{0}_{1}", obj.Car.AvailibleStyles[index].Styles.name, C.Bought));
}
error:Car is null in LockedContent, ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
NullReferenceException: Object reference not set to an instance of an object
Car is scriptableobject
This is a question for #💻┃code-beginner
The fact that you don't understand what the error means proves that this is a beginner question
This is an extremely basic error
You've struggled with understanding arrays for one year and think this automatically an advanced issue? 🤦♂️
.\
A month is just as bad
dont comment it if you cant help i dont need any judgement from anyone
I'd be willing to help if you stopped with this arrogance
ok
this
if (obj.Car.AvailibleStyles == null index < 0 index >= obj.Car.AvailibleStyles.Count)
is not even close to C# syntax, so how can this be an advanced question?
They're using || in there, but it's unformatted code so it's changing it to spoiler tags.
But also this is definitely not an advanced coding issue. #💻┃code-beginner. The channels are not for the kinds of people who can help you, but for the kinds of questions being asked.
So I made a little mistake here 😆
Part of the design of C# source generators is that the output of C# source generators is completely invisible to other C# source generators.
Guess what MessagePack uses to make serializers for your MessagePack annotated C# types?
If you said "also Roslyn source generators", you would be completely correct!
Notice there are not generated formatter classes here for my generated companion types 😭
can you not reference one source generator from another?
It's looking like MessagePack might be out for this project. On the bright side these generated objects are completely dumb POCOs so it will be easy to swap in another serializer. The question now is... which one? For the moment just playing around with Newtonsoft but it's quite slowww. And MessagePack can't handle serialization without a formatter in IL2CPP because there's no Reflection.Emit which is what it would use to generate formatters on the fly at runtime
you pretty explicitly cannot 😢 https://github.com/dotnet/roslyn/discussions/48358
I'm trying out System.Text.Json, and it's looking good
there's also a new Unity package for serialization: https://docs.unity3d.com/Packages/com.unity.serialization@3.1/manual/index.html
not sure about the best options for binary though
yeah. makes sense
May I dm you?
I was originally thinking of an ultrafast binary serializer (hence the Messagepack exploration) just for performance/user experience reasons (I LOVE when games are super snappy when it comes to saving and loading), but I also see the appeal of allowing users to modify save files etc. THere's a nonzero chance I'll make a setting in the menu somewhere to switch between binary and json formatters 😆
sure
I use STJ in my project, but I've never benchmarked it in Unity 🤔
well, when you pick json performance is not priority anymore 😄 so I guess any of the popular frameworks are fine
how much time is taken up by the serializer in your typical save/load operation?
don't know about typical, but I've done some performance comparisons over various objects used in a unity game and json serialization takes approximately 3 x the time required by binary serialization
i was just wondering, percentage wise, if that even matters relative to other things going on during save/load in typical projects
probably depends on the project but a couple of gameobject instantiations could potentially make any serializer gains irrelevant
I guess that depends on the mechanics, I recently had someone wanting to implement a replay mechanic and with json it was just not feasible but with binary serialization it was
thats more of a streaming situation?
no, just the ability to save, for example, every fixed update without noticing a drop in fps
i would call that streaming 😉
I would call streaming replay without control, this is actually replaying the gameplay from data
continuously serializing data in memory as a binary stream each fixed update and periodically dumping it to disk would be performance efficent
but how are you going to deserialize, serializing is easy, deserializing sensibly is the hard part
as long as it is in memory its not a problem, not sure what the goal is, but just avoid write/read calls to disk
love to see you try to write a proof of concept of that approach
I wonder if you could approach it like video compression
Store an "I-frame" (a full game snapshot) every few seconds, then store "P-frames" (just the inputs) very rapidly
You can reconstruct any game state by rewinding to the most recent snapshot and then simulating the game from there
thats how event-databases work, also how git works
Should I use a global pool or a specialized pool for each weapon? Imagine if I have 10 different weapons in the scene, all shooting different types of projectiles, missiles, lasers etc. Should each weapon itself have its own pool or should I use one big pool for all bullet types?
I would use one pool per projectile type
That is the conclusion I came to, just not sure about if the overhead is big
the beauty of a pool is that it uses basically no memory until it's needed
The disdvantage is that once elements in the pool are allocated, they generally stick around until you manually dispose of them
so if you have, for aexample, a big firefight happen, with lots of projectiles, and the pool gets large, and then the fight stops, the pools will remain full of objects taking up memory until you manually dispose them.
its generally a good idea to make budgets for your game's systems and not allocate dynamically so you don't run out of memory unexpectedly
growing pools without a hard limit should be avoided (they can easily run away). In many cases prewarming them to decent size offers the best UX.
That would work for me, I have a combat scene that I just get rid off after the combat is over
Sorry - maybe this is an obvious question, but with MessagePack I've always used their ahead of time compiler/sg because IL2CPP was out for one of my platforms anyway.. (Android IIRC?) Was that not an option for you? I always did a post-build message pack generation on my "shared" DLL projects (which I used for the POCOs between the server and unity projects)
SGs are a bit above my head - I tried to dabble in them a while back, along with a custom linter.. and gave up because it wasn't giving me the dopamine hit in time for me to stick with it 😛
The AOT compilation is only possible because they use source generators to generate serializers for your types
That's specifically the part that won't work for me because the types I want to serialize are generated by my own source generator
If I have empty animation curves in my Animation Clip (definition: if curve has only two keys and they are equal, then this curve is empty), is there a way to remove them from animation clip asset, maybe via script somehow? I didn't find any information, how to get curves from anim clip in script, maybe I am missing something or asking a wrong question?
if curve has only two keys and they are equal, then this curve is empty
the condition here would just mean that the start and end values are the same. even if that's the case that doesn't guarantee that the value doesn't change at all
are you sure that's the definition you want?
yes, I am sure about that. I've spend a lot of time cleaning animations from this type of curves. Why? When you export model from blender (FBX), it will automatically fill not used curves with two identical keyframes, this prevents unity from properly "blending" animation clips with animation layers
just to be clear, im not talking about false negatives, im talking about false positives
this kind of animation curve fits your definition of "empty", so if you're not actually looking at the curve, but just its endpoints, then you could end up removing actual animation data
nah, they are really empty. Thanks for warning though, but now I am just looking for a way to get curve from clip, see it's points, and if needed, remove it.
I think just additional check the tans of points will prevent removing actual anim data
hmm, looks like it, I will try to use it, give me a minute
i guess you would do
GetCurveBindings to get all the float bindings
GetObjectReferenceCurveBindings to get the object bindings -> GetObjectReferenceCurve to get the keyframes, which... is undocumented..?
Yeah, I think Animation Utility is what I need, it has all needed functions. Thank you!
also SetCurve with a null curve removes it
You also might just want https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AnimationClip.SetCurve.html
oops, i somehow didn't see the last message
Oh, that's neat
I've been generating a ton of animation clips via script recently
(for VRChat purposes)
To set, yeah, but I also needed a way to see keys of the curve that I want to remove
ah, yes, and you have to use AnimationUtility to get the curves
I don't fully understand the distinciton between editor curves and regular curves right now
Unity internally combines position curves, scale curves, and rotation curves. When curves are combined, keyframes are set at the union of all keyframes points. In the Editor AnimationClip, you can specify special editor curves that are not combined and allows the user to edit curves in a more intuitive way.
Same
so I guess that the editor curve is what is presented in the animation window
and then you actually get more keyframes than that
if you set X at t=0 and Y at t=1, I guess you get keyframes at both times for the non-editor curves
what is the effect you are trying to achieve?
If I understand right, you can set layers in Animator controller to play animations "on top of each other". For example character walks, and if you interact with it, it will play face animation not stopping it's movement animation, face animation will just overwrite curves for some bones on top of moving animation. Or for example I have a robot, that should approach the player, but also look at him, turning it's head, and I can't turn the head via script if there is those "empty" curves in clip
are you saying you want a way to have the robot be able to do two animations at once, like walking and interacting with the player meaning... like a gesture?
and you also want to be able to animate the robot looking at something while also walking, for example?
basically, yes
what would you say is your experience level with animation
with animation components or animating the models?
for first, not much. For second, none at all, all models and animations are being made by our 3d modeller
creating a rig, understanding ik, and the approaches to solve problems like the one you are describing using either unity or cinema tools like maya
gotchya
well generally if you have another person rigging your character for you, you are supposed to use IK to solve things like looking and interacting; and animation layers to solve things like having a separate facial state from body state.
the humanoid avatar is similar to the humanik solution in maya
i am pretty sure they are totally compatible? i haven't done this using unity 6
you're not supposed to programmatically manipulate the animation curves
if you are doing that, you are going to end up reinventing IK
and suffer lots of other issues
does that make sense?
i think this can sound way more intimidating than it actually is. one cheat you can do is upload gnomon workshop videos about this to Gemini, and then ask it about the content.
you can also reject my advice and continue down your path but it is unfortunately not viable
the way animation works is based on a bunch of conventions/traditions
but i don't know though, i've just done feature animation and make games lol
there are also asset store assets that are more opinionated about how the character should be rigged, and solve a lot of problems for you
the alternative system is something called motion matching, and there is also a high quality asset store asset to achieve this
actually, yes, but this kinda isn't the case. Before making actual characters we've experimented and learned about animator controller and animating in blender, and the problem we've encountered is actually with the blender, because it creates a lot of empty curves for all of the bones, even if they are not used. This prevents animations from being layered properly, empty curves of one animation overwrites non-empty curves on lower level. We will eventually get our hand on fixing this in blender, but in simple words, we don't have that much time to do this with our 3d modeller, just because he is 15 yo and got exams soon, so for temporary solution we've decided to hand this to me, since I can write script in unity to clean all unused curves
i am pretty sure there is going to be a good solution to this
it isn't viable to write code to clean the curves and stuff. it's too much of a waste of time
how many animation clips have been authored?
like how many animations are you trying to deal with
for example, a walk, attack and idle animation?
that's "3"
i'm pretty confident you can clean empty curves when exporting from blender. you definitely can when exporting from maya
we've got three simple animations: walk, put hands down and put them up, but it's just now. Today modeller finished another model with much more complicated rig that will have a lot more animations (10-20) and almost all the time there will be about 2-3 of them layered on top of each other, so this blender shenanigan becomes a real problem
we are pretty sure too, but again, we don't have a lot of time and all of us are still going to school every morning, so I'm pretty sure that the problem is very simple, we're just blind. And also, our 3d modeller tried to install Better FBX Exporter, but it just kept crashing the blender, maybe if we fix this, this addon will give us what we need
hmm... i guess when you are working with the modeler, it's essential that they do the right stuff for you
so one thing we are doing is trying to describe the actual problem. then you can at least google around for a solution. it sounds like you've tried
can you try
Export with Correct Settings:
When exporting to FBX, ensure that only the necessary objects and animations are selected.
In the export settings, under the "Bake Animation" section, enable "NLA Strips" and "All Actions" to ensure all relevant animations are included.
Set the "Simplify" value to 0 to prevent Blender from adding unnecessary keyframes during export.
do you have blender open right now with the proper stuff?
well, yeah, but hey, we don't have money (well, we do have a Patreon and stuff, but it brought us less than ten dollars), official employment, registered company, time and other essential stuff, only the steam page and a few social media accounts, and we are basically friends, so there is no blame for such stuff
no, I don't have the projects, but we will surely try this and I will write back to you later when we will try you solution! Thanks for trying to help me and our collective!
hello team, i have this image (province map from eu4) and im trying to make provinces i can click. ive come to a solution using marching squares but im kind of stuck now.... i want to have a map of the edges of provinces (the border of 2 colours) by the targeted color WITHOUT reading over the whole image file (since thats taking forever for even a single province). any help/advice would be appreciated
void GenerateProvince(Texture2D colourImage, Color32 target)
{
Dictionary<KeyValuePair<int, int>, int> pixelAreaOccupation = new Dictionary<KeyValuePair<int, int>, int>();
for (int x = 0; x < colourImage.width; x++)
{
for (int y = 0; y < colourImage.height; y++)
{
if (colourImage.GetPixel(x, y) == target)
{
pixelAreaOccupation.Add(new KeyValuePair<int, int>(x,y) , 1);
}
else
{
pixelAreaOccupation.Add(new KeyValuePair<int, int>(x, y), 0);
}
}
}
}
current code (trying to get a pos-1/0 map but its alwful slow since the image is like 5000x2000
You want the edges of this image?
Is there a dead space color to the image?
Such as "unused" pixels which aren't a part of the used content?
i want the edges of the individual colors (theyre all a different code)
I would scan row by row, jumping by some fraction of the minimum area height looking for where the area might be.
Then I would spread out from the found pixel once 1 was found.
At minimum you skip a lot of pixels in this naive approach.
Ideally though, I would do this in an editor script and pre-build this data.
I would have a scriptable object which has a list of all territories where the key is the color and each entry would have a pixel offset.
Then I would be able to scan a much smaller list of territories instead of scanning through 10 million pixels.
Or at least then I would have a pixel coordinate per territory which I could scan at runtime if this territory map changes.
A starting point to do a "growing search" which continues growing pixel by pixel to all neighbors which match the territory color.
void GenerateProvince(Texture2D colourImage, Color32 target)
{
Vector2 firstPixelOfTarget = new Vector2(0, 0);
Dictionary<Vector2, int> pixelAreaOccupation = new Dictionary<Vector2, int>();
for (int x = 0; x < colourImage.width; x++)
{
for (int y = 0; y < colourImage.height; y++)
{
if (colourImage.GetPixel(x, y) == target)
{
firstPixelOfTarget = new Vector2(x, y);
}
}
}
// check north
if (firstPixelOfTarget.y + 1 < colourImage.height)
{
if (colourImage.GetPixel((int)firstPixelOfTarget.x, (int)firstPixelOfTarget.y + 1) == target)
{
pixelAreaOccupation.Add(new Vector2((int)firstPixelOfTarget.x, (int)firstPixelOfTarget.y + 1), 1);
}
}
// check south
if (firstPixelOfTarget.y - 1 >= 0)
{
if (colourImage.GetPixel((int)firstPixelOfTarget.x, (int)firstPixelOfTarget.y - 1) == target)
{
pixelAreaOccupation.Add(new Vector2((int)firstPixelOfTarget.x, (int)firstPixelOfTarget.y - 1), 1);
}
}
// check east
if (firstPixelOfTarget.x + 1 < colourImage.width)
{
if (colourImage.GetPixel((int)firstPixelOfTarget.x + 1, (int)firstPixelOfTarget.y) == target)
{
pixelAreaOccupation.Add(new Vector2((int)firstPixelOfTarget.x + 1, (int)firstPixelOfTarget.y), 1);
}
}
// check west
if (firstPixelOfTarget.x - 1 >= 0)
{
if (colourImage.GetPixel((int)firstPixelOfTarget.x - 1, (int)firstPixelOfTarget.y) == target)
{
pixelAreaOccupation.Add(new Vector2((int)firstPixelOfTarget.x - 1, (int)firstPixelOfTarget.y), 1);
}
}
}
so i quickly assembled this. and it loads when i play, in theory i have a map of vector2 + 1's, what would be best way to visualize this?
i dont even need the dict, just a list of vector2
You're going to need to stop scanning the entire map once you find a single pixel of the desired target color. After this you would grow the selection until all adjacent pixels are found.
As for visualization, I don't know enough and it's outside of the scope of the original question.
true
And as mentioned, I would precaculate the regions before runtime unless this is dynamic. But in either case I wouldn't work with image data in either case for a full implementation of whatever you're doing.
I would have the regions as individual data sets which can be scanned through in a fraction of the time.
the list of, presumably, roughly 200 territories would be much faster to iterate than the 10 million pixels in the source image.
that is true
The method used to precalculate those territories is irrelevant if it can be done before the game runs
are you suggesting manually making these regions?
I'm suggesting you could preprocess the image at design time generating a data set which is more conventient to work with.
You could write an editor tool which can take a source image and output a ScriptableObject derived type which has all territories as datum in a list.
Those territory entries could have their bounds within the original image, their target color, whatever.
that does sound quite handy
Each entry could have an array of the territory pixels, an offset where this block of pixels originates from in the original map, etc.
Whatever is convenient for your needs.
But I wouldn't work with a raw image in this case unless I had no other choice, in which case I would preprocess it once if possible at runtime.
i see, tho, if i may ask, do you know how to work with coding shaders
since i already have a mapping of Province Id's and their respective target colour (which will be the base of all data driven logic) so all of what searching for is to visually show the provinces
and i thought going for marching squares / meshes would be feasible
It still sounds like you need to precalculate those regions (you mentioned it being slow), and after that it sounds like you need to generate geometry for the regions.
yeah
You'd need to look at 2d hull generation algorithms.
This would be my first thought.
Someone else might have a better idea/approach.
Personally though, if this is a 2d map and you've already preprocessed the data to find each territory, you have map of each of the regions.
Could just generate an image per territory and render each one on an appropriate quad with a texture generated from the pixel data.
didnt think of that before
Hopefully useful. Good luck.
thanks alot
An alternative algorithm, btw, is to not seek a target pixel color.
You already have to iterate the whole map per territory in what you showed.
Instead perhaps iterate the whole map, and generate a bucket for each unique color found.
Then just keep adding to the buckets until finished.
You iterate it once, instead of hundreds of times.
After that you have a map of territories to iterate (a couple hundred) to find a given territory, and not 10 million pixels.
this is whats happening for the definitions
Yes.
If you were to have each Procince have a list of pixels then you would have subdivided the whole map into regions.
Each time you find a pixel which is already matching a key in ProvinceDef then you add that pixel to the province.
Then you know every pixel belonging to each province.
You can take these lists of pixels and create whatever you want with it for display.
I'm dying of cringe can someone help me fr? #💻┃code-beginner message
Dictionary(Color32, List<Vector3Int>>
I'd just have a Dictionary<Vector2Int> in each Province instance as we don't care internally about the color.
Er... derp
List<Vector2Int>
hm, Dictionary requires a key and value
Then later I would probably generate a texture and store an origin relative to the source map coordinate system.
still going to need a way of identifying the province
so as I said, only split up
Just a bit different, yep.
why not, great way to get the mouse over without colliders or some such
You wouldn't need it in the end. If you generate texture, an appropriately sized quad, for each of the provinces, you can raycast all then do a sub region check to see if your pixel coordinate falls into the province or is in dead space within the bounds.
or if he generated a hull (mesh) you don't even need that check.
You just rely on raycasts to tell you what province you're in.
Lots of options.
Your thinking works too I'm sure.
so why not just do a mouse over and check the colour that the mouse is over?
He wanted to be able to do more interesting rendering too.
So it'd be conventient to have the per province data in either case.
This is just how I thought about it based on his descriptions.
@simple bobcat Consider what @upbeat path has said here as well, it's an interesting approach.
You could have a shader which just acts as a map where you decide how each pixel is to be rendered if the color in the sampled "map" texture matches the color of the province you're interested in.
Playing a bit of catchup but sounds like you basically want a reverse-bucket-fill? Assuming all the borders of one 'colour' are guaranteed to be only in one place
Sounds correct. It really depends on his needs.
tbh, to make it efficient, I'd throw a Bounds into the mix depending on the kind of data interaction required
I think I mentioned generating a bounds per region when you fill the buckets.
But maybe not.
You'd want it for appropriately positioning the quads if you generated a texture per region and "rebuilt" the map.
They may not need any of this though if all they wanted to do was render the hovered region differently.
not just that but to use for a narrowing down process if you needed to ask which Province is x,y,z a part of
Your suggestion of just sampling the color in that map based on hover and rendering differently based on sampled color could cover a lot of cases.
Much simpler too.
You'd just need to keep track of the key pixel colors.
Could allow for conquering territories too if you group territories.
Lots of stuff.
👍
the interacting was already implemented 😼
👍
idk how "interesting rendering" materializes but i just try to find out provinces with borders. 🥹
like, for more detail or whatever. i dont need to interact with the visuals itself.
tho
copying a province looks promising
by color/id
though i also found this video
In this series, I will talk about how to implement the area movement mechanism, which is used by many board games and popular Paradox grand strategy games, in Unity. The first video will address the most subtle part, pixel shader based coloring and area selection.
Chapters:
0:00 Introduction
1:04 Edge detection Shader
1:56 White & Black map
1:...
which utilizes shaders
indeed
In a shader, if you have your texture, and you were to sample the adjacent pixels then any time you find adjacent pixel color doesn't equal source pixel color you would know it's a border pixel.
im digging more into shaders so
do you need to generate it dynamically?
thats preferable
tho
pregenerated is also fine
i just... dont want to make them manually and theyre purely visual
seems relatively simple
I'm using the unity pool namespace for my pooling of enemies. However, when I am prewarming I do
private void PrewarmPool()
{
for (int i = 0; i < initialPoolSize; i++)
{
Health health = healthPool.Get();
Debug.Log($"Prewarmed Health instance: {health.name}");
healthPool.Release(health);
}
Debug.Log($"Total objects in pool after prewarm: {healthPool.CountInactive}");
}
However, the Release function actually removes it from the hierarchy instead of just inactivating. From what I understand this isn't expected behaviour. Any ideas? (if I comment out the Release() function they are definitely being created). Is the unity pool namespace just a bit buggy and not worth using? I'm on 2022.3
Not sure what you’re doing here but the Unity provided pools require you to supply the get/release functions
It's expected if the pool is full, as it says in the documentation
private void Start()
{
healthPool = new ObjectPool<Health>(
CreateHealthInstance,
OnTakeFromPool,
OnReturnToPool,
OnDestroyPoolObject,
true, // Allow the pool to grow beyond max size
initialPoolSize, // Starting pool size
maxPoolSize // Max pool size (limit)
);
PrewarmPool();
}
private void PrewarmPool()
{
for (int i = 0; i < initialPoolSize; i++)
{
Health health = healthPool.Get();
Debug.Log($"Prewarmed Health instance: {health.name}");
healthPool.Release(health);
}
Debug.Log($"Total objects in pool after prewarm: {healthPool.CountInactive}");
Debug.Log($"Max pool size: {maxPoolSize}, Current inactive pool size: {healthPool.CountInactive}");
}
private void OnTakeFromPool(Health health)
{
Debug.Log($"Taking from pool: {health.name}. Pool has {healthPool.CountInactive} inactive objects.");
health.IsPooled = false;
health.gameObject.SetActive(true);
}
private void OnReturnToPool(Health health)
{
Debug.Log($"Returning to pool: {health.name}. Pool has {healthPool.CountInactive} inactive objects.");
health.IsPooled = true;
health.gameObject.SetActive(false);
}
private void OnDestroyPoolObject(Health health)
{
Debug.Log($"Destroying Health object: {health.name}");
Destroy(health.gameObject); // Only destroy when necessary
}```
maxPoolsize is 300 and initialPoolSize is 100
OnReturnToPool(Health health) is being called, but the object is being destroyed anyway
OnDestroyPoolObject(Health health) is not being called
(what happens here is that 100 are created in prewarmpool() and then healthPool.Release(health) just destroys them totally)
How does the stack trace of the OnDestroy method of Health look like?
The way you're prewarming simply won't create a lot of instances,no?
Afaict you only have one instance at a time
I don't see 100 beong created in the prewarm
You would need to get all 100 before releasing any for that to happen, no?
this is interesting I'm currently looking at how to get a stack trace from a function that doesn't have an error in it, I haven't done that before. I just tried:
{
LogStackTrace();
if (!IsPooled && !isPendingRemoval)
{
TriggerPendingRemoval();
}
}
void LogStackTrace()
{
StackTrace stackTrace = new StackTrace();
string stackTraceString = stackTrace.ToString();
UnityEngine.Debug.Log("Stack trace:\n" + stackTraceString);
}```
but it's not writing anything
Debug log already includes a stack trace
also interesting, why not? If I comment out the release() it creates the full 100... I would expect release() to just inactivate the object so that it could later be used hot, as it were?
You neednt do anything special
Yes, and it will be reused on the very next loop iteration
You create one, release it to the pool, and then get that same one again
100 times
I don't think anything is being destroyed here
You're simply only creating one instance
iiiinnnnnteresting this sounds entirely possible
because yes I have 1 "surviving"
Basically the pool is working exactly as intended
To do the prewarming you basically need two loop passes.
First Get 100 times without releasing, then release them all
I generally don't bother with prewarming though unless the instantiate cost has been shown to be particularly high
just testing a fix for this but your reasoning is solid
I'm spawning up to 300 enemies at once which have their own init scripts and stuff so I'd rather front load them
Don't they need to be init-ed when they get pulled from the pool anyway?
Even if they were prewarmed
I think it would be worth profiling to see if prewarming actually has tangible benefits. Because it comes with a definite cost
things like heatlh, position etc. yes, but not a bunch of getcomponents() etc.
I get a noticable game freeze for a couple of frames on first instantiation
in editor anyway
Of a single object? Or during the prewarm
If I have a script that spawns 100 or whatever enemies during runtime I get a momentary pause (without pooling. it is instant when pooled - using a different method I've abandoned)
Does that ever actually happen? 100 at once?
The prewarm is guaranteed to do that
yeah, the idea is that prewarm happens before you even experience anything, and have no frame of reference to see a stutter
Given an arbitrary y = f(x), what's an algorithm that can be used to rasterize it such that it doesn't look horribly aliased? Eg I have an arbitrary f(t) where it gives a player's performance at time t, I'd like to plot it as a graph.
wouldn't it just be smoothing at the boundary?
something something cubic Hermite splines
You need both values and derivatives, but you can just approximate the derivative
Ah, but that's not the issue -- this is about drawing a line or filling in the space under a line, right?
Yeah, filling under the line.
In that case, you might be interested in something like the Gupta and Sproull algorithm to draw a nice anti-aliased line.
You'd completely fill in all pixels beneath the line afterwards
I haven't actually implemented that one before. I've only done Bresenham's line algorithm (to pick targets for a line-shaped attack)
and that one is not anti-aliased
Yeah I've looked into Bresenham and the derivates that support anti aliasing, but they are designed for drawing a line from P1 to P2, not for any arbitrary function.
Can you not just do linear interpolation between each point?
I guess not if you want to do something fancier like this :p
Well kind of, I was thinking to treat "drawing the column x = 4" as "drawing line P(3.5, f(3.5)) to P(4.5, f(4.5))"
And apply whatever anti aliased line drawing algorithm to it.
But I feel like there might be an established way to do it out there.
What is a good way to ensure I only have 1 scriptableobject in the project of a type. For example config files?
dont make more than one, they do not create themselves
😄
actually, if you are using a menuitem you can disable them if, for example, an object of type exists
I am using the right click menu. I would be satisfied with just logging an error if it already exists in the project and returning
so you are using menu items
Right, asset menu I guess it's called, CreateAssetMenu
ok, here is some example code
[MenuItem("Tools/Save for Unity/Manage Script Optimisation", false, 2)]
public static void ShowWindow()
{
// Open window
}
[MenuItem("Tools/Save for Unity/Manage Script Optimisation", true, 2)]
static bool SourceGen() { return Save.roslyn != null; };
note how both options have the same MenuItem, one with true and one with false
the first version will be used if the second returns true
if the second returns false then the menu item is disabled
That is for the top menu? It does not seem like CreateAssetMenu has the same functionality?
[CreateAssetMenu(
fileName = "DatabasesConfig",
menuName = "Game/Config/Databases Config",
order = 0
)]
public class DatabasesConfigSO : ScriptableObject
{
public StatDatabaseSO StatDatabase;
}
Yeah, seems that way that's a shame
what are you trying to do
nm got it thanks
i think the chatbot can handle this
PraetorBlue got it
are you saying you want to programmatically control the fills and borders of provinces in a map?
How to encrypt local build asset with a private key?
what's the goal?
make harder for ripper asset tool, I know it's not completely.
Im not sure this is possible unless you say encrypt or sign asset bundles as most assets cannot be loaded at runtime(from some file)
some sprites I am using for SpriteAssset (TMP) need to build locally
er i dont follow but you could decrypt a generic image fine like png/jpg and load that at runtime but it wont be efficient or quick
and the fact that the game needs to be able to decrypt the file makes this kinda pointless as someone who cares enough will bypass this
yeah i also think so
Encrypted assetbundles sounds like a good suggestion though for adding that extra hurdle to dissuade people trying to rip your assets.
If it's sprites, they can just use something like PIX or renderdoc to get the textures right from the GPU I think.
No encryption would help.
Of course it would help, if we're talking about dissuading. Any additional layer of PITA you add will weed out your average script kiddies.
The asset bundle route may be best, i wonder if with a custom provider in addressables would make it easy to integrate 🤔
Help against what? If you need people to not have your assets, then dont put them in a game. All it takes is one person to get it, then they can distribute as needed
I mean, you only need one person to get your assets. Then they're basically in public access.
That is true, I imagined this was to avoid modding.
It's not necessary to be absolutely secure, as long as the thieves get so frustrated that the reward for their efforts will be that pile of assets
I guess it could help a little bit. But there's also the performance overhead to consider and the time/effort/money you gonna spend on implementing it. Probably not worth it for any indie game.
It's really not worth worrying about. Save your time and effort to do something else
First you need to make a game where people would wanna rip the assets in the first place
And then you realize it doesnt matter what you do, as people will rip it anyways
Thank my guys
But if you're dead set on encrypting, just Google it. There seem to be some plugins/assets for unity that do it. Honestly, this is really not an advanced question, unless you need specific advice on implementing it yourself.
At which point you should probably have at least some idea of where to start.
I have encrypted my bundles using AES for the assets route (It's not absolutely secure, but I'm satisfied with it), and I'm looking for ways to encrypt assets locally. I really appreciate everyone's advice.
Have a good day!! 😊
single assets isn't possible unless you can load the asset in from a generic data source at runtime (textures, videos, some models via gltf)
Bundle route is going to be best i think 👍
Question I hope someone here can answer, I'm trying to create a custom Unity Crash Handler to deal with crashes and issues but I don't know how the Unity Player will tell the crash handler that a crash has occurred. I would presume that when playing a Unity project and a crash occurs, the crash handler (if open) would get a call with the details of the crash but how would I know this has happened? I'm using .NET for the handler so It should work. Anyone know how I can do this?
I have found PlayerSettings.enableCrashReportAPI but the docs doesn't provide any information. Is this what I need?
How you manage unhandled exceptions/signals for native code differs per platform. Managed .net exceptions wont cause a crash
I mean that when a Unity project crashes, I want a .NET app to handle the report since the built-in Unity crash handler dosn't mean anything to me
I've found out that Unity runs the crash handler at start of a Unity project, now I just need to know what Unity does with the app when a crash occurs
"unity project"? You mean the editor or builds?
Builds. Sorry for not clarifying
Then check for the platforms you want to support how to configure a crash/sig handler for a process. I presume the editor already has some handling setup for common platforms but im not sure how unity cloud/firebase or others interface with it (or if they implement this on their own)
hopefully some investigation of these can reveal more info
I'll look into it. Thanks!
Best i can find is an example of how to replace handling on android via sigaction() (which would work on linux and maybe mac too)
https://docs.unity3d.com/6000.0/Documentation/Manual/android-handle-crashes.html
what kind of crash do you want to handle? this is on android?
unity's approach is to quickly record crash information when it occurs, given what the platform permits you to do. then, that at the start of your game, it uploads crash reports
both google play and the apple app store provide crash report collection
what are you trying to do in terms of "deal with crashes and issues"?
This is for Windows. All I want is to know if a crash has occured
Look at the log file
Not the best but I'm not looking in memory
did you enable Cloud Diagnostics?
Tried ages ago with a test project but I found the UI and system to be annoying to use
if you use the crash report API, you will only get the reports the next time the game runs
is that what you want?
the game has crashed. so it's not like you get a chance to upload something to the internet from inside the game
"Note: this API currently is available only for iOS targets." is kind of illuminating for what this is meant for
what kind of crashes are you seeing on windows? actual crashes might be quite rare
compared to exceptions
All I want is when my Unity projects crash, a sperate application will be aware of the issue and do some logic about it. I looked a bit before on how to do this but it would mean tapping into the Windows Registry and stuff which I don't want to deal with. So it seams like what I want to do isn't possible which a lot of code
ok trying different angles on the vfx challenge i talked about here. any of yall got any clever ideas i can start hacking at? #✨┃vfx-and-particles message
the fundamental design constraints im working with are this:
- procedural zones with wide variety of theme and structure.
- each zone has 12 altars (procedurally) scattered throughout the zone, players have to unlock each altar to unlock the zone and progress to the next zone
- each zone starts out "impassible" -- originally i was thinking a wall-of-fog type effect, and the unlocking of each altar clears out the wall-of-fog for a radius around the altar (which grants visbility to nearby altars that can then be unlocked
but at this point i just want a super-simple way to implement this so i can prototype the gameplay. i know there are lots of ways to potentially implement this, but im looking for the MVP approach
Have you considered integrating something like the Sentry SDK into your Unity builds to report any crashes? No need to reinvent the wheel then they have built comprehensive tooling and a dashboard for this.
Firebase is pretty good for what is free but sentry can be self hosted. I even made a sourcemod extension to use it for tf2 servers (creators.tf)
hey im looking into building a little multiplayer text-based RPG where the multiplayer functionality is pretty much just a database with shared data between clients.
So far i made a little authentication script with Unity gaming services and im looking to use Cloud Code and Cloud save as well.
I'm slowly chewing through the documentation and some youtube resources but i was wondering about some do's and dont's. For instance, could i just access the player data on login and then save on application quit or is that not reliable?
Can i handle changes in player-specific data like item equips, unequips, item drops, experience, levels, health, etc.. on the client side and then just save? Probably not right?
Do I need every data change to go through the server and then get responses?
Thanks!
I'd save periodically and on player quit. It's reliable though (as long as your app doesn't crash).
If you're saving items on the server - then you're probably gonna wanna do a trusted and untrusted version of the player model. For a game I did in the past, I would let the client have free reign on the player data, and serialize it for networking - send it to the server, where the server would throw away any untrusted data (and re-hydrate the object with the "known" data). Whenever I'd send a player file back to the player, I'd strip out the same.
Every data change can go through the server if that makes sense for you, but it's probably more efficient to create messages for actions (instead of sending the whole player file back and forth every time there's any tiny change) and then just keep the data files in sync on both devices
This is a big architectural task, but mostly because managing data across two brains requires some thought and effort.. It's not complicated per se, but it is a lot of work.. Happy to show you some code examples for my solution if you want.. create a thread here and ping me. @fringe root
Awesome dude, i'll do that tomorrow for sure. That can totally be a great help! Do you have any resource you recommend for learning those nuances? @misty glade
twelve months of staring at a screen and trying to figure it out 🙂
In all seriousness, no, I kinda bumbled my way through it on my own, talked to a lot of industry connections and friendly developers (and this discord). I'm sure I didn't do everything right but what I did come up with worked pretty well.. it made finding cheaters pretty easy too.. literally Day 1 of the app being released we had someone trying to send clearly modified data up to the server (setting things like PlayerLevel=999999999)
Does Unity 6 still have a lot of garbage collection overhead from using reflection methods?
Are you asking if Unity's own code is garbage-heavy, or if using reflection in your own code is?
Reflection in my own code
I'd like to cleanly get a method with a custom attribute on it without garbage collection overhead
I'm working on a library that targets Unity as one of its supported use-cases
yeah depending on the use case, a source generator might be a better option
I think a source generator would be a better option than reflection.
jinx
dammit
lol
Here's an example of what I'm trying to do
[Subscribe(DatagramTypes = typeof(DatagramA), priority = 1)]
public void MyMessageListener(IDatagram datagram)
{
// client code
}
psuedo garbage code
You could totally do this with a source generator, if I understand it properly. You want to put this attribute on a method and have it get called whenever a DatagramA event is published?
yes
Yeah with a source generator you could basically automatically generate code for this class to register itself and that method to the event bus if that attribute is present
.NET Standard 2.1 supports source generators?
The source generator itself must target .NET Standard 2.0 to use it in Unity, but you can use it from any project afaik
Cool, cool. Could you direct me to a good source generator resource so I can get going on that? I'm not familiar on how to implement one
I just did this myself for the first time last week
there's a slight learning curve but now that I'm in the groove of it it's great.
How do I do this in a way where it's completely abstracted away from the client?
Like the client application so it's like reflection magic using source generation?
Reflection is fundamentally garbage-heavy, there's nothing Unity can do to fix that
Or in other words, it's not really Unity's fault -- the current design of the API just requires lots of objects and boxing
There's work underway in .NET to add new APIs (if you know member names statically you can use UnsafeAccessor in modern .NET for example), so things may improve in Unity 7 when CoreCLR is available
But yeah, source generators are usually the better option here anyway
I wouldn't particularly recommend the guide Unity has there because it uses the old ISourceGenerator interface instead of IIncrementalGenerator, so your generator will be subject to a lot of restrictions and will perform quite poorly relative to an incremental one, but the downside is that Unity doesn't support incremental generators out of the box because the C# compiler it ships with is too old, so you have to update it manually for them to work
I have a tool for updating the bundled Roslyn here: https://github.com/DaZombieKiller/UnityRoslynUpdater
But just note that doing this requires modifying your Unity install, so if you aren't comfortable doing that (or requiring it for your project) you're stuck with the old ISourceGenerator API
incremental source generators work in unity 6, and probably 2022. 6 uses code analysis 4.3.1
Oh so they finally updated the in-box one to support them? Nice
I still update Roslyn manually though since I use C# 13 
Howdy folks. So I've got a bit of a Unity 2D performance killer here. My game's UI is organized on its own canvas, ordered to render above the game's tilemaps and sprites and whatnot. It has a render mode of Screen Space, and renders to the Main Camera. The game is a top down RTS style, so I adjust the camera's Orthographic Size for zooming on the map. Unfortunately I've found the act of zooming is causing the entire UI and all its elements to redraw/calculate every frame of the zoom. On mobile this is destroying performance. As a temporary workaround I disable the UI during zooming. But it would be nice to keep it around. I'm just not experienced enough with Unity to understand why it is redrawing every frame during zoom actions, and how to redesign the UI to avoid this performance bottleneck. Any insight would be appreciated!
Does the Ui have any bearing on the objects that are not UI? Like are these map markers or something?
If not, couldn't you render the UI on an overlay camera, which wouldn't need to be zoomed?
The UI consists of some borders, buttons, backgrounds, resources bars and text. That sort of thing.
The reason it's redrawing is because you're changing the camera size which means the positions of the UI objects all need to change to adjust for the new camera settings
:nod: Yeah that makes sense.
If you ever look at a screen space - camera canvas in the scene view, it literally follows the camera around and adjusts to its frustum
I recall when I first set everything up, having it as an Overlay didn't work well. Like, perhaps there was a bug on mobile with elements blocking raycasters and this is how I worked around it. Something...
Well I was mentioning an overlay camera, not switching to an overlay canvas
Oh, the camera itself.
as in - using camera stacking
I'll have to read up on that more, I've not heard the term.
Are you using URP?
Yes.
Thank you for the links!
Ok so I effectively have one camera pointing at the UI, and another pointing at the gameworld, and I can combine them together?
Well the overlay camera (which draws the UI) would draw on top of the base camera
Cloud save architecture
Is there a way to trigger a domain reload through a script?
Thats perfect. Thank you
Can I use strings with jobs/burst?
burst keeps saying my struct must be unmanaged and all it has left is an array of structs containing bools and ints
Does burst hate arrays too?
Managed arrays aren't supported in Burst, because they aren't unmanaged.
I'm not sure what a managed array is
A normal array in C#. T[].
As opposed to NativeArray, which is unmanaged.
I naively thought that converting a function to jobs would be easy
now I don't even think it's possible for me
Just use a native array
is there a way to get the triangles of a particular agent? NavMesh.CalculateTriangulation();
nacmesh baked with nacmeshsurface
The triangulation has the areas property so you can check which area each triangle belongs to, does that help?
I forget how exactly agents are bound to areas
Oh right, agents an Area Mask property in the inspector
So sounds like areas should have everything you need.
You can iterate over the triangles and skip the ones that are in an area that the agent doesn't use
I'm drawing meshes with a CommandBuffer, but I'm running into an issue. I'm trying to change the color on the material between calls to DrawMesh, but only the last color is drawn since the command buffer doesn't get executed till the end. How can I set the color on a material with the CommandBuffer?
I can get it to work with MaterialPropertyBlock, but I'd prefer not to use that
this would require each agent to have its set of areas and each navmesh (1 per agent) to have its navmesh modifier to set the area of their navmesh
it's doable and might work well
This looks like one option but requires using a global color of course which might not work for you...
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rendering.CommandBuffer.SetGlobalColor.html @lofty falcon
Property block is probably the best I think
what are you trying to do?
what is your goal? the chatbots are capable of doing the rote work of rewriting functions into jobs if you really need it
it's procedural, provided what you want to do is supported in the first place
Unfortunately I've found the act of zooming is causing the entire UI and all its elements to redraw/calculate every frame of the zoom.
changing the orthographic size of the camera should not invalidate a screen space overlay canvas. there is some other bug
have you looked at the profiler?
additionally, redrawing the whole UI on a modern mobile device isn't expensive
tilemaps and sprites are not in a canvas. so you only have one canvas. i wouldn't use the words "organized on its own canvas" - i guess, it's the only thing in its own canvas
you are probably doing something else that invalidates the canvas while zooming as a side effect
Id love to see this UI that is soo complex it does this.
Also wouldnt using 2 cameras solve this as you could avoid modifying the "ui only" one?
the UI isn't rendering to a camera at all in screen space overlay
the canvas is in "Screen Space - Camera" mode, hence the problem
" It has a render mode of Screen Space, and renders to the Main Camera." is too vague
i thought you could select the camera it uses
ideally you'd just put it in Overlay mode
If camera stacking doesn't cause a major performance hit, then that sounds fine too
I can understand why screen space camera causes a redraw as i presume it needs to be resized + positioned and thus is all made dirty
Sorry I had gone to sleep, heh. But yes, profiling is showing the entire UI and all its sub elements are being completely recalculated/re-rendered every frame during zoom operations.
Mobile devices are the ones being affected by this detrimentally. Dropping from 30fps down to 10fps during zoom events. As long as I hide the UI during zooming its fine, but I'd prefer not to do that.
The main camera is an orthographic projection camera using the CinemachineBrain. I basically followed a tutorial ages ago to setup the pan and zoom effects on a 2D tilemap and didn't think much of it beyond that.
I'm preparing to try stacking to see how it shapes out.
Maybe you can share the profiling data just to be sure we're on the same page?
In time perhaps. Going to see if stacking fixes it all first.
Voxel terrain generation, I figured out the mesh generation part but I'm having trouble with UVs because nested arrays are not allowed. Also for now it's not running in parallel, is there a way I can call a single job so it runs in parallel and only generate the mesh(on the main thread) when it's ready? Something like: I call the job on frame 1 and when the mesh data is ready on frame 4 I generate the mesh
have you looked at vfx graph at all?
and have you looked at any assets that do this?
No, why?
Hello there!
I have this netcode code:
async Task ConnectThroughLiveService(string sessionName)
{
Debug.Log("ServicesHelper: ConnectThroughLiveService - Starting");
try
{
var options = new SessionOptions()
{
Name = sessionName,
MaxPlayers = 4,
IsPrivate = false,
}.WithDistributedAuthorityNetwork();
m_CurrentSession = await MultiplayerService.Instance.CreateOrJoinSessionAsync(sessionName, options);
}
catch (Exception e)
{
m_ConnectionState = ConnectionState.Disconnected;
Debug.LogError($"ServicesHelper: Failed to connect: {e.Message}");
Debug.LogError($"ServicesHelper: Stack trace: {e.StackTrace}");
throw;
}
}
On PC and Mac m_CurrentSession is assigned succefully, but on WebGL is always null. Can someone help me out?
Funny thing is that the WebGL client still creates or joins a session, but just does not assign value to the m_CurrentSession. And I kinda need that later to take the player offline and such.
PS.: Catch is also never called.
Thanks for any help.
I dont know what platforms ugs supports (and if webgl is included). Does the async function ConnectThroughLiveService() actually complete or is it hanging?
I ask as webgl doesnt support other threads so im not sure if thats causing a problem
Alright, camera stacking fixed the performance issue entirely, and was actually quite simple to implement. Just added another camera of type overlay, and made the UI canvas render to it. Then added that camera to the original camera's stack.
Only caveat, is I liked seeing the UI render in place in the editor where it belongs, floating over the tilemap/sprites. But I have to move it out of view or it'll pick things up I don't want it to. Not sure what the best solution for that is.
At this point, why not just use a screen space overlay camera?
If I am not mistaken, I had that originally. And while it worked fine in Windows, it had many issues on mobile platforms due to raycasting bugs in the 2022 unity release.
I really need to document engine workarounds better going forward, heh.
In any case, it fixes the issue enough that I can move on. Appreciate all the insight. I've moved onto Unity 6 for other work, and am sure everything will turn out differently going forward with it.
glad that fixed it. Not sure what these raycasting bugs are i have worked over many 2022 versions (mobile too) with UI and 2d physics with stuff
Sounds weird. Did you have none ui objects(colliders) on your canvas? Because otherwise it should be working. Ui and physics use separate systems for raycasting.
would it be possible to modify the TMP code to add another custom rich text tag, and then how would i go about checking for that tag in my code and finding out what words are within that tag?
You can modify the mesh as its created so I wonder if you can have it "hide" the open/close tags and then modify the mesh as you want for the actual text.
https://docs.unity3d.com/Packages/com.unity.ugui@3.0/api/TMPro.TextMeshPro.html#TMPro_TextMeshPro_OnPreRenderText
maybe i should explain fully what i am trying, so i am trying to add an addition to my game's dialouge system to add text effects like how games like celeste have them, so i bought this text effect asset and am trying to hotwire a tag system as a separate script because i do not understand the scripts code at all (almost all the variables are random Spanish characters??) by modifying the imputed ForceWord Var (i think that determines which words the effect is given to), i have been trying to make my own tag system, but thought that might be easier to hotwire TextMeshPro's rich text tags instead, so i was wondering how i would do that and then get what words have that tag to put into the ForceWord variable, if that is even possible (sorry for the long message)
best i can think of is reference how something like this impements it: https://github.com/Luca3317/TMPEffects
this is way better than the asset i had, thank u so much
i rememered one that may be better but no idea where that is. Searching github and openupm can find cool stuff!
thank u :)
Building block ability system
Can somebody help me? I've been struggling with this for a while in this pic im trying to determine the red dot points position based on their heigh meaning that the highest point is "left" the one in the middle is obviously middle and the closest to the threspoint which is the blue line respresents "right" this is the start of the song the notes are very close to the threspoint hovewer if we move more forward in the song for example the second image the notes go like really high you now see why im struggling I cannot set an umbral for this and idk any other approach I could go with any ideas?
What is MultiplayerService.Instance.CreateOrJoinSessionAsync? I'm not familiar with it
If this is socket-based then it might be possible that this system uses sockets not supported in a webbrowser.
I would expect an exception however
Either I am too dumb to understand, or you have to rephrase your description, as I do not really get, what you mean with "left" and "right".
So like im trying to make a rythm game and the red dot with the highest Y axis is considered as left and the lowest is considered as right, I have like this grid and I need to assign those red dots to it
I've tried this method but it puts the notes in random places which is not good ```csharp
string DeterminePosition( float spectralFlux )
{
if (spectralFluxSamples.Any())
{
//float maxFlux = spectralFluxSamples.Max( s => s.spectralFlux );
//float threshold1 = maxFlux / 3;
//float threshold2 = 2 * maxFlux / 3;
//if (spectralFlux < threshold1)
// return "left";
//else if (spectralFlux < threshold2)
// return "middle";
//else
// return "right";
var rand = new System.Random();
int randomnumber = rand.Next( 1, 4 );
if (randomnumber == 1)
{
return "left";
}
else if (randomnumber == 2)
{
return "middle";
}
else
{
return "right";
}
}
return string.Empty;
}``` you can see in this vid https://youtu.be/r4f2_VXgcpE
song name is VØJ, Narvent - Memory Reboot
The commented code is more like peak oriented which means that it will try to find the highest peak but it always output "left"
I mean randomness sometimes is not half bad but is not rythm oriented
Im trying to make something like audiosurf which it has this grid kinda thing
So you need a relative distribution based on the highest and the lowest red dot within a certain time span?
Yeha I guess that works but the dots are not consistent
You mean, sometimes your red to y span is from 0-2 and later from 2-20
I mean sometimes the highest can reach 3
whatever 3 means in your case. is that high, low?
so its like a float it can go from 0 to the highest
Im not sure how to explain
Maybe with this you understand ```csharp
public void setPointHeight( Transform point, float height )
{
float displayMultiplier = 0.06f;
point.localPosition = new Vector3( point.localPosition.x, height * displayMultiplier, point.localPosition.z );
}```
Yeh, I get that. But you dont know how to get the highest, because the highest could be at 20 (for example) and only if one note is that high, all other dots would be to the left because of dividing by 3 simply would result in this
Did I get your issue right there?
More or less you are in the right track
Right now im trying this which it finds the highest peak but is not perfect https://paste.ofcode.org/83ZeZrXBYyPDQYckEbb7fb
I mean yeha it finds the highest peak but sometimes there are other dots below which are high as well
As you seem to have a time span in your song based on your visuals, like you can only see 20 at that time (in distance), you can use that as a timespan and calculate your distribution a) based on the height and b) based on the amount of notes being in that height range
Not sure, it is clear, what I mean with the dynamic distribution. So you dont divide only by 3 to get left, middle and right, but you would have a range percentage, that adapts based on the amount of notes, that are in there
Technically this is preproccessed
which means the audio gets processed before playing it
Im not sure I understand maybe you would need to see the code
For the height detection I use this article https://medium.com/giant-scam/algorithmic-beat-mapping-in-unity-real-time-audio-analysis-using-the-unity-api-6e9595823ce4
I use the preproccesed one
Now the problem is organizing the notes accordingly to be "left", "middle", "right"
I do not really care about the process of the song. In the end, you get your array of red dots and their heights. No matter where they come from. And from this array based on its values, you need to distribute them on your 3 visual tracks. And to do so, you can chunk the array into parts like from current note + 20 and take that range to calculate the next note track
So your distribution would always adapt to the next range of heights instead of the whole song for example. And within that range, you need to check, how many of "high" notes are there to basically ease out peaks
I guess what you mean is what it does here like it only displays a certain amount ```csharp
public void updatePlot(List<SpectralFluxInfo> pointInfo, int curIndex = -1) {
if (plotPoints.Count < displayWindowSize - 1)
return;
int numPlotted = 0;
int windowStart = 0;
int windowEnd = 0;
if (curIndex > 0) {
windowStart = Mathf.Max (0, curIndex - displayWindowSize / 2);
windowEnd = Mathf.Min (curIndex + displayWindowSize / 2, pointInfo.Count - 1);
} else {
windowStart = Mathf.Max (0, pointInfo.Count - displayWindowSize - 1);
windowEnd = Mathf.Min (windowStart + displayWindowSize, pointInfo.Count);
}
for (int i = windowStart; i < windowEnd; i++) {
int plotIndex = numPlotted;
numPlotted++;
Transform fluxPoint = plotPoints [plotIndex].Find ("FluxPoint");
Transform threshPoint = plotPoints [plotIndex].Find ("ThreshPoint");
Transform peakPoint = plotPoints [plotIndex].Find ("PeakPoint");
if (pointInfo[i].isPeak) {
setPointHeight (peakPoint, pointInfo [i].spectralFlux);
setPointHeight (fluxPoint, 0f);
} else {
setPointHeight (fluxPoint, pointInfo [i].spectralFlux);
setPointHeight (peakPoint, 0f);
}
setPointHeight (threshPoint, pointInfo [i].threshold);
}
}```
But still this would not work because I proccess the song once
and then the notes move according to the time
But even with the whole song, you should be able to distribute all notes evenly by adapting the percentage of your visual track distribution according to the amount of notes in that range
So if dividing by 3 (your track amount) would end up in
| oooooo | ooo | o |
you can then just shift the division to the left to get something more evenly distributed
| oooo | ooo | ooo |
if you get what I mean
🤔 trying to come up with an example
Right now I have like this```chspar
private IEnumerator HandleEndProccessing( List<SpectralFluxInfo> spectralFluxInfo )
{
if (spectralFluxInfo != null && spectralFluxInfo.Count > 0)
{
for (int i = 0; i < spectralFluxInfo.Count; i++)
{
SetupTarget( i.ToString(), spectralFluxInfo[ i ] );
yield return new WaitForEndOfFrame();
}
FindHighestPeaks();
}
yield return null;
}```
Wait, why do you even consider the height of notes, if you distribute them evenly anyways?
we can use spectralflux is the same thing
the height is based on that
also another thing to consider I wanna add sliders
But to distribute to middle, left or right, you basically just need to add up all height values, divide by 3 and then check against those, right?
This would already consider more notes being low and only one being high
yes check in the list which one is the highest
This is what each note contains csharp public class SpectralFluxInfo { public float time; public float spectralFlux; public float threshold; public float prunedSpectralFlux; public bool isPeak; public string position; public bool isSliderStart; public bool isSliderEnd; public float sliderDuration; } dont mind the position because thats what im trying to fix right now
also the slider didnt test it yet
ispeak determines if a note is above threshold and makes them red
Side note, why are you returning a string here? Why not an enum?
What you mean the position?
I could use an enum but the point is how I determine this position
Sure, but returning hardcoded strings are a huge smell
By all means keep doing it, especially since it doesn't solve the issue. I just don't see why you would do this over an enum
Consider allocation, magic strings, stuff like that
Will take into account
So if you have an array of heights (your note class holding the heights, just for simplicity) like [1,3,6,4,15], then the middle height would be 5,8. Now you would need to take this and get the middle to the highest and lowest to get like the range
1 (Left Track) --- 2,4 (Middle Track) 5,8 ( Middle Track ) 10,4 --- (Right Track) 15
I am sure, there is some mathematical calculation to this, I do not know 😄 But to get the concept of what I meant, it might make it clear (or not) 😉
OKay so what if
for (int i = 0; i < spectralFluxInfo.Count; i++)
{
yield return new WaitForEndOfFrame();
}``` I iterate through the notes and basically check the next note to see if it is the highest also check the note before or something like that?
so we have like 3 notes
Then you will never take into consideration all notes, but only in relation to the previous one. So imagine, you have a note sequence going down. 7,6,5,4,3,2,1,0 based on that, your 7 would be right, 6, middle, 5 left and the rest will run on left
Then I dont understand what you saying xd
maybe a range between 10
Take 10 notes and see the highest of those
Checking the size of the list and checking if doesnt go beyond the list
Ill try to write a simple example. give me a second 😄
Alright cause im getting hella confused
I mean I get your point but im not sure how to implement it
Hope I can make it in time, gotta go in some minutes 😄
No big deal I will come up with something eventually I guess
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ugly, but maybe it explains what I meant. You can add and remove on the fly to the array and see, how things get redistributed with simple calculations. At least something to start off https://paste.mod.gg/apjmjduuoczs/0
A tool for sharing your source code with the world!
Why on the update?
To see the inspector update on runtime 😄
Can I do this from 1 go instead on update?
Because I cannot see inspector this unity version it freezes when debugging
Im using 2022.3.0
Did you add something to the array in inspector?
No I dont touch array in inspector only code
Its just for testing. But I guess, it freezes cause your array is empty. Its a simple and not well build code just to explain. Do not rely on it and hope, there arent any errors 😄
Besides when enabling debug mode in inspector unity bamboozle
No need to enable debug mode in inspector tho
I mean like it dies
On unity 6 it doesnt happen but still laggy as hell
ANyways Ill try to implement your code into mine and test
So I gotta go, but I am sure, you can figure it out. Also realised, the order is flipped, so low values are on right and high on left track, my bad. You can of course call the function instead of putting it in update. Its just for me to test on ispector when adding and changing values in the array
Its okay as if it works its fine
It will at least give you some ideas what you could do with your array 🙂
Alright thx for the help
@midnight violet Hey man im getting this error you forgot something? SetKeys: Invalid input AlphaKey array UnityEngine.StackTraceUtility:ExtractStackTrace () DistributeUs:Update () (at Assets/_ASSETS_/_SCRIPTS_/DistributeUS.cs:43)
Well its not a big of a deal I figure it out for myself the error
I have no idea why but is not detecting any right even tho I flipped them.
What I did is parse the spectralflux as it is csharp if (pointInfo[ i ].spectralFlux > pointInfo[ i ].threshold && DistributeUs.heights.Count < pointInfo.Count) { DistributeUs.GradientHeight gradientHeight = new DistributeUs.GradientHeight(); gradientHeight.height = pointInfo[ i ].spectralFlux; DistributeUs.heights.Add( gradientHeight ); }
Do I need to change any value in your code or all this is automated?
ALso maybe because its on the update it doesnt work properly lemme change that
Nope still same result
What the hell the value is massive thats why it doesnt detect any right.
For example the last value is 30 something ,5 and the rightvalue its like 0,4 something
That is weird 0.3 considered as "left"?
Maybe like I need to round these variables
nope thats even worse
Idk no clue
Okay not sure what I did but now it works 👍
I had to change some values to make it work ```csharp
private void Update()
{
if (heights.Count <= 0 || !proccessdata) return;
heightSum = 0;
heightAverage = 0;
leftAmount = 0;
middleAmount = 0;
rightAmount = 0;
heights.ForEach( h => heightSum += h.height );
heightAverage = heightSum / heights.Count;
float maxHeight = heights.Max( h => h.height );
// Ajustamos los rangos
rightRange = new Vector2( 0, heightAverage * 0.5f );
midRange = new Vector2( heightAverage * 0.5f, heightAverage * 1.5f );
leftRange = new Vector2( heightAverage * 1.5f, maxHeight );
// Actualizamos el gradiente (si es necesario)
UpdateGradient();
heights.ForEach( h =>
{
if (h.height <= rightRange.y)
{
h.track = Track.Right;
rightAmount++;
}
else if (h.height > rightRange.y && h.height <= midRange.y)
{
h.track = Track.Middle;
middleAmount++;
}
else
{
h.track = Track.Left;
leftAmount++;
}
} );
}```
Now I need to implement this mess into the other mess
But first I'll take a break
I am back at the office, but seems like you made it work. You can completely remove the gradient stuff, it was just for visualisation. Great you made it work! And still as you asked, you can also remove the update thing and just make a method with a param of your array and call it. No need to do update at all.
Yes I know its for visualization but it looks cool
a lot of what you want to do makes more sense to do with vfx graph
voxel terrain with vfx graph?
yes
they already have an example of it
you are reinventing vfx graph anyway
right now
can you link to this example?
never heard of it either
Are these arrays of varying sizes, or are they all consistent?
In the latter case, it is very easy to just use a 1D array -- maybe with some methods to perform 2D or 3D indexing
I'm in the middle of implementing that, should be easy enough
Yeah. You'll just get it backwards 4 times in a row 😛
Here's an example from an old project https://paste.myst.rs/9gvg9yis
my chunks store 3D blocks in a 1D array so this shouldn't be as bad
I am unable to find this.
ah, thanks! google was failing me
either way I got the mesh generator working and it's running way better compared to the version without burst and jobs
nice (:
just make sure you don't log 3 million times per frame in a job
it's a hilarious experience
Okay but it’s worth looking at the example
Also I think there are assets to do this stuff
Im trying to make a simulated programming language but im having trouble figuring out how to handle a print command. I want the user to be able to type some combination of text and variables e.g(something like: print("Words" + variable)) and have it function like the c# print commands. I cant figure out a good way to split up the string and replace any variable names with the respective numbers, then stitch it all back together to be printed. Any ideas?
Oh boy!
You're about to learn about parsers
you can probably use something like ANTLR to generate the actual parsing code. You'd still need to write an interpreter that can understand the resulting parse tree, of course
maybe you just want to use Lua? (:
regex
probably the easiest way would be to divide the command by spaces into an array and check if the first element matches any command, then use the arguments for that
so something like print a is divided into print and a, the first element is print so you execute the print function
(but it won't work in general for any non-trivial programming language)
i had considered that but i sadly cant use the .split command due to the user string possibly containing the splitting char
yeah, get that sort of idea out of your mind -- it will not work for even very basic languages
Depends on how serious you want to take the "making a programming language" part. If you are serious about it, I can recommend https://craftinginterpreters.com
It's an enlightening journey!
I wrote a Scheme interpreter in Scheme (how silly!) in college, and I taught students about parsing in grad school
so far ive been working out references but i do have basic variables, mathmatical expressions ,loops, and if statments working
A programming language isn't something you just "make" in an afternoon, unless you are using something like ANTLR mentioned above (at that point ANTLR is making the language for you), it's far more involved than just splitting strings.
Even then, that's just the parser
You still have to implement the interpreter
hey look!
oh yea i know making a real language is a ton of work, what im making is not really a whole language just a basic scripting language for a game im making
Question off the top of my head without really understanding your code/what you want your implementation to be, but, could you like, make a dictionary where all the keys are the variables the player has, then use string.replace? So like, when the user sends a command, you could check if the string contains anything that's a key from the dictionary, and if so, replace that instance with the given key's value? Just spitballing here 🤔
I do have a string, float dictionary for playermade variables, the problem with just finding instances and replacing them is that because the user can type both variables and strings a replace call would replace the variable name anywhere it shows up even if the user wants it to be a string and puts in in quotes
You really want a parser that parses the code into AST before doing execution like resolving variable values.
Maybe you could make the system require the player to use a Tag of some kind when he wants to indicate he means a variable. Like [], so like [var001]. Maybe you could implement that to help the system distinguish? These are fun questions
they would distinguish by putting it in quotes, the thing is i dont think you can filter the replace command to find only cases where its not in quotations
In essence, this is basically a simulated gameplay mechanic right, so I'm thinking about this as basically a case of handling complex user input, not an actual language im guessing
pretty much
I would really recommend going through the Crafting Interpreters book here, it's free. The first part of the book goes through a parser and a tree walk interpreter, which is the simplest kind. You can skip over the latter half of bytecode interpreter if you don't care about performance. You can skim through the first part in an afternoon and get an idea of how programming languages are actually made, instead of trying to invent your own solution that probably has tons of problems.
There are so many string method's and things you can do.. I always tell myself I'm going to learn more about it hehe. I mean, you could like, split the string into substrings on the space character (' '), then for each of those substrings, check if the substring begins with [ and ends with ] (in my tag system), then if so, we know that substring is a variable
I did a few of these, and when the syntax gets complex it becomes unusable lol
There's StringReader which allows you to scan a string sequentially, and you have full control here
That solution wouldn't even work for print("A text with spaces and] [brackets] in it")
Crafting Interpreters is really good btw, recommend
yea thats the problem i was thinking about
Why would it not work?
Anything else will wind up being a hack that falls apart very quickly
Yeah hence why we recommend you to read the book, this is more or less a solved problem and see how parsers properly deal with this.
[brackets] would be replaced in the text even though it's not meant to. If you bend the rule and say "yes in my language it will always be replaced that's how it's supposed to work" then there's no way to output [brackets] text without it getting replaced.
Yes, that's what i meant, it would be replaced. I think there is a misunderstanding here
And it's not desirable to always replace.
It is for the algo i suggested XD
Fundamentally "splitting text by space and inspect each term individually" has the issue that each term does not have the surrounding context. The a in a = 42 has very different meaning compared to print("Eat a bannana"), you simply cannot look at a term by itself without context.
If you say "okay, we can look at the terms one by one in sequence, and if we encounter " then we know the future terms are in a string and we shouldn't replace them, until we encounter a pairing " at which point we exit the string mode" then congratulation, you have more or less arrived at how a primitive parser would work. Which is why I suggest taking look at existing resources because people have been solving this problem and perfecting the art for a long time, it's good to stand on the shoulders of giants.
amusingly, this "context" is allowed in a context-free grammar
Parsing is the art of un-creating a string
this is all a lot of really good info, thx for the help everyone. Im def gonna go read that Crafting Interpreters book
Is programming part of the gameplay? Like a zachtronics game?
Its based on a game idea i saw online that seems quite fun. The high concept is you're in a small spaceship that received some damage, your goal is to program basic ship routines to gather resources and repair / maintain the ship using a approximation of a 16 bit computer.
A game idea you saw online. You mean Markus persson’s spaceship game?
what nooo, id never steal from hit game devloper Markus "notch" Persson. (yes it is)
Should it feel like programming or gameplay? Like is it natural language with rules that aren’t that important? Or is it all about carefully following rules?
So far ive been making it a simplified version of C, so it would be following rules but it will hopefully be relatively lax because i want to make it beginner friendly-ish.
oo a programming game? If i were to id probably integrate something like a lua interpreter or similar
im not the biggest fan of using lua but it might be a good idea if i can find something like that
there are a lot of ways to skin this cat
https://assetstore.unity.com/packages/templates/systems/blocks-engine-2-201602?srsltid=AfmBOor6uZauAP7ZM082YfolMtjPGTjwnpYYK7PegwlrYXd_4FKx9Wr5 it really depends how important it is aesthetically that people type code and make syntax errors lol
https://github.com/imagicbell/ublockly also perfectly good
yea im still unsure on a lot of things about the final game. I think ill have a few difficulties and the higher the difficulty the less pre made ship control scripts i give them.
the thing people are going to react to is typing
do you want people to type at all? how much?
the zachtronics games do not make you type
if you have to type, to a normal person, it's a lot of syntax errors
which is not fun. unless the game is intended to be a syntax error simulator
is it aesthetically important that the game have a vibe of retrocomputing programmer bullshit?
hmm, that is a really good point to consider. I want it to feel like your using an old terminal based computer. Ill do some playtesting on syntax when i get it into a useable state
have you ever used an old terminal based computer?
yea thats the kinda vibe i was thinking about going for
somewhat i have done a lot of coding on cs50ide which is from what i understand very similar to a terminal computer
on the one hand you can make what you are saying
on the other hand, you know, it couldn't be a better time, maybe in the history of the world, to make a terminal based typing programmery thing but where syntax doesn't matter
because if you ask chatgpt to call functions, it will. like that works
so that's why i'm asking, is it a syntax simulator?
4 years ago, you could only hope to make blockly, or a syntax simulator
but now you could make typing, but it does not have to be a syntax simulator
if you do that though, retrocomputing people hate LLM stuff. i mean, unless they are using it to write Arch configurations, in the privacy of their own homes.
secretly
that is a very cool idea, the only problem i can see is chatgpt charges something like 10 cents per web request
do you know how much it actually charges
not exactly i cant find the documentation
it's like kopecks
the pricing per web request is closer to nanodollars than it is to cents
it's all about vibes here
so it's whatever vibes you want
there's an asset for runtime c# compilation
it's easy to write a DSL using plain C# and make that the game
and it will feel like C
does anyone want to do that? i don't know
it seems the free version allows for 3 webrequests a min on gpt 4
https://openai.com/api/pricing/
gpt4o mini is $0.150 / 1M input tokens
it's insanely cheap
it's nanodollars per request
oo i was on the wrong page i was looking at the ratelimit page
on the free versoin gpt4 is ratelimited to 3 requests a min
that's not the rate limit for the api
i mean, i don't know what you are looking at. you sign up for the api, you put in your credit card, and you can go nuts with requests
it's like any other service
idk what frequency i need to pay that tho
it's not 500 requests
okay well
i know a lot about this
i'm trying to tell you what it is
so if you want to build a game around it you definitely can
people already do
this is just an idea though
oh wait i think i understand it now, the tiers are just how much money you spent on the account its not a charge in itself
yes, that's how much you have credited
so as soon as you put in a $5 credit, you are tier 1
ok i see now, yea that isnt that bad then
ill take it into consideration thx for the tip! :)
i've made a retrocomputing terminal blah blah game
and i didn't make people program in it
since it was about the aesthetics you did a puzzle adventure
it's tricky if you want to do this stuff
yea definitely
If you are comfortable integrating native code this could be an option for python: https://github.com/pocketpy/pocketpy
and ofc for lua something like: https://github.com/moonsharp-devs/moonsharp
would it be at all possible to create my own script abstract class type and then create an editor field where users can drag and drop scripts that derive from that abstract into it only?
like my own version of MonoBehaviour
Maybe you want some sort of property drawer that supports SerializeReference and has a type selector
Not drag and drop but a dropdown instead. Dragging in a "script" would not make sense, because MonoScript objects only exist in the editor.
Another option is to have your base class inherit from ScriptableObject so you can drag & drop SO assets
uh yeah basically im making a simple cinematic builder tool and one of the options is "Custom Script" which would let the user override and write out a custom script to run instead of some blocked actions
have another idea might be easier
one sec
yeah tried that, didnt work
Why not?
fwiw i might just be unaware of the way to make that happen
Each SO needs to be an asset before you can drag it in
still relatively new to unity but i figured this was an advanced question
(on the cinematic SO)
That setup looks ok, except you don't need [Serializable] for scriptableobject
Not sure how this attribute works tho
What exactly are you trying to drag in?
My guess is you are dragging in the script file, which is incorrect. You need to create a SO asset and drag that in
wait what was that about making the SO an asset?
You need to add this to your SO class so that you can make instances of it in the editor https://docs.unity3d.com/6000.0/Documentation/ScriptReference/CreateAssetMenuAttribute.html
can't be abstract though can it
Add it to the child class
Example...cs [CreateAssetMenu(fileName = "New Child Class", menuName = "MyFolder/Child Class")] public class ChildClassSO : BaseClassSO
that just opens the script for the child class
What opens a script?
What's wrong? This is an inspector of an asset instance of the child class
right, but i need it to make a new child class of CinematicScript i mean
You can drag it from the project folders to a a field with the type CinematicScript
like a unique class where the user can write their own Run override
Wat. This was not part of your original question at all
Wdym by "user"? A developer?
What's the problem? You just made a child class
i'm trying to rig up cinematic events so non programmers can set scene actions up
nvm i think i got an easier solution
Anyone worked with importing and displaying gaussian splat .ply files in Unity?
I got stuck for a while now, I do believe I am importing position, rotation and color correctly, however the scale of splats seems to be off...
I assume that values in .ply file is at exponential values so while importing data I use Mathf.Exp() function. As if I dont use it, the displayed data doesnt make sense at all. Maybe someone had experience and know what kind of math I am missing?
What if you have the wrong base?
Maybe it’s 2, not e
Bit of a shot in the dark (:
Thank you, I tried Log 10 or 2, but as scale values have negative values I get quite alot of NaN values (most of them), which makes render invisible.
Do not ping everyone. see #📖┃code-of-conduct
No, this is not the correct channel see #🔎┃find-a-channel
Finally post !code correctly
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
There we go, all fixed normally, posted in DOTS section
- Can Object.InstantiateAsync method instantiate multiple instances concurrently, or is it just one at a time? I'm aware of the overload that takes a number of instances to create, but the docs don't specify whether they all are created sequentially or not
Are you asking if it could spread that work over multiple threads for a large number of objects?
I would expect all of the objects to come into existence simultaneously, rather than one at a time, if that's what you're asking
- That is exactly what i'm asking. If i simultaneously fire it 100 times, it seems to instantiate objects one after another, one at a time. Since touching unity objects is strictly prohibited from anywhere besides the main thread, i believe there's no way to speed this up?
oh, you mean if you call InstantiateAsync many times in a row?
that's going to be 100 completely unrelated operations
It's likely because this team (that did the instantiateasync api surface and work) were all laid off last year. 😦 https://x.com/_jura_z_/status/1758703011453608298
Before leaving Unity I came up with the idea and wrote the foundation of https://t.co/Nr3k5YBDkJ but couldn’t land it.
My friends Ryan Caltabiano, Matthew Davey, Adam Smith finished the work and landed it! Thanks a lot, guys!
And then their org was completely laid off :(
(the documentation being incomplete)
I don't know the answer to your question but a light google shows that this feature is not well-implemented..
I would guess that multiple calls to it will be just fine - I'm assuming that multiple calls to it in one frame queue up the engine to start the process in an async manner, and each tick of the game, you check on the result to see if the object's been instantiated [yet] or not and act accordingly.
Since our code works all on the main thread, I don't know how the async implementation works under the hood, but I imagine it will be just fine.. and you should maybe just try it and see what happens :p
It would be completely insane if you couldn't call it twice
I'd expect the order of completion to be undefined, of course.
- Isn't grouping them merely going to aggregate these many unrelated operations into a large one that's going to take just as long? I'm trying to split the load evenly between many operations instead of doing a large chunk of instantiating, followed by a chunk of configuring instances just as large. I was aiming for a "run X instancing ops -> whenever one finishes, do Y to its result" flow instead of "do X instances -> do Y for all of them"
the result of the call should be fine for you
allowSceneActivation is badly named here
it's inherited from AsyncOperation
You can set it to false to prevent the operation from completing -- so it won't do the last synchronous integration step
yeah - just instantiate a buttload of them, listen to the result every tick, and do the "Y" when the result is "done" for the thing you're making
So, fire a bunch of operations and set allowSceneActivation to false on all of them
You can then allow a fixed number of operations to complete per frame
oh, there's also this
Wild guess: This limits how much time can be spent on integration per frame
Brainstorming.. I need to draw arrows on my hexes to denote a path. I'm looking for nifty ideas to draw/scale the meshes (I'm planning to use a flat 3d mesh) in the hexes.
My thought is to make an anchor point game object, stretch a hex between point1 and point2, and lerp the size of it so the arrow heads don't overlap (since the anchor point will be right at 0,0 (a few pixels up).
Any better ideas?
end result would be something like this:
that's not really going to work if the points of ingress/egress are the flat sides of the hexs
why not..?
put 2 of them together\
What does "stretch a hex between point1 and point2" mean?
sorry, stretch a mesh* between the points
I don't see why this wouldn't work. Seems pretty standard
so .. if you take hex1's "center" and hex2's "center".. pardon the ascii art:
[hex1-------A------------------B--------hex2]
A and B would be calculated positions between these center points - and I'd plop the mesh down at A, and tip it towards B, if that makes sense
(in the shot above - there'd be 5 of these arrows)
Sounds alright to me 🤷♂️
I mean, alternatively, and perhaps better UI, would be to just make one "rainbow" shaped arrow going from the start of the path all the way to the end
(instead of small arrows on the path along the way)
but the UX I'm trying to improve here is a mouse with a special ability that runs along a path and does damage to enemies along the way.. so the path sorta matters, not just the end destination
oh - current UI is to just draw numbers on the tiles which is where this is coming from
(I don't love it)
Placing an arrow between two hexes would be trivial, yeah
Vector3 pos = (hex1.position + hex2.position) / 2;
Quaternion rot = Quaternion.LookRotation(hex2.position - hex1.position, hex2.up);
choice of "up" is slightly arbitrary there, but I presume the hexes are all facing the same way
the other thing I have to solve is... when the hexes have 3d meshes.. the arrow hex (and the number text above) is obscured.. not sure if I want to do a see-through material for that but.. maybe that's the solution
Perhaps each hex could signal how much clearance you need
you'd add that offset to the position
this would let you have arrows tilt up and down for free
hm... i dunno if that's easy for me to figure out.. the level designers plop meshes down willy nilly
i'd have to .. do some bound calculation.. and i'm not always sure if the hex will have the meshes underneath them
It looks like you have "clear" tiles and "grass" tiles
like some levels are gonna have some meshes that are "world" meshes
plus a few tiles with a couple tiny shrubs in the back
oh, no.. lots of world stuff:
(there's hexes under those rocks and stuff)
like one level has rocks that get destroyed and enemies come out
you mean over here?
yeah
that looks totally impassable anyway
not that i need UI for it, i guess.. yeah, exactly
the mouse can't run up that sheer slope, I imagine
I'm only interested in tiles that could plausibly need to display something on their surface
There is no "surface" on an impassable tile
You could also just render the arrows without checking the depth buffer, of course
i have a post processing layer i could put the stuff in.. i think that's gonna be pretty close to the best/easiest
lemme slap world text in it and see how it looks
hm.. doesn't work..
oh, maybe post processing only works for skinned mesh renderers?
not the normal mesh renderer
i'm not sure what a "post processing layer" would entail here
do you mean the layer that you've put your Post-Process Volume on (meaning that you're using the built-in RP and the Post Processing v2 package here?)
I think - I didn't build that part, but my understanding is it's some settings in URP that adds something to materials (which we're designating by unity "Layer")
meshes on units in this layer have a see through effect:
ok so it's a "renderer" that I'm thinking of - looks like my tech artist made a "universal renderer" that has a "render objects" .. thing? that after rendering.. does this:
and that material has the coloring and stuff
anyway.. I think I could do the same with an "arrow" mesh that lives in world space
yeah, this renderer feature causes it to draw renderers on a certain layer at a specific point in the rendering process
Fen do you got some time to help just dunno anymore
Funny thing is - I think I like the numbers (not arrows) better.. Proof of concept:
(since the ability lets the scout move 10 squares.. the arrows wouldn't be easy to see how far you've gone without counting hexes manually)
yes, the numbers seem like a good idea
just my opinion but if its to indicate the path they take, id have some visual element with it still like a dotted line (perhaps that animates in the move dir?)
Or arrows as suggested. Something that indicates the route and dir even easier than just some numbers.
Anyone got any tips to improve build times for release versions with the webgl builds? our app takes 40 (!) minutes to build on my reasonably high end dev machine and times out with our CI/CD machine
Just kinda how web exports are. I know for sure the first time you build it takes forever, but it does seem to reduce the second time around. I've noticed that dev builds are much quicker in that regard as well.
I believe they did optimize it a bit more with the release of 6, so may be worth looking into updating and trying it out if you're still on an older version
Yeah, I'm on 6 but .13 so probably could update.. i think latest is .33f now
but 40 minutes is just kinda terrible.. and my CI/CD pipeline doesn't seem to cache things properly so it's building from scratch every time
it's timing out anyway (not a unity limitation but my CICD tool) so I can't get the cached stuff done once even
you using github/gitlab or a self hosted thing like jenkins?
where i work we have self hosted jenkins using mac minis as nodes (cus we do android + ios)
codemagic.io works pretty well for me as far as the .. deploying (to google/apple) part but.. the building part is a little underpowered
do they limit how long builds can take then if it times out?
I guess each time its re importing the whole project hence the shit build time. One thing unreal does better i guess.
is there any way to .. build locally and then use those files in other locations?
i don't even see any cache files in the web gl builds
you know how normally android builds have that _SaveThisButDoNotShip folder or whatever, alongside the release artifacts
that stuff is the il2cpp output for debugging i think
Usually the parts that take the most time is asset importing then il2cpp code gen
i mean, i really wanna use this release build stuff - it lowers our build asset from 90mb to 35mb and it's for the web so it's important.. but man.. it's such a headache to do a release build
can you not build locally or do you not have access to a mac?
no i can build locally but the "link_webGL_wasm" step takes forever
2231 sec in yesterday's build.. (37 minutes)
if on windows make sure your project is fully excluded from windows defender or any other anti virus
and ofc have the proj on a fast drive
oh, yeah, i could probably do that.. i have the build assets on my windows pooled drive