#archived-code-advanced
1 messages ยท Page 40 of 1
Yeah, looks like beginner physics 
this doesn't make sense
why?
that's why i used (position-shoot).normalized
so you'd just directly do DrawLine(pos, shoot, ...etc)
this doens't make sense
I did it before
er wait
yeah I guess it does lol
but it's kinda weird to convert from position to direction then back to position then back to direction lmao
xDDD
What do you actually want to do here?
name your variables better so I'm not so confused ๐ตโ๐ซ
You should also name your variables better, so you know what they contain just by looking at their name
I want a ray which goes from the point in front of the white square. This ray has a direction. If the ray hits a gameobject which has the layer "Mirror", it reflects the ray from the normal of the collide
that's what i want initially
Okay step by step, get rid of the reflection part and get the cube to mirror working first
Debug.DrawRay(pos, ray.direction * scalar, Color.red, 1f)
Reflections would be a recursive call anyway, so not much changes if the original method to make one ray works
Yeah, true, i have the recursive ^^
I just need a Vector3 as a starting point
and a direction, right?
Yes
to start the recursive i mean
the starting point is this
Vector3 pos = new Vector3(transform.position.x + 1f, transform.position.y, 0f);```
i need this one
how can i calculate the direction now?
One unit to the right of the object this script is on
yes
second argument should be the direction and scaled to the length of ray - relative to drawray.
Direction, depends on where you want it to go. It can be as simple as a Vector3.right which is a direction that points right
I will draw my ray that way
Yeah, but i need to do it on the right, but with a certain angle (which is a float)
like this
the red line is Vector3.right
but i want the black one ( the angle is approximative)
What you can do is make an empty object rotated up, and take its transform.right instead
there isn't another way?
That will make it versatile, if you need to have another rotation just rotate the whole object
So example... a direction could be mouse position converted to world position subtracted by initial position.
yeah but this is a light emitter, which is static
I mean, rotate it is not a bad idea
Relative to angle, yeah you could compute it with rotation - guess it's how you're generating the data to start with (doesn't matter as long as it's correct)
ok i will do transform.right
There are pure code ways, but some of them involve vector math with Quaternions which is a bit hard to understand at first
Simply put, a Quaternion represents a rotation. Multiplying a direction vector with a Quaternion rotates the vector
But yeah for a light emitter it would make sense having a standalone object you can copy-paste here and there, and rotate
I'll leave the rest to you guys. Idea would basically be keep shooting rays starting from initial point and direction with recursive hit points and normal directions.
Good luck.
DrawRay is wrong
:x
You're mixing them up
kinda stupid
Rest of the code looks good though
Okay good, now you want to actually raycast with these parameters and use the hit point and the normal of the hit point to recurse down
Some basic pseudocode would be like cs while(length > 0) hit = Physics raycast 2d ... if (hit.collider != null) distance = hit.point - origin draw ray (origin, direction * distance, ... ) length -= distance origin = hit.point direction = hit.normal else draw ray (origin, direction * length, ... ) breaketc (cleaned it up a bit)
Basically, the code that fires the ray should take the start position and direction from method parameters, that is if you want to make it recursive
There's also the iterative way like Dalphat just posted, with a loop that updates variables at the end
Depending on the angle of the mirror, i got this, or this :
I tried to do like u said before, but i have a stack overflow xD
Pseudo code, recursive method
void ShootRayReflect(Vector3 position, Vector3 direction, int depth)
{
if (depth > someMaxDepth)
return;
// fire ray here...
ShootRayReflect(hitPoint.position, hitPoint.normal, depth + 1);
}
"Simple" as that. Always have an exit condition for recursive things
I'm just dying xD
maybe i just fail the part "else if(hit.collider.CompareTag("Mirror"))"
Not sure for the quaternion mess to reflect the vector, you can just Vector3.Reflect(direction, hit.normal) and that does what you need on one line
The incoming direction, that is the direction you used to fire the first ray
So yes that would be the direction param
Hm why are you constructing yet another Ray in this
You can just call the method recursively with hit.point and nextDirection
yeah but it doesn't work ๐ฆ
it works dependly of the rotation of the mirror
some rotation makes the reflection with 2 magenta rays (like the screen i just sent)
and some rotation are good
Okay so it might just be hitting the object it's starting into, and it freaks out
Sure, you can offset the start position of the new ray along the reflected direction
like hit.point + someValue
yeah
i mean maybe with doing
hit.point * direction * 0.5f?
You already compute the reflected direction so it would be: hitPoint + reflectedDir * smallOffsetNumber
So it'll start along the travel path of the new ray
Nice. I had a project that used reflections but I can't find the code anymore. Was about to pull it up to compare if it didn't work out
ohh okay i see
Oh well I found the code, but it doesn't even compile? lol
xDD
Yep it's completely broken. I use a variable I never declared, along with the horrible code formatting. Project is from 2018, time flies by
It doesn't have the reflection system implemented lmfao, must have dreamed of it working
maybe ๐
Just checkin in here, but for performance purposes, is there any way to get attribute references without reflections?
nope:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/
After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.
But you can cache the reflected data for reuse
in most cases
You can use other pattern if the context make it possible. You could create a Base Type that every class inherit where you can then do what you would have done with reflection.
what are you trying to do?
Hi everyone, I'm making progress on my hidden character game and the next pattern I need to create is making all of them bounce off the sides of the camera/screen/game area. I have a game reference as MP4.
And here is a generic reference of a bouncing DVD logo screensaver:
https://www.youtube.com/watch?v=5mGuCdlCcNM&ab_channel=RaรบlBlanco
I don't believe there is any difference in behavior between the game reference and the generic reference.
I have a script that can instantiate all the characters onto a grid and give them their own unique direction and speed to transform. I think that to produce this pattern, I need use the cross product to get a vector perpendicular to the original vector of the character and the side of the game area, then replace the character's vector with the perpendicular vector. Then we just need to repeat it every time the character runs into a side of the game area right?
If it hits a corner, what vector should be used? I'm unsure about that.
Bouncing DVD Logo screensaver for modern screens (4K 60fps 16:9) - 10 hours NO LOOP
Don't crosspost
No need to post in different channels. If someone can help they will.
Okay I'll make sure to only post in 1 channel
Hopefully this question is complex enough to be considered advanced:
Setup:
My player has a controller script. My player can equip weapons and armour. All items in the game (which include weapons and armour) are scriptable objects.
I want my player to have abilities. An ability is any kind of combat action - swinging sword, special attacks, fireballs, ets...
I want to write the abilities as something like coroutines; having them take control of my players movement for their duration.
I want each weapon (scriptable object) to be associated with an ability (or a collection of), such that when the player has that weapon equipped, the player will have access to that weapons associated abilities (as apposed to having access to every ability and being told which one to use).
Question: What would be a way I could achieve this? - Having IEnumerators on weapons, passing the weapons to the player, and having the IEnumerator effect values in a script sitting on the player?
(I'm not set on IEnumerators, just my current idea)
Write it as a list of key value pairs
Hello. I am working on an A* pathfinding algorithm for my grid-based game. What is a good variable type to represent my grid as data? Currently I am using the position of tiles and obstacles in the world, some of which can have negative coordinates so using just a two-dimensional array is not practical. What about a Dictionary<Vector2, TileData> ? Or something else?
Ideally you'd use an array anyway
Using an dictionary will only slow your pathfinding down, since each key would have to be searched for using the hashing algorithm
An array on the other hand can access an index without such algorithm, which for a brute force algorithm such as A*, is definitely what you want unless you don't care about performance whatsoever
Average access time for dictionaries is O(1) but it just is multiple times slower than array (it doesnt get slower for bigger dictionaries but its slower to begin with)
Yeah big O notation defines complexity and not speed
Aka how many iterations you on average to find your item (or best/worst case)
Lets say i have an unity app.
Can i load resources from an external folder on my smartphone to do stuff with them ?
Like an additional folder where mods are stored, or skin materials or whatever.
Is this possible or does unity forbid this ?
It's more about the platforms restricting access, not unity
Asset bundles are a good option
Or you can load textures from file
So its possible... I only need to load in models, textures, materials from an external folder. No code or scripts.
If you want models/materials then asset bundles are easiest
Alright thanks ๐ iIts basically such a scenario where the user is capable of designing "gameobjects" outside unity to load them in and view them. Kinda like a basic 3d tool, but without scripts.
That's not as easy, you can't export asset bundles at runtime. So you'll have to figure out a way to save/load them yourself.
What could be such ways ? A own dataformat ?
A file format that defines a bunch of texture, fbx and material references aswell as how they are applied to each other ?
What about those adressables, i heard we can export/inport them at runtime ?
Addressables is the same as assetbundles
And yeah your own data format or find a library that supports your needs
Damn should have picked something else... Thats gonna be my bachelor thesis xD
Hoped it would be easier
What is the player able to do in your editor then?
Can they create meshes of their own or just pick from existing ones and put them together with position and rotation and maybe material selection?
if its preexisting content just put together, you can easily do that with a serialized json for example @vocal dagger
The scenario is the following one, the player/user should be able to construct gameobjects/models outside of unity to export and load them during runtime.
The materials, texture and models do not exist at that point in unity. So nothing pre-exists.
Then the user can play around with it during runtime, switching materials, rotating, placing e.g.
However i just saw that theres gltf which does this pretty much. Or probably we could force the user to just provide a common ready to use fbx file by himself.
I do not think you can easily import fbx file through runtime tho
Not sure about gltf. Its a good format but usually for webgl, isnt it?
There seem to be runtimefbx plugins form the assetstore, might be worth a shot.
Problem: Garbage Collection Spikes:
I am working on a endless procedural world which is generated at runtime. My world is divided in chunks with are constantly generated and removed as you move around in the world, i got a the generation set up on multiple threads and i am also caching data with stays consistent across multiple LODs and it works pretty well. I am experiencing a slight stutter though when moving from one chunk to another I tracked it down to the garbage collector removing the chunks which are to far in the distance. For example the issue completely disappears when I disable the deletion of chunks entirely and resort to only disabling them, while this is kind of fix it is not really an option since this way I clutter the memory over time.
I am experienced in programming but quite new to unity and c#, so I don't fully understand how the garbage collection is working.
I guess this should be a kind of problem which has been solved over and over again though I couldn't really find a satisfying (simple as in only a few lines of code) solution yet. Does anybody has any ideas tips on how to tackle this kind of problem? Is it for example possible to keep the garbage collector in the AutoIncremtelMode for everything else while handling the removal of the chunk related data manually ? Or is it that this incremental mode unity offers is not working they way i think it does, as my chunks are "normal" c# classes and not part of the unity ecosystem, so it would help for example if I convert them to script able objects?
Much thanks in advance
Your problem might be, that your "chunks" are just a big load of objects, scripts and what not, that are being removed at once. Thinking about removing it partially might help to spread the garbage collection over a wider timerange and therefore avoid spikes. Also considering unloading chunks on a different distance then just disabling them (if you dont do this already) might help, keep the reloading simple. You could also use addressables to load assets but not instantiate them rightaway and also release the instance, which might be working more performant than just destroying them, but thats not proven from my side. But that might also give you the benefit of smarter resource handling across your objects that are being loaded.
I am already moving the assets around trying to reuse as much as i can, but the addressables solution sounds interesting. Though currently the chunks only contain a simple mesh for the terrain at the time when they are removed. Is there a way to not remove all chunks at once because in there is more than enough time in theory to remove them one after another until the player crosses the next chunk border, at the moment it is removing every single chunk the moment i cross a border.
Incremental GC should work for regular C# objects.
I'm not familiar with how the magic works, but I would assume if say a huge array object needs to be collected, that still has to happen in one go and can't be paused and split into multiple frames. Perhaps your mesh data is just one huge object?
You could take into consideration where your player is moving or exiting the tile. So if you exit north, check the south chunks and so on.
each chunk holds its own mesh, i tried decreasing the size of the individual chunks but that makes it worse, since while they are smaller now, more of them have to collected given i still want to have the same overall viewing distance
Yes but what if I turn around than to look behind me?
You dont unload the last chunk, but the one after that. Thats what I mean. ๐
Well if the reason to your huge GC spikes was that each chunk was too large and too much has to be collected at once, then smaller chunks should help as incremental GC should be able to split the collecting workflow over multiple frames (unless you are allocating faster than its split collection speed)
are you calling the garbagecollector manually?
But in general for GC related performance issues, the priority is to find ways to reduce allocation altogether, before looking to improve collection.
I tried but I removed it again
so maybe not removing chunks at all but have a fixed number of them which update and move around accordingly would help maybe?
You can still remove chunks, but reuse the underlying mesh object (if that's majority of the allocation)
I would really look into addressables tbh. That might help a lot in reusing stuff but might be some refactoring needed. Did you profile what ONE chunk is actually doing to your garbage collection?
No I dont know how to do that
I would profile how much allocation for each chunk creation first, and what it includes, before looking to optimize.
Thats something I havent tried yet
In general you should strive to reduce allocation as much as possible (0 allocation even) during core gameplay loop.
If there's no allocation, there can't be GC pauses ๐
So on startup I calculate the max number of chunks(from the max view distance) create all of them and than keep using and reusing them for as long my program runs
But if you reuse them, how do you get garbage collection?
Well, you could use good old pooling, once a chunk is done using a mesh return it to the pool, and new chunks simply grab them.
But I would profile first to make sure if your mesh is really the majority of allocation.
no i dont i was just clarifying buritos suggestion
Ohhh okay, my bad ๐ Is your game meant to be reusing chunks, sounds like. If yes, go for the pooling one.
are your chunks just the same or like a variation of a specific count?
what do mean by the same?
Like do you have a list of prefabs your chunks are being made of?
They are said to be procedurally generated so I assume probably not.
Oh my bad, missed that procedural part
I think i will try to use pooling
cant wait to get home to play around with that ๐ Thanks for your help
I already have chunkbuilder class which manages the creation updating and deletion of chunks so I think it wont be hard to integrate pooling
I haven't done much mesh manipulation, but in my project the mesh needs to be recreated every frame, and it's just one single mesh object throughout the entire lifetime, that gets updated via SetVertexBufferData/SetIndexBufferData with native containers, so it has zero allocation at all.
If it was done similarly to that, then I would encapsulate the mesh as well as the native containers as one class, and pool them.
But as said before, really profile and figure out where majority of the allocation is coming from, before going ahead with it.
there was Event for When list Change I did not know abt
}
void someList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
//do somthing call event or whatever
} ```
Wait, is that a built in thing?
Oh, with a hacky way of adding a property to each item in that list
Isnt like WPF code ? I am not sure you want to use this library.
Hey guys, i got a problem: i have a floater script and a ocean script. There is a function in the ocean script that is supposed to calculate the wave height at the position of the floater x and z coordinate.
This is the code: https://paste.ofcode.org/Lx3spqCRehtk7dyqfeykE2
The floater moves correctly at (0,0,0) tho the one at (0,0,20) moves the same as the one at (0,0,0).
The error must be how i pass it into the function or something. Chat GPT is not smart enough for it and neither am i ๐ฆ
Hi everyone! I have 8 compiling errors in this C# code that is designed to add UI elements to a game (as a modification). I have tried ChatGPT and fixing it on my own but to no avail (I'm kind of dumb), so may somebody help me with this? https://gdl.space/yijupirare.m
Start with the first. you try to pass a value to a delegate, thats not expecting that I guess. show your code pls#
Cause I was blind ๐
Ahh
are the lines correct of your error and your pasted script?
I modified a bit the code rn, will provide the link to the newest code
This is the newest link
So, what line are the errors?
Lines 56 x 3, 57 , 60 x 3 and 61
What is night.UpdateAndCommit doing?
Basically changes the time of the day in-game
The UI modification should result in this:
can you show the stacktrace of your first error?
This?
Thats just the log, below the console is a window with the full stacktrace
I'm trying to make a unit test (i've never made a C# unit test before). So that I can write tests for some of my helper functions. So I created a new unit tests project in my solution. The problem is I can't seem to import classes from unity. For example I'm trying to access Vector2Int, but I can't. Even if I put using UnityEngine; this class is still undeclared. Any idea what I'm doing wrong?
Okay, I set the stacktrace to 'Full', but it still shows the same error, do I have to restart Unity for this to work?
select the first error, is there more?
Yeah it sounds a bit bugged on your side. I guess there is one error and thats it.
Just for dummies, you are not in playmode, right? ๐
No
Do you have any delegate function anywhere?
oh you do have a lot
var textModel = new TextModel("Text", () => Time.realtimeSinceStartup.ToString("F3"));
You sure your TextModel is expecting a function as 2nd param?
Does anyone know how to pass this code to c#?
I'm definitely not sure
Trying to troll?
as a riddle? And he said, put that in c#?
how do I do that?
Try to find patterns in it and see, where it leads you
I be not programmed i wanna be character artist. I just want to do it to pass
Cause character artist are dumb and can not solve difficult tasks? ๐ Give it a try
You don't need to be a programmer to figure out that it uses symbols and numbers to give the approximate shape of letters that you can then just read or type yourself
But I like the teacher pasting code and ciphering it ๐
ok I'm going to try it and I'll tell you if it turned out well 
Not me 
Just try it ๐
Can you give me the text as text or do you have it only as image?
just paste it in pastebin website or so ๐ send me the link ๐
thank you
Ha, thanks! ๐ love those riddles
Literally gave you a unity script ๐
did you translate them in 3 minutes?
another I tracked it down to the garbage collector removing the chunks which are to far in the distance.
how did you determine this?
For example the issue completely disappears when I disable the deletion of chunks entirely and resort to only disabling them
do you mean the difference between destroying and deactivating game objects?
Look at default unity scripts and your riddle, you might get the clue ๐
good teacher - creative way to get you familiarising & appreciating the code structure
Hey, I have a LineRenderer at the good positions. However, the "angle" is not where I want it to be. I tried to disabled use world space, but the line goes further (out of the world)
ok i got it
Are you OK calling Get Component<> outside game object env?
or caching all components of a game object in a specific component and then get any component through it
because when writing get component outside a game object, you should be sure it exists
i'm not too sure what you are asking about. You can call GetComponent on any gameobject as long as it exists and you are on the mainthread
Surely. I can
The important section is are you OK?
It means is there any better alternative way
because when writing get component outside a game object, you should be sure it exists and has been assigned
are you asking if the component doesnt exist or if the gameobject doesnt exist?
as that sentence completely changes when you said and has been assigned as gameobjects arent assigned
sure you can have a CommonComponent script to store monobehaviours which exists on the gameobject and then it just references when you need to get a reference to something else on the gameobject, to avoid doing lots of GetComponents awake caches
The problem is if inside that CommonComponent script you have monobehaviours which doesnt exists on all objects. And then accessing the reference without null checking would still error
Yes I get your meaning
The problem exists even by caching
You can get around the expensive null check and just have a bool check instead by having a bool set after the initial GetComponent. I've got a generic class to store that.
So the only way is to be sure they exist?
If they are removed because of new design or other stuff, we should check
I hate runtime exceptions
I think if calling get component is restricted and be called only inside game objects, it can prevent some problems like runtime exceptions or at least mitigate
nope it doesnt at all
In game objects, I can add require component, also binding helps in zenject
Game object context
you need to either 100% know based on your knowledge that a GetComponent will always return the script (prefab knowledge, etc) but obviously if you change/add/remove scripts and don't take into account that you have no checks then your code could error
or you will need to check the result (or use TryGetComponent), either by null checking or storing a bool after the GetComponent as to whether it was found
(then using the bool to check whether it exists instead of null checking)
No
If someone removes a component, I can know it as fast as possible if I use zenject.
It returns zenject exception
But if I call Get Component somewhere else outside the game object , how I can get the error at the beginning?
public class ComponentB : MonoBehaviour
{
}
public class ComponentA : MonoBehaviour
{
[Inject]
private void Init(ComponentB componentB) // if ComponentB does not exist, I get an exception at the beginning, when the game object is created.
{
}
}
public class Script : MonoBehaviour
{
public void Func(GameObject gameObject)
{
var c = gameObject.GetComponent<ComponentB>(); // late exception
}
}
Throw or log error when GetComponent result equals to null
Question: Can I tell if the code is currently executing inside of Job system? Is there API for it?
are you wondering about internal Unity jobs and wondering if they are running?
or are you literally asking for a way to put in your functions to know if using the job system?
Literally trying to check if my code is called from job system
not to sound obtuse but surely you know if you are using the job system?
No, my library can be called from main thread, threadpool thread, or job system thread
But if the code is called from threadpool, and if I use Allocator.Temp I would get this:
ArgumentException: Could not allocate native memory. If this allocation was made from a managed thread outside of a job, you must use Allocator.Persistent or Allocator.TempJob.
well my other suggestion was to look and see the thread id, but that won't help you since you also could be using a threadpool
thats because the job system sets up an allocator for the thread (or for the whole job, i cant remember which) being processed, so allows for Temp in the job
If Unity does check for it then there should be a way to confirm that it is from job thread?
I'd like to use TempJob only if the thread is from threadpool (that is not running job)
i've found this JobsUtility.IsExecutingJob
returns true when inside C# job
try it out
Ah that looks promising
Works well! Thank you ๐
Is there a better way to write this so I only have to get reference once?
var h = b.GetComponent<Enemy>().health = (int)(b.GetComponent<Enemy>().health * 0.1f);
If I get reference to my Enemy component beforehand, like code below, I can't set it
h = (int)(h * 0.1f); ```
Enemy e = b.GetComponent<Enemy>();
e.health = (int)(e.health * 0.1f);
As int is a value type, it will be copied when passed around with = or in method arguments. You can't make it reference the original one, you will modify a copy
Oops mixed up some names, fixed
ahh I was confused. Thank you!
working on a dynamic action menu system. so i'll choose a character and that character has a list of actions. the list of actions will have the selected one in larger text and the rest of the list below it. if you scroll up once, it should "slide" the list up, so that the previous action is now above where it was before, smaller text, and the one previously below is now in the same place as the previous and has larger text. i'm sure this has been used in games before but can't find a good example video to show it off. but to summarize, an action list, start at the top, as you scroll, the list moves and each action becomes the middle action as you scroll.
so i've got the menu itself using a grid layout, but unsure how to scroll using a script by specific increments (it's a ScrollRect component on a grid layout group) and also how to detect which one is the active item to enlarge. any general tips on how to go about that? thanks!
can someone edit a script for me to set rotation for the object to the controller rotation (already included as gameobject bool) If yes dm me
@gritty crescent Don't crosspost. As I said in #๐ฅฝโvirtual-reality , you can ask your question properly in #๐ปโcode-beginner
List<Vector4> openNodes=new List<Vector4>{new Vector4(startCell.x,startCell.y,0,-1)};
List<Vector4> closedNodes=new List<Vector4>();
int iteration=0;
List<Vector2> exploredCells=new List<Vector2>();
Vector2 resultCell=new Vector2(Mathf.Floor(endPosition.x*RegionHandler.chunkSize),Mathf.Floor(endPosition.y*RegionHandler.chunkSize));
Vector4 pathResult=new Vector4(0,0,0,-1);
while(openNodes.Count>0&&iteration++<2048) {
if(resultCell==new Vector2(openNodes[0].x,openNodes[0].y)) {
pathResult=openNodes[0];
break;
}
if(!exploredCells.Contains(new Vector2(openNodes[0].x,openNodes[0].y))) {
exploredCells.Add(new Vector2(openNodes[0].x,openNodes[0].y));
for(int i=0;i<4;i++) {
Vector2 moveDirection=new Vector2((i+1)%2*(i>1?1:-1),i%2*(i>1?1:-1));
Vector2 newPosition=new Vector2(openNodes[0].x+moveDirection.x,openNodes[0].y+moveDirection.y);
if(!walkableCells.Contains(newPosition)) continue;
float gCost=Mathf.Abs(openNodes[0].x-startCell.x)+Mathf.Abs(openNodes[0].y-startCell.y);
float hCost=Mathf.Abs(openNodes[0].x-resultCell.x)+Mathf.Abs(openNodes[0].y-resultCell.y);
float fCost=gCost*.25f+hCost;
openNodes.Add(new Vector4(newPosition.x,newPosition.y,fCost,exploredCells.Count-1));
}
closedNodes.Add(openNodes[0]);
}
openNodes.RemoveAt(0);
openNodes.Sort((a,b)=>a.z.CompareTo(b.z));
}
if(pathResult.w==-1) return null;```
could anyone see if im being inefficient with my A* algorithm
or if it has any mistakes
ive been looking at this for over 2 hours and cant seem to figure it out
- removing the first item from a list is inefficient
- Re-sorting the open list every time is somewhat inefficient (why not min heap?)
- Checking the entirety of exploredCells for an item is inefficient, find a way to use a hash set
- Repeatedly accessing openNodes[0] is somewhat inefficient (why not cache?)
- I imagine walkableCells has the same issue as exploredCells
- And maybe nitpicky, but setting some capacity on your lists and/or reusing them would also save you time. It's worth the tradeoff in memory unless your map is huge
I didn't check your algorithm itself
- what should i do instead
- ill look into min heaps
- ill look into hash sets
- no idea how to cache
- same as 4
- all right
you don't seem to limit your search area, so I'd add some kind of limit there
well for (1) the simplest optimization is to reverse the way your open nodes are sorted, and removing from the end of the list instead. But a better and more common optimization is to use a min heap instead of a simple list to keep track of the next node to explore
my search area is
limited by my iterations i guess
i have a preliminary A* for regions
oh right, that'll work I guess
by 4 I just mean don't access openNodes[0].* repeatedly, store it somewhere.
var openNode = openNodes[0];
if(resultCell==openNode) {
// ...
i use this to speed up the process because i have a really big world
otherwise my A* would take up to 14 seconds for the same area...
isntead of 1.5
i see
the thing is
im sorting it based on the lowest f cost
oohh i see
i define that in the while loop
right
thank you for your help
i will look into this
iirc it would depend on where unity is executed from
like if you fire it up from the termnial it will have what ever was already in the envirement
i think you should be able to export a env var within ~/.profile
and that should be picked up on the next restart
yeah i think it might only be executed at login though
so not sure how many things you need to restart for it to take
if you are launching unity from the terminal, its easier since you can add the thing to ~/.profile then source it then execute unity
yeah doing some reading there is no global way to do it like on windows
more or less the varians ~/.profile ~/.zshrc and others execute on a login shell
so would only take effect if something is executed from the shell
if you look into it its easy for shells, but for executed via the dock or spotlight both require a separate method
keep in mind how the environment works, its not 1 set of vars
like some vars are set say in the shell and something is launched, that would inherit vars from where its launched, but that process can also set vars that would also only effect its self or something laucnhed from it
this matters since the vars unity gets for most people are inherited from unity-hub and are what ever it picked up when launched
also most shells let you do stuff like this as well
ENV_VAR_NAME=SOME_VALUE some_command where that var will only be set for what you run that one time
also curious why you want to use env vars for this command line args or a config file
GCost is suppose to be the real cost.
Why multiple the GCost by .25f ?
You can cache your fScore.
You can make the operation on a separate thread.
Dont use a for loop for 4 direction. Or at least put the direction in a cache and query them.
If your grid is infinite and you may encounter memory issue use IDA or SMA algorithm instead.
Is there no way to subclass MeshRenderer? its not sealed but my class doesn't appear in the add component menu oddly
agh, Renderer derives from Component, foiled again
Do not derive from MeshRenderer... What you want to do ? It certainly exists better way to achieve that.
Looking for a way to distribute a package for modders to use and create mods, but id need to distribute art assets to let them build addressables and everything, so the plan was to subclass MeshRenderer and basically just add a field to assign a Guid that would be resolved at runtime to replace the mesh. The whole issue with the normal mesh slot is I'd have to distribute asset store assets to allow them to use them in mods, which isnt allowed
youre right there is likely a better way to do it
why do you need to subclass MeshRenderer for that? Just add a script that does what you want.
doable but subclassing meshrenderer and overriding start really doesnt seem like that much of a stretch
im not opposed to just making a new script
anyways - is there any good way to handle this where they could see the assets in engine but still be packed? cant possibly load an addressable bundle in the editor?
ideally they dont have to just construct scenes out of these things by guessing and checking their object positions because they cant see the mesh until they build and load up the game
No, I repeat my concern.
A component should be removed, it is obsolete or whatever. Someone removes it. In a script, we have written g.GetComponent<ObsoleteComponent>(). It should be changed. If you don't care, you get runtime exception, when? When this line of code is executed, maybe in another scene, maybe in specific situation. It is bug prone. I hope you have got my problem.
Now, I suggested I can cache all required components in specific component, then get a component through this specific component
// Script A
g.GetComponent<BaseComponent>().ObsoleteComponent
So, if a person deletes ObsoleteComponent, I get compile errors and I am happy
public class BaseComponent:MonoBehaviour{
public ObsoleteComponent ObsoleteComponent{get;}
private void Awake(){
ObsoleteComponent = GetComponent<ObsoleteComponent>();
if(ObsoleteComponent == null){
throw new Exception(); // or Debug.LogError
// get compile error if ObsoleteComponent does not exist or fast early run time exception
}
}
}
Also, if I change or delete public ObsoleteComponent ObsoleteComponent{get;}, immediately, the compiler says where the problem is, all places
g.GetComponent<BaseComponent>().ObsoleteComponent
it makes it really slow
and inefficient
if i set the gcost equal to 1
That is because the GCost is not the correct formula and your HCost might not be representative. You might also have an issue with your code because you don't need to multiple the GCost by any variable, in fact, you may incorporate other issue.
GCost is the ACTUAL cost from A to B, where your HCost is an approximation from B to C that needs to be the closest but under the actual cost of B to C.
At the moment, you just fine tuned your parameters to your direct observable environment . You are overfitting your algorithm.
a min heap didnt speed it up, caching openNode[0] sped it up by 2%. Sorting the other way around and using the last value sped it up by another 2.4%
What is your test scenario.
If you tested on a 16 by 16 grid, your constant cost is going to be to large to figure out the actual gain.
my test scenario
is starting the game with the same position
and then getting the average of 5 tries
my game has an infinite world
firstly i split the world up into walkable regions
and use A* on that to find a region path
so i dont have to explore thousands of nodes
regions are a max of 8x8
and then i run A* on the nodes in the regions
How many node you have ?
... in average, in your solution
depends
5 ? 10 ?
if youre standing far away
or more like 10000 ?
In your A* solution
What is the amount of node you traverse in your A* to get to the given solution
Which is nothing
but if i stand far away
And you wont get anything from optimization
well my code runs this in 1.5 seconds
which i think is very slow
i think i might be doing something wrong
im not worried about the regions right now
just the general A*
that i use for my general nodes that i fetch
Is your world fill with a lot of obstacle ?
Except the fact that your A* is wrong, I feel you like you may have other issue. Did you profile correctly ?
quite a lot in villages
float start=Time.realtimeSinceStartup;
Debug.Log(Time.realtimeSinceStartup-start);```
You need to profile* in Build...
Your editor may take a significant amount of time.
building
Anyone here have any good solution for dealing with editor/inspector "data loss" when prototyping? That is losing serialized data when for instance renaming a field or property, or when changing what class another class inherits.
I really like relying on the editor as much as possible, but lately I've found I've become hesitant to change things when I know I will have to "rebuild" prefabs or SO:s.
I came to think that if I had some kind of external "database" e.g. json files or similar I wouldn't lose the data. I would just need to reformat it after making changes.
But working with both seems to defeat the main purpose of SO:s and prefabs which I think is speed. Is there some middle ground?
I know about the [FormerlySerializedAs("")] attribute but don't love it since it seems I can never be 100% certain removing it (even at a later stage) won't brake things. Also it only solves the problem of renaming fields/properties.
i was calling the time
before i did the region system
so the pathfinding itself is very quick
but my region system is veryyy slow
now my min heap sped up my pathfinding by 30%
i look at my region code
and realize that it can not be saved LMAO
i managed to optimize my f cost function
so now its 40% faster again
plus min heap
50% faster in total
Anyone here have any good solution for
Hey guys, I'm observing a strange behavior that I don't understand the source of, can anyone explain how my _equipment variable is becoming null in my OnSlotClicked handler? https://hastebin.com/namizonati.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So, you are not fixing the issue ...? If your region code is slow, you should optimise that, not your path-finding...
Seems pretty clear from the error
Don't see anyone calling you a loser.
Welp, I was trying to link you a good resource to help you set the setting but apparently I don't have to spend the time now
It's not a code issue anyway, delete it from here and post in the correct channel .. #๐ฑโmobile
my region code
uses pathfinding
i optimized it and now its 60% faster than it was
so now it runs in 1 second
which is not ideal
i have to think of a good region system
you can profile in dev you just need to be careful
it also depends a lot on your CPU
if you have less then 4 physical cores its probably a bad idea but otherwise its unlikey that your main threads core is going to be swapped inside of whatever function you are testing
and its less likely to happen in a build, but it still theoretically can so either way you should remove outliers
obv this wasn't possible before unity supported in-editor optimization but now that they do its saved a LOT of dev time for me because i've been able to get fairly accurate and consistent preformance numbers in the editor
you've also got to avoid certain errors that happen both in editor and in builds, like your code getting JIT compiled inside of your loop, or not compensating for function-call overhead
In my experience, you cannot profile correctly on the editor (When you want to know how much time a function is taking (Absolute value)). Even less if you use Time.realtime to figureout the time it takes.
Unity is mainly single thread, if you have 1 core or 4, it does not change much. It is also not about swaping in the function your testing, because the function is not threaded.
Hello people I have a problem regarding to shadows, I need to set the shadow distance higher because things that are under some object which are far away from the cameras should be dark but they aren't because shadows are not rendered that far away, now I tried setting the shadow distance higher in the quality settings but that made my shadows look like trash increasing the cascades helps but that only goes to 4. How could I fix something like that?
Not sure if this would help but have you tried increasing the shadow map resolution as well? The more shadows being drawn, the less space everything gets on the map. That's assuming "looking bad" means artifacts and low res.
All of this would affect performance, though, just a warning.
yes looking bad means low res and se jittering and artefacts
How high can I increase the res?
and optimisation ideas would also be great
Anyone know how I can have a script listen to audio sources in one location and then replicate what it hears in another location?
Hey gang, I'm trying to iterate through a list of gameobjects and grabbing a component on each game object. I'm then trying to pass through a dictionary key to each game object. The issues is I'm trying to iterate through the array and I don't know how to also iterate through the dictionary at the same time
I essentially want to pick out object 1 from the array and assign key 1 from the dictionary
Then go to object 2 and key 2
Essentially this
But I don't know how to make it work
Did this, might work
ElementAt is bad way to do it. What you want is Zip, but keep in mind that Dictionary keys are not ordered and order can be changed later.
Flip it around - foreach key in keys, and use your value iterator for the list of gameobjects.
Somewhat redundant as Zip works great for this, but ElementAt for a dictionary is going to be doing a lot of iteration each time I believe
When we compile monobehaviours into a dll, the classes will still be available in the component drop down list right? What happens if someone presses the edit button on it like a normal script?
i have this error when build "Error building Player: BuildFailedException: Burst compiler (1.8.2) failed running"
Hey, I want to make basically a mirror, that shows all the things happening correctly at a smaller scale.
Refer to the images if you don't get what I said
depending on what exactly you want to copy this will be simple or complex. Jut copying positions/rotations is simple enough - make proxy objects that copy localPosition/localRotation from the "real" ones and just put them under a parent which is scaled/positioned/rotated as you wish
if you want to copy animations etc, that will require more work, but the similar principle applies
Wait, what about
What about just making every side of the cube have a camera, that renders the contents to a render texture, then we can treat the render texture as a "portal"
then you have to do all that complicated portal math - and also it would block anything behind it
in your image I can see the green world behind it
wouldn't be able to with the RenderTexture/Portal approach
Ouch
I wouldn't completely rule out some shader magic
Hm?
Do you prefer fast forward or not when merging features/bugs to main/dev or main/dev to master for your projects?
Which one is default merge strategy for you?
hello, I am looking for someone who can develop some codes for me, information by private message.
not an advanced question and also !collab
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
Is anyone familiar with DOTS ? I'm having trouble instantiating X prefabs with unique seeds for their random generator
Thanks !!
Okay, what about also copying what's happening in the clone?
For example, if do something to the clone and the properties of the objects inside it change, I also want the properties of the original to represent what's happening in the clone
Kinda like the same thing, but the other way around
you can't modify prefabs at runtime. there's no concept of a hierarchy of modifications in the player
that's why when you hit play, the hierarchy on the left loses all the blue colors and it's all white.
I meant position and rotation etc. when I said properties
What is the best way to execute code at the end of a particle's lifetime? Ideally it'd be something like an event or action that gets triggered at lifetime 0, and returns that particle's position. Only thing I can find is this: https://docs.unity3d.com/ScriptReference/ParticleSystem.GetParticles.html
I'm assuming I'd have to add every particle to an array or list then check if its lifetime is 0 every frame. Asking in case there's a more performant method
there's Particle.remainingLifetime which might be useful for something more performant
you could rig up a callback and a basic frame with them bound
a cache
dump it when you're done and run cleanup if necessary
you don't want hangnail callbacks to null objects
Could you elaborate on this? I'm not sure what you mean by a frame with the particles bound.
depending on what exactly you want to copy this will be simple or complex. Jut copying positions/rotations is simple enough - make proxy objects that copy localPosition/localRotation from the "real" ones and just put them under a parent which is scaled/positioned/rotated as you wish
Okay, so, I'm trying to do this but I have a gameobject inside the parent gameobject that copies the local position and rotation of the parent object.
However, I'm running into issues
Will send a video in a bit
a containerized object with the concept of a single job
The parent game object is rotating btw
in this case you would want the job to be a callback, and you would want it to be containerized so you can determine when the particles are in fact done
essentially you'd want something simple like fire event when complete
which isn't much code
you can also use yield or any number of async shapes
As you can see in the last few seconds, the child gameobject clips through the parent.
Code: ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProxyObject : MonoBehaviour
{
public GameObject representingObject;
void Update()
{
transform.localRotation = representingObject.transform.localRotation;
transform.localPosition = representingObject.transform.localPosition;
}
}
so what you're doing here is a logical anchor issue
Me?
yes your smaller cube is anchored to it's own centerpoint in the math it seems
when it should be the child of the larger object
amirite?
so it should stick to the internal like glue?
Wdym?
I'm trying to basically mirror all movement of a level in a smaller copy of the level
OH I SEE
I see now, i zoomed in
that's a pretty cool idea btw
i've seen it done in different forms
I was originally going to make portals that cover the object's 6 sides, but that was too hard for me (100% the math)
so what happens here is, you have different rules for the smaller cube, as you have for the room and the larger cube
if you're using OnCollisionEnter to detect
the scale affects the collision
though i don't know exactly what you're doing other than update
Nothing
I just assign the inner cube ProxyObject component
And then set the representingObject as the parent

you could run a secondary validation
a, logic check if it were
to ensure the rotation matches the parent, and the relative position within the area matches
Maybe the inner cube is just too big
if you want it perfectly to scale, then you should use a logarithmic scalar
as it will progressively become smaller mathematically and naturally
I have no idea what that means
err sorry, I had to relearn trig recently
Are you talking about 3*log_5(2) = log_5(2^3)
Alright
still an interesting one though
most likely you'll solve it using an exacting mathematic
Logarithmic scale maybe?
Okay, yep
The problem was the size
I also want to, like, when you shake the copy of the level, all the props in the level (including the ones in the copy) shake as well, so kinda like a reverse proxy, if you will

You going to have an ambiguity issue if you do it bidirectional.
Given an object with different position in the world and in the proxy. Which one is the correct one ?
Otherwise, I suggest that you read on Coordinate System. Something like that could help you figure out the math you need to copy the world into a smaller version. https://www.khanacademy.org/math/linear-algebra/alternate-bases/change-of-basis/v/lin-alg-changing-coordinate-systems-to-help-find-a-transformation-matrix
In theory, there is probably a good combination of transform that could works.
Finally create replicable scenario. (Do not use a player controller for your "input/forces") It could help you significantly if you struggle with some math issue.
This image seems correct with what you were trying to achieve. Ask yourself where is the celling in your cube image.
ok this doesn't sound advanced but I'm very confused
I'm spawning a new bullet from a bullet prefab, and when I try to set the velocity on it, it stops it from spawning in the first place
I've split the code up to as many lines as possible and the one that's the culprit is when I try to set the velocity on the new bullet
without the line of code, the bullet spawns, but with it, it doesn't even spawn
it's not in the hierarchy window and I'm not getting any errors
Visual Studio debugging says all the values are correct and it was able to get the component properly and everything
no nulls or anything
and I've triple checked to make sure I'm using newBullet instead of the original bullet prefab when I need to
I am beyond stumped what is happening
GameObject newBullet = Instantiate(bullet, parent.transform.position, Quaternion.identity);
newBullet.transform.up = parent.transform.up;
Rigidbody2D rb2D = newBullet.GetComponent<Rigidbody2D>();
Vector2 velocity = newBullet.transform.up * _speed;
rb2D.velocity = velocity // This line causes the weirdness.
I can confirm with breakpoints that the function is still being ran
but that one line causes the object to not spawn in the first place
The script spawning it is a Scriptable Object, but the parameter parent is being passed from a gameobject
that wouldn't prevent it from spawning since by then it already has. are you certain it isn't being destroyed due to some collision when moving?
the scriptable object has been instantiated to make a copy from the original so the og's values don't change
I'm pretty sure, but I'll disable all colliders and see what happens
well it wasn't the collider, but there was another script on the bullet (that I didn't make) that was causing that to happen
thanks
the script says to destroy the bullet if it's velocity magnitude is too low
idk why lol
Alright, I'm in the big boy channel now
I'm trying to code my AI in a way where the player can't easily trick the AI into falling off the ledge
However, I can't seem to find a method that fixes this
I'm using A* btw
This channel is to discuss advanced topics, not to get help for beginner questions by advanced users. You have your question already in #archived-code-general l
What A* has to do with that ? Just make unpathable hole ?
Do you know any tool to pack some textures in an atlas in unity? texture not sprite
Now, I do it manually. I create a texture atlas, then for each tile (tile size can be different), send tile data to shader (origin + size) to get tile rect and correct uv.
It is OK for developers but for designers not
I want
Input: some textures
Output: A texture atlas + tile data (origin + size) it should be normalized (0,1)
I'm experiencing a situation where when entering playmode, unity reloads assemblies. Sometimes this process is smooth and fast, other times (after a few iterations of entering and exiting) upon entering the process either takes an eternity or crashes. I've noticed that when this happens the memory usage in unity spikes from something like around 3GB to close to 15 to even 20GB.
I'm trying to sort out what is happening here but I'm having trouble identifying causes so far.
If anyone has any suggestions I'd love the input.
On initial load it looks like it's sitting at 1.8GB at the moment.
So the 3GB mark was my previous run.
I'm blaming myself at this point of course.
But it's a head scratcher thus far.
Using the memory profiler package, I see unity has allocated 300MB in about 30 seconds of me moving the mouse around over the unity window.
I've seen some weird memory leaks in some unity versions before, no idea what version you're on but might be worth updating to the next minor or something like that
I can think of a workaround: have a single "staging / intermediate" blender project, where you add all your assets, and it's fairly easy to remap uvs in blender. Then all your assets come out sharing uv space.
I'm pretty sure you can just create the atlas and the binding will be automatic. You do not need to do anything special, just use the texture as how you were using them. If we are talking about https://docs.unity.cn/2021.1/Documentation/Manual/class-SpriteAtlas.html.
Here a more concrete reference then my voice:
https://learn.unity.com/tutorial/introduction-to-the-sprite-atlas#5cdc74c6edbc2a1684d5a3ae:~:text=Sprites that have been packed do not require any special handling%2C and Sprite Atlases are an easy way to (potentially) dramatically optimize your gameโs performance.
You would need to profile the editor itself and try to find out what is happening. If it is a major production project, you might be able to get help from Unity. Otherwise, you would need to replicate the issue and make a bug report. Also, you should try to know if it happens for everyone else, it may be an environment issue.
I have experience major slowdown myself. Panning in the Scene view taking 3s. I do not know how it happens, but usually, a Unity restart fix the issue.
At the end of the day, Unity is a really complex program made by people, for millions of people. It is expected to find issue.
Question for you. How many shader needs to be "compile". If you answer the question correctly, you will understand the issue. Hint: Shader Variant
I have tried stuff with portals several times, and in every video I have watched, the camera will make the portal it's behind invisible before taking a picture, and then make it visible again afterwards. I have tried this:
myPortal.transform.GetComponent<MeshRenderer>().enabled = false;
//positioning stuff
myCamera.Render();
myPortal.transform.GetComponent<MeshRenderer>().enabled = true;```
However, it still ends up taking a picture of the portal. Also this is being called in Update, not sure if that's causing problems. Please ping me if you have any ideas?
I'm currently trying to copy the portals done by Sebastian Lague just to get them working before adding the stuff that I need for my game.
I don't think that I can properly post a clip, but what's happening is the cameras are positioning properly, but they are still seeing the portal that they're supposed to be looking through when they render.
Hey im getting a really weird issue where a game object only delete if the scene view camera is facing it, so if i go full screen or turn the camera away it wont delete ```void Update() {
GameObject objectToDestroy = GameObject.FindWithTag("PLEASEWORK");
if (objectToDestroy != null)
{
StartCoroutine(DestroyObjectCoroutine(objectToDestroy));
}
}
IEnumerator DestroyObjectCoroutine(GameObject objectToDestroy) {
yield return new WaitForSeconds(3);
Debug.Log("DESTROY");
Destroy(objectToDestroy);
}``` is this a bug?
Try without a coroutine. Destroy can take a delay as argument 2.
Destroy(obj, delay);
should i instead make i own timer, cuz i need to wait x amount of time first!
ohhhhh
As for the potential issue, if the object that started the coroutine itself gets destroyed, then the coroutine stops right away
omg thank you so much
yeah that i know, but why does it depend on if my scene camrea is looking at it or not
Maybe you have something that disables objects entirely when you're not looking at them?
Unity does that out of the box, but it doesn't disable, it just doesn't render them (they stay active): frustum culling
Oh weird, I randomly tried making both portals go invisible and it's working now.
Actually I guess it was just that I had the wrong one going invisible.
hey, im trying to get a 2d scene onto a book (warp it a bit) and close it, is ther an easy way to do this? would also work to just get a freezeftame of the current camera and put it in a book and close it (also just getting an scene to warp in any way would be fine, i think i can figure out the rest)
im gonna put this here since i dont know how advanced it it
if you have any questions/suggestion that micht work feel free to dm me, im thankful for any help i can get
You wont be able to "wrap" a scene if you mean that you want to curve the whole space in function of the movement of a book.
But, you can "wrap" a plane with a shader that would render a RenderTexture of the capture of the camera.
https://docs.unity3d.com/Manual/class-RenderTexture.html
You would use 2 camera:
1 rendering the "scene"
1 rendering the "book"
On the page of the book, you apply the texture that has been generate by the first camera.
You then deform the book with an animation.
can you do SetPixels/SetPixels32 in a secondary thread or does it have to be main thread??
Good question. Test it yourself.
Texture access in threads
Hi! Anyone can explain to me why something like this won't work?
Grid<Node> a = myGrid;
Grid<IPathNode> b = (Grid<IPathNofe>)a;
Node implements that interface
Here more ressources: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/creating-variant-generic-interfaces
I'm still trying to learn/memorise the concept myself so I wont be able to help you.
Didn't know about that concept lol, I will save it for tomorrow since it seems like an extensive read. Appreciate it! โค๏ธ
Anyone know how I can ignore code lines or other packages being used, etc. Depending on which platform is selected?
I want to make it so that if I have the build platform to Windows it allows me to use Steamworks, but if I have the target platform to Android it doesn't use it
Right now even if I use #if UNITY_EDITOR || UNITY_STANDALONE, it gives me the problem of "'Steamworks' could not be found" as soon as I switch to mobile
well UNITY_EDITOR is going to be defined in the editor regardless of platform, so that's an issue right there
Need help, how do I make this work?
Sometimes T2 is GameObject, and GetComponent<GameObject>() doesn't give me the GameObject because its not a component.
public T2 GetFromDict(T objEnumType)
{
return _prefabDictionary[objEnumType].GetComponent<T2>();
}
okay, just write it out
_prefabDictionary[objEnumType].GetComponent<T2>(); will never be a GameObject
public GameObject GetFromDictGameObject(SomeEnum objEnumType)
{
return _prefabDictionary[objEnumType];
}
public T GetFromDict<T>(SomeEnum objEnumType) where T : Component
{
return _prefabDictionary[objEnumType].GetComponent<T>();
}
That's brilliant, thank you so much <3
ty so much my man, that looks like exactly what i need
public override void UpdateState(CharacterStateManager manager)
{
Vector3 screenPos = Input.mousePosition;
screenPos.z = manager.transform.position.z;
screenPos.y = Screen.height - screenPos.y;
screenPos.x = Screen.width - screenPos.x;
Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);
worldPos.z = manager.transform.position.z;
manager.transform.position = worldPos;
}
So this is the code that I'm using to find the screen to world point. But when in 3D this isn't exact as the objects x doesn't line up exactly with the mouse x position since it's a 3D space so objects further away will be more desynched.
Does anyone know how to better sync up the x position?
Example, red is where the mouse is
My closest guess would be to mess with the screenPos z more
tweaking the screen position like that is weird and suspicious. Create a ray from the Camera, create a plane facing the camera at manager.transform.position.z, cast the ray at the plane and use the intersection point
https://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html
https://docs.unity3d.com/ScriptReference/Plane.Raycast.html
Why thank you kind stranger!
I just changed the z to this and it worked
screenPos.z = Camera.main.nearClipPlane - 1.5f;
but I love learning new things
It says UnityTransport could not be found even though it is a component of the network manager object.
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(
allocation.RelayServer.IpV4,
(ushort) allocation.RelayServer.Port,
allocation.AllocationIdBytes,
allocation.Key,
allocation.ConnectionData
);
Here are the directives:
using System.Collections;
using System.Collections.Generic;
using Unity.Services.Authentication;
using Unity.Services.Core;
using Unity.Services.Relay;
using Unity.Services.Relay.Models;
using Unity.Netcode;
using UnityEngine;
I am really confused..
why is it being a component relevant? You can have components from different namespaces in the same GameObject. If this is the right doc, it's in Unity.Netcode.Transports.UTP.
https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.Transports.UTP/index.html
Thank you, I am watching a tutorial and it said nothing about including this line.
They are using some auto writer plugin, it adds directives automatically I think.
I think you have not read my question. My requirement is different.
It is not sprite, it is texture. Also as I mentioned I want to have tile origin + size in the shader for each vertex.
There is no generic tool/workflow that makes atlases for non-sprite textures desirable or convenient
what do I need to learn about to be able to make my game app open a web page in the game (to get some information) then take that information and continue wiht the game??
or is it impossible?
hey
how can I prevent and orbiting camera from flipping when it reaches the top or bottom
Not really an advanced code question but simply clamp the rotation value
clamp?
Clamp is a Methode to keep a value between a x and Y value
Kind of like min and max
I have worked with web requests ... I want to open a page and show the page on my game not just send a request and receive data
You canโt simply clamp a quaternion
You canโt render a page inside unity
? you can
There are plugins to load a webpage inside a UI element
A quaternion still uses x y and z axis
So yes, you can theoretically clamp the quaternion if Iโm not mistaken
ok can I open a webpage using the browser on the phone, and then get the info needed to the game?
Google helps
Ofc you can conceptually clamp it but not trivially like you suggest
For this you would rather use Euler angles and only convert them to Quaternion after applying the clamp!
yeah it's a bit hard for me
Didnโt know he was using quaternions
is there a way to disallow flipping of camera, I don't care if the world is upside down
it's even better for me if the world can be upside down
I got a space game, upside down is normal
Can you perhaps show some code
The problem is, quaternions handle gimbal lock, euler angles dont. You gotta prevent your euler angles from reaching your desired treshold, or even easier, use cinemachine if that fits your needs.
there are 2 empty objects, 1st is parent, it rotates on Y axis, it's child is a second object, it rotates on X, the camera is the child of 2nd object, it has no code
1st object
Vector2 targetMouseDelta = Mouse.current.delta.ReadValue();
var tr = gameObject.transform;
if (targetMouseDelta.x != 0)
{
tr.Rotate(0, targetMouseDelta.x * 0.3f, 0);
}
log2 = $"X:{tr.rotation.x} Y:{tr.rotation.y}";
2nd object
Vector2 targetMouseDelta = Mouse.current.delta.ReadValue();
var tr = gameObject.transform;
if (targetMouseDelta.y != 0)
{
tr.Rotate(targetMouseDelta.y * 0.3f, 0, 0);
}
@tender gust Don't cross-post, keep it to the #๐ปโcode-beginner
I deleted it from there
can someone help me on this? I want to open a webpage using a browser (since the game can't do that), make the player log in and retrieve info to my game from the browser... can anyone help with that
It's a bit too broad of a question, it highly depends on what your auth system uses.
you need your game to register a URI scheme, then just open the browser process via command line (check google, it depends on browser, etc)
then you will be able to call a URI scheme from the website
and the game can parse the request
It's for mobile
yes
URI schemes still work in mobile afaik
Deep linking has security issues (eg vulnerable to another app registering the same URI scheme and intercept your token)
but it's the only way, unless he is willing to hold state on the server and poll the data
Nope that's not the only way
Both iOS and Android provide secure web contexts specifically made for this purpose.
But yeah it depends on the auth system you are using, if it's a third party they usually have integration guides.
You can trigger a webview from your app that will be like in a sandboxed state only holding the data for that session until you click Done on top left (on iOS). Default thing to be used for oAuth for example
Yeah for iOS there are separate native API (not WebView) that has higher security guarantees. On Android as well, and Google OAuth wouldn't even let you sign in unless you are using that.
If you are using some home baked solution, keep deep link interception attack in mind, and secure the data so that even if it was intercepted, it cannot be used by attacker.
I will see what I can do... I thought it was easy
if I declare generic class like this
public class IntSolver : GenericsSolver<int> { }
Will Il2CPP compile it properly?
All generic methods will rely on int in this case.
Yes.
It works with texture also A Sprite Atlas is an Asset that consolidates several Textures into a single combined Texture. . I've used in my project. For albedo texture on shader. Might have been a modified version that we built. You could also build your own atlas, if you don't want to test it. See the function https://docs.unity3d.com/ScriptReference/Texture2D.PackTextures.html
I am looking for resources on how implement mod support to my 2d steam game
not necessarily, the code stripping options could remove support for the generic option
IL2CPP doesn't have any issue with generics as far as I'm aware
generics are simply not compiled unless you call them from code
class declaration seems to be equal to that
Not sure how to use generics other than in code ๐ค
Reflection, Interfaces
this is not reflection
add the [Preserve] attribute to classes that are not referenced by any other code, or reference it in a monobehavior anywhere, even a monobehaviour that isn't attached to anything.
I don't use user code stripping
so it's not necessary
but I am aware of this attribute, yeah
to preserve GenericSolver<string>, GenericSolver<Vector3>, GenericSolver<...> this is easiest:
class AOTWorkaround : MonoBehaviour {
void Start() {
var x1 = new GenericSolver<string>();
var x2 = new GenericSolver<Vector3>();
...
}
}
nah, in my case strict class declaration is easier
as I will later obtain that type through reflection
if you do not know ahead of time what the type will be, don't use generics. they are most suitable for collections
doing so with generics is painful
I have a very niche case ๐
I am developing data binding for UITK
And I need those generics to avoid boxing
also for fastest delegate usage
vs PropertyInfo.GetValue
you should use the [Preserve] attribute to classes that are not referenced by any other code that you will need in an il2cpp project, regardless of your stripping settings
il2cpp will only strip engine code though, unless you specify otherwise
i am trying to convey knowledge to you
but indeed, that would be a good idea if I release it as library
it's your choice what to do with it
the stripping settings do not mean what you think they mean
their explanation in manual is pretty straightforward ๐ค
i forget if you were asking this earlier... you should probably use a pre-existing solution like playfab.
that said, you can also use an oauth2 asset from the asset store. they are incorrectly named oauth2 even when they will work with e.g. okta*
consider using cinemachine
IL2CPP uses shared generics for reference types. If you use the new "Faster build" code generation option, it will also share generics for value types.
https://forum.unity.com/threads/il2cpp-build-time-improvements-seeking-feedback.1064135/
the source to vector3 is open
aight
Fancy seeing you here. 
Hi! Reposting since I can't fix it yet..
I have a Grid<T> object
A PathNode class
And a Node class that implements the IPathNode interface.
IPathNode has a PathNode GetPathNode method
Now, in the constructor of node I a grid reference, and also create a new PathNode
```public Node(Grid<Node> grid, int x, int y)
{
pathNode = new PathNode(grid, x, y);
}
But the constructor of PathNode is like this and will fail.. what can I do?
``` public PathNode(Grid<IPathNode> grid, int x, int y)
{
this.grid = grid;
this.X = x;
this.Y = y;
}
What can I do? Since I can't do:
Grid<Node> a = myGrid;
Grid<IPathNode> b = (Grid<IPathNofe>)a;
But the constructor of PathNode is like this and will fail.. what can I do?
Wdym by "fail"? What happens here?
You need to show more code and the actual error(s)
what is your objective?
This is the grid constructor:
public Grid(int width, int height, float cellSize, Vector3 gridOffset, Func<Grid<T>, int, int, T> createGridObjectMethod)
{
this.Width = width;
this.Height = height;
this.CellSize = cellSize;
this.GridOffset = gridOffset;
GridObjects = new T[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
GridObjects[x, y] = createGridObjectMethod(this, x, y);
}
}
}
and this is how im creating my object:
grid = new Grid<PathNode>(10, 10, 1, new Vector3(-5, -5, 0), (g, x, y) =>
{
Grid<IPathNode> test = (Grid<IPathNode>)g;
return new PathNode(g, x, y);
});
The grid allows any type, now, the type that im making has a variable pathnode too
I'd really rather see some type definitions
and compiler error messages
what is this for?
Made a stackoverflow post so here is all the relevant code:
https://stackoverflow.com/questions/75289800/cast-changing-generic-type#comment132854828_75289800
The error is: Cannot cast expression of type 'Axvemi.Commons.Grid<Axvemi.Commons.Pathfinding.AStar.PathNode>' to type 'Grid<IPathNode>'
Creating a world
the code is kind of a warblegarble... you haven't said what your issue is
still no compiler errors
this might be a #archived-code-general or #๐ปโcode-beginner question
Yes, Cannot cast expression of type 'Axvemi.Commons.Grid<Axvemi.Commons.Pathfinding.AStar.PathNode>' to type 'Grid<IPathNode>'
the way you are doing this is pretty muddled
what is g? Its definition is not pictured or included in any of your code snippets.
Its on the constructor of grid on the stackoverflow post, its the grid
you probably want
public class Grid<T> {
...
public Grid(int width, int height, float cellSize, Vector3 gridOffset) {
...
GridObjects = new T[width, height];
// remove constructor
}
public Grid<T> Fill(Func<int, int, T> withConstructor) {
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
GridObjects[x, y] = withConstructor(x, y);
}
}
return this;
}
}
@hollow rapids does this make sense? eliminate all your other code
it doesn't make sense to have this ipathnode / pathnode thing
going on
it makes no sense
then you can do
struct WhateverYouWant {
int x;
int y;
}
var grid = new Grid<WhateverYouWant>(10,10,1,Vector3.zero);
grid.Fill((x, y) => new WhateverYouWant() {x = x, y = y});
that's it
the grid does not need to be aware that the items inside have whatever properties that they do
The problem would be the same then, since PathNode asks for a grid of IPathNode, and the grid would be made of another type (even if it implements it)
pathnode is a bad class
The problem is creatiing those objects
Grid doesn't care about pathnodes
it's just a collection
just like List<T> does not care about T
it doesn't know anything about T because it doesnt' need to
Yeah, and it doesnt care, but PathNode does care about its grid
You don't want Grid<IPathNode>. You want Grid<T> where T has a generic type constraint of where T : IPathNode
then you can make a Grid<Node>
struct WhateverYouWant {
int x;
int y;
Grid<WhateverYouWant> grid;
}
var grid = new Grid<WhateverYouWant>(10,10,1,Vector3.zero);
grid.Fill((x, y) => new WhateverYouWant() {x = x, y = y, grid = grid});
that's it
if you want your thing to care about the grid, go ahead and do that
the grid doesn't have to know anything
you don't want to do the constraint or anything like that
it will only confuse you more
The problem is that I cant edit the Grid class, cant add that restriction there
if you want a 2d array with some extra helper methods called a Grid go for it
i am showing you that you do not need the restriction
you don't need ipathnode
stay focused on what i am saying
look at my example
this fulfills all your requirements
I do need the interface since I am trying to make it work with any class. Node will have a NodePath for the pathfinding data, floor data, object data and whatever more, so it implements that interface so the pathfinding works
Since I would need to access the PathNode
my example works with any class
the problem you are trying to conquer is the same as trying to have multiple kinds of items inside a list
it's Bad
And how do I get the PathNode from there, since the struct doesnt implements the interface to get it
if you want to try to do that, go ahead and do a #๐ปโcode-beginner question because that's what it is
why does it need an interface at all?
it's WhateverYouWant
you can put wahtever you want into this type
do whatever you want
you don't need constraints, or interfaces
it's not doing anything for you
Because how do I get PathNode from Node if it doesnt implement the interface? Or I add node2 with other things, but it keeps the PathNode
Not a beginner question, more like im not explaining myself, or I dont understand you
But that would not work
well i think #๐ปโcode-beginner might be more helpful sorry about that
@hollow rapids
people are always trying to do
interface IInterface {}
class A : IInterface {}
class B : IInterface {}
class C : IInterface {}
List<IInterface> someList;
someList.Add(new A());
// ugggggghhh what do i do now????
void ListsOfA(List<A> someParam);
ListsOfA(someList); // compiler error
ListsOfA(someList.OfType<A>().ToList()); // works but only because List : IEnumerable<T>
when you should be doing
struct Union {
A a;
B b;
C c;
}
List<Union> someList;
someList.Add(new Union() {a = new A()));
because it more accurately describes how generic collections interact with polymorphic types
I cant just create a struct and add new classes, since its a different package. Also, I dont think the first approach is wrong depending on the needs
otherwise you can use LINQ OfType<Derived> to work with polymorphic lists. you can enable LINQ for your custom collection using : IEnumerable<SomeWrapper<T>>, but surely you can see that SomeWrapper<T> is just Union
so it's Just As Hard
well you gotta say what your goal is
it sounds like this code is negative ROI for you so far
what are you actually trying to do? what is the y of your xy problem?
I do have a Grid<Node> which is my world data.
Node contains data for the floor, object etc etc and that stuff. And, implements the interface since it has data for the pathfinding too.
=> I need to be able to create that PathNode (for the pathfinding) in the Node constructor. That PathNode asks for a Grid which type should implement that interface.
I cant add the restriction to the Grid class.
I cant create the PathNode instance because I have a Grid<Node> instead Grid<IPathNode> even if Node does implement that interface
okay, are you saying you want to support navigation in your grid-based game?
i'm not asking for what you have so far
don't tell me anything about how you actually engineered your game
The navigation is done with the PathFinding class (irrelevant here) and the PathNode class yeah
I want to implement that to the rest
I could have just another Grid for it yeah, but it would not make sense even if it would work
A grid whose nodes each can have a grid. Are you trying to implemented the HPA* algorithm?
Your recursive definition needs an out. A way to define "leaf" PathNodes that do not contain a grid
You can try reducing the complexity of the code by removing the generics and interface portions of the code.
Is there any reason why your Grid most be of type Grid<Node> and not Grid<IPathNode>
This feels weird. IPathNode knows about concrete PathNode? and PathNode has to use Grid<IPathNode> not Grid<PathNode>?
What you want is covariance, which only supported in delegates and interfaces, not concrete type Grid
Hey. Have anyone here implemented mod support for a Unity game?
Any idea what this method does internally?
https://docs.unity3d.com/ScriptReference/AnimationClip.EnsureQuaternionContinuity.html
hello, anyone good w/ Socket programming?
Better to ask the question properly in #archived-networking methinks
thanks
Hello!
I am trying to disable reload domain but there are a few static member in my custom assembly. Is there a way that I can recompile or reload a single assembly whenever going into play mode? Thanks in advance
@willow sigil you can't reload only a single assembly, but you can write your own custom code which explictly resets those static members and subscribe to the playModeStateChanged event to run it
Thank you for the reply!
Now I understand about how it could be done. I am also looking to write a test in Test Runner for it.
Is there a way I can trigger reload domain in test? (As reload domain is disable in project settings)
you might need to do something like explicitly trigger a reimport of a script or something, I'm not sure offhand if those YieldInstructions actually force a domain reload to happen
I had tried this earlier. Where I apply new value to a static member and then performs recompilescript but the value is not reset
Thank you! I might look into this direction then
btw, it looks like there is a little package which might help you: https://github.com/joshcamas/unity-domain-reload-helper
This is a big help! Thank you so much again for all the info!
Anyone experienced unity not recompiling when making script changes? Unity 2021.3.8
Not in play mode.
Just when making changes with the editor open.
I sorted this out, looks like we had a change in our project preferences asset pipeline auto refresh setting.
Has anyone found a solution for the iOS audio shifting problem when using a voice chat?
Found this repo https://github.com/cbaltzer/UnitySpeakerFix but does not work with the current versions of Unity and iOS, neither the "Force iOS Speaker" option from Unity
It drives me crazy
Whats the issue? Just to get the fundament
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.
You can get to the point with those
Whenever you Start using the Microphone the audio is shifting in iOS
From the guy suggesting the force method, could you check the current state?
sorry but current state of what ?
the devices being used or the output selected int he system
It's an iphone device and I've tried some different iOS versions. The output selection is based on the system so...
It can be managed somehow with Objective-C code as a plugin for Unity, but I can't find the key
Hi, I want to load an image (.png) from the assets folder and convert it into base64, all through code. How is it possible ?
not exactly an advanced topic. but you can load an image in multiple ways, through a direct reference in a serialized field, using Resources.Load, addressables, AssetDatabase (this is editor only so not available in build). Then you could use the EncodeToPNG extension method which returns a byte array which can be converted to base64 using c#'s Convert class. there may an even easier way, but this is what i found in just a couple seconds on google
Hi ๐ Trying to implement PAD with addressables and the resource provider fails with Exception: Exception: The ProvideHandle is invalid. After the handle has been completed, it can no longer be used . I cannot figure out how the providehandle gets invalidated, it is never accessed from the resource provider...
Does anyone have info about the subject?
do you have any code for us to check out? But as it says, you might try to use the result of a call which is gone already
can i add update function to unity's default component?
what is unitys default component?
for example i want to add update function in every object that has unity's mesh collider
can i do that? 
Why the heck would you want to do that, but I think, if mesh collider inherits from mono, it has an update function anyway. You just cant access it
Sorry I was engrossed in stuff. I'm using Unity's "official" sample: https://github.com/Unity-Technologies/Addressables-Sample/tree/master/Advanced/Play Asset Delivery/Assets.
It turned out that the issue was with using LoadAssetsAsync . Since I was using a labeling system it was the obvious choice. For a temporary solution I just switched to loading them individually.
Yeah async loading needs to handle the result inside, otherwise the reference is gone ๐
is it possible to make y = 0 while keeping the same rotational axis?
on a quaternion
NotSupportedException: Specified method is not supported.
System.RuntimeType..ctor () (at <0da48681ced7494d83ae6a612d2206fc>:0)
``` How do I debug this error? It's the full error log, no trace.
what are you trying to do
it seems likely you have accidentally done something of the form var type = object.GetType().GetType()
and then tried to call Activator.CreateInstance on that type
but i am asking what you are doing big picture that led you to this
I have a problem with this when I'm trying to read Rigidbody's property
Can anyone help please?
#๐ปโcode-beginner var rigidbody = GetComponent<Rigidbody>()
im doing
well it's telling you what the error is
?
What problem does that code solve? That's a bit unusual way to do things.
i want to get properties of each components that is attached to the object
But why?
runtime serialization
That feels like a pretty fragile way to go about it
There's no guarantee that setting all properties to the previous values will restore the previous state correctly.
Maybe Unity has API for it, if not I would personally write de/serializer for each specific type.
My project is a NodeTree based framework that implements a very important EditorBlackboard class and a INodeTreeObject interface.
When using the framework, there's a few types I gotta define that are extending some of these classes (EditorWindow, EditorBlackboard, Nodes, NodeViews, but not INodeTreeObject and it's inheritors, which don't need to be extended).
So, when opening the extended framework window, in another namespace, if an EditorBlackboard does not exist in a static Dictionary<string typeName, IEditorBlackboard ebb>, it creates one based on the declared extended class type by the extended framework's tool. Here, typeName is someType.AssemblyQualifiedName. I then use that typeName in Type.GetType(TypeName) and use Activator to create the instance of that type and safe cast into the interface IEditorBlackboard
I hope this was clear.
Whenever setting the EditorBlackboardType, it also sets the EditorBlackboardTypeName by default:
public bool TryGetEditorBlackboard(out INTEditorBlackboard ebb)
{
if (EditorBlackboardTypeName.IsNullOrEmpty())
{
ebb = null;
return false;
}
if (!NTGlobalBlackboard.Instance.TryGetEditorBlackboard(EditorBlackboardTypeName, out ebb))
{
var ebbType = Type.GetType(EditorBlackboardTypeName);
if (ebbType != null)
ebb = Activator.CreateInstance(ebbType) as INTEditorBlackboard;
}
var ebbExists = ebb != null;
if (ebbExists)
{
editorBlackboard = ebb;
editorBlackboardType = editorBlackboard.Type;
EditorBlackboardTypeName = editorBlackboard.TypeName;
}
return ebbExists;
}```
ye, but isint it beter to make an automatic one, where no matter what unity adds in the future versions that the code still works for those new components too
That's going off the assumption that "setting property values to previous state's will restore previous state" which isn't necessarily true.
It's going to be a nightmare to debug when bug pops up, or bugs could go unnoticed.
ok if we put that aside is still get an error when im trying to get properties of a rigidbody
Well exactly like it says, those properties are deprecated.
You can always create your CustomBehaviour class derived from MonoBehaviour and add a new rigidbody property
Fundamentally that's just the wrong way to solve this problem imo.
RectTransform for example, has weird interactions between its position and anchor, so the order you set those properties will change where it ends up being.
Just write de/serializer for each type, it's an one time labor, and even if you have tons of components you can always reach for editor scripts/source generators to do them for you.
thank you for advice ๐
is it possible to make y = 0 while keeping the same rotational axis on a quaternion?
Elaborate on your question - it's very vague
what is y in this scenario?
wdym by "keeping the same rotational axis"
Its a very complicated question sorry for making it so vague, i fixed it by using this
Quaternion quat(Quaternion d, int step)
{
Quaternion inputQuaternion = d;
float y = inputQuaternion.y;
float x = inputQuaternion.x;
float z = inputQuaternion.z;
float w = inputQuaternion.w;
float magnitude = Mathf.Sqrt(x * x + y * y + z * z + w * w);
float pitch = Mathf.Atan2(2 * (y * z + w * x), w * w - x * x - y * y + z * z);
float yaw = Mathf.Asin(-2 * (x * z - w * y) / magnitude);
Quaternion newQuaternion = Quaternion.Euler(pitch*15, 0, yaw*-15 * step);
return newQuaternion;
}
no idea what that does or what you were trying to achieve but glad you got it working
What is that magic number 15 for? I have this source you can take Forward from Quaternion and get Yaw, Pitch from forward vector. If that helps
https://github.com/cathei/RotationMath/blob/main/Packages/com.cathei.rotationmath/Runtime/RotationMath.cs#L108
well the error says what it says. it seems like you accidentally did something of the form instance.GetType().GetType() or type.GetType()
and tried to instantiate it
knowing nothing, i am probably guessing correclt.y you can try setting an exception breakpoint and inspecting the stack to find the error
Not sure if this belongs here - but does anyone have any experience with VContainer?
Dont ask to ask, just throw your question in ๐
Tryna find out what's the standard here.
I've got four Unity projects: three are applications and one symlinks then all together to end up with one executive.
Out of the four, A is mostly standalone, B is linked to C, and D is the catch-all
The question becomes: is it better to just have the one project and enforce divisions with folder/assembly structure or as I have it now with the separate projects.
any help would be greatly appreciated , the project was almost complete and i was about to pitch it , there is nothing in it now
it's not clear why you would do this
That was not the solution though , sorry for cross posting
As in why would I combine them or why are they separate?
Depends on how you work. If you plan on doing a "framework" and reuse it in other project, it can be fine to have it in a different project.
Having 4 project is a bit suspicious. Maybe you should reevaluate your needs.
Also, you can divide by assembly/folder
It's effectively three actual applications.
A builder to create the files,
A sort of lobby system which handles various setup and multiplayer,
and
A player application which runs what was built with the builder and chosen/setup based on what was given in the lobby system.
Realistically, could probably combine 2 and 3 into one and knit in the builder in some way.
The fourth project just grabs from all the others and knits them together which is likely not needed, but is fairly lightweight
I do agree four is a bit much. Could maybe roll player and lobby into one, make lobby do the bridge to builder and remove the connector altogether.
I'm struggling to understand how to inject reference dependencies to a Monobehaviour that lives on a different scene to the LifetimeScope that's registering the component I need.
I have a setup scene with an ApplicationController : LifetimeScope that registers some pure C# classes. After setup, I go to the MainMenu scene, containing a GO with a MainMenuUI component that needs a reference to something registered through my ApplicationController. When I add another LifetimeScope to the MainMenu scene and set it's parent to the ApplicationController, the class I need ends up firing its constructor twice. How do I pass the reference without this behaviour?
EDIT: So I realised the docs cover this pretty extensively (oops), although RegisterInstance isn't desirable in this situation. Decided to just refactor the appropriate constructor so that it's not running any one-time initialising and call that separately instead.
The error it gives says almost nothing. I'm not an experienced programmer and I've never seen this error. Googling didn't help either. But ChatGPT did a little.
Been meddling with the code and trying to ditch some reflection if I can, set/create objects in a more clear way (it was a little bit convoluted from being freshly written).
So for the first time I've got a StackTrace
// STARTS HERE
menu.AddItem(DuplicateFromInputGUIContent, false, () => NodeTreeSO.Duplicate(EditorBlackboard, OnTreeChange));
// THEN
public static void Duplicate(INTEditorBlackboard ebb, Action<NodeTreeSO> action)
{
var newTreeSO = Instantiate(ebb, action);
var newTreePOCO = ebb.NodeTreeObject.NodeTree.Clone(newTreeSO, ebb.TreeTextFieldValue); <========================
newTreeSO.Clone(newTreePOCO);
action?.Invoke(newTreeSO);
}
// THEN
public virtual NodeTree Clone(INodeTreeObject intObject, string newTitle)
=> this.DeepClone_JSONUtility().HandleNewContext(intObject, newTitle); <========================
// THEN
public static T DeepClone_JSONUtility<T>(this T obj) => JsonUtility.FromJson<T>(JsonUtility.ToJson(obj));```
I'm not an experienced programmer
...
ChatGPT did a little.
i think maybe ask #archived-code-general / #๐ปโcode-beginner - a lot of what you've shared makes no sense
what are you trying to do?
big picture?
simply do not use multiple scenes, use prefabs instead. this will eliminate the huge anguish and bookkeeping of this nonsense dependency injection and lifetime management you have created
at the moment do you have a working game?
what?
it sounds like you are trying to use multiple scenes to build your game
simply do not do that
you do not need multiple scenes
you can build your game in 1 scene
then you do not need a LifetimeScope thing, or a setup scene, or whatever you are doing here
you don't need DontDestroyOnLoad, you don't need to check which scene you are in, etc. etc.
scenes were a mistake
unity has them because flash had them
I see use in multiple scenes when you're dealing with large levels--split it up into multiple levels. Is there a better way to handle that?
that is not the user's issue
Would you also keep all your code in one script so you don't need to meddle with all those pesky references? ๐
That's an extreme example, and I can see your viewpoint, but I like the organisation scenes provide. Yes there might be some additional setup, but I'm prepared to do that do keep things as clean and as organised as I want.
you can use a prefab to organize
it's the same thing
Sorry I was just wondering if you thought scenes would be the way to go or not with big levels
a prefab is superior in every way to a scene for organization, and has none of the downsides of having multiple scenes
it's your game
if you want to deal with LifetimeScope go for it
personally i think that's a huge waste of time
no, it's not. don't use multiple scenes. use 1 scene
how do you do lightmaps then
like I have a racing game with tracks in levels that are loaded additive async from a hub scene
and it works pretty well
navmesh and lighting for each level
You'll have to show me a project where you've used prefabs in place of scenes and not felt like there was any maintenance to doing that
I feel like in place of scenes you'd need a manager that handles loading/unloading of everything instead
kinda like frustum culling, but for everything
If you can contain everything in a prefab, you would just need to instantiate/destroy prefabs in place of scene transitions
and it'd be hard to deal with staticly placed things potentially, since you'd need to have a mechanism to save positions/statuses of things when they're loaded and unloaded
i think pretty much everyone trying to do something sophisticated with lightmapping uses assets to work around unity's warts
a scene is more maintenance than a prefab
yes, you woul dhave to activate and deactive a game object
I know SECTR is a tool that does it with scenes, I wonder if there are tools for dealing with one scene
scenes do not make this easier
generally, unity is bad at lightmapping. the ideal way to author a high quality level geometry, including its lights, is the fbx-based DCC workflow with a dedicated tool like maya
my content was made in maya, but it's baked in unity
Yeah I guess you're right, scenes will reload and reset things to their Awake loop positions anyways
i think you are proving my point that
you are basically doing all this rigamarole
but no splat it's painted into UV channels