#archived-code-advanced
1 messages · Page 12 of 1
:D
Also Idk if peeps will know it here, there's no legal issue with using bricks that resemble lego right? I looked into it they can't trademark a shape, but they trademark their logo on it and the minifigure
Probably is
Well I mean in the UK we have tons of fake lego at like stores n stuff
But there is many fake lego products isn't it
The patent on the basic shape has expired, but you can’t use any still patented shapes or allude to any association with them
Sounds good, will check their patents appreciate uit
you also can’t use minifigs as they are part of the trademark
Maybe the shape is fine to use, but the knock off brands are always somewhat different aren't they
You can always release it as a fan product
yeah, I'll probs switch stud shapes but other than that should be golden
use triangle studs 😛
Hexagons, the bestagons
use no studs
dragons
forgot how fun Unity is tho, let go of it like 2 years ago just came back and its fun af just messing around
HAHA triangle
Gotta love github copilot too, have to rewrite some code usuallyt but sometimes it gets it spot on
did it compeltely wrong tho
so
nvm
github sucky
When it looks like spot on but when there is one variable wrong
HAHA true
Even AI uses GameObject.tag instead CompareTag
is CompareTag better?
Yes, GameObject.tag creates new string
But honestly I don't use tag at all. They're too limited. Cannot even have two tags at one time
i often avoid tags, and just use what interfaces are on components
It's nearly perfect B) just gotta make it so it goes to the highest Y position and make the Overlapbox a little smaller so it doesnt make it touch when its on the outskirts
thanks @sly grove
yeah I'd do the overlap box with a slightly smaller box, as you said!
yeah doing that now :)
I would save 3d grid or object list somewhere and check if anything overlaps in there
Just to prevent timing mismatch or something causing object overlap
It's perfect :)
Yeah I mean for its simplicity this is fine for now, if it becomes an issue I'll convert the grid to 3D
Anyway to rotate the the OverlapBox with the rotation of the transform too?
OverlapBox accepts orientation
oh yeah it does
missed that
it's so fun to mess around with haha, distracted by my own creation :(
Would this be the best channel to discuss a unity standalone build crash?
it looks really great
@brave widget do you currently use source control like git or plastic?
and are you using Input System / Event System?
I know this should be in #💻┃code-beginner, but I don't wanna disturb them.
Hi, everyone! Why is the static Transform::LookAt(Vector3) method rotating my model incorrectly? I've tried messing with the look direction, but that appears to be in world space (it was doing weird stuff)... Thx for the help. I've attached a video.
I'm sorry for the terrible quality, but I don't have nitro 😛
I mean, the code is extremely self-explanatory, but if I'll be happy to share it.
Is there a lattice modifier available for Unity>?
Is your model looking at +Z direction from prefab?
Well... I've noticed that when I drop in the model, it's automatically rotated -90 degrees to the X axis. Is there a way to add a rotation offset?
fix the model in blender
and/or fix your export settings
Also this is an #🔀┃art-asset-workflow question, not #archived-code-advanced
👍 ok, thanks
string bar = "Hello";
public List<SerializableBaseClassWithConstructor> foo = new List<SerializableBaseClassWithConstructor>()
Is there a way for me to pass bar to the constructor of SerializableBaseClassWithConstructor when the object is initialized/added to the list through the inspector?
You're constructing a list with that type, so no. You can instance SerializableBaseClassWithConstructor and pass the value there
Then add the instance to the list
Figured, maybe Odin has a fast workaround for this =/
CustomAddFunction
So I'm getting a crash in the standalone build when changing scenes and the issue appears to be related to this:
Setting up 8 worker threads for Enlighten. Thread -> id: e7a0 -> priority: 1 Thread -> id: e7a4 -> priority: 1 Thread -> id: e7a8 -> priority: 1 Thread -> id: e7ac -> priority: 1 Thread -> id: e7b0 -> priority: 1 Thread -> id: e7b4 -> priority: 1 Thread -> id: e7b8 -> priority: 1 Thread -> id: e7bc -> priority: 1
Any ideas? This is from the player.log that the build produces.
It never occurs in the unity editor either.
Hm ive seen these but they never caused crashes
those appear in every log afaik
It doesn't appear in the log when the build doesn't crash
no doesnt appear in mine but im not using enlighten at all, but ive seen it before in working builds
I did a test where I built the game 3 times. The two that crash happen after that. The one that worked didn't
so the log from the working build didnt have gi?
Correct
do you use enlighten?
I have no idea what it is
did you bake global illumination?
I haven't baked global illumination
this may be a crutch, but try going through your scenes that go in build, go to lighting tab, and disable all forms of global illumination there
i dont know the root cause, if it is enlighten, it can potentially fix it
Okay. So just turn off all lights
okay let me check that
it may be a bug in unity, so you could update to latest matching major version
Wow i thought those pics would stack different. Here is what i see
press new lighting settings, then set lightmapper to none/disabled
on other scenes reference same lighting settings
ah shit im blind, its disabled anyway
no
im correct, yes do the same for other scenes
Okay. I'll give it a shot.
Wasn't it. Same last line.
`Unloading 5 unused Assets to reduce memory usage. Loaded Objects now: 2047.
Total: 3.543600 ms (FindLiveObjects: 0.137200 ms CreateObjectMapping: 0.072400 ms MarkObjects: 3.290600 ms DeleteObjects: 0.042600 ms)
Setting up 8 worker threads for Enlighten.
Thread -> id: ad44 -> priority: 1
Thread -> id: 7fe8 -> priority: 1
Thread -> id: 6c30 -> priority: 1
Thread -> id: cbd4 -> priority: 1
Thread -> id: 8cf0 -> priority: 1
Thread -> id: 2808 -> priority: 1
Thread -> id: ad68 -> priority: 1
Thread -> id: ddc0 -> priority: 1 `
Its not possible for a plane to pass a triangle in such a way that it intersects a different number of edges other than 2, right?
if the plane and triangle are coplanar it will intersect all three
or if they intersect at one of the corners... well you decide what that means
other than those degenerate cases your options are 0 and 2
Not currently using any source control atm, and as for the Input System I will convert to it, the only inputs atm are just WASD and the old input manager for axis
Hi, I'm hard stuck on a problem that's probably over my capabilities. I'm using a thread (task) to load objects from a class used to save the objects in a chunk. Every time I create a chunk in my world it either gets created, or loaded from data, if a chunk had already been created in that position. This works every time, the loading thread here works flawlessy, without crashing. However when I'm loading a world from the menu, all the first loaded chunks crashes and have an infinite loop inside them. Using the debugger I've come to one of the weirdest behaviours of all time, where trying to get a static instance of a singleton restarts the thread. Here's what the debugger sees:
It starts from the beginning. Goes on until...
it gets there:
Here's the calling of a singleton. To be sure that no thread is calling the same singleton at the same time you can see at line 99 that I've added a (static) mutex on this class.
When I enter this line, it correctly send me there:
Exactly where it should be.
But, the problem, is when I execute this line. It send me there:
Accessing properties of a Transform in a thread is risky business
This is the place where I call the thread
it's liable to just kill your thread gracelessly
you can't really access any unity data from a background thread
Where am I doing that?
what is objectContainer?
it will be turned into a transform in the SpawnObjectsManager singleton, that I guessed it spawns them in the main thread since it's a singleton and I'm using a static instance. At least, I hope it does.
Same as before, another class for storing data
no it won't automatically do anything in the main thread
Shouldn't a mutex block weird behaviour anyway?
you can't access unity data from a background thread
mutex or no
the unity engine doesn't know about your mutex
How is it working then?
so I'd guess whatever is happening inside SpawnObject is part of the issue
It also worked until yesterday
can you show that code
Yeah, but it's not supposed to be executed outside the main thread so you'll see any kind of bad code there
This, calls this:
yaeh there's the bad stuff
God why is it working and why did it work for so long
almost a week without breaking
Ok - is there a way to call that singleton and execute it in the main thread?
not sure 🤔 it shouldn't work at all. Are you sure your code is actually running in a background thread? How are you starting it?
Oh, hold up
hold up
I got it
I know why it doesn't work (but I don't know why it worked all this time)
Did you use Task.Run before?
When the world is NOT spawning (the first spawn when you load a game from the menu), it doesn't go to the direct instantiate method, but it goes to spawnManager.addObject above that. This just adds the object to a queue that the main thread process every update (up to a limit per frame, to reduce lag).
But when the world is spawning it goes right into the direct instantiate method, crashing
could it be this?
that's the direct instantiate method
Before this project no,
Never had to optimize anything, this time the world is pretty big
Gotta say that, threads are way less useful than what I thought since I can't use all unity api inside them
when it worked ‚last week‘ I mean
Ah, yes
idk what I changed now that broke it o.o
and anyway this debugger behaviour is extremely confusing, I guess it's what you get when you work with threads
the debugger can indeed be incredibly confusing when working with multiple threads
threads are not trivial. And they won’t help much making unity load smoother
It's also the first time I'm using the debugger
never actually used it with Unity in my 2 years experience (as a hobbyist, so not 2 year of work, I'm still a total newibe)
What's your goal with this code?
have you considered using an asynchronously loaded scene?
My goal is to load a procedural map made of chunks
I noticed that when all the code was simply executing, instantiating and loading thousands of objects every time I loaded a single chunk the game froze for seconds
What are you actually loading?
It depends, the biggest load are single chunks
is this like minecraft where each block is a GameObject?
each one has about 5k objects inside
how do you load them?
No, no
not voxel
more like valheim
hold up:
That's what it looks like when it works
If you focus you can see in the distance chunks spawning, and a very small lag sometimes
I basically gave up reducing that lag, gonna admit it, it took me two weeks to decrease the lag from very high to acceptable and I'd just like to go on ahah
seems its about time you started doing https://www.gameprogrammingpatterns.com/flyweight.html
Wait...
Tbh a world like this should spawn all those prefabs dynamically
Not store any of the positions in a file. No loading necessary
with unity you can just render same tree using gpu instancing, and use a pooled collider you literally just move around from "tree" to tree when players get near
if the tree state changes at any point, it receives damage for example, you swap it for an actual tree object
yes
big, popular book
I tried to do it btw, it reduced lag
do you have profiler results?
I wasn't talking about normal lag, the lag I had was the chunk loading lag, because in a single frame I was spawning thousands of objects with raycast, instantiate, json serializing, file reading etc
btw... it didn't work
Now spawnobject only adds the object to the list, and it still causes that weird behaviour
i dont know what can cause the lag without profiler
you can try preloading files
see if its disk read locking it
is it consistent or only first time an object is spawned?
I'm not talking about the lag now, I mean I'd like to but maybe after I resolve the main problem... an endless thread loop
oh sorry then i got it wrong
The world streaming lag you get in unity that you also can’t fix will not show in the profiler. It’s an engine issue caused by internally iterating all the objects that get loaded. It’s what happens between 90 and 100% in an async load
This
is still happening even without touching transforms
any links to read about it?
I think it’s described in the firewatch GDC talk
Yeah, I figured it was something like that. I optimized a lot of code and the profiler said they were causing lag when a chunk was loading.. And it was pretty impossible, since the same code was being executed in less than 1 ms the frame before loading it, with the same amount of calls. It also lags waaay more in the editor, so it's even harder to profile it. But that's not my main problem now
Most engines have this issue and there are numerous talks at GDC where object init was a major issue when implementing streaming
in unity your only option rn is to hide it or load very small chunks
or not spawn it and just render
subnautica had the whole world octree on disk
so theoretically that should be the "smoothest"
you dont need chunk load objects you can grab them directly from octree by proximity
yes
Preload all assets, spawn prefabs incrementally
doesn’t matter where the data to configure them comes from so long as you don’t trigger the internal init for 1000s if things in one frame
Yeah I'm spawning them incrementally
the spawnQueue.Add above is literally that
I've made a video of the debugger:
InfiniGrass/VegetationStudio help a lot with spawning stuff without storing positions
aand it's too big
The simple get instance is causing a loop...
could you try making this an actual async Task with a return?
I have absolutely no idea on how to do it T.T
Task.Run(async () => {
// do some synchronous/blocking stuff
await Task.CompletedTask;
}
better make the method async, pass in a cancel token and make sure you arent actually running ophaned threads still
Doesn't await waits the task to be completed, blocking the main thread?
you would not await on the main thread
the await is also not necessary
but the Task allows you to reference the thread and check its status
Doesn't work, it asks me for a ";" and gives error when I write it
Translating "There should be a )"
if you have issues making this work you should really not be toying with threads yet
the point of Task is to have access to the thread and inspect it, to be able to await it and to get return types
You're awaiting CompletedTask? 🤔
thats what its for, to close a synchronous method cleanly that has no await
This does the exact same error
an infinite loop
it would not change the bug
it would just give you more access to observe whats going on
How can I do that?
Wouldn't it be better just return them? Unless it's demo purpose
With the debugger?
that would be semantically incorrect as far as the code analyzer is concerned, functionally i think it makes no difference
Not actually the same error: this blocks there, before getting to the spawn manager
the next line executed is this:
you can also just make LoadObjectsThread async
Yeah if you need LoadObjectsThread to finish before the lambda completes you should be awaiting it too
LoadObjects is blocking
Wait isn't what I just made
you made an async lambda that wraps a synchronous method
A simplification would be to not make the lambda async, as it runs on the thread pool, won't block the main thread
we are trying to get a handle on abug inside that thread, the task wrapper is to provide more access to the thread
Ah alright then
anyway, i'm not seeing this going anywhere
this is impossible to debug remotely unless someone has had the exact same issue before
T.T
i suspect the debugger actually suggests the wrong thing
Well... I can move this method on the main thread again... But it will increase a bit the lag 😦
It's like if the debugger stops debugging a thread and it moves to the next one
You can select the thread via the dropdown at the top
Looks like the method that runs the async task is in Update, is this intended (sorry if question seems weird, I just arrived)
good point
It'll spin up a new task each frame
Yes, it should do it once... wait
wonderful
Unity Moment™️
Is it? I always go with return Task.CompletedTask instead and make the method non-async. I wonder it makes any difference
idk, it doesn't matter probably
also there is Task.FromResult()
suppose it (the warning) is just meant to help you avoid casual mistakes
memory leak
Ok, I resolved the endless loop
still not spawning objects, but I'll try to resolve that now, thanks guys
if you guessed it it was an incredibly dumb mistake
about the level of a simple syntax error
the weird ones are often very trival to fix
like ```cs
if (foo);
DoThing();
No it was just dumb and I don't know how it worked until now. I mean , I think I know.
Basically this method as I mentioned before was made to be executed in the main thread, and I just moved it in a thread... In the update method. It was not a problem before since after executing it it set a boolean variable to true and didn't execute it anymore
but when it's a thread, the update loop is faster than the thread, so the variable never actually becomes true, and it simply spawns a thread each time it goes to the update loop
i think over time one develops intuition/habits that prevent such things...
So yeah, that IS intended, but I forgot to add the simple boolean variable "isThreadRunning" and spawning it only if the thread is not running
Man I program since 2016 ahah and I got a job, oh god if I do those kind of mistakes I will be fired ahahaha
really embrassing
but you fixed it
so no reason to be embarrased
its normal to make these silly mistakes
i've heard people with decades of exp say, they still frequently make 1-off mistakes
and i would say anything involving actual threads/parallelization or of a distributed nature will always have something new to surprise you with
especially if you use sync primitives or get into performance code
Well threading is probably the most complex topic I know.. And my university didn't take it seriously, we just did some threading with C and it was extremely easy
That's what I wanted to do, I've got a nice c++ threading book in my bookshelf but I never actually read it
but also consider that nobody who studied before 2010 has any formal knowledge of it unless they took an optional course on it
I used it back in the days when I tried to code a multiplayer game with c++... in 2017.. obviously I didn't make it, but I learnt a lot
Why?
it was largely irrelevant before multicore CPUs became popular and the cloud (cluster computing) happened
Mmh. As far as I know the threading course of my university has been introduced during those years
same with neural networks... before 2012 or thereabouts they were considered a curiosity
its also quite difficult (it seems) to find qualified lecturers on the subject
especially distributed systems are very tough to teach well
Well you usually have to know basic threading to code, no? You need advanced threading knowledge only if you work with big supercomputers
as far as i know, at least
supercomputers are generally distributed systems (clusters)
whether you code for 2 or 200 cpu cores doesn't matter code wise
and the concurrency theory is the same independent of how that concurrency is executed
its just math
usually the concurrency that was discussed before multicode became a thing related to databases
I thought you had to manually code parallelized code to use 100% of the cores
You declare threads, each one does something, then organize their output
like computing a whole map made of gps data, if you break it in pieces and give it to different threads then it should be faster no?
yes, there is a whole theory around how to break up tasks most effectively
that's an example some scientists made me some years ago when I was visiting a research centre
its not trivial
probably too advanced for me, I'm still a junior developer 😛
there are also multiple ways to parallelize stuff
I'll probably need it when I'll do my thesis
there is branch prediction, vector operations, multi-core, different CPUs, cores that share a cache, CPUs that dont
I was thinking about simulating a network of biological neurons, and moving the code from CPU to GPU, but it seems really complicated
and probably my code would go slower on it, so I still have to consider it
that level of thesis is this?
A bachelor's
you wont have to do anything complicated like that
true
I already used threading to create more simulation of the same neural network, so I could train 15 of them at the same time and speed as one
is there a pre-existing way to view the state of physics in the near (1-10 frame) past?
as a hobby, not as a thesis, bringing it as a thesis would be a dream
anyway thank you so much for your help, I still learnt something and I would've probably resolved it in a week 😊
i think people who take their thesis seriously and want to make something fun become good developers
I hope so... I'd like to become a good one, and sometimes I do something complex, but then I lose hours and hours on dumb mistakes like the one that you helped me with
where I forget a single line and everything breaks
hey,
how to make a 3d object act like a slider ... slides from one point to another were one end has a value of "0" and the other has the value of "1" ?
You want to drag it with the mouse?
With rotation/scale or just position?
position only
And is it non-linear, like for a value of 0.5, it's not in the middle of the two points?
i have 2 empty game objects , and another cube game object, i want the cube gameobject to be able to slide between the 2 empty gameobject only and cant go anywhere else
its linear motion
Vector3.Lerp(point1, point2, ratio).
I'll give it a try 🙂
wait how to do define the ratio ?
yeah but we are in 3d space
we have 3 vector3 which defines the position of each object
we do? That's news to me.
By Lerping between two Vector3s, you definitely can move the object in 3D space
Mind you, it's Vector3.Lerp, not Mathf.Lerp
2 empty objects ... one defines the start and one defines the end .... and then the cube that the player can move
Mhm, Lerp between these positions
yep so everything SPR2 is saying
listen to him
cube.position = Vec3.Lerp(start.position, end.position, progress)
ok I cant imagine how I could transalate the cube's position ex: vector3(1.01,2,0.3) to a ratio?
What value of ratio should be if the cube is not on line?
float ratio = Mathf.InverseLerp(0, Vector3.Distance(a, b), Vector3.Distance(a, myObject.position));```
public Transform p1;
public Transform p2;
public Transform p3:
Vector3.Lerp(p1,p2, ?? )
this creates a position FROM a ratio
do you want to input the ratio and get a position?
Or input a position and get a ratio?
Yeah I understood the question backwards
I need the ratio
Then something like this @woven kettle
the position is given by the player
although it assumes that the object is on the line between the objects
its kinda on a line but it moves as the time goes, so I'll have to keep it in update
thanks i'll give that a a try
@sly grove that was perfect!!! thank you!
apologies :D
can i get help with my double click on a 3d object function```
void Start()
{
healthBar.SetMaxHealth(enemy.maxHp);
healthBar.SetHealth(enemy.currentHp);
healthBar.SetName(enemy.name);
firstClickTime = 0f;
timeBetweenClicks = 0.2f;
clickCount = 0;
}
private void OnMouseDown()
{
clickCount += 1;
if (clickCount == 1 && allowed)
{
healthBarObject.SetActive(true);
nameText.SetActive(true);
firstClickTime = Time.deltaTime;
StartCoroutine(DoubleClickDetection());
}
}
private IEnumerator DoubleClickDetection()
{
allowed = false;
while(Time.deltaTime<firstClickTime+timeBetweenClicks)
{
if(clickCount == 2)
{
Debug.Log("clicked 2 times");
break;
}
yield return new WaitForEndOfFrame();
}
clickCount = 0;
firstClickTime = 0f;
allowed = true;
}
what i currently have but when i click once it doesnt go back down to zero after 0.2f seconds
void OnMouseDown()
{
if(clickCount <= 2)
StartCoroutine(MyFunc());
else
//Do other things
}
private IEnumerator MyFunc()
{
yield return new WaitForSeconds(coolDownTime);
//Do other things first
clickCount++;
if(clickCount == 2)
clickCount = 0;
}
I'd not use coroutine for this, but it's up to you
when can i set QualitySettings.maxQueuedFrames ?
it seems setting it in a void Start crashes the game
Crashes in editor or build?
Hi everyone, I have a problem with my game. Actually it's not that bad but really annoying. When I build my game on ios, my fps are really low with freezes while on android, it's running really smoothly. Someone know why it's doing that? I also have a runtime mesh generation but it's not a big performance hit so I really don't know
Try using Profiler
the thing is that I get 1 ms and sometimes spikes to 2-3 ms on pc but on ios it's really lagging
Try using Profiler to profile your iOS dev build
hmm where do I start to make that?
ok do I need to connect my phone to the pc?
I mean where is the profiler going
Connect or use remote profile
It’s on the doc
i'm trying to design/build an audio solution where you can add an ambient sound to something like a river and depending on where you are in conjunction to a set of points set along the flow of the river it'd reposition a 3d audio source to more accurately represent where the sound might be coming from
i got it mostly working, but i'm wondering how to give more weight to points closer to the player position
the black points are points on the lines between points closest to player
you mean like something like... ?
float pointWeight = Mathf.Clamp01(1 - Vector3.Distance(pointPosition, playerPosition) / maxDistance);
yesss
definitely not an advanced topic. but get the difference in position as the offset at the beginning. then object2.position = object1.position + offset and that's literally it
[redacted]
that wasnt meant for you, the other person deleted their question
my apologies 😄 it seemed somewhat relevant hehe
im wondering if there is any way to get a struct to show up in the inspector that is not serializable (i cannot make it serializable due to this acting very weird with native arrays, often breaking them for some reason)? I'm happy to use a custom editor script should it be required!
think the custom editor is the only way to go
ye probably lol, cant seem to find any good examples, almost all rely on the fact that the struct is serializable, and mine sadly is not lol
i suppose i could create a variable for each thing in the struct, but it would make my code quite messy looking lol (mainly due to the struct having over 30 things inside it lol)
something strange is going on, another array in the struct is working fine, despite the first one not
Having arrays in structs sounds like a bad idea to me... and not only me - in fact any reference field in a struct might be a bad idea, see https://stackoverflow.com/questions/945664/can-structs-contain-fields-of-reference-types
Any particular reason to not turn it into a class instead?
dll interop
even worse they are c style arrays
ScriptableObject with a list of objects of classes that all derive from either an interface or an abstract class. The list doesn't seem to serialise with either. Is there a way to do something like this?
I've tried using all sorts of [Serializable] and [SerialiseField] with no luck. It may be an issue with my ui but the list is not showing up in the json at all so I'm pretty sure it's a serialization problem.
it should work with the abstract class, but keep in mind UI wise it will only show you fields on the abstract class not the extending classes
[SerializeReference] can be used with interface types
but it will cause things to work quite differently
json? you mean the serialized scriptable or you try to serialize it yourself?
unity data is stored in yaml variant
he does not say json anywhere
It may be an issue with my ui but the list is not showing up in the json
oh missed that
either way if relying on unity's serialization and not something like json.net, it really does not like interfaces or polymoprhic types unless [SerializeReference] is used and i am 90% sure that is not supported by JsonUtility and just yaml
are the objects in the list derived from UObject?
My bad, mixed that up; I do indeed mean the yaml file that was generated for the scriptableobject.
I have a system that allows me to edit and display fields of a class that's derived from an abstract class or interface, I'm pretty sure it works perfectly fine and that the serialisation is the issue since there isn't even a blank list in the scriptableobject file.
well like mentioned [SerialiseField] does not care about interfaces at all
and am pretty sure with [SerialiseField] it will not save all the data you need just what is on the abstract type used
why i suggested [SerializeReference] but if you use that you do not get a editor or inspector support for free. but it does support interfaces and polymorphism
in the yaml it will be structured different though more or less everything with [SerializeReference] will end up at the bottom of the file with ids and those ids get referenced where used
Ah! Wow, that worked wonders, I had no idea [SerializeReference] existed until now. Thank you so much!
(and my apologies if I was a bit dense ;-v-)
its newiesh
SerializeReference is OP!
think maybe 2019 unity
It's my new favorite
i like it, but find it can be fragile to type name changes
since it does not have a guid to match it like a component or so gets
ye serializable-ing a struct that contains arrays is really buggy it appears, sometimes it works, sometimes it doesn't, for seemingly no reason, as much as i may hate the solution, creating over 30 variables might be the only solution
yeah in my current game our npc behaviour trees use it, so the states for each node can just be a interface type and all be serialized into 1 SO that contains the whole node network with edges and nodes saved with SerializeReference
yeah, it's a feature that's been begged since 2016
now what i want, is being able to click and drag in components of a interface type in the inspector
but yeah before SerializeReference, something like the behaviour tree i did with a crapton of SO's as subassets. this is cleaner asset wise, and well interfaces are jsut better to work with for stuff like this
wait would it be a stupid, alternate solution to instead create a duplicate struct that is serializable, while leaving the original unserializable then copying everything from the serializable one to the original?
No, not this channel
lmao
Gg
You are not even beginner man
Lol
To your blank console?
Go to #💻┃code-beginner if youre not higher
<@&502884371011731486>
You were asked to share code in #💻┃code-beginner. You didn't do so. Go back there and share your code and your question.
!warn 976018323957514280 You've been told already not to crosspost. If you continue to be annoying, you'll be muted.
Muhamm3d#9902 has been warned.
Went in here and the first thing i saw lol
For Unity? I think you can look into this one
https://docs.unity3d.com/Packages/com.unity.test-framework.performance@1.1/manual/index.html
if we do this...
MyClass.OnActionInvoked += (state)=>
{
DoStuff();
}; ```
are we listening to the event just once or do I still need to unsuscribe inside ?
like..
your listener will run every time the event is invoked
yes but that's not possible to do in a lambda like that
agh shit
You'd have to do it like this:
MyDelegateType listener;
listener = (state)=>
{
DoStuff();
MyClass.OnActionInvoked -= listener;
};
MyClass.OnActionInvoked += listener;
``` for example
easier if you use a real method rather than a lambda
yeah ill use a method, thanks a lot
can someone help me with this?
Close Unity, delete your Library folder in File Explorer then open your project again so the Library is rebuild
now you see why unirx makes basic stuff less painful
never used it, if i remember correctly... is some framework to adopt some pattern like mvc ?
im starting to get crazy with to many events and different listeners, want to do some sort of central class that listens to all those wo send events so my other classes would just have to listen to this one
i cannot make it serializable due to this acting very weird with native arrays
serializable should not make anything behave differently withNativeArray
it sounds like you your Y to your XY Problem is "I have a bug in my Burstable Jobs code"
what is your goal? it sounds like you are doing something wrong
you have issues with your jobs code. this can work around your issue, but it's because you are using jobs wrong
Scriptable objects in this case are characters, the list of instances inherent from a Skill interface.
It works as of now so I think I’ll be fine :P
ok
Hello, I'm trying to understand scripting backends, IL2CPP and Mono, and I have a few questions
Do they both use the Roslyn compiler ?
With Mono, the code is compiled just in time so is it as slow as an interpreted language ?
they both use the same compiler yes
JIT compiled languages are not as slow as interpreted languages
they are compiled on the fly to machine code - so once the JIT compiler takes a first pass at the code, it should be comparable to a normal compiled language.
For Mono you get:
C# -> IL then at runtime IL -> machine code with the JIT
For IL2CPP you get:
C# -> IL -> CPP -> machine code and ad runtime it runs the machine code directly
(hence IL2CPP)
Thank you ☺️
I want to have automated documentation system with documentation comments. Which I could generate documentation viewer via some library (e.g. DocFx). Then I want to highlight or generate difference-only document, compare to other version in source control, to share to my colleagues. Is there any tool or use case for this?
i've never heard of the differences being generated
But do you think it will be useful if there is tool like that?
Yeah what I wanna do is when I done with feature, just generate diff and share to let people know what has been changed
They can look at the actual diff.
git diff 😄
But checkout if you can roll out something like swagger? https://swagger.io/tools/swaggerhub/?&utm_source=aw&utm_medium=ppcg&utm_campaign=SEM_SwaggerHub_PR_NA_ENG_EXT_Prospecting&utm_term=swagger&utm_content=511173019806&gclid=Cj0KCQjwjbyYBhCdARIsAArC6LIGTCDbm7NCWWJKrSn9dAj-aOyWV25gbsyn95OEY6optwPjqZrIY-gaAp9yEALw_wcB&gclsrc=aw.ds
Join the world's home for REST APIs. Design fast and generate documentation automatically with the OpenAPI Specification.
That kinda ruins purpose of generating documentation 😢
But docs will only ever be used by devs?
Hmm I do use swagger, but I want to generate doc for internal api changes
I personally update a changelog on push.
Lazy to do that tbh lol
I also wrote a changelog that pulls push comments but you have to add minor, major, bug values yourself.
{0,1,0}
That's the best way I've found.
Ping me if you do find a good solution.
Sure I will share if I find something
a diff from the code-adjacent docs right? you mean docstrings
or whatever they're called
Yes, the xml format docstring
can i ctx.cmd.Blit between render textures with different graphics formats?
what happens?
i am seeing white when i blit a cameraColorBuffer into a render texture
I'm wondering if anyone here is familiar with the Unity test runner. I have a handful of play mode tests and I am noticing that each test just adds more things to the single test scene that is generated when the test suite kicks off. I'd like to start with a new scene each time (or open to other suggestions). I have tried SceneManager.LoadScene() for a test scene I made in the Setup method and I have tried destroying all objects on TearDown. Loading a scene seems to not be recognized by the test runner and looping through game objects and destroying them just locks the test runner up.
Any ideas on how to do this properly?
I ran into this issue few days ago and it turned out you need to wait one frame after calling LoadScene to your test case to be able to find game objects. However there is no UnityOneTimeSetup, so this is what I ended up:
[TestFixture]
public class TestSceneTests
{
private bool initialized = false;
[UnitySetUp]
public IEnumerator Setup()
{
if (!initialized)
{
initialized = true;
SceneManager.LoadScene("TestScene", LoadSceneMode.Single);
yield return null;
}
}
}
If you want to load scene for each test in fixture then you won’t need to have initialized flag
Ah man you're awesome, that did the trick. Thank you!
as far as i know im not using any jobs or burstable code, although i suppose there is a chance that nvidia flex is behind the scenes
perhaps it was because i was being a tad vague lol, what i meant by native array was an array that a dll was reading, so it is marshalled in some way
what is your error message?
i guess what are you actually trying to do?
you are using flex?
yes im using nvidia flex, no error messages, just that gravity stops working it appears when i make the struct serializable lol
not sure if it actually matters but is it the fact that theres no space between the ,
looks like your arguments are in the wrong order to me
oh
@gray pulsar thank you so much, that weight formula worked perfect.
No C# isn’t sensitive to that stuff luckily
ah really? mustve taught myself that it is then
Yeah, but when you put a semicolon it spaces them out for you in VS, to make it look better (unless you put it before you changed the comma space)
ah right okay
that's weird
is it possible to move one script from a object to a prefab? like i have a object with a few classes for a rpg on it and i want to move the chosen one to my player prefab before it is created
@hallow turtle I'm having trouble understanding exactly what you're trying to achieve. Can you give me a more succinct example. what is the object with the classes, what is the script that you want to move and what effect are you hoping to achieve by moving it?
ye it is lol, oh well i can always create a fake ingame inspector using ui and remove it later lol!
Hello everyone!
Debug - Attach Unity Debugger.
I'm having this weird issue with my editor, when I try to launch my debugger I have 2 port to choose from.
Someday I only got 1 to select, but more than often I have 2 instance.
And as you can imagine, it's quite annoying to keep the port number in head (which changes every day btw), and re-relaunching the project just for this... Anybody have seen this issue? I'm trying to search for this on Google, but no real hit so far...
(please (at)me in your answer)
Many thanks for reading my post!
That is pretty much vs code Unity debugger extension being weird like always
Btw what Unity version are you on?
2020.3.3f1
(we are close to a major release... but after that we should update in this LTS...)
Yeah for me that issue was dissapeared after some version update
Does anyone have a properly configured setup for GRPC communication? It seems to be pretty annoying to set up https://stackoverflow.com/questions/72907696/how-to-get-grpc-working-between-a-unity-game-client-c-net-and-tonic-rust-b
Then unity side is what I'm interested in
Or should I be using https://github.com/Cysharp/MagicOnion instead?
i have a 3 cameras 1 for world 1 for UI (screen space canvas) and a 3rd one that focuses a 3d object and i render over the other 2. But this object always appears behind the UI. Is there any way to make him appear below the UI whenever I want to? Here is how it looks
below blurred is what the main world cam renders... a tile map. the UI you can see, the below buttons and this street menu
but this cube, im using a 3D camera
and I'd like to be able to put stuff below the UI (as it is) but also in front
Shift the UI up?
You want the cube to be in front of the UI?
I want to be able to control it yeah, sometimes below sometimes in front
1 way would be with a renderTexture and convert it to UI
but id like to know if there's an easier way
Yes, that's what you would do. Then move its sibling index.
isnt there any other way than using renderTexture?
Or put it on its own canvas and change its render order to be higher or lower than the main UI value.
hmmm i should put the cube inside of a canvas for this?
i've been trying that but for some reason the cube stops being rendered
If you want to do a special shader/render feature in URP, sure. Seems a lot of work for it though.
No, it needs to be a render texture for it to work in UI.
nah, i dont use URP and dont know shit about shaders 😅
I mean, if you didn't want to put the RT into the main UI canvas, you can use its own.
damn it
I don't see why using a RT is an issue though. 🤷♂️
how do i profile memory BANDWIDTH? i think there is too much shuffling data but not sure where.
you should be able to profile memory usage over time, your memory rw usage is going to be dictated by your allocations
no, it can be data copy to a pre allocated variable or parameter, won't show on profile but still kills mem bandwidth
can someone remind me how to add code please?
like create a script?
in VS2019, I have a function with variable, when I right click the fn variable and choose "Create and assign field context" it auto creates a variable for this, ie on context: public AccountController(DataContext context){} it auto creates the variable private readonly DataContext context; how do i change the behaviour to name it _context?
as in that code, to make it more readable
not really an advanced code question, but here: https://ardalis.com/configure-visual-studio-to-name-private-fields-with-underscore/
This is the dilemma. I'm working on a greedy mesh algo. but now seem to require the use of multiple materials to allow me to repeat the texture. Idk if anyone has any other solution.
not really sure what greedy mesh is but if you have multiple submeshes, it's one material per submesh. Otherwise each material will be applied to the entirety of the mesh
and texture mapping is as usual done via UV mapping
it's stretching because the UV is going from 0 to 1 down the side of the object. If you're creating the mesh yourself you can just make the UVs for the vertices carry on past 1, and set the wrap mode on the texture to repeat
If you're not creating the mesh you could create a simple shader yourself that decides which part of the texture to sample based on world dimensions rather than object space dimensions
yeah you can map UVs to world coords 1 to 1
you can also use horizontal/vertical/all axis tiling atlases
the uv coordinates refer to coordinates in the texture
not coordinates on the mesh
you assign the appropriate UV values to the appropriate vertices on your mesh (in a process called UV mapping) to get the part of the texture you want on each triangle/face of the mesh
long story short - learn about UV mapping
@ivory prawnMate, that's exactly what I was after, thank you.
glad I could help!
Does anyone know how can I set the control scheme in code whith the generated C# class rather than the player input component?
Try #🖱️┃input-system
This good in terms of getting the local Bounds of an object before any transformations? ```cs
private Bounds getLocalBounds(Collider collider)
{
Type colliderType = collider.GetType();
if (colliderType.Equals(typeof(MeshCollider)))
{
return ((MeshCollider) collider).sharedMesh.bounds;
}
else if (colliderType.Equals(typeof(BoxCollider)))
{
BoxCollider box = (BoxCollider) collider;
return new Bounds(box.center, box.size);
}
else if (colliderType.Equals(typeof(SphereCollider)))
{
SphereCollider sphere = (SphereCollider) collider;
float diameter = sphere.radius * 2.0f;
Vector3 localBox = new Vector3(diameter, diameter, diameter);
return new Bounds(sphere.center, localBox);
}
else if (colliderType.Equals(typeof(CapsuleCollider)))
{
CapsuleCollider capsule = (CapsuleCollider) collider;
float diameter = capsule.radius * 2.0f;
Vector3 localBox = new Vector3(diameter, diameter, diameter);
localBox[capsule.direction] = capsule.height;
return new Bounds(capsule.center, localBox);
}
return new Bounds(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
}```
Oh god those type checks
There is Collider.bounds tho
if (collider is MeshCollider meshCollider)
{
// use 'meshCollider' variable
}
Then you can InverseTransform
not even necessary, bounds belongs to Collider
Yeah, that was just a design tip though
You can rotate it with the worldToLocalMatrix or some shit
You may need to cast, actually 🤔
Forgot the variable name
No, it doesn't work with AABB
Oh well, ignore me then
hello
when windows kills an app for launching a GPU job (compute shader) that takes too long to complete, is it because of the entire execution time is too long, or because some threads took too long to compute ?
I fixed the issue by better parallelization, but would like to know in case I need to write a heavier compute shader
when windows kills an app for launching a GPU job (compute shader) that takes too long to complete
why do you figure windows kills anything?
windows doesn't care what your process is doing
what do you really mean?
it literally said that
that you click inside your unity window, and you see "Your app has stopped responding" faded background modal dialog?
hmm
do you have a screenshot of this?
or do you remember the actual words
it killed unity and said that a GPU took too long executing
you would have to remember the actual words, verbatim
because i'm not finding anything about such an error message on google
you are paraphrasing / interpreting a different error message
should've made a screen shot before fixing that issue
I'll try googling the error message
suffice it to say there isn't such a windows error message. Unity might have an error message
but it's not windows
your process can crash, of course, with a gpu-related error
usually running out of memory
do you have a log?
you might use too much memory*
I'm pretty sure it was coming from a graphics driver or windows, but can't be certain 100%
your logs would say "CRASH"
because of how it was worded
it wasn't windows
are you asking if unity prevents you from running runaway compute shaders?
probably
why wouldn't it?
i forget what you are trying to do
"Failed to present D3D swapchain due to device remove/reset" or something?
That fits the description
that particular shader rasterizes some regions defined by polygons
one of the regions was very big, so one of the thread ran way too long
okay
sounds familiar, but I probably should reintroduce that error
and get the exact message
so that can happen for a bajillion reasons
did that occur in the middle of running your game?
you probably ran out of GPU VRAM (horses)
did you screen go black?
did you see a windows "gpu recovered" message? (zebras)
it's a one-off calculation
Usually the error happens when the driver hangs due to an expensive operation, and Windows think it crashed, so it resets it
Killing Unity in the process
windows will tell you if it reset something
failure to present d3d swapchain is a unity crash
it sounds like you ran out of GPU VRAM
knowing nothing else
In the event viewer yes, you'll have a log that it was recovered
you might have more information in the logs
it will show a popup in the system tray
on Windows 10 at least
only if unity keeps old logs, I ran it multiple times since then
was this in the editor?
it was
i guess what is your goal?
to use more GPU VRAM than you have?
you can try to load pieces of your work in batches
which is what it sounds like you did
I doubt it's a gpu ram issue, because the memory footprint of that algo remained the same
it really depends
i don't remember what you are trying to do
with a compute shader
that particular shader rasterizes some regions defined by polygons
one of the regions was very big, so one of the thread ran way too long
in my experience, the most common reason you will see a GPU-related crash is running out of GPU RAM
well
that isn't very informative
what is it really?
it would be pretty hard for 10 GBs
yes, but you are running in the editor
and there's a lot of stuff going on that you wouldn't immediately comprehend. for example, if you had both the scene and the game view visible, well it would run the shader twice
but i don't know
i don't know what it does!
you haven't told me yet
rasterizes the polygons into a texture, that is literally it
i don't know what that means
a bunch of point-in-polygon checks
what is the purpose of the shader?
for every cell of the output
like what is its gameplay / logical goal?
are we talking about a fluid simulation?
like what are you trying to do
okay
I'm moving a bunch of rasterization logic from CPU to GPU
you are generating a map?
so immediate goal is to offload calculations
you are procedurally generating a map, and this shader plays a role in...
what exactly? placing props like trees and rocks?
that too, basically there's a number of maps that tell which region is where, depth to the water bodies, depth of the biome, etc
I have it, I have working hlsl code as well
okay well the simple answer is that probably your compute shader is buggy
if the application crashes
was buggy, I wanted to know how to organize my other compute shaders, to not run into the same issue again
because I still don't know if a long running compute shader caused the crash, or only a long running thread
well there are almost certainly limitations on everything
sure, knowing limitations would be nice though
The default timeout period in Windows Vista and later operating systems is 2 seconds. If the GPU cannot complete or preempt the current task within the TDR timeout period, the OS diagnoses that the GPU is frozen.
so it doesn't matter how exactly you cause it to hang
Those are AABB to world space
Yes I realized little after in the chat
So you probably needs to cast 😌
But do use is operator #archived-code-advanced message
will do lol
you can change it
registry edit
Haven't heard about Vista such a long time
Does anyone know when material properties are pushed to the gpu? I’m trying to alter a material property inside OnPreRender in a vr game but only the left eye seems to be getting the correct value (the right eye ends up with the same value). I’ve verified with the debugger and logging that I’m calling SetVectorProperty with different values for each eye
%^#&@!%#^!&@%$& I don't understand why but using Shader.SetGlobalVector worked instead of setting it directly on the material
that's weird
you can probably ticket that as a bug
hrm. unlikely to help me cause this is for a mod for a game using 2019.4 :/ But thanks for confirming I'm not crazy. burned a lot of time on this
even a workaround that can force material properties to be pushed would be useful though
turns out SetGlobalVector isn't really a great solution because there are situations where I need more than one instance of this effect running with different values...
lol
well if you're modding a game
Unfortunately got no answer in there
why would you want to do it insteadof using the player input asset?
I want to have more control over my code and design my own input system, for that I'm using SO so player input component would not work with that
creating and designing your own input system is ever easier with the provided asset
i have my own input system where i handle stuff, fire evernts on context.started/context.performed etc, whenever i want
Thank you for your suggestion, but since I'm working on a larger scale project with multiple objects controllable I would like to use a different approach, I hope I'll figure this out
sure, but that's what i created my input system, for large projects
you can create different maps and do whatever you want with the input asset in your own input system class
when you want to controll different object just change the map
Yeah ik that but I have multiple objects using the same action map, so thank you for your suggestion
lets say i have an ortho camera somewhere and i want to calculate the clip space position of a vertex if the camera was at 0,0,0, how do i go about that? can i somehow "translate" the camera projection matrix in space?
Yes
also, #🖱️┃input-system
There's a dedicated channel for the input system package -> #🖱️┃input-system
Other channels are being used so will pop this in here-
Just wondered if there was a shortcut to get the Assets folder file-path as a string?
(e.g. Projects/MyProject/Assets)
I don't want to get the path for a specific asset, as in AssetDatabase.GetAssetPath()
I assumed there would be something along the lines of AssetDatabase.ProjectAssetPath() or something but no joy
Any ideas? :)
What's the problem with a string tho?
The problem? I have no problem with a string
I just want to retrieve wherever the current assets folder is
The file path to that would be a string
Ah that's perfect, thanks!
I assumed it would be under the AssetDatabase stuff so missed that!
:D
It's been a while since I was working with VR in Unity now, but the XR Interaction Toolkit (is it still around in preview?) came with a big folder of tests written for all kinds of interaction and input events in VR - worth checking out as you seem interested
I made now a video, I hope this is now more easy to understand what I want and What I got already...
I want to wrote the information's, I collect in my IJob Structs, into a TMP_Text, but the text field doesn't show up in the inspector.
How can I run it in the struct (this would be the best result)
or in worse case, how can I transfer my integer value: "randomNumber" from my IJob Struct, to my MonoBehaviour class?
that's a repo for examples using the toolkit, the toolkit itself contains the tests - you may need to add the package from within Unity
looks like there's a clone of it here: https://github.com/needle-mirror/com.unity.xr.interaction.toolkit
I've been looking for an out of the box solution for a locomotion system for the quest 2 and have come up dry in previous searches. Might you have any links or hints to one?
I've just been wanting to get the player to move forwards using the joystick 😐
Can anyone point me at some good resources for active ragdolls/physical animation?
There are some incredible ragdoll physics in the now-open-sourced C++ game engine that was built for Overgrowth: https://github.com/WolfireGames/overgrowth if you just want to look at a strong implementation. I'm sure it would be possible to translate it into a Unity-specific approach.
I love overgrowth, but never realized that it's open source. Thanks!
Sweet! I love Wolfire. And if I happen to run into ragdoll stuff more to do with Unity, I'll circle back. I sadly don't know C++ (yet!) so that codebase is meaningless to me lol
How can I collect my string or integer from a IJob Struct, into my MonoBehaviour class and ask for every external threads information, to put them at this frame all into the TMP_Text?
Because it is not possible to put my new information from my IJob struct directly into my TMP_Text, because I heared that structs and especially IJob doesent support that. so I want to use the main thread, to ask for all the external threads (in my case 16 threads) for all his integer or string values to put them one by one into my TMP_Text...
Use NativeArrays to communicate between mono environment and Jobs.
Hey! Not sure if this is counted in advanced scripting but I couldn't find anything more suitable, but i need an application to run in the background (kinda like how Spotify runs in the background) on Android, i dont think i can use services here and i have tried to edit the build files too using Android studio, but it throws a bunch of errors for some reason(will send error log if needed) thanks in advance!
Probably something relating to pause: https://answers.unity.com/questions/1496424/how-can-i-make-music-player-running-in-background.html
ironically thats the solution i was referring to,
for some reason android studio refuses to build it
Without logs, folks can't help you.
If they're Android Studio compilation errors, try asking an Android Studio discord/forums and Unity forums.
I have an issue and was curious if anyone has experience with this type of problem. I am working on a project with "Passive Item" mechanic similar to games like Risk of Rain & Binding of Isaac and I'm about to revisit their implementation. These Item's effects are triggered in various ways either through a timer or some event. In the case of events I have quite a few, each with their own method signature. My problem stems from these events.
If for example I want to make an Item that spawns an explosion when the player dashes, my first approach would be to make a rather generic/modular SpawnObjectItemEffect script (derived from ItemEffect) and a PlayerDashItemTrigger script (derived from ItemTrigger). The PlayerDashItemTrigger script would subscribe to the player's Dash event (with a signature of Vector3) and holds references to ItemEffect scripts. It would call their "ExecuteEffect" method when the particular event is Triggered... This works fine until I want to Hook up the SpawnObjectItemEffect to a different event with a different method signature. For example if I make a PlayerHitEntityItemTrigger that subs to the player's OnHitEntity event which passes the hit entity and an IHitData instance. The data from the Hit event couldn't be passed to the ItemEffect without a specialization in ItemEffect to account for the Hit event's data (hitEntity and IHit).
What would be an eloquent solution to this "problem"? Should I make a "SpawnObject" script for EACH event type/signature? Should I have a method in the base "ItemEffect" script for EACH event signature that every ItemEffect needs to implement? Should I wrap my events into a unified data structure (PlayerEventArgs for example)? Every solution I come up with feels... extremely sloppy.
Not using scriptableobject definitely help and use C# object to contain event information. PlayerHitEventData or something like that.
ohk i didnt know android studio had a discord thanks! also i can provide the logs if needed
@jolly token I would still need different methods to accept the PlayerHitEventData and stuff. I was thinking about consolidating all the event signatures into a single struct that just marks what type of event it is when created. I just feel this is still pretty awkward and will require a lot of "hard coding" within my scripts for each event type still. I really don't want my scripts to end up having big switch statement blocks for example.
Ah, okay while creating struct specialized for an event is common practice, it is also valid approach to take single big structure that can hold various info. The latter is more likely end up having some sort of switch case. I’m not sure how is your structure, but if you are using event, it’s not bad to have a struct per event (or a group of event).
@regal olive What do you mean about parent objects?
I can't exactly pass this info in any more of a generic form. Like for example the data generated from a particular combat Hit cant be reduced down really. I can pass this data as an Object or GameObjects... but I would need to pass more info with it to describe it's context, event type, etc to know how to cast it properly. My issue isn't the types being passed, it's the variation in method signatures itself. I would still need multiple method signatures to account for the variance in Event data. I guess I could make the data more generic by just packing all of the data from every single event into a single struct like I described in my OP. But like I mentioned in another reply that would cause the same issue that Im having in a way because I would still need some kind of switch statement to "know" what to do with each event's data.
How about keeping a common signature amongts all events ?, Pass a BaseItem component from which everything derives and each recievers, according to their behaviour.. Make GetComponentCall<T> from that Item ? Assuming everything is ComponentBased.
THis way IOC is achieved via GetComp and you can scale it, Though each reciever script will depend on the <T> it fetches from the call.
@jolly token For sure. I've seen solutions like that before. I'm worried it wont be extensible. I will have to hamfist every type of event into a potentially large object type that is passed around and processed in countless ways, mostly within a single method on each script.
@obtuse arch Do you mean I should do the whole PlayerEventArgs thingy except it's a container for concrete typed EventData (like DashEventData, HitEntityEventData, etc). I would access the EventData using a generic <T> method based on the Event type being received in that Item? Wouldn't I still need different bits of code for each Event type within each ItemEffect script in order to actually process the EventData from the PlayerEventArgs container? Honestly I think it could potentially be cleaner to just make a "SpawnObjectX" behavior for each event type and have the single responsibility of processing each events data kept strictly in a single component. It's a lot of components though...
Not a container for all EventData, But instance EventData(assuming its base) passed down in the signature. and each subscriber gets the required component from the Base by invoking a GetComponent<ChildType>() call. I dont know much of your code but assuming everything is monoBehaviour this should work,
Similar to CollisionHandling pattern where a Collider/Collision is passed and from its GameObject once can retrieve required components, assuming the mapping is correct
If your event only used by event caller and handler, then there is no need to worry about extensibility, is it? You can easily change that part if something about specific event needs to be changed as long as concerns are separated.
As he said multiple handler can listen to multiple caller but need to implement signature occurs.
Event and delegates is a solution but still his problem of signature retains.
By scalability, He means no need to implement calee’s reciever’s signature.
If im getting it correct ig.
Ah okay I see. Thanks for helping me understand
In that case, the problem I see is coming from that Trigger and Effect is decoupled but somewhat dependent. You could make interfaces that constraint them, for example IHitTrigger can only trigger that implements IHitItemEffect and passes IHitEventData. and IGenericTrigger can accept any IItemEffect and passes IGenericEventData, something like that.
I love the idea of interfaces. Maybe I'm just not working on a project that's big enough yet, but every time I start integrating interfaces into a new feature or system I'm building, I seem to always transition it into an an abstract base/inheritance structure. I think I need to read through some code on GitHub or somewhere and get a better understanding of how to use them properly though.
I'm also super interested in reading some professional project code/source files. Does anyone knows where to find something like it?
These aren't pro code bases but this is a cool list of some open-source projects made in Unity. Some of them have very dedicated contributors and are quite huge. https://github.com/proyecto26/awesome-unity
how would you implement a canonical hexagonal in unity?
also what advantages it has over ioc/ddd/ecs and how will it help deliver product in time, are there any examples where a project was using it?
thanks, I may just take a look into that
understood half of what you said lol *me running back to #archived-code-general *
This approach will solidify context of each signature and will invert the deps from actual components.
Letting you inject behaviours.Though new code or new relationship between components will require additional code since there was no such relationship present.
hey guys, is it possible to play webrtc (i have the working server + url) in an android app? i found the webrtc package but that is not for playing url, more like stream
why do you do that, rather than just implementing something and seeing how it functions?
How can I sync Instantiated prefabs (like projectiles) in online Photon game?
Do I have to Instantiate them differently?
Anyone have any idea how to convert this algorithm from a recursive one to an iterative one?
Recursive means it uses internal stack. It’s always convertible with a stack and you can start from there
Well what does GenerateLegalMoves do? It doesn't take any argument. Does it assign always same thing?
It generates moves depending on the state of the chess board and adds them to the move list
move list being a stackallocated array
So it's basically calculating number of cases that can happen after N moves. hmm
Yeah it might. What is the purpose of converting? For memory, or performance, or something else?
@jolly token GPU
Recursion on GPU is slow.
So trying to convert to an iterative version
Ah hmm.. I'm not experienced running algorithm on gpu, but maybe making move calculation parallelized can help?
That doesn't help in converting to an iterative?
working server + url
webrtc works with signaling. there is a barely used "standard" that is unlikely to be the one you're using
It doesn't make it iterative but it was a suggestion to parallelize the process as an alternative. If it doesn't work for you then nevermind 🙂
you can try the experimental/directrender branch for usable android webrtc receiving
you can read the xmage or spellsource source code for implementations of spell effects that are tested
This is a ‘dynamic programming’ category problem where soln for next state is calculated on soln for previous state.
Making it iterative wont help you parallelise since the othercore will have to wait for previous result of any other core anyway.
Better approach would be identify individual non dependent calculations batch (batch meaning a sequence of calculations though dependent but only on result of sequence itself)and run those sequo in parallel.
This way you will achieve multithreading some way but still most of cores will wait anyway.
Also i would suggest looking at job system, The overall framework is good and you will find much functionality needed.
I'm talking about GPU parallelism here
not CPU
GPU is just an extra computation unit(CPU) specially for graphics processing XD,
Yes architecture difference is there but fundamental principles remain same for achieving parallelism
Though your problem is more directed towards cpu, even if you manage to run it on gpu im sceptical wether you will see any actual performance boost.
Do profile and scale upon that is what i suggest.
Hi, does anyone know how to make a custom virtual cursor?
You mean change cursor graphic in game ?
Or crosshairs like in fps?
kind of like crosshairs
I want a crosshair so a cursor locked in the middle of the screen and invisible but to have it also be able to click buttons in world canvases
Well yeah i guess
Hmm
Ill try that, thanks
That might be too advanced for a simple thing such as this
It's possible to use webrtc as one to many, and that is my case, i can play in the browser the webrtc://localhost/live/teststream/test but there is no example how to use the unity's webrtc that way
@regal olive Sorry. I didn't think I explained my problem well enough initially
no reason to be rude about it
You're trying to over generalize your behaviours, even if they can't really be generalized
You'll spend ages trying to fix bug in specific combinations and likely introducing new bugs in other combinations
There's no way to reasonable do that
@regal olive ahh okay, thought you were being sarcastic haha.
Take a good look at your passive items that you designed and go figure out what 5 are common enough to share an implementation
@hollow rapids Yeah seems to be the issue. No reasonable way to structure this how I've been structuring all my other systems.
Also, if you don't have passive items designed yet. You should do that first, trying to make a system that encapsulates all possible passives items you might ever want is an easy way to shoot yourself in the foot
??
@hollow rapids I have a few in my brain that are very different from each other that i've been using to inform the code.
Unique behaviours like that don't tend to generalize either way, so you might still have a custom behaviour for that in both systems
@flint sage im not even sure what it would look like to code something like this in a less generalized way.
@regal olive I guess you could describe it as a combo between Risk of Rain and Vampire Surviver... kinda. When the player levels up they get to choose 1 out of 5 randomized Passive Items. The same item can be stacked multiple times to give additional bonuses.
@regal olive I have an implementation of this working but the Passive Items are just Stat Modifiers atm. I want them to have more interesting functionality.
Actually, it's insanely different. Please read up on it.
I already have a CPU parallel algorithm
But GPU one seems out of reach
Really depends what you're making tbh, porting a cpu algorithm won't work very well obviously but some things are very well suited
I am putting this here, not because this is particularly "advanced" but because i have been debugging for ages, have asked tons of developers for advice with no avail and have been searching online to see if anyone else has had any issue like this.
I have created a asynchronous loading screen to build the game scene, track it's progress on the slider and wait for the min load time if it loads too fast. Pretty simple. It works perfectly the first time around but if i return back to the main menu and press play again, it activates the loadingBackground for .3 of a sec, runs up to line 57, the says progress is 100%, fails to run any of the other lines then deactivates the loadingBackground. I have no idea what is happening, any advice or tips would be awesome, thanks in advance !
Hello there, I'm not sure if it could be written better than this.
I have this GetAllPopluatedSlots which is an IEnumerable, but I can't convert it into an array on the fly, so I've been forced to make a new foreach loop
List<EquipLocation> equippedItems = new List<EquipLocation>();
foreach (EquipLocation itemLocation in equipment.GetAllPopulatedSlots())
equippedItems.Add(itemLocation);
for (int index = equippedItems.Count - 1; index >= 0; index--)
{
items.Add(equipment.GetItemInSlot(equippedItems[index]));
equipment.RemoveItem(equippedItems[index]);
}```
Can I spare a for-each in some way? 🤔
Or maybe in performance meaning it's a non-problem?
public IEnumerable<EquipLocation> GetAllPopulatedSlots()
{
return equippedItems.Keys;
}```
equippedItems is a Dictionary
Have you consider interface approach?
#archived-code-advanced message
You can also create interface like interface IItemEffect<in TEvent> so you can get benefits of contravariant generic constraint.
Im intrigued about how you managed it in parallel. Do share if you can.
You can use LINQ's ToList() to convert IEnumerable to List.
If your items is list, for that logic you could also do
items.AddRange(equipment.GetAllPopulatedSlots());
equipment.Clear();
https://github.com/TheBlackPlague/StockNemo/blob/master/Backend/Perft.cs Feel free to scroll down and see 🙂
the method is called Move Generation
It uses parallelism when depth > 4
for all depths <= 4, it does it synchronous as moving data to other threads is more expensive then the actual operation
@jolly token Could you give me an example of how that would work? I'm struggling to figure out how I would use the interface to get around the extensibility issues. Wouldn't I end up with the same type of problem compared to using the abstract base class or just wrapping Event Data into an object?
Let me write some example code
hmm
well what's your objective @hushed moth ?
what is the game?
loading screen to build the game scene
hmm why?
the tabbing is off at the bottom, have you configured your IDE correctly?
i think you are making something too extensible and complicated
how many items do you actually have?
that you have written?
Its more like to display 360 stream in VR, and i need low latency, rtmp is not supported by unity so the only option is webrtc
okay you just sound
As soon as the user clicks play in the Main Menu, this script throws up a loading screen, tracks and displays the progress of the next scene to the user using the slider then disables the loading screen when the minLoadTime is met. It's works perfectly fine the first go round but if i go back to the main menu and press play again in the same session, it's fails.
not very experienced in all of this and it's very very hard
are you trying to stream from a desktop over the network to a quest device a 360º rendered video?
and then beam back positional information? what is the idea?
what is the game / application
well because the idea is pretty buggy
i can tell you how i would write it
based on the code snippet you shared things are in kind of bad shape
i would be intrigued to hear more innovative ideas because every loading screen tutorial online uses the same Asynchronous Coroutine Method that i have displayed but just in different ways
What if you just didn’t have a loading scene
Right before you transition scenes
In your old screen throw up a UI image that says loading
Then synchronously load the next scene
What kind of game is it? The right answer is don’t use scenes but I’m tired of saying that
Interesting approach but i just find it would be a lot more cluttered and unorganized to put every GameObject in a parent and keep 1 main scene alive throughout my entire games lifecycle, and just set it to active/not active when using or not using so i create scenes for major sectors of the game.
And using 1 scene for the entirety of the game may not be an issue for you depending on your memory requirements, and performance requirements but may cause issues for others.
So nobody can realistically avoid load times. They are going to occur. Objects take time to load so i do need to make a reliable loading screen.
https://gist.github.com/cathei/ed8ea7f088237b681a43db2dfec256ea
Here I made an example script how you could apply interfaces to your Trigger/Effect system
The point of the system is you can put IItemEffect<IEventParam> to any trigger that has more specific event parameter. So you don't have to create multiple overloads for same ItemEffect.
If your ItemEffect requires more specific event param like IPositionEventParam, you can only add to the EventTrigger supports the params that extends IPositionEventParam. (and it's correct behaviour because otherwise it wouldn't make sense).
Anybody able to help with a Serialization issue? I'm trying to create a dropdown for a custom class. It works, but when I actually select the class from the dropdown, nothing happens. Here's the problematic line: "property.managedReferenceValue = Activator.CreateInstance((Type)obj);"
Anybody know why that wouldn't instantiate the obj type within the property?
Hi I need some help
I'm trying to use this package
I have a server : camera ->rtmp->webrtc and i would like to display the webrtc stream in unity. I think it should be possible since the unity is supporting webrtc i just couldnt find any example for external webrtc url render/display
So the scripts compile, no errors nothing, but it doesn't connect to the node server
I tried using the exact code that is on the documentation (the example code) but it doesn't work
Can someone confirm running the package on their pc ? I just want to know if it's only my problem.
- Yes I have set unity API compatibility to 4.x
Debug to see if you're getting any connections.
Are you receiving data?
In a web browser webrtc player? Yes, the stream is perfect with low latency
In unity?
That is the question. How to receive stream from external source?
Your original question was how to render/display.
And that would be MaterialOverride or RenderTexture
So you're not receiving data?
no, I don't
https://github.com/Unity-Technologies/com.unity.webrtc/issues/652
I would like this more-less so somehow receive the data (from external URL) and make a raw image (video stream) from it
You don't want to write to a raw texture, that's way too expensive.
im having problems with my code (not technically my code) its the unity fp movement code but after c/p it, there are eroors with the code, I dont really know why... but there are 3 ; errors and 1 } error, and when i go to the line of code there are ; and on the other 1 there is a {
ill send the code momentaraly along with the errors
Just read the errors, and it will tell you the issues.
then what do you suggest?
And that would be MaterialOverride or RenderTexture
But right now you need to focus on receiving data.
Assets/universal player scripts/movement/player movement.cs(139,75): error CS1002: ; expected
Assets/universal player scripts/movement/player movement.cs(139,80): error CS1002: ; expected
Assets/universal player scripts/movement/player movement.cs(139,80): error CS1513: } expected
error CS1002: ; expected
Assets/universal player scripts/movement/player movement.cs(139,102): error CS1002: ; expected
error CS1002: ; expected
ik
What does that mean?
i checked and its missing a ; somewhere but either im blind or there is no ; missing
ik means i know
Lol, no sorry I mean what does the error mean.
it means im missing a ;
Check your lines: player movement.cs(139,75
Also you should not have spaces in your file names.
i did
What is the question if you know?
float targetSpeed = _input.sprint ? SprintSpeed : MoveSpeed;oint error prone, and is cheaper than magnitude;
What is oint error prone, and is cheaper than magnitude
That doesn't look like c# to me
its a temp code 4 movement out of the fps unity example
ima change it out later to fit my game
dude read the line 😂 this isn't anywhere near #archived-code-advanced anyways
sry 😦
Not to be mean but that oint error.. part isn't a code. It suppose to be a comment but seems to be cut off from somewhere.
Also you may want to configure your IDE to show where is the error. #854851968446365696 IDE Configuration
Unity is an abstracted way of displaying components (classes) to have everything in one class is possible but it's like "why".
It's very hard to handle references or pass around data that way as well, and it would make it harder in the long run to write and update your code.
i have it set up, it just is weird sometimes
I don't really understand what you're trying to say.
Having classes is not complexity, it's abstracting your code out in component like objects that you can reuse.
Classes (if anything) make your job easier.
How would you have dynamic systems if it was all one class?
How can you have 10 or 20 enemies?
How many years do you have?
Most development pattern and techniques are for teams not for single developer. To make a big project maintainable.
To put your question into perspective, you're asking something like.
When I go camping I bring my entire house with me.
Any book on the topic explains when and why they should be used.
Yes, but it's not your entire house.
You don't bring a fridge (network code) in a tent (enemy)
"Can you justify the complexity of breaking apart your game software into a whole zoo-ology of different classes when a single component could suffice?"
This depends on what game you're making and the complexity, you could make pong technically in one class without any issues, but if you ever wanted to extend it you would have to do 2x more work. (this is just looking at practical's of development) iterating on design and development.
To answer your question, there's no truths in programming, you will never make the best possible script and even if you do then there's so many factors as to what is a good script, is it speed? Dev time? Compact? etc.
But in terms of asking "Is something complex" is that asking from a new developer standpoint or general terms?
Breaking your properties apart is the easy thing to do, it adds readability as well as keeps your code compartmentalized. So in terms of complexity I believe having one class would expand that exponentially. Imaging having to have render code in the same scope as player movement.
Also debugging, teams, networking, generics, dynamic systems, iterating, tasks / threads. Would all be nightmares to do.
Sure, and 90% of tuts are done by juniors.
You can shoot your foot however you want to when programming.
How can I answer that?
I try and make my systems least complex as I can.
But literally how can anyone answer that?
With classes 😄
My classes are done in a way that they do one thing.
Or act on one object.
When I started programming, I believe everyone does.
But you learn.