#archived-code-advanced
1 messages ยท Page 34 of 1
a custom one- it handles input. Stuff like moving and jumping is written in other scripts with a reference to input controller
the core of it is maybe in three files.
- he has task queues (arrays of Tasks
async () => {}) for every specific instant (e.g., PreUpdate, PostLateUpdate) in the player loop that you would want to run code. this is an implementation of a task scheduler and synchronization contexts (i.e., the moment in time & thread that a task should continue executing on), it is arcane. - when the player starts, he adds a playerloopsubsystem for each corresponding player loop instant with queues. this playerloopsubsystem is the thing in the unity api that lets you schedule code to run at specific "execution phases" as per its docs.
- then he defines the helpers.
When using hinge joints, how can i specifiy the axis of rotation relative on the connected body, if I dont want to rotate the object first? essentially I have to objects with their hinge joints labeled as a transform with a direction, but I want to avoid aligning them first
Just downloaded the project and will look at the code, I feel like this may be a little over my head though so we shall see xD
Thanks
is there where i can ask about ScriptedImporter ?
var result = new TaskCompletionSource<Texture>();
async Start() {
// unity main thread
...
using (UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(url))
{
UnityWebRequestAsyncOperation asyncOp = webRequest.SendWebRequest();
while(asyncOp.isDone == false)
await Task.Delay((int) (1000f / 30f));
....
result.SetResult(texture);
}
Task.Run(async() => {
// other thread
await result.Task;
});
you can coordinate via task completion sources
this is much simpler than using a queue
or a lock, or whatever
it's the best synchronization primitive for Tasks i.e. async/await
Ah brilliant thank you. I have a few questions though that I wanted to ask to get my head around things,
How can you tell which task is running on what thread? Since Start is now an async void I was under the impression this then make it called it asynchronously. Which I know doesn't mean to start a new thread, but with the await inside the using block what thread is that then running on and when is it awaiting?
Do tasks always run synconously until the first await they hit?
And final question sorry, if the task was already on a different thread (for example in my case we are doing a web request first to get url's off of user profiles and then calling this funciton) would that keep still have it be on the main thread or would it be on the one the call was from?
Sorry for so many questions
How can you tell which task is running on what thread?
usually people check the current thread's managed thread id. on unity you can compare to the id that you read onStart(), however it is typically 1 (i forget if it's 1 or 0 but it's always the same)
Since Start is now an async void I was under the impression this then make it called it asynchronously. Which I know doesn't mean to start a new thread, but with the await inside the using block what thread is that then running on and when is it awaiting?
my example there is to just show there is a pre-existing unity synchronization context that is flawed compared to unitask but it does indeed work. you can also do
void Start() {
// forget is a unitask extension but
// you'll see it literally does nothing
SomeAsyncMethod().Forget();
}
async Task SomeAsyncMethod() {
...
// you are on the unity thread
await x;
// you are still on the unity thread
}
Do tasks always run synconously until the first await they hit?
yes. the full answer to this is really complex.
And final question sorry, if the task was already on a different thread (for example in my case we are doing a web request first to get url's off of user profiles and then calling this funciton) would that keep still have it be on the main thread or would it be on the one the call was from?
without unitask, you would want to run the task that uses the unity api in the way i show above. that ensures you are running on unity's synchronization context, and thereforeawaitreturns on the main thread. you can continue to use whatever other technique for starting tasks on background threads that you are familiar with.
you can always copy and paste my admonition "use unitask" to your colleagues and invite them here to argue with me lol
When using hinge joints how can i
Thank you, I think I understand things alot better now, but I am still unsure on how to access Unity's build in synchronisation context, from your example it doesn't seem to be used. Have they chaged Task.Yeild() to be this?
I may do as you say though and ask if they are happy with me brining UniTask in, I think they will be, but they want to release a beta soon for one of there updates, so brining in things right now may not be a great solution but in 2 weeks I think I will get the go ahead to do things properly with UniTask and such.
but I am still unsure on how to access Unity's build in synchronisation context,
hmm... i think as long as you run an async Task-returning method from the main thread in unity, which means anywhere within an e.g.Update, you are using the unity synchronization context
they configure it up front for you
their source code is available. i'm not going to read it right now but the way it probably works is, it checks if you are starting a task from the unity thread. if you are, use their synchronization context. otherwise use the default one.
starting a task meaning SomeAsyncMethod()
not Task.Run()
you don't have to do anything special to access unity's synchronization context is i guess what i am saying
Ah thanks, that clears things up.
Hello people, i made a train with wagons and the AI of the train is located on the front engine, in order for the wagons always go together with the engine i made so the engineAI update calls the wagons to move them at the same speed the engine is going:
left is the engine Move method, that's called by the Update
right is the wagon
it works well but to my surprise after some time playing the wagons are separated from the engine, something has happened that they have not been moved exactly like the engine
did i overlook something basic here?
i thought by forcing the wagon inside the engine update i was forcing it to move exactly like the engine but seems im not
it's hard to tell, but you might need an approach similar to DOTween. lerp between the positions based on the total elapsed time since the waypoint, instead of incrementing positions
it's the only way to guarantee that in aggregate you have everything arriving in the right place at the right time
hmmmm at the right time you say
whereas with your current approach, the aggregate behavior is that ArrivedAtWaypoint will be sometimes be "wrong" because of how the position changes accumulate over time
hmmm i think i get what you mean
here is a screenshot of whats currently happening
the engine is the one going up
the rest are wagons
this would be hard because i need to adjust train speed when approaching to curves or stopping in stations
so i would have to take that into account , pretty hard ๐คฆโโ๏ธ
yeah
i assume its not colliders interacting and stuff
maybe i can make a 'correction' function on each function and put the wagons together ๐
you can try to position them analytically relative to the engine
no, they are not
yeah
i mean it's tough. for the thing you are building, you do need a position analytically
position and orientation as a function of time
i'm not sure if this is avoidable
hmmmmmm true, and i dont need to be doing it continually right?
for this approach you would have to do it right after the engine moves
yeah ill do that
but then you're maintaining two movement systems instead of one ๐
yeah, shit
you can maybe record the the previous position of the engine and use that
but then that's 3 movement systems lol
so really you should do position and orientation on track as a function of time
im trying to think of a different approach but nothing easy comes to my mind
i like the voxel trains btw
piecewise functions are not hard to author. the idea of a sequence of tweens is not bad
if you wanted to prototype it
you can make a function that creates the sequence of tweens for any vehicle. then offset the delays
and run that sequence for each vehicle
the thing that makes this tough is what happens when the track changes
okay that sounds interesting
if track changes i kill the train
and respawn it
didnt want to make it more complicated
in other games like mini metros i think they have the vehicles and stuff operate in a decoupled way, but not within the unity scene
so they have a pure CS environment where decoupled things determine their positions
each curve has a waypoint so train simply follows waypoints
i had it ready to have... 'dynamic' waypoints
so if one is destroyed ....
the only viable long term approach is that the actors in your game are decoupled
but too hard for a first version
like you have it now
and you can either master the ways to achieve that using Unity Physics Rules or write your own Rules that don't touch theu nity api
yes they are, thats what i learned after making a car traffic system, better decoupled
so my feeling is the IsArrived function is the problematic one
i can see how that would magnify accumulations of position changes issues very quickly
because only a teeny weeny difference could cause the answer to that function to differ by a frame, which is a huge distance
i see... i might do a check after each waypoint and correct or go for de dotween approach
but then again, the changes on the speed
ugh
ill check dotweens docs
based on how far apart these are
and the exact screenshot
i think you are probably doing a euclidean distance
versus a track distance
and that's the bug. it's rounding a corner and for 1 frame, it happens to be close enough to the future point
because it's on a corner
so if the waypoint position isn't exactly on the corner
if it's somewhere along the track
the bends can mess up the answer to a euclidean distance comparison
hmm... but i think your waypoints are just on the corners so that woudln't happen
especially because it looks like the train turns
and the rear of the train is on the corner, but the comparison is to the center
so i think there's probably something wonky there.
i have to say this happens after a long while
as the train turns, the distance from the corner to its center will change nonlinearly
and playing on editor....
so probably it's just accumulation of differences in distance and using this arrived at waypoint, which is very sensitive to very small differences by design
hmmmm
it would probably happen on a straight track
you mean it would probably not happen on a straight track
i think it would happen on a straight track eventually
on straight tracks
but to demonstrate the issue
ah ok ok
hmm or maybe not. maybe it is the turning
damn
fuck it, im gonna correct wagon positions on each curve ๐คฃ seems the easiest
first ill check what dotween has to offer
uhmmm DoPath, interesting
i would check out the OpenRCT source. i think they tightly couple frame rate to simulation rate and use exact time deltas
and that's how decoupled stuff Just Works - it has the same errors everywhere
interfaces vs abstract?
hey all, im prototyping a tile-based grid system and right now im developing some of the tiles and tile properties. I use to use an abstract TileBase class that kept track of the tiles position, z index, name, type, and sprite. I moved away from that and started using interfaces. So I have an IEntity, IEntityName, IEntitySprite. Then I would make a script called TileGrass which inherits those interfaces, whereas before it would inherit the TileBase abstract class.
Thoughts on either system?
Does each of your interfaces actually have meaningful role?
IEntityName what is this used for
IEntityName would be used for say, a player selects a tile and I would grab that interface for a UI display
IEntity is just to register a script with an interface all entities would have, so to detect if something is a tile i would check instance of IEntity
I'd call it ISelectableEntity or something then
Each interfaces should have meaningful role, and you won't need more abstraction than you need
makes sense
yeah, each interface has their own property and functionality as of now
the issue is lets say I have 10 unique tiles
if I add a new IEntityFunction.cs with a new interface, then id have to add that interface to each unique tile script too
so scalability and quality really are my concerns
Will they have unique behavior for that new interface?
If they shares most of behaviour using inheritance makes more sense
Well they would all inherit that property, which would be unique compared to other interfaces
so like for example
I would have 2 undestroyable tiles like grass and concrete and would have the IEntityUndestroyable, then 5 wall tiles that may have IEntityUnpassable
Let me make sure we are using same term. Inherit is for base-derived relationship between classes. Implement is for interfaces..
Hmmm okay this sounds like ECS
yes exactly
Maybe it will go better with DOTS?
Hm probably, this is my first time hearing of DOTS
The system we had before this was a factory system, basically
cathei, have you got your paws on dots yet?
In ECS it doesn't really use interfaces or inheritance
It's a composition of Components
I did some work with Svelto
It's a ECS framework https://github.com/sebas77/Svelto.ECS
starting with a framework, huh
What would the advantages of DOTS be for say, a game that has like 100+ different tiles or "entities" that could be moving around at all times or being static
Well DOTS is also a framework ๐
framework over dots I mean ๐
Main advantage would be performance
And as the logic would be modularized, you won't have to care about the 'scalability' issue you mentioned
You'd just add system, and add components to each entity if required
Yeah ๐ as it works outside of Unity as well
cathei, is it right to say that OOP systems are way more easily extended and changed?
OOP versus ECS?
yea
ill look into DOTS, thank you
Depends, I think if you are making a game that fits for ECS, like thomas here is doing imo, it can be easier with ECS. Like you have 'entity' and an 'entity' can do many common things depending on their archetypes
Good luck, I think you can get some ideas from it even when you go with OOP way ๐
Is creating a game in OOP and releasing build in ECS to boost performance a thing?
Like prototype in OOP?
That would require rebuilding most of it, but sure why not
currently what im doing lol
Yeah you can do PoC with OOP if that's faster
I already released the game, but I'm not too happy about it so I'm overhauling the entire thing
yea
Depending on the games I think
But sure OOP is more flexible in terms of changing game mechanic
To something else .. like while prototyping
If you have enough time to rebuild everything afterward ๐ค
oh i got plenty of time right now, no hard deadline is set atm
I envy that
well i say that, because it's more so a hobby project lol
do you have a screenshot you can share
i have a gif lol hold on
this is showing the current build system
each tile is a 2d game object sprite, i use to use UI images instead lol
why doesn't it work?
PlayerSettings.SetIl2CppCompilerConfiguration(BuildTargetGroup.Android, Il2CppCompilerConfiguration.Release);
Change Mono to IL2CPP
It is still Mono
@jolly token how is your experience with Svelto? is it any better than working with pure dots?
okay well in light of
I already released the game,
i think the highest yield thing would be to keep doing what you're doing and not worry about DOTS
well im not too happy about the current construction and grid system which is entirely dependent on how i set up the entities
i might use abstract classes again, but really clean it up
it's just the beginning of a very long journey
it really depends on what your goals are
looking at this gif did give me a fun idea for a game though - it's a grassy field where you zoom in to progressively reveal a more detailed tile world
kind of like the infinite zoom in supreme commander meets arcane simulation like Dwarf Fortress
Not really easier but I like idea of it as strict framework
it should be better for performance or multiplayer scenario (as not Unity-bound)
it's for a coffee shop management game actually haha
you build the cafe from the ground up, either in the city or in a suburban area
Do Presets have a bug that prevents them from storing any object assignments?
Hello, i have a problem with unity crashing constantly when i go in play mode, not all the times it crash but a lot of them it does.
0x00007fff21cfcb49 (UnityOpenXR) unity_ext_RequestEnableExtensionString
0x00007fff21d04751 (UnityOpenXR) unity_ext_RequestEnableExtensionString
0x00007fff21cfd824 (UnityOpenXR) unity_ext_RequestEnableExtensionString
0x00007fff21cfae03 (UnityOpenXR) unity_ext_RequestEnableExtensionString
0x00007ff6ee7e827f (Unity) XRInputSubsystem::Update
0x00007ff6ee7ea011 (Unity) XRInputSubsystemManager::Update
0x00007ff6ed1738d9 (Unity) CallbackArray::Invoke
0x00007ff6ee7cc886 (Unity) `XREngineCallbacks::XREngineCallbacks'::`2'::EarlyUpdateXRUpdateRegistrator::Forward
0x00007ff6edad0c4c (Unity) ExecutePlayerLoop
0x00007ff6edad0d23 (Unity) ExecutePlayerLoop
0x00007ff6edad6969 (Unity) PlayerLoop
0x00007ff6eea19238 (Unity) PlayerLoopController::UpdateScene
0x00007ff6eea1741f (Unity) Application::TickTimer
0x00007ff6eee5f8aa (Unity) MainMessageLoop
0x00007ff6eee6417b (Unity) WinMain
0x00007ff6f018582e (Unity) __scrt_common_main_seh
0x00007fff993f7614 (KERNEL32) BaseThreadInitThunk
0x00007fff99f026a1 (ntdll) RtlUserThreadStart
Is there a benchmark of sorts?
IDK if there is benchmark versus dots ecs ๐คทโโ๏ธ though it is burst compatible
Anyone skilled about how Unity handles P/Invoking with Mono? I'm having the odd issue of a DllNotFoundException, ONLY on Linux, not Windows. And to make it even more confusing: Other files in the same folder work. To also rule out the native library in question, I replaced the "one in question" with one that is successfully loaded by unity, and now that one is also not loaded anymore. So somehow Unity doesn't properly resolve that specific native library / .so? How could I debug that further? I've done 2 days of debugging already, which ended at inspecting the MONO_LOG, that shows how it's trying to search exclusively the lib directories of the editor and it's mono install
what are you trying to do
there are a few obscure patterns that help with this stuff
like using th eplatform to select the string constant of the path to the DLL, which makes it work in specific situations in e.g. il2cpp better
Actually trying to port my SWIG-Wrapper to Linux (https://github.com/MeFisto94/UnityPhysXPlugin/tree/feature/linux). Actually deleting the .meta and .so file and "reimporting" it miraclely worked, but now I'm getting EntryPointNotFoundException's for symbols that are correctly exported on that file. I guess I need a fresh brain tomorrow on that, but so far I'd take every debugging tip, I can get.
FWIW, it's not il2cpp, plain mono, just wrapping the native physx.
hmm
so when you update the binary
in the assets folder
did you know you have to quit and reload the unity editor
for it to use the new copy of the library?
it will silently keep using the old binary until you quit and reopen
on linux
indeed, nobody uses the linux editor, so it has all sorts of idiosyncracies
That's a good point already. That may also explain why whatever I tried in between was pointless and some other things I saw.... And why it worked when deleting the meta and so file, because I shut down Unity for that
but isn't that potentially the same on windows? they at least survive domain reloads / aren't related to a domain obviously
hmm, restarting again made it go back to the DllNotFoundException... (which I btw also had in the release build, but now I can't build anymore due to the ui not working well on linux)
hmm
i agree this is very finnicky
why are you trying to get things to work on linux in the first place
which, imo, is a waste of time ๐
Steam Deck mainly
And for the dedicated servers in the future secondly (currently they are too cheater friendly, not knowing physics)
It's very weird though, I'd expect problems when compiling the so itself or loads of render Bugs, but not loading a dynamic library
And it works for everything else like SteamAudio
i think you are only doing something very teeny tiny wrong
carefully copy the harness from a pre-existing plugin
the weird const name trick is key
you mean the C# side? The weird thing is, that plugin has dots in it's name, which is uncool because it could be interpreted as file extension. But then, I created a dummy plugin that worked.
but yeah, I guess I just need a clear brain and a happy little accident ๐
is there a way to make this add not reference itself in memory
when the second line executes it affects both
wdym "it affects both"
What are the "both" that it affects
Do you mean the object at the end of the list and the object at i?
so I am duplicating the element at i and then replacing the z + 1 value
If your list is a list of a reference type, then it is merely a list of references
but it replaces both
yeah that's the thing you're not duplicating anything
you're putting another reference to the same object in the list
yeah
You'd have to make another object
You'd probably want to deep copy instead of shallow copying
I think i tried that in a different but similar scenario but it didnt work
If you can get away with using a struct in the list instead of a class then that would also do it automatically
/shrug you did it wrong
what's the syntax for this
use new to create a new object
new instance
not here you didn't
i wanted to see if there was an easier way that doing that
like in python its list[:]
to make a new reference
- use a value type instead of a reference type
- create a new object
those are your options
did not fix
Maybe you're misunderstanding something. We're referring to the object being copied not the collection..
yes because you're not copying anything other than a reference
Example:cs Something a = new Something(); Something b = new Something(a);//Implies there's a copy constructor
If you do this:
List<string> x = new();
List<string> y = x;
x.Add("hello");
print(x.Count);
print(y.Count);
they will both print 1
because List is a reference type
you are merely copying a reference to the object, not the object itself
yeah i just didnt know the syntax
If it's a list, yes there's a copy constructor already
if it was a custom type you'd have to write your own copy constructor
so i could do the original but do .copy or whatever inside the add?
instead?
idk its fine this works thanks
no there's no such thing as .copy unless you wrote that
When saving game data, like for example "level, weapons, kills, experience", say theese are my release v1 data. What if i later add a data list or object "shields", when i load the saved data to the application, my application is going to wonder what shield is, well, atleast if i use persistent data and save things as a SaveObject? When i add a new list called shields in SaveObject it will fail to convert on load?
.
Cant see my message is it sent lol
Now i see it:)
A typical approach is to save a "save file version" in the save file somewhere. Then your application can check what version the save file is. And you can write "migrators" which upgrade each version to the next
another approach of course is to just reject data from older versions ๐
Also you'll generally want to make it so adding data is harmless
I know that later i will add new features, such as transport vehicles and i need another parameter for vehicles owned etc
i.e. don't use serializaers that require fields
generally adding data should be very easy
I see
it's when you remove fields or change a field's datatype for example that it's harder, or renaming fields, etc...
When u say serializers that require fields wym
I mean make sure your serializer won't generate an error if the data is missing a field
So in your example here if you have a save file that doesn't have the "shields" field, it shouldn't throw an error
Yeah i renamed a field and then it said it couldnt make the load, this got me thinking abt the problems that can occur
it should just assume some reasonable default
There are also things like https://docs.unity3d.com/ScriptReference/Serialization.FormerlySerializedAsAttribute.html which can be stopgap solutions
Yeah like rn i do "SaveObject = (local) SaveObject
another syntactical question that i havent found an easy answer to. how would you guys make a 2d array unique? .Distinct().ToList() does not work
I could have a method LoadSomething()
That takes in the parameters needed and set them to the new objects, and for the fields missing i put them as empty or default. The logic of a constructor sort of?
@sly grove
what would the end result of that be? Doesn't really make sense to me
2d array as [][]?
yeah but make the first dimension act as a value
per element
and to make that unique
so only the first dimension?
also this isn't a 2d array this is a jagged array
[,] is a 2D array
[0] - > [1, 2, 3]
[1] -> [2, 3, 4]
[2] -> [1, 2, 3]
you would remove the last one
like theyre both lists
but just make it unique using the first dimension
So you mean a jagged array?
and wdym by "unique" here
for it not to be unique, the whole row would have to match?
[0] - > [1, 2, 3]
[1] -> [2, 3, 4]
[2] -> [1, 2, 3]
this would turn into
[0] - > [1, 2, 3]
[1] -> [2, 3, 4]
jagged arrays are generally preferred over 2D arrays anyway
ok so again is this a jagged array, or a 2D array?
jagged array is int[][] 2d is int[,]
yeah then no i guess
no what
it does not make it unique
Can you answer which one it is lmao
what's a 2D list?
List<List<>>
List<List<int>>?
yes
i did it cause this is a function for lists
but it only works with 1d
which is reasonable
You need to define unique
like unique int?
well yeah if you do this with a List<List<int>> it's just going to check if any two lists are the same list
I think you want SequenceEqual
to check if any two are the same
You can use https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinctby?view=net-7.0#system-linq-enumerable-distinctby-2(system-collections-generic-ienumerable((-0))-system-func((-0-1))-system-collections-generic-iequalitycomparer((-1))) and use SequenceEqual in the equality comparer
basically... myList.DistinctBy(l => l, (a, b) => a.SequenceEqual(b));
something like this?
I think you actually need an IEqualityComparer which is annoying for that second param
You do need to define equality comparer with proper GetHashCode ๐
oof
so it'd be like:
class SequenceComparer : IEqualityComparer<IEnumerable> {
public bool Equals(IEnumerable a, IEnumerable b) {
return a.SequenceEquals(b);
}
public int GetHashCode(IEnumerable a) {
return a.Count();
}
}
myList.DistinctBy(l => l, new SequenceComparer);```
some nastiness like that lol
Well what is your lists for?
It is pretty much what Linq can offer
If your lists are immutable it would make more sense
it doesnt make sense then
lmao
i need it to make a bunch of links between things
but it only needs to show one link
or one line of links
Sure, so it's like graph?
If there is (1, 2, 3) and (2, 3, 4) wouldn't (2, 3) part consider duplicated?
if 1 leads to 2 then 2 must always lead to 3
so 1 2 3 would always be in the list
2 3 cannot be
but if 2 is on its own then 2 3 will be unique
even if 1 2 3 exists
nvm
maybe
im confusing myself now
Lol
alright ill give the full explanation cause like its tough not to
one sec though i have to stir a pot of soup
Sure ๐
ALRIGHT here goes
so im making a game about algorithms and completing them
we're going all the way back
and
i need to find the time complexity of the users algorithms to compare efficiency
so i am making an algorithm that takes code as input and find time complexity
one of the pieces of it is dealing with functions and calls
so i am creating a chain of "function one" calls "function two"
this is as an array with the first in 0 second in 1
and i am then iterating through all of those x calls y, y calls z, ... and linking them all together
to then later have a x calls y calls z calls ...
i have this working
i just need to make it a unique list
im at this stage
but then it has an extra of the last one
we went deep
So it's kinda stack trace and you want unique stack traces.. huh
Rubber duck works
I wonder why second index is constantly increasing
I would expect [0][3] then [1][0]
and i didnt set the index to 0
nvm
lmao
i incremented for my viewing only
disregard
I see.. but maybe tree structure is what you want?
Tree of the call stack
maxHeight - alterSomething - isStackable - something
ใด somethingElse
ใด checkStackValue
Rather than list of lists
i was thinking of doing a tree
but i was in too deep
man i need to reformat this at some point
not today though
yeah you definitely want a tree my friend
You actually kind of want a Trie / prefix tree
https://en.wikipedia.org/wiki/Trie
In computer science, a trie, also called digital tree or prefix tree, is a type of k-ary search tree, a tree data structure used for locating specific keys from within a set. These keys are most often strings, with links between nodes defined not by the entire key, but by individual characters. In order to access a key (to recover its value, cha...
hm
yeah
lol
yeah im going to rest for now lmao i think ill need to update a lot of this code i just needed to make it work for now
"future work"
ill call it
trie is a great data structure but be wary, x-fast and y-fast tries are insane to implement and there is an entire rabbithole on optimized data structures using tries. it's really easy to get trapped in hyperoptimizing once you start working with tries. do not make the same mistake i have!!
Do you have an example of being trapped?
And what hyper optimization stuff you do
The goal of a trie is to reduce the complexity of searching for elements. X-fast and y-fast tries are examples of van embe boas tries, and they are built on a couple of atomic operations that are very fast but hard to implement properly. In general, a trie is a tree where every node is, abstractly, a dictionary that uses characters or some kind of element in a sequence as a key. because they're abstractly defined like that, there's a ton of work you can do to optimize for your given problem
a common use for tries is word autocomplete. in this case, you have a set of words that are "valid" and as you type, the set of possible valid options narrows. that set is a list pulled from the sub-trie and enumerated so you can put it into a visible dropdown list or something
this is an ambitious game that will take you on a very interesting journey
๐ซก
knowing you are working with words is a start for optimizing, if you are only working in english you can force everything to be lowercase, then you know you only have a max of 26 possible branches at a given node. you can use a 32 bit field to mark if a character at a node has a branch and then you can use an array instead of a dictionary to store branches. then you don't have to deal with dicitonary lokups
Okay that is really useful
Yeah I already have a few places I can use that
Thank you
like I said, it's a rabbithole
its very easy to obsess over every way you can make things run faster. ultimately, performance is all that matters. if your game works, there's no need to dive into this
Itโs about efficiency so Iโd feel like a hypocrite lol
I think that's more applicable to something like profanity filter trie ๐
game programming is all smoke and mirrors, jsut because your game is about algorithms doesn't mean you need to write the most godlike code on the planet ๐
Thatโs the goal though
I began this to get better at programming
I said this before in this discord but I asked people how to get better and half said make a game and half said do algorithms
So I chose the most difficult route
that's a good attitude
Algorithms*
jsut don't push yourself too hard
I am absolutely pushing myself too hard lol
This is my first game too
I like it though
you're goign to have chgallenges regardless, dont make it harder for yourself than it needs to be, in the end you jsut want to produce something
my advice: focus on finishing a project. then step things up for the next project
if this is your first game, I wouldn't even worry about implementing tries. just implement something easy that works and make sure you have some velocity
oh I see
All of my experience making games will come from past experience making this game lol
I already implemented c# c++ Java and python in it
I won't tell you what to do but if this is your big idea, it might be worth it to take part in some game jams or do some maller projects first to get some experience with the general game dev cycle
Like Iโve done way too much work
there's a lot of challenges you don't anticipate
Like for game making or programming in general
it sounds like you're new to both?
I bridged from a bad college programming course into computer science and dove in head first cause they didnโt teach us well
I also have ADD so I forget a lot
Then I began this game from this
that's ok
have you tried prototyping at all
just throwing some lazy hasty crap together as a proof of concept
it's a good exercise, I recommend it
Just stuff like this today Iโm making outside of Unity
So the next part is I showed one of my profs this game and the idea and he is like some educational video game specialist
So I got chosen for an honours thesis and my mentor was mentored by him
So this game is a thesis
Like unintentionally
oh, so you have a deadline on this too
Yes
well then, its even more important you dont get bogged down with implementing complicated data structures
I wrote my honours paper specifically on implementing a y-fast trie
I would like to continue this past the thesis
that alone took months for me to study
So Iโll take all the info I can get
Thatโs cool af lol
Info from the best guy
it was a fun project but I'm jsut saying, it's a big topic
Yeah everything Iโve been doing is
Like Iโm learning a lot which is good
But itโs tough
i briefly read your concept above, you want to make a game about implementing algorithms? does that mean you plan on creating a kind of scripting language
or how will a player interact with this
i am making an in-game tilemap painter and it seems like for some reason my "painting" is not aligned with my cursor
the code used to get the cell is pretty straightforward and standard :
So unity is giving me a internet connection problem when I'm tryna download the newest one
Idk how to fix this
not a code question. #๐ปโunity-talk
also check the pins in #497872469911404564 for a checklist of things to do when the editor fails to install
ok it's just incorrect Tile Anchor value setup, the code is correct
Hi guys, bit of a wierd issue. So I have my own assembly def, that houses my custom rendering code. It references Unity.Collections. Now, I'm trying to yoink a certain utility class from the entities.graphics package. That package also has it's own assembly def that references the collections asm def. That utility class uses a internal struct from the Collections and ofc compiles fine, how ever in my case I get a error that it is inaccessible. What gives ?
I want to show an outline on my 2D sprites when you hover over them so I made an outline shader and applied a material to my sprites. The problem is that I don't know how to handle the actual show/hide part as it doesn't seem possible to disable/enable the shader or material on the fly. Do I need to add some exposed alpha property to my shader which controls if the outline is showing or not and then set that property from the hover script? Or is there a better way?
posting here as im guessing this is an advanced thing: is it possible to figure out the target platform of a built asset bundle file somehow? In other words, does the asset bundle file contain information about to which platform it was built for?
Hey, I'm probably doing some basic mistakes in this code because I'm getting 2 errors over names not existing in their current context. Can someone take a look at this script https://pastebin.com/wSf9AHMk and tell me why both these errors are happening? I'm not sure why they occur or how to fix them, as I'm quite sure that I've defined them earlier already.
The errors are The name 'maneuverPoint' does not exist in the current context in line 119, and The name 'coordinates' does not exist in the current context starting in line 134 and going to line 138.
I thought I was defining the maneuverPoint name in line 115, and the coordinates name in line 119. But apparently that's not the case.
The problem you are not taking scope into account.
coordinates only exists inside the if statement and maneuverPoint only exists inside the for loop
Aaah, okay. I didn't know there were scopes for definitions. So technically I would have to define the names outside of their functions, kind of like the parameters I have at the top of my script?
yes, kinda
Alright. Thanks
#๐ปโcode-beginner in the future for questions like this.
I'd love to ask for advice about inventory architecture. I will write it down and any feedback would be great.
1. An item prefab will hold the Scriptable object of the item with all the detail needed to make that item work.
2. When the player collides with the item to pick it up, the item will be destroyed and the ScriptableObject will be stored in the Inventory GameManager.
3. The inventory slot will be created and the inventory Panel and will read the ID of the item Scriptable object and it will be saved as a private read-only variable on the item slot.
4. When the item inventory slot is clicked on, it will use the ID to loop through the ScriptableItemGameObjects that have been picked up to date. If There is a match, it will then read the data from the SO that is in the inventory Game Manager and display the description or equip that item.
```This way I minimize the duplication of Scriptable Object. I have a single point of reference. I can then also use the ID to check the amounts held or not held by the player etc. Is this a good path to take or are there other/better approaches to this ?
Why not just pass around a reference to the scriptableobject?
if both the prefab and inventory slot have a YourObjectType data and you just assign slot.data = pickedIetem.data; there's no actual duplication of the SO?
architectural boundaries should be drawn along the possible reasons for a change to implementation. You need to define those first, then you can make up an architecture that suits your project. Such reasons can be a specific performance bottleneck, a designer deciding to change the rules of how items are aquired/used, a balancer needing to tune the values, QA finding a bug, business deciding that there is no more budget and stuff needs to be simpler, among potentially a lot of other things. So without knowing your context there can be no advice on a "good" architecture.
When using the observer pattern with Scriptable Objects, whatโs the best way to pass in scene references to objects? Is this where the scriptable object system sort of falls is you canโt do that?
Like I have cameras which have an IK target which I wanna set to my player
Which means I have 2 separate prefabs instances that need to communicate: my player and a camera
The camera needs the players transform
do you mean using an SO as a mediator?
Yes
Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...
This is the talk I watched, it seems very useful for quicker development
its a very dangerous pattern, can easily ruin your project
How so?
it quickly becomes very difficult to understand whats going on in your project
Hmm
mostly because you put relationships into data that are mostly interesting to someone looking at code, so its very hard to trace how logic flows
It makes your code extremely reusable and makes your project do stuff that it wouldnโt be able to do normally with concrete implementation, thatโs where it catches my eye. But I see why it could nest into design issues
this is the promise, yes, but its a chimera
I imagine thereโs debuggers you can use though to see what the flow of events is that could be leading to your issue
there are some implementations that aim to mitigate the issue, but none of them is really all the way there
I mean I have to figure the time to fix a design issue severely outweighs the time to debug something, and the total time to fix something in your project that would already be decoupled with SO
technically the SO mediator is the same as a channel or message bus, so its not a bad pattern in of itself, it just needs to be used carefully and SO-mediator just fragements too easily (its too easy to make new channels) vs. using a code-only message bus / mediator with an architecture based on IoC
Iโll try it in this project Iโm working on to see if I like it. As far as my previous question goes, does an SO mediator in itself not have a good solution for that issue?
I tried a DI container (Zenject) but it took way too long to implement basic things and while it does have pros it has a lot of cons I wasnโt a fan of
dont use DI containers, but do use IoC with manual injection
Isnโt that just the unity inspector?
you can do injection with the references you assign in the editor but thats not IoC
IoC is about making "engines" that "run" specialized pieces of code without either knowing about what specifically the other does
Are there any existing frameworks that donโt have the time overhead of a DI container, while maintaining a similar style?
Right
I should rephrase what I said before. The unity inspector is DI more than it is IoC
all DI frameworks at the end of the day get abused and become a nightmare of tightly coupled code (ie the problem they aimed to solve)
Right, itโs just a huge pain with factories and stuff especially when you get into multiplayer itโs just a big pain
i think all you need is a dev team that deeply cares about and understands IoC, then you don't need any frameworks
Isnโt the general idea of IoC that the framework controls your workflow, rather than yourself?
Like a DI container Is a form of IoC because it controls the dependencies that are injected via bindings in the framework
but its important that this is not a logical argument, its one based on how development happens over time, in a context of constrained resources, in theory all the frameworks are great.
I dont think thereโs a one best framework or pattern I think itโs all based on personal preference
@silent matrix if a dependency injection felt like too much work, I'd recommend a code only event bus - like Anikki said. I manage to keep things very separated, but I'm a solo dev on a small project.
My personal preference is to have as much code reusability as possible, with my project being as flexible as possible, thatโs why SO abstraction catches my eye
I agree DI is too much work, but it could also be my limited knowledge of the framework. As far as an event bus goes, isnโt that similar, or the exact same as SO event channels but SO event Channels have less code and more flexibility?
in IoC, fundamentally, you make a bunch of little engines that can be injected with objects that implement specialized behaviour. Unity itself is an IoC framework, it gives you the Start() and Update() callbacks, which you can use implement behaviour in, but Unity itself cares little about what behaviour it will run, likewise you care little how unity calls these callbacks, you just care about the contract (start runs only once, update runs continuously in time slices that represent "frames)
Right, yeah IoC is very powerful in my opinion but I havenโt found an IoC framework for unity that does what Iโm looking for
Thereโs not really a good one solution for all projects as far as that goes though
@silent matrix I guess, but it specifically keeps all the logic in code so you can read through and follow the events without considering an asset instance and how it's configured
why do you need a framework for that? you can do this very simply without one, its just an idea how to structure and call code.
I mean framework as in a standardized workflow for all games which isnโt possible
@silent matrix have a look at this: https://youtu.be/RPhTEJw6KbI
i don't think its a good idea to structure a game project along the lines of any one pattern, the needs of various systems are too diverse. IoC itself however does not contradict any of them, you can implement it always in different ways, even in data oriented ECS which is the purest form of IoC
My only issue with relying on events is that it almost looks, like a parallel / threaded system, so at least once I tricked myself with the order of execution of my listeners. And currently have one ugly "Invoke()" which is only there to make sure it runs after all other handlers
Thatโs what I mean. You canโt have one pattern or framework fit all projects
Iโm watching it now
Also I Chose the SO system because my team of friends doesnโt know how to code but they do design
there are still a couple of things you should do in any game that almost always work out to good ends, and that is separating data from data-logic control-logic from data-logic and and views from all logic
So this way my team could influence the game without coding
How do you mean by this?
the idea is to use data-only objects as the primary way of communication between layers and systems in your architecture, this way your dependencies are on data, and not on behaviour of other systems.
this is a very general idea, there is no specific way to implement it, but having components dedicated to holding state (fields) and others exclusively to behaviour (no state) based on those data components is a start.
This was a great video and I get the idea of how that might work in comparison to design only, Iโll take it into consideration with my projects
it turns out that this makes it easier for your game to adapt to spec/rule changes and makes your code very reusable (it just depends on data and encourages to make small components)
Okay that makes sense
But as far as in scene references go, SO doesnโt really help with that I imagine?
I have to write some other script for it?
I mean Iโm a programmer I like coding, I just donโt like writing similar classes over and over again when I have the ability to reuse code (like every other coder I imagine)
As well as the data and operations split, I'd also suggest a third, that of relationships... to objects, prefabs, instances and/or specific components on them that you'll want to communicate with, kind of like little "relationship managers". The power of this, and convenience, becomes more essential the closer you get to iterating towards completion
scene references don't really exist at runtime, best you can do is reference a build index or name
There are LOTS of problems with relationships in Unity, from finding objects, to links breaking in the Inspector, to pooling, performance issues, memory management and scene loading and unloading vs retaining some objects, etc... all of which you'll do in multiple different ways along the road to completion, so having a relationship manager is IMPORTANT!
What do you mean scene references donโt exist in runtime? They exist in build time and runtime?
I mean scene references as in like gameobjects within a scene
Not prefabs in the editor
ah, ic what you mean, well SOs cant store references to scene objects in their fields, but you can obviously pass them as arguments to any methods on your SOs
Right, thatโs the issue I was facing, but because it forces you to not have that in scene reference it works independently of any scene state
Do you mean relationship manager as in singleton 
yes, the while point of SOs is that they exist outside/independently of the concept of a scene
Right thatโs a large advantage
some argue that SOs in themselves are also a bad idea when used for lots of things in your project because there is no good UI to manage them besides clicking on them and editing their inspectors individually
so, if you opt for using a bunch of data SOs, of any kind, you should expect to write a bunch of custom tools (either in the editor or externally) to keep things manageable. But thats true either which way if you have a bunch of data.
Actually someone just told me you can set an SO field in code, it wonโt serialize but it will work, and you can set it to a scene object
a SO is just like any other object in that regard
but if you set SO fields at runtime (treat them as mutable), you're basically setting yourself up for a mess
its commonly considered a bad idea to mutate serialized fields (just from experience and how it makes it much harder to understand and reason about your code), its obviously a bunch of work to implement a "default serialized value field with actual value field and properties to manage it") but thats the clean, explicit way to do it, or just find a different pattern that doesn't require overriding serialized values.
sadly the whole bunch of built-in components violate this principle
and typically any assets you buy on the store also go down the easy path of just overriding the serialized defaults directly. Which is somewhat OK because these external codebases can be differentiated from your own and nobody on your team is going to change them without you noticing.
this global static event processing yields the same mess in code that SO Mediators in the editor produce, it needs a serious dose of dependency injection and IoC to become safe. Granted, it may work for short term solo projects.
Can you give me an example of how this may bite you later in a project and how it becomes messy?
its globally accessible so any system at any time can use it to fire any event, there is no concept of encapsulation, layering or scoping, putting all the responsibility of correct usage on the client with a bunch of non-explicit conventions. She is also tightly coupling her code to the existence and expected behaviour of this event system (which is essentially, anything can happen for any reason at any time), requiring any subscribers to handle all edge cases themselves. Basically what she's doing there is again abusing a singleton pattern for easy access. As i said, its not bad to have a Mediator, you just need to make sure there also is IoC. Typically you'd put the responsibility to communicate between systems into some sort of layered managers on higher levels of abstraction that specifically deal with communication between systems and facilitates the responses in its client object.
Most of the time though, isn't it just one thing that sets a variable and you use that information which the SO acts as the abstraction between your data implementation and data itself in that example?
Like if I have a security camera which I want to look at my player
I could create an SO, LocalPlayerTransform, which is only set by one thing, my player
and anything that uses it is not gonna change what LocalPlayerTransform is
its all fine during the first couple of weeks of development, it only breaks down when you need to change things that arent neatly encapsulated by your previous decisions or when new people join the team.
note that these aren't implementation changes, they are relationship and flow changes
also, this argument about layered managers to handle communication that i mentioned makes all this very cumbersome to implement, so nobody wants to do that, which naturally coaches your into using DI containers, only to realize that you gain nothing (same pattern of singleton abuse emerges) and the only clean solution ends up being an ECS structure, which has a different bunch of issues, not the least being that it forces a different way of thinking and it becomes very difficult to bring domain concepts and code concepts together.
so a simple, soft precursor to going all out ECS is this vague notion of "using data objects for communication" and "when given a choice, opt for IoC"
And when you say IoC, are you referring to the coding aspect or a more figurative "designer" IoC. I.E. designers use the flow of data to control the gameplay, rather than code in itself
i was thinking of the code architecture IoC but i suppose the designer IoC would also make sense to consider. There is certainly added complexity when allowing designers to control too much of the logic.
I'd be immediately worried if a designer can hook up events to drive how arbitrary entities in the game interact (mainly it becomes hard to see what the identity of something is). Designers are very creative and some are very excited to be given tools to implement logic. But to caveat this a bit, its very nice to give them such tools in a clearly scoped way, say to implement the behaviour of a monster, here the whole system their logic acts on is represented in one place and nothing outside it can be affected. The code then becomes a pure implementation of IoC, behaviour engine + vocabulary of action nodes and allowed relationships and the designer can add data to make it express something, but its never used to allow the designer to use logic to define the identity of something (i.e. what something is) in a roundabout way (if that makes sense).
So you mean like the designer should be able to influence what an enemy attacks or properties of an enemy attacking such as speed, but not how it attacks in implementation?
like they shouldn't be able to somehow control the AI system through SO lol
i think it should be wrapped into different systems that cannot influence the details of each other (both can be designed by the designer). they should be able to piece together the actions, flow, timing, decisions of the monster but not how the monster gets spawned or what happens if it finally dies, its loot or any scoring as part of the same system.
You had me until you said they can't control the loot ๐ Why can't they control the loot? They're designers
you are missing the key concept
its all designed by designers, but not in the same system
the point is, the fighting behaviour system should have no way to modify the details of the loot distribution system and vice versa
that same separation of concerns should be present in code, it does not matter if the person changing it is a designer or coder, its a matter of making decisions flow along a clearly defined path, with explicit interfaces and obvious boundaries.
No, that if you're going to make separate components for data vs operations, as Anikki suggests (and I would also suggest) then anything remotely complex should also have another separate component for building, maintaining and creating relationships, especially during the creative and iterative processes of evolving your game
I work better off of examples. Would this tie into my security camera and local player example, or is that not complex enough?
@silent matrix i think this idea of capturing everything, especially relationships, in some way is indeed very important. So if you have for example a character and that character has a different move set based on whether they are in a fight or in the world (think JRPG with specific fight mode as an extreme example), you this notion of "has different move sets" needs to be explicitly managed somehow. and as you can see from a JRPG example the relationship between the player and the world is fundamentally changed by whether or not the character is in a fight. This transition also has to be captured. Its very easy to do this quickly by a switch or if but the more this is an integral part of the game, the more it should bubble to the surface (i.e. a higher level of abstraction), become an enum, then a separate class, then maybe a framework. It should never exist purely implicitly in the way some events are hooked up in the editor. Note that OOP is inherently bad at capturing relationships in of itself.
Hi, i have this code that is a simple follow player script, and the AI shall avoid anything it collides with, except with the Terrain Layer. This is the code:
void Start(){
player = GameObject.Find("Player").transform;
//obstacleMask = 1 << LayerMask.NameToLayer("Terrain");
excludeObstacles = ~(1 << LayerMask.NameToLayer("Terrain"));
}
void Update() {
// Calculate the distance to the player
float distanceToPlayer = Vector3.Distance(transform.position, player.position);
// If the distance to the player is within the follow range
if (distanceToPlayer > followDistance && distanceToPlayer > stopFollowDistance) {
// Get the direction to the player
Vector3 directionToPlayer = (player.position - transform.position).normalized;
// Check for obstacles using colliders
Collider[] colliders = Physics.OverlapSphere(transform.position, avoidDistance, excludeObstacles);
if (colliders.Length > 0) {
// If an obstacle was hit, calculate a new direction that avoids it
Vector3 newDirection = Vector3.Reflect(directionToPlayer, colliders[0].transform.position - transform.position);
transform.position += newDirection * speed * Time.deltaTime;
} else {
// If no obstacle was hit, move towards the player
transform.position += directionToPlayer * speed * Time.deltaTime;
}
}
}
}
For an unknown reason it now ignores every layer, while i specifically excluded layer Terrain only. Any ideas?
EDIT: solved, problem was a collider attached to the game object in inspector, that triggers collision on its own. Fixed with:
if(colliders[numPreAttachedColliders+1].gameObject.GetInstanceID() != gameObject.GetInstanceID()){
... or remove any (in inspector-) attached collider, then it works too.
Okay I think I understand. So like you said there are defined boundaries in code that are implemented that provide a cleaner game interface for designers that defines how far they can stretch as well?
you could say that yes.
tried negating the layer mask?
Yes, well afaik this is already the "negative" version, indicated by ~
excludeObstacles = ~(1 << LayerMask.NameToLayer("Terrain"));
(or?)
negate whatever you have then (remove the ~)
correct
Sorry, not sure what your example was/is. I'd say a general rule of thumb, as to when your little commander object (with its separated data and operations) needs a little relationship manager component of its own, is if you're asking yourself, often... "I wonder how this would work with... -someOtherObjects-?" And if you're working with designers and they're often wanting to swap in and out different objects and/or create or try differing relationships, then the relationship and communications manager component becomes an increasingly good idea. And/or the more outer relationships become interesting to test/explore in the design and evolvement of iterative creativity etcc
So
excludeObstacles = ~(1 << LayerMask.NameToLayer("Terrain"));
and
Physics.OverlapSphere(transform.position, avoidDistance, excludeObstacles);
is fed with "excludeLayers", which defines a negative mask, meaning it should now collide with everything except terrain. But it does not, which is a mystery to me
if it collides with everything except the terrain, then invert the mask and vice versa
ok i will fiddle around with this again and report back if it worked, thanks guys โ๏ธ
(current state is it collides with nothing)
and obviously make sure the colliders you want it to collide with actually are on the right layer and the layer name is correct.
i was trying to avoid having to set layers for all obstacle objects, instead, i wanted an "exclude" way of going, meaning i exlcude anything the AI shouldnt collide with.
The way having a positive mask and setting all obstacles to an "obstacle" layer was tested and is working in the same code, but as soon as i use negate (~), it stops working. Maybe Physics.OverlapSphere is not intented to work with negation masks, but i believe this is tied rather to "LayerMask", which allows negation. So the behaviour of my code in current state makes no sense, it should work as expected. Well i will try to debug further and let you guys know if i found out the reason for this not working. Thanks a lot for the input!
the mask you pass to overlap sphere should mark the layers that you want to include, as per documentation:
A Layer mask defines which layers of colliders to include in the query.
ah so it is limited through overlapSphere if i understand this correctly? As when working with Raycasts and Layermasks, the exclude (~) operator works well (tested just yesterday). I thought this ~ feature is bound to unity's LayerMask class. Thanks for pointing this out!
its typically a good idea to make layers such that they define a shared aspect of all its members.
generally layers are an optimization feature, a way to very efficiently query for a subset of things
if you want to define grouping for gameplay purposes you'd use tags or a system based on Tag-components (built-in tags are essentially an unlimited list of layers without any utility for optimization)
Thank you for the insights, so layers and tags are "best practice" way? I tried to stay away from them until now as i thought it may impact performance more than native ways (but i may be wrong).
For the current situation, i see one problem with layers/tags: imagine bigger asset libraries with lots of 3D objects, dozends of trees, gras, rocks, etc.. When having a positive obstacle layermask, i would have to go through each individual 3D model asset and check if it is something the AI shall collide with or not.
i dont know many people who use built-in tags, but layers are required for certain things, especially physics and rendering.
ah ok, thank you for pointing out, i will make more expections then for layers in future, when i have to decide if to use them or not
the most common way of identifying objects in a collision would be hit.TryGetComponent<T>(out T other), and then checking some sort of enum or hash on the other object if you need more specific identity.
itering through all collisions and then check for layer.. good idea indeed ๐
you'd use layers to exclude all the collisions that are categorically irrelevant to the system you are currently working in from ever being queried, and only then iterating over results.
After figuring that Physics.OverlapSphere does not support negation masks, your last mentioned method is the best suitable way i believe, i will do this then : )
so in your case, you would have a layer with movement blocking colliders, and query only that layer, and ignore all colliders that are irrelevant to a blocking check
its common to have multiple colliders on any entity with different shape and on different layers for various purposes
ah, well i wanted to go like "if (!layer=="terrain").. something like this (to preserve the negation mask effect)
just make a blocking-objects layer
or multiple ones
but i would have to assign this to each tree, rock, etc.. i believe the negation way works well now too, after itering through the collisions by hand
you could have layers that are called "environment" and "props" with environment also used for blocking checks and props deliberately not checked for blocking
then you could use these same layers to toggle rendering of the environment when you go indoors, if you ever run out of layers
wow ok the last one is an extremly good example of how layers may be usefull, the indoor/outdoor blending is something i can imagine be eased up a lot when using layers more than i used to in the past
i dont think its a particularly good idea to overload layers that way
but its certainly possible
Ok thank you, this is still great input! Overall, i overthink using layers more often from now on ๐
I'll head back to the IDE and test the given tips, thanks a lot @compact ingot ๐
I though about this and my running issue is, the inventory manager will have the reference of the SO, then the Slot will have the reference of the SO and the equip slot will have reference of the SO. This way, should I want to remove the SO completly I would need to remove it from the Inventory manager, Slot and or equip slot as well.
Thanks for the reply.
Considering I am a solo dev just trying to make my game dev journey a bit easier by avoiding as much pitfalls as I can. No budget, a small deadline for when I want to complete something to keep me accountable and possibly a few testers in the coming months. I am pretty much just trying to find my feed in the most efficient way possible . Should I fail on an idea, the knowledge of how the idea should be executed or how I should approach any of the 10 possible solutions should not be the causing factor of the failure right?
i think the best way to learn is trying things with the intention of failing while understanding how the decisions one made led up to the failure. Then trying to push the failure point further and further back on each subsequent project. But never worrying too much if it happens even sooner from time to time. Considering advice found anywhere, its important to consider who is giving it and if their context matches our own. Just because something sounds plausible, that doesn't mean it works for you, and a bunch of plausible ideas gloss over the gaping pits you can fall into when applying them without truly understanding their context/motivation. If anything, strong opinions should make you cautious, but there is often an opportunity for review of ones own conclusions/opinions when they bump into opposing ones hold dear by others.
also consider that the bigger a team gets, and the more points of friction such a team has, the more abstraction/indirection is required in a project just as a way to facilitate the team's workflow and politics. You could say that, in some sense, you should make a separate class in your code for each meeting you take to isolate the concepts/changes discussed in it.
@compact ingot i apologise, i just figured that the code i posted half an hour is working perfectly (even with negation mask), the problem was an other collider attached to a child game object, which (i didnt see) was triggering wrong collisions, that i didnt catch with debugging. Still, i took away some things about layers, so thank you โ๏ธ
is it possible to figure out the target platform of a built asset bundle file somehow?
@jolly token I'm trying to build a game whose installers create the needed objects themselves without relying on Zenject, as you suggested. But I meet trouble of getting references to loosely related fields in runtime (when instantiating). For example, how would I go with connecting score and movement modules so that when characters passes some distance, the score raises? I cannot use [SerializeField] as prefabs cannot have references to scene assets and it's very very very very undesirable to create hierarchies of zenject contexts (very). Do you have any ideas how to do it properly?
With all regards, Telov
I tend to have Monobehaviour factories/spawners that hook these things up manually. Often this stuff is simple enough to not really need automated dependency injection.
could you give an example?
It's generally just a Monobehaviour with inspector serialized references and a spawn method. Spawn method has bunch of TryGetComponents in it to fill dependencies those components need. Nothing here is automagic.
hi, i use an old version of Unity (5.6.5) and when i try this script :
i get this error :
then i tried that but i got an error too
in the first case you're trying to use a language feature that isn't supported in unity 5
In the second case you're using the collection initializer for Dictionary wrong
https://gdl.space/ahuqakerot.cs
PlayerSpawner might call into some other spawner to create the object to share some of this set up with AI objects instead of using Instantiate directly, but it's essentially the same.
I had already figured out the problem but I don't know how to replace the first case with something that works in C#4
static constructor
wdym
Did you google it?
Yes using factory as danny suggested makes sense - you can place factory (spawner) in the scene and then it can reference scene object. It can inject the scene reference to instance at the timing of Instantiate
If you have a static dictionary, you should just add either one keyvaluepair or create that dictionary in your constructor. And what is Test?
I think the factory is so.... narrowly specified and inagile
You need to add a keyvalue pair, you are trying to add two keypairs for c#, but one is just the id and second is your condition.
What I do is I have reactive โmodelโ (that should be injected) then both player and UI only sees/modifies model, not directly referencing each other
can i rearrange my code to make it work?
unirx?
Google on how to add objects to a dictionary and be sure on what you want. You can have a dictionary outside of your constructor. And the constructor then sets the values, but you have to make it right
I use them but it can be plain C# event or anything
could you provide an example?
Maybe when Iโm in front of PC ๐
I'm excited to see it
No errors, than its right. But what do you actually wanna do with it? Calling a new instance of that class just to get the same value added all the time doesnt sound right
Think of it as a "code as configuration" solution for Unity ๐
Generally I just focus on keeping to glue code outside of components that could be arranged in different ways, allowing me to change the setup if needed by reconfiguring few glue scripts.
The amount of work the machines that replace these glue scripts were doing just didn't seem right for anything I was using them for.
i just want to assign a value to this dictionary, but i guess i can't do that without calling a new instance (the error say that i can't autoassign the dictionary)
no no, you can just add a function and call that function
public static void AddCondition(string id, condition myCond)
{
Conditions.Add(id, myCond);
}
something like my example, its discord written, so no testing ๐
I have a question: is there an equivalent to void Start() outside of MonoBehaviour? (when i just use "class" instead of "class : MonoBehaviour")
Nope, if you just use a class, its a class on its own. Nothing Unity knows about if you dont hook it into something afaik
ok thanks for confirming :D
Look into constructors in C#
I'm struggling to imagine the code behind this if it's not a singleton.
sure...
if (Status != null) {
var afterTurn = Status.OnAfterTurn;
if (afterTurn != null) {
afterTurn.Invoke(this);
}
}```
I just learned that gpu execution way differs from general source execution with the cpu. So when you do rb.addforce() it compiles to bytecode I assume, and then itโs runtime executes it. Butโฆ what does the bytecode for addforce do besides like itโs normal stuff. Like at the lowest level, how does it go from a cpu bound task to then showing up on the screen?
AddForce has literally nothing to do with the GPU at all
it's just a call into the physics system
which happens to be a native library called PhysX
Ye, but Iโm saying, where does that then get translated to showing up on the screen.
Like from whatever it does, then where is it actually applied to moving stuff on the screen.
And why exactly canโt the gpu execute bytecode like C#โs or pythons.
because C# and python bytecode compiles down to x86 or ARM machine instructions which GPUs cannot run
There's a rendering phase where all the objects in the scene are rendered
Is it bc of the cores?
physics isn't really relevant to this
Before that tho
it's because of the architecture of the chip
Not specific to addforce. Iโm acting like in general.
before that... physics and all your scripts etc run
Here's an overview
https://docs.unity3d.com/Manual/ExecutionOrder.html
Like, going from the script to the gpu.
Like, when all the code compiled
there's basically no link between your script and the gpu
your script moves things
Ik. Itโs hard what Iโm trying to say
the engine sends commands to render all the things to the gpu
Give me a sec ima try and reword
the gpu draws them on screen
So when you do addforce. It then goes to the cpu which does smth right. Then it goes to smth else. Now it has all of its data. So then does the cpu then generates code that the gpu can run and then uses the c header to send it to the actual gpu using the kernel and execute?
No?
the only time the cpu is sending code to the GPU is when it's loading shaders into the GPU
At no point does anything related to AddForce cause something to run on the GPU
The frame works like this, roughly:
- physics happens and moves objects
- your Update code happens and moves objects
- At the end of the scene, unity goes through all the Renderers in the scene and tells the GPU to draw them
I know the add force is an exampleโฆ
Iโm saying going from point A to point B
So what runs the renderers. The gpu right?
renderers are handled in the CPU world. They are components attached to your objects and they tell Unity to make draw calls to the GPU
I think the part you might be missing here is the Graphics APIS
like DirectX, Vulkan, OpenGL etc
these are libraries in CPU world which pass commands to the GPU to draw things
just one example - in DIrectX you can draw stuff like: https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-draw
And what are the commands that is actually being sent?
stuff like this
etc
these are what people are talking about when they say "Draw calls"
of course UNity supports multiple graphics APIs, not just DirectX, so this is just one example
there will be corresponding functions in Vulkan, Metal, OpenGL, etc..
Unity calls these things for you, typically you don't need to worry too much about it
So how do the calls work? @sly grove
you call them, the gpu draws stuff on screen
Like what do the calls actually do?
on what level? That's an extremely vague question, I don't even know how to answer it
They tell the GPU to draw things. That means running little programs called "shaders" which ultimately result in coloring pixels on your screen
Like at the lowest level
Hm. So are the shaders pre written?
Or autogenerated relative to the input of the calls
um... well you see the atoms in the silicon have electrical charges and... IDFK go read some research papers lol
Shaders are written by people
or generated by tools like shader graph
#archived-shaders if you want to discuss them more
Lol
So the data psssed into those calls to be rendered. Donโt they have to be appended to the shader script so that the stuff that is rendered is different?
You pass data to the shaders, yes
stuff like mesh data, textures, and any other properties the shader needs
this is done by writing that data to buffers in GPU memory
Buffers? Iโve heard so many implementations if the word buffers. Like a variable temp cache? Or waiting to store data like a YouTube video buffer?
a buffer is essentially just a reserved area of memory
Hm I see.
basically an array
youtube video buffering is called that because video data is stored in memory before being played
Interesting. So why canโt there be other shader langs that compile to the same binary or bytecode that the gpu requires?
Hm interesting.
there are
Unity basically has a transpiler that converts its own shader language into the different ones used by different graphics apis
So what is the difference between gpu machine code and cpu machine code.
it's just in a different language
because the devices have different capabilities
so they support different commands
Like, why coukdnt C use a lib that generates the same machine code as a shader lang?
it could
Thatโs what I donโt get. Is it a different type of machine code?
Oh
or do you mean
writing shaders in C
It could deinitely done but the language just isn't really designed for how GPUs operate
it would be very clunky
Like you need a separate language that a can understand. So what makes it different and why.
Hm ye.
it's nothing that different, it's just designed to miake the kinds of things you do in shaders easier
in fact GLSL and HLSL code has a very c-like syntax
but it makes it convenient to do operations on vectors and matrices, which are often used in shaders
So the machine code is exactly the same? Like same binary structure and everything? It is just that a shader language has all the built in things u may need?
How does that differ. In terms of what it looks like?
Like what the machine code looks like?
this answers it better than I can
Ah ok Iโll check it out. Tysm for all ur help @sly grove Iโve been using python for a bit snd started making more complex things but I always wondered why. So I wanna understand low level things so I donโt take anything for granted. And eventually make my own low level useful tool. Also itโs so goddamn interesting.
It sure is
And in the python chat ppl were talking abt game engines. And we were getting into the nitty gritty on why python is good or not good for game dev. So I wanted to take a deeper dive on that.
And here is the best place for asking abt game dev!
I think the short answer is it probably looks kinda similar in structure to CPU assembly, which looks something like this:
_start: mov rax, 1 ; system call for write
mov rdi, 1 ; file handle 1 is stdout
mov rsi, message ; address of string to output
mov rdx, 13 ; number of bytes
syscall ; invoke operating system to do the write
mov rax, 60 ; system call for exit
xor rdi, rdi ; exit code 0```
The difference would just be the instruction names and register names
Ah that makes sense. Register names? Arent registers like the frames within cpu memory? I dont know exactly what data structure registers are.
I just know it has to do with cpu memory.
When I say "register" here I'm talking about CPU registers. They are basically very tiny memory slots that are the lowest level fastest memory on the CPU. THey are for holding temporary results of calculation and memory addresses etc. that the CPU uses for executing the program
any time you do something like add two numbers, those two numbers need to be loaded into registers, and the result will get spit out into a third register
from there they can be copied to and from main memory, etc..
Thats very interesting.
What is the format of registers? Is it like a small stack?
Like a super small stack that just pushes and pops data coming to it?
And do they all do different things?
there are many "special purpose" registers - for example that hold the address of the current instruction in code, and ones for holding the place of a calling function etc.
There are some "general purpose" registers which can just be used for whatever the programmer wants
Ok i kinda even explaioned that wrong
the wiki has more info than me
I see. Doesnt the callstack hold the data generated from a function call?
Can anyone put me on the right track for how to implement lots of interactable environmental objects? like trees, bushes, rocks etc? Do you use the same kind of chunk based method you do for voxels?
https://gist.github.com/cathei/e904d00d522e6dcca6708127cc2bcb9d
Here you go, it's pseudo code but you'd see only PlayerSpawner knows about Player and ScoreUI
If you want you could also split it to PlayerSpawner and ScoreUISpawner
You can create a base class such as Interactable which provides all of the implementation for an interactable object, and then apply that script to anything you want to be interactable. You could also add virtual functions such as OnPickedUp which lets you have modifiable events for more complex items
That second part would be more an item
so maybe separate that
For example if you know ahead of time that all items are interactable, then you can extend Item from Interactable
and then you could have something such as Vegetation which extends from Interactable as well, but it's not an item
it depends on your game and how you would like it laid out
different solutions work for different games
I'm wanting to do some animated text with rich text and TextMeshProUGUI - and realized that I can't unfold this one character at a time since the RT tags aren't complete until .. later. Anyone cleverer than me have a solution?
my first thought is: let TMP generate the entire message, and unveil it a character at a time by manipulating the mesh
Appears I can't understand it without knowledge of reactive programming
Trying to get Mesh.CombineMeshes to combine me some meshes, but it looks like I don't understand how to do submeshes
Can I just feed all the submeshes into the CombineInstances and generate one big mesh in one fell swoop?
Or do I need to generate all the submeshes, then generate a master mesh and assign all the submeshes to that one?
Looks like it is definitely the latter
Anyone knows how to write to a Unix Terminal when starting a Server in headless mode?
Or just writing to Linux Terminal in general
Hey all, I've just gotten back to an old project and no matter what method I try, I cannot get a rigidbody to move (new object + new rigidbody default settings + 1 line of code in update - velocity is set but no movement). However, if I do the exact same in a new project - same version, it works fine. Does anyone know of any project specific settings that can mess with the physics? 1 package of interest I have installed is FishNetworking but I dont remember this being an issue when I first installed it
Hey, I'm using addressables to load an image asset when selected in a list. The problem I'm having (and I could be using addressables completely wrong here) is that when I load the first image and then load the second image, I release the first one but then if the user goes back to the previous one, I get an error saying that the asset was already previously loaded. How could I solve this?
(Apologies didn't see the #๐ฆโaddressables channel before posting this)
anyone have exp with static batching at runtime? i have an issue, i want instantiate a game object at runtime and make it static to be static baching, what i have to do ? (try some way in internet but not work)
static batching is run at build time
everything that instantiated cant be static batched
there is the StaticBatchingUtility
it allows you to combine multible objects together if you have have a group of objects that will not move or only move together under on object
Perfect, thanks.
Not really! Like I said it's a pseudo code, just event subscription and value update is all I used there
Oh, would help if it was some real code I guess
How so? What part do you not seem to understand?
With actual UniRx code it will be more complex to understand
Just to get a glimpse on how reactive programming works and how it can help in the case
Well as you see Score is ReactiveProperty
If you set Value there it will publish OnChanged event
Rx's Linq-style operations are just sugar on top of that
lol? i saw that @thorn flint ๐
Spammers! Everywhere
Bot seems to do the work, haven't seen a scam link in quite some time here
It's pretty good at deleting them, but we still then have to notice it's happened and ban the account
Wouldn't it be possible for the dyno to message a mod? or modmail, or would that be overencumbering
It's pretty obvious when it happens because all the channels become unread instantly since the bot attempts to hit them all at once.
How do I display real time or month through text?
Hi, how can I store the unity logs in a string array and update it everytime there's an update ?
does anyone know how I can fix this problem?
how to test custom package in CI pipeline? since git repo is a package and not whole project that can be run with unity CLI
Create a project that contains the package and run your tests in there
but that would require another git repo, import tested package there and all that in pipeline. theres rly no other way?
and thats 2 git repos in single project folder (and package mgr manages that, not git submodules)
Hey does anyone know how i could make a Gradient Rainbow Border Effect on a UI image?
so it looks something like this:
might be better to ask her perhaps?
This is a single gameobject. Is there any easy solution to simplify the mesh? It has too many indicies now.
if it has multiple meshes, you can combine them into a single mesh
if it's already a single mesh, leave it be imo.. very likely not worth the hassle for this few vertices
They where multiple meshes, and then I combined them. But I want/need to optimize further. Ive heard about greedy mesh, but im not sure yet how to implement it.
not sure about the 'greedy mesh' term, but to further optimize you'd need to do smth like this:
which would require adjusting the UVs to keep the texture intact
which is a pretty headache-y task, and may/will degrade texture quality even if done properly
if you're fine with that, then just go at it.. it's just math ๐
I was thinking more like this.
That way, its always a square, and easier to put texture on.
sure
are you planning on releasing an asset for it? or, just educational? or optimizing your game?
might be worth a look ^
it likely doesn't remap the texture or UVs (which is the hard part), but may be a good start
Oh, this might be nice! Ill look into it.
Do you see if it has any documentation?
no but it comes with source code :p
Hi there
does anyone know how to access streaming assets of a webgl build?
I've already implemented it with a UnityWebRequest, which works perfectly on a local build
but once I put the build on the server, all requests fail with a 404
Runtime generated meshes are invisible in build/IL2CPP/Standalone !!!
but it is completely OK in Unity editor
sure it the mesh and not the material?
Yes, I guessed as you do and test it with unlit material and it did not differ, still it is invisible
dos it work if you set some pre saved mesh?
How can I test it?
save them in runtime and then load?
have a variable with some basic mesh and then try to set it to the meshfilter at runtime
if that works its how you generate the mesh
Editor
I have added lunar console but it only works for android?
I want to see if there is an error in the console
Yes, I assign the mesh to meshfilter
you can make a a debug build and connect the console to see what is up
OK, thanks
another usfull tool might the frame debugger be
it lets you see what is going on in each drawcall so you might be able to see what is going on with your mesh when its been drawn / not drawn
[Collab] Collab service is deprecated and has been replaced with PlasticSCM I am trying to use plastic scm but is highlighted grey and i have this message in console
Don't cross-post, this is not a programming question either.
Show what you tried
not a code problem
My fault, Sorry
Hello everyone, was just writing a custom RP.
Wanted to understand if there are any guidelines or best practices while issuing draw calls?
Hello! I'm having trouble trying to call this line of code from a multithread job
nearbyHits = new NativeArray<RaycastHit2D>(Physics2D.CircleCastAll(transform.position, radius[index], transUp[index], radius[index]), Allocator.TempJob);
I've looked online and it seems like I'm not the only one with this problem. Is it at all possible to do a CircleCast from within a job? is there a way I can call a method from this thread back to the main thread and return it to this thread in a clean way?
Similar question:
https://answers.unity.com/questions/1721502/is-there-a-thread-safe-way-to-check-for-overlap.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Hey so if I use GetIndexBuffer on a raw buffer and send it to a compute shader, how do I then read it if its 16 bit? as far as I can tell theres no way to read the raw index buffer if its set to 16 bit on the mesh in a comptue shader but there must be a way right?
basically is there any way for me to read 16 bits from rwbyteaddress buffer so I can support meshes whos indexs are set to 16 bit(as opposed to 32 bit)
I ended up having to copy the CPU side indexes into a comptue buffer and send that... not ideal but it works, if anyone has an alternative please let me know!
Not sure if this is the right channel for this but I just ran into an issue that is driving me crazy. I've never had anything like this happen in Unity before...
I've been refactoring and cleaning up my RPGStat system and it's custom editor (using OdinInspector). I basically finished yesterday and everything worked like it should. I minimized Unity and when I opened Unity again ALL of my "StatDefinition" ScriptableObject Assets have Missing Mono Scripts. They all just sponaneously broke... I have no compiler errors and the "StatDefinition" script exists in my project... When I manually select the script from the SO Asset inspector I have to add it twice for the broken asset to become a StatDefinition again... and when it does all the data it previous had is wiped. I'm at a loss for what happened and I'm second guessing using ScriptableObject assets for this purpose... If this happens in my primary project after I implement this code it would be soul crushing to lose the data and references for dozens and dozens of Assets.
did you muck up the meta files somehow? that's usually the cause of something like this
This is why you should use version control even for random prototype throwaway projects, it takes less than a minute to set up and could easily fix this issue, if it is indeed due to meta file shenanigans.
I didnt mess around with anything. It worked and I minimized Unity and when I came back the data was broken.
you didn't rename or move any files while refactoring?
I created a few class files and moved some stuff into folders but not the StatDefinition class. Also when I did do those things I was still actively coding it and it was working fine.
I just tested out moving files around and nothing broke. If that was the cause I guess it's just rare right? Thankfully I dont care about this data it was just made to test stuff but now Im afraid to use the code until I figure out what caused this.
Are you using SerializeReference or SerializedScriptableObject of Odin?
@jolly token Nope not using any of Odins serialization. Just normal ScriptableObject.
and normal SerializedField for references.
Hmm that's good. If you are doing version control I would see what changed to those assets with issue..
@jolly token yeah I should use version control with the smaller side projects. Thankfully it was just placeholder data i was using for testing.
Hey, I recently ran into an issue. i want to create a terrain represent ing a desert with dunes. My issue is how I can calculate the height, with which formula? I thought about using Gerstner Waves, due to their similarity in appearance, but I still don't have a formula for my desert dunes. May anybody help me out?
I dont know if there is a specific 2d circle cast command but you can use this https://docs.unity3d.com/ScriptReference/SpherecastCommand.html
As far as I know there is raycastcommand spherecast and capsule cast
Hi guys,
I have a big circle with buttons around, and I want the buttons to adapt to their environment.
Here's an example above, if we move the big circle to the corner of the board, it will adapt.
An other example will be another circle coming to close to this circle (for example on the right and it will push the buttons to the left)
Where I should go/look into to achieve this ?
Thanks a lot
(And i guess ignores the display of the description, it will be independent of the logic i'm trying to achieve here)
I would say Physics 2D. Use colliders 2D and rigid bodies 2D on each button and the circle, then make the buttons follow their circle. It's the easiest way and with some trick and empirical parametrization I guess you will reach the desired result.
So I have a dictionary (nodes) with Vector2Int keys and objects as values, I also have a very simple criterium to determine which values are connected through a certain property (edges), mainly that the objects are adjacent to one another. The user can add (as long as no Vector2Int is occupied twice and as long as all objects are connected to one another through a certain path) and remove objects.
Together these nodes and values can be represented as a connected graph. Now I need to be able to, when you remove a node, get all connected components and store them in separate graphs so that each graph is a connected graph again.
Currently I'm doing this using a depth-search CPU algorithm, just for prototyping, and as expected this can get very slow rather quickly.
I was wondering if there would be a more efficient (maybe using the GPU) algorithm to use here.
My idea is that the usual algorithms go through the entire graph from a random point and do this until no nodes are left unsearched, and that this can be sped up in my case due to the fact that I know where to start my search for each subgraph (a neighbour of the removed node), and how many subgraphs there can maximally be (the amount of neighbours the removed node had).
Maybe its better stepping away from the graph theory all together and I could implement an algorithm that does a far less intensive calculation upon adding nodes, to calculate if that node removes a "weak point" (that would result in several subgraphs upon removal) and then check if the removed node is one of those weak points, this can remove unnecessary searches (as it is very quick and easy to identify if removing that node results in several subgraphs) but resource-intensive searches are not completely gone if this does result in several subgraphs.
I am not quite sure and was wondering if you guys might have an idea.
Sorry for the long explanation, please ask if anything is unclear
Hi,
How easy is it to move a big chunk of my code to a separate thread with the jobs system? I'm not familiar with the jobs system or multithreading. What exactly is that separate thread not allowed to do? How do I avoid it breaking my entire game
Hi.
Q: which scripting lang to choose?
There is few variants. fitst is c# but there is security issues. if ill compile and load it then i can call kinda Env.Exit() and destroy host app.
next ones is:
Lua
Python
Javascript
there is also another cool idea wasm. But there few issues.
- How to configure linker correctly? (bc i dont know to what will compile code)
- How to compile to wasm
c#as example? and how to say that any print functions likeConsole.WriteLinemust be compiled to$consoleWriteLine
You can speed up your graph traversal by a lot if you store it in an array and donโt make objects for each node. You can only skip the traversal or optimize it if you have a constraint on your graph that would enable the algorithm to eliminate sections based on that constraint, for example if your graph is a tree you can skip checking for cycles and add directionality to skip most of the parent traversal, in fact it wouldnโt even require traversal to generate your new graphs
currently ive got them in a dictionary because they are objects with more data then just their position, and i use that other data as well, just not in this part of my code
Recipe for terrible traversal performance
if you can store only the information about edges in an array youโd need a very large graph to make it slow
this is unity. doesnt it only use c# ?
ingame scripting
so if i made an array consisting of the edges, which shouldnt be that hard to achieve from the list of objects, so a pair of 2 positions, a pair of ids or something like that, that would make it more efficient, and then i could use those positions/ids to apply the result to my objects if needed right?
The jobs system has a lot of restrictions you need to know about if you want to use it properly, look into the docs and the examples
Multithreading is hard to do safely with gameobjects. If you have logic systems which are entirely separate then it might be possible to "easily" thread it
But interconnected stuff increases the complexity a lot. Which is why DOTS exists, as entities and ECS is better for that way of coding
Use the deep profiler and find your bottle necks and see if you can refactor and get better performance before trying to multithread
i dont think its possible to get better performance from an ai calcuation with tens of thousands of iterations, but speaking of deep profiler, i tried it and i still dont understand how it works. it does not tell me which lines in my script are taking a long time, all i saw was how many milliseconds UI calcuations take etc. just general stuff that dont tell me much. and i did use the deep profile button
With deep profiling you should see the which functions are taking the longest, you'll need to send a screenshot if you want help with that
How many Ai are you running?
where do i see that though? it doesnt show me any functions
just one. its for a very complex turn based game
Like one Ai controlling every other player like Total War or literally just one Ai opponent?
Cus you could maybe make a system to run every Ai at the same time, would take work though
If it's just one Ai then you'd need to split up all the internal stuff in order to thread it
its like a board game, just 1 ai who freezes the game for a bit when he's deciding what to do on his turn. and the freeze is what i'd like to avoid
humm in that case you might be able to just spin up a normal C# thread and just do the work in order to not block the mainthread
would'd need to make sure you don't change any info on the mainthread until it is done
but then at least the game wouldnt freeze up
im just afraid that i might be using a method or something that is only allowed on the main thread and breaks everything completely
wait you mean normal C# thread not the jobs system? im not familiar with multithreading at all, whats the difference?
yeah not the job system
also if i use a method or something thats not allowed will it tell me via an error or something or will i suddenly encounter some weird stuff happening which i will have no idea what it is caused by?
cause i'm afriad everything will break and i won't know what