#archived-code-advanced

1 messages ยท Page 40 of 1

orchid marsh
#

Should just be origin, ray.directon * scalar

sly grove
#

pos-shoot probably doesn't make sense

#

unless shoot is the hit point

fiery nebula
#

is kinda my "first direction" tbh

orchid marsh
#

Yeah, looks like beginner physics UnityChanOops

sly grove
fiery nebula
#

why?

sly grove
#

or at least

#

it's not a direction vector

#

it's a position vector

fiery nebula
#

that's why i used (position-shoot).normalized

sly grove
#

so you'd just directly do DrawLine(pos, shoot, ...etc)

sly grove
fiery nebula
#

I did it before

sly grove
#

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

fiery nebula
#

xDDD

fresh salmon
#

What do you actually want to do here?

sly grove
#

name your variables better so I'm not so confused ๐Ÿ˜ตโ€๐Ÿ’ซ

fresh salmon
#

You should also name your variables better, so you know what they contain just by looking at their name

fiery nebula
#

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

fresh salmon
#

Okay step by step, get rid of the reflection part and get the cube to mirror working first

orchid marsh
fresh salmon
#

Reflections would be a recursive call anyway, so not much changes if the original method to make one ray works

fiery nebula
#

Yeah, true, i have the recursive ^^

#

I just need a Vector3 as a starting point

#

and a direction, right?

fresh salmon
#

Yes

fiery nebula
#

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?

fresh salmon
#

One unit to the right of the object this script is on

fiery nebula
#

yes

orchid marsh
#

second argument should be the direction and scaled to the length of ray - relative to drawray.

fresh salmon
fiery nebula
#

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)

fresh salmon
#

What you can do is make an empty object rotated up, and take its transform.right instead

fiery nebula
#

there isn't another way?

fresh salmon
#

That will make it versatile, if you need to have another rotation just rotate the whole object

orchid marsh
#

So example... a direction could be mouse position converted to world position subtracted by initial position.

fiery nebula
#

yeah but this is a light emitter, which is static

#

I mean, rotate it is not a bad idea

orchid marsh
#

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)

fiery nebula
#

ok i will do transform.right

fresh salmon
#

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

timber flame
#

Read carefully method args

#

They are important especially when working with physics

fresh salmon
#

But yeah for a light emitter it would make sense having a standalone object you can copy-paste here and there, and rotate

orchid marsh
#

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.

fiery nebula
#

Thank u, i will try it, i'm trying to program it

#

I have this

fresh salmon
#

DrawRay is wrong

fiery nebula
#

:x

fresh salmon
#

You're mixing them up

fiery nebula
#

kinda stupid

fresh salmon
#

Rest of the code looks good though

fiery nebula
#

here we go

fresh salmon
#

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

fiery nebula
#

yup

#

I still have the same method as before

#

Do you wanna check it?

orchid marsh
#

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)

fresh salmon
#

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

fiery nebula
#

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

fresh salmon
#

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

fiery nebula
#

I'm just dying xD

#

maybe i just fail the part "else if(hit.collider.CompareTag("Mirror"))"

fresh salmon
#

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

fiery nebula
#

what is "direction" in that way?

#

the direction on my parameter?

fresh salmon
#

The incoming direction, that is the direction you used to fire the first ray

#

So yes that would be the direction param

fiery nebula
#

This do the same as the screen upper

#

wait

fresh salmon
#

Hm why are you constructing yet another Ray in this

fiery nebula
#

i dunno xD

#

I mean it's more understandable

fresh salmon
#

You can just call the method recursively with hit.point and nextDirection

fiery nebula
#

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

fresh salmon
#

Okay so it might just be hitting the object it's starting into, and it freaks out

fiery nebula
#

Yeah, but can we fix that?

#

or not?

#

Maybe to change the hit.point

fresh salmon
#

Sure, you can offset the start position of the new ray along the reflected direction

fiery nebula
#

like hit.point + someValue

#

yeah

#

i mean maybe with doing

#

hit.point * direction * 0.5f?

fresh salmon
#

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

fiery nebula
#

hallelujah xD

#

it works pretty well

#

thanks a lot

fresh salmon
#

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

fiery nebula
#

ohh okay i see

fresh salmon
#

Oh well I found the code, but it doesn't even compile? lol

fiery nebula
#

xDD

fresh salmon
#

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

fiery nebula
#

maybe ๐Ÿ˜‚

bronze geyser
#

Just checkin in here, but for performance purposes, is there any way to get attribute references without reflections?

sly grove
# bronze geyser Just checkin in here, but for performance purposes, is there any way to get attr...

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

bronze geyser
#

I SEE

#

Welp that settles that, thanks

dusty wigeon
slender bolt
#

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

โ–ถ Play video
charred lotus
slender bolt
#

Okay I'll make sure to only post in 1 channel

twin sinew
#

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)

sly grove
#

Write it as a list of key value pairs

tender solar
#

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?

wary swift
#

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

somber swift
#

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)

flint sage
#

Yeah big O notation defines complexity and not speed

#

Aka how many iterations you on average to find your item (or best/worst case)

vocal dagger
#

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 ?

flint sage
#

It's more about the platforms restricting access, not unity

#

Asset bundles are a good option

#

Or you can load textures from file

vocal dagger
#

So its possible... I only need to load in models, textures, materials from an external folder. No code or scripts.

flint sage
#

If you want models/materials then asset bundles are easiest

vocal dagger
#

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.

flint sage
#

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.

vocal dagger
#

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 ?

flint sage
#

Addressables is the same as assetbundles

#

And yeah your own data format or find a library that supports your needs

vocal dagger
#

Damn should have picked something else... Thats gonna be my bachelor thesis xD

#

Hoped it would be easier

midnight violet
#

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

vocal dagger
# midnight violet Can they create meshes of their own or just pick from existing ones and put them...

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.

midnight violet
#

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.

robust flare
#

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

midnight violet
# robust flare Problem: Garbage Collection Spikes: I am working on a endless procedural world ...

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.

robust flare
#

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.

scenic forge
#

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?

midnight violet
robust flare
#

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

robust flare
midnight violet
#

You dont unload the last chunk, but the one after that. Thats what I mean. ๐Ÿ˜„

scenic forge
#

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)

midnight violet
#

are you calling the garbagecollector manually?

scenic forge
#

But in general for GC related performance issues, the priority is to find ways to reduce allocation altogether, before looking to improve collection.

robust flare
robust flare
scenic forge
#

You can still remove chunks, but reuse the underlying mesh object (if that's majority of the allocation)

midnight violet
#

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?

scenic forge
#

I would profile how much allocation for each chunk creation first, and what it includes, before looking to optimize.

robust flare
scenic forge
#

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 ๐Ÿ˜‰

robust flare
midnight violet
#

But if you reuse them, how do you get garbage collection?

scenic forge
#

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.

robust flare
midnight violet
#

are your chunks just the same or like a variation of a specific count?

robust flare
midnight violet
#

Like do you have a list of prefabs your chunks are being made of?

scenic forge
#

They are said to be procedurally generated so I assume probably not.

robust flare
#

ah no they are created on fly

#

yes

midnight violet
#

Oh my bad, missed that procedural part

robust flare
#

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

scenic forge
#

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.

humble charm
#

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 
       } ```
midnight violet
#

Oh, with a hacky way of adding a property to each item in that list

dusty wigeon
severe aurora
#

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 ๐Ÿ˜ฆ

dusky saddle
#

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

midnight violet
dusky saddle
#

The code is in the link that I provided

#

Why the eyes emote lmao

midnight violet
#

Cause I was blind ๐Ÿ˜„

dusky saddle
#

Ahh

midnight violet
#

are the lines correct of your error and your pasted script?

dusky saddle
#

I modified a bit the code rn, will provide the link to the newest code

#

This is the newest link

midnight violet
#

So, what line are the errors?

dusky saddle
#

Lines 56 x 3, 57 , 60 x 3 and 61

midnight violet
#

What is night.UpdateAndCommit doing?

dusky saddle
#

The UI modification should result in this:

midnight violet
dusky saddle
midnight violet
wide loom
#

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?

dusky saddle
midnight violet
#

the bottom half of the console

#

thats the stacktrace if you select an error

dusky saddle
#

Weird, I don't get what you get

#

(In the bottom half that is)

midnight violet
#

select the first error, is there more?

dusky saddle
#

No?

#

Sorry, I'm kind of confused

midnight violet
#

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? ๐Ÿ˜„

dusky saddle
#

No

midnight violet
#

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?

upbeat snow
#

Does anyone know how to pass this code to c#?

dusky saddle
midnight violet
upbeat snow
#

no

#

my teacher put us as a riddle

midnight violet
#

as a riddle? And he said, put that in c#?

sly grove
#

It's just a cipher

#

Replace characters with others to get the real characters

upbeat snow
#

how do I do that?

sly grove
#

Figure it out

#

It's a puzzle

#

Where's the fun if someone else does it for you

midnight violet
#

Try to find patterns in it and see, where it leads you

upbeat snow
#

I be not programmed i wanna be character artist. I just want to do it to pass

midnight violet
#

Cause character artist are dumb and can not solve difficult tasks? ๐Ÿ˜„ Give it a try

thin mesa
midnight violet
#

But I like the teacher pasting code and ciphering it ๐Ÿ˜„

upbeat snow
#

ok I'm going to try it and I'll tell you if it turned out well sadok

midnight violet
midnight violet
upbeat snow
#

yes i have text

#

I'll send it to you privately or here?

midnight violet
#

thank you

upbeat snow
midnight violet
#

Literally gave you a unity script ๐Ÿ˜„

upbeat snow
#

did you translate them in 3 minutes?

undone coral
midnight violet
obsidian glade
fiery nebula
#

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

timber flame
#

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

stiff hornet
timber flame
#

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

stiff hornet
#

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

timber flame
#

The problem exists even by caching

stiff hornet
#

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.

timber flame
#

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

timber flame
#

In game objects, I can add require component, also binding helps in zenject
Game object context

stiff hornet
#

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)

timber flame
#

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
    }
}
jolly token
#

Question: Can I tell if the code is currently executing inside of Job system? Is there API for it?

stiff hornet
#

or are you literally asking for a way to put in your functions to know if using the job system?

jolly token
stiff hornet
#

not to sound obtuse but surely you know if you are using the job system?

jolly token
#

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.

stiff hornet
#

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

stiff hornet
jolly token
#

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)

stiff hornet
#

returns true when inside C# job

#

try it out

jolly token
jolly token
valid plover
#

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); ```
fresh salmon
#
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

valid plover
#

ahh I was confused. Thank you!

rapid helm
#

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!

gritty crescent
#

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

humble leaf
gusty nimbus
#
        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

long ivy
#
  1. removing the first item from a list is inefficient
  2. Re-sorting the open list every time is somewhat inefficient (why not min heap?)
  3. Checking the entirety of exploredCells for an item is inefficient, find a way to use a hash set
  4. Repeatedly accessing openNodes[0] is somewhat inefficient (why not cache?)
  5. I imagine walkableCells has the same issue as exploredCells
  6. 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
gusty nimbus
#

my map is uh

#

infinite size

gusty nimbus
long ivy
#

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

gusty nimbus
#

limited by my iterations i guess

#

i have a preliminary A* for regions

long ivy
#

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) {
// ...
gusty nimbus
#

otherwise my A* would take up to 14 seconds for the same area...

#

isntead of 1.5

gusty nimbus
#

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

brisk pasture
#

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

brisk pasture
#

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

dusty wigeon
small sail
#

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

dusty wigeon
#

Do not derive from MeshRenderer... What you want to do ? It certainly exists better way to achieve that.

small sail
#

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

sly grove
small sail
#

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

timber flame
# jolly token Throw or log error when `GetComponent` result equals to `null`

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

gusty nimbus
#

and inefficient

#

if i set the gcost equal to 1

dusty wigeon
# gusty nimbus and inefficient

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.

gusty nimbus
dusty wigeon
#

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.

gusty nimbus
#

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

dusty wigeon
#

How many node you have ?

gusty nimbus
#

infinite

#

its a procedural world

dusty wigeon
#

... in average, in your solution

gusty nimbus
#

depends

dusty wigeon
#

5 ? 10 ?

gusty nimbus
#

if youre standing far away

dusty wigeon
#

or more like 10000 ?

gusty nimbus
#

what type of nodes

#

region nodes or general

dusty wigeon
#

In your A* solution

gusty nimbus
#

i dont understand the question?

#

because i use A* twice

dusty wigeon
#

What is the amount of node you traverse in your A* to get to the given solution

gusty nimbus
#

for the general nodes

#

i get around 20

#

with 45 closed nodes

dusty wigeon
#

Which is nothing

gusty nimbus
#

but if i stand far away

dusty wigeon
#

And you wont get anything from optimization

gusty nimbus
#

then its 200 open

#

and 600 closed

gusty nimbus
#

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

dusty wigeon
#

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 ?

gusty nimbus
gusty nimbus
dusty wigeon
#

You need to profile* in Build...

#

Your editor may take a significant amount of time.

gusty nimbus
#

building

gusty nimbus
#

right

#

๐Ÿ˜ฎโ€๐Ÿ’จ

near anvil
#

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.

gusty nimbus
#

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

near anvil
#

Anyone here have any good solution for

proven hatch
dusty wigeon
flint sage
#

Seems pretty clear from the error

craggy spear
#

Don't see anyone calling you a loser.

flint sage
#

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

craggy spear
gusty nimbus
#

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

naive field
#

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

dusty wigeon
#

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.

spark raft
#

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?

patent bear
#

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.

spark raft
#

How high can I increase the res?

#

and optimisation ideas would also be great

kindred wyvern
#

Anyone know how I can have a script listen to audio sources in one location and then replicate what it hears in another location?

round summit
#

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

jolly token
obsidian glade
# round summit Did this, might work

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

plush hare
#

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?

agile wharf
#

i have this error when build "Error building Player: BuildFailedException: Burst compiler (1.8.2) failed running"

regal olive
#

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

sly grove
#

if you want to copy animations etc, that will require more work, but the similar principle applies

regal olive
#

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"

sly grove
#

in your image I can see the green world behind it

#

wouldn't be able to with the RenderTexture/Portal approach

regal olive
#

Ouch

sly grove
#

I wouldn't completely rule out some shader magic

regal olive
#

Hm?

timber flame
#

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?

distant path
#

hello, I am looking for someone who can develop some codes for me, information by private message.

thin mesa
thorn flintBOT
plush lion
#

Is anyone familiar with DOTS ? I'm having trouble instantiating X prefabs with unique seeds for their random generator

plush lion
#

Thanks !!

regal olive
#

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

undone coral
#

that's why when you hit play, the hierarchy on the left loses all the blue colors and it's all white.

regal olive
#

I meant position and rotation etc. when I said properties

valid plover
#

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

obsidian glade
split forge
#

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

valid plover
regal olive
#

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

split forge
regal olive
#

The parent game object is rotating btw

split forge
#

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

regal olive
#

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

}

split forge
#

so what you're doing here is a logical anchor issue

regal olive
#

Me?

split forge
#

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?

regal olive
#

Wdym?

split forge
#

err

#

what is the intended goal?

regal olive
#

I'm trying to basically mirror all movement of a level in a smaller copy of the level

split forge
#

OH I SEE

#

I see now, i zoomed in

#

that's a pretty cool idea btw

#

i've seen it done in different forms

regal olive
#

I was originally going to make portals that cover the object's 6 sides, but that was too hard for me (100% the math)

split forge
#

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

regal olive
#

Nothing

#

I just assign the inner cube ProxyObject component

#

And then set the representingObject as the parent

split forge
#

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

regal olive
#

Maybe the inner cube is just too big

split forge
#

if you want it perfectly to scale, then you should use a logarithmic scalar

#

as it will progressively become smaller mathematically and naturally

regal olive
#

I have no idea what that means

split forge
#

err sorry, I had to relearn trig recently

regal olive
#

Are you talking about 3*log_5(2) = log_5(2^3)

split forge
#

i'm not sure of the exact nature of this problem

#

since i've never fully explored it

regal olive
#

Alright

split forge
#

still an interesting one though

#

most likely you'll solve it using an exacting mathematic

regal olive
#

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

regal olive
split forge
dusty wigeon
# regal olive

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 ?

#

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.

dusty wigeon
# regal olive

This image seems correct with what you were trying to achieve. Ask yourself where is the celling in your cube image.

frozen ravine
#

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

thin mesa
#

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?

frozen ravine
#

the scriptable object has been instantiated to make a copy from the original so the og's values don't change

frozen ravine
#

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

carmine lark
#

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

humble leaf
#

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

dusty wigeon
timber flame
#

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)

timber shadow
#

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.

timber shadow
#

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.

flint sage
#

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

tropic stag
dusty wigeon
# timber shadow I'm experiencing a situation where when entering playmode, unity reloads assembl...

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

devout dirge
#

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.

brittle fulcrum
#

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?

fresh salmon
#

Try without a coroutine. Destroy can take a delay as argument 2.

#

Destroy(obj, delay);

brittle fulcrum
fresh salmon
#

No, you pass the delay as argument 2!

#

Look at my example

brittle fulcrum
fresh salmon
#

As for the potential issue, if the object that started the coroutine itself gets destroyed, then the coroutine stops right away

brittle fulcrum
#

omg thank you so much

brittle fulcrum
fresh salmon
#

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

devout dirge
#

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.

jovial plover
#

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

dusty wigeon
#

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.

regal glade
#

can you do SetPixels/SetPixels32 in a secondary thread or does it have to be main thread??

dusty wigeon
patent bear
#

Texture access in threads

hollow rapids
#

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

hollow rapids
#

Didn't know about that concept lol, I will save it for tomorrow since it seems like an extensive read. Appreciate it! โค๏ธ

brazen ginkgo
#

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

long ivy
#

well UNITY_EDITOR is going to be defined in the editor regardless of platform, so that's an issue right there

brazen ginkgo
#

...yep that did the trick LOL

#

ty!

gusty tusk
#

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>();
}
undone coral
#

_prefabDictionary[objEnumType].GetComponent<T2>(); will never be a GameObject

undone coral
gusty tusk
#

Ah, right I can do that

#

Thanks!

gusty tusk
undone coral
#

good good

jovial plover
round summit
#
    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

long ivy
round summit
#

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

leaden sandal
#

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

long ivy
leaden sandal
#

They are using some auto writer plugin, it adds directives automatically I think.

timber flame
compact ingot
pale silo
#

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?

tender gust
#

hey

#

how can I prevent and orbiting camera from flipping when it reaches the top or bottom

unique ermine
tender gust
#

clamp?

unique ermine
#

Kind of like min and max

pale silo
compact ingot
compact ingot
midnight violet
#

There are plugins to load a webpage inside a UI element

unique ermine
pale silo
unique ermine
#

Google helps

compact ingot
devout hare
#

For this you would rather use Euler angles and only convert them to Quaternion after applying the clamp!

tender gust
#

yeah it's a bit hard for me

unique ermine
tender gust
#

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

unique ermine
#

Can you perhaps show some code

midnight violet
#

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.

tender gust
#

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);
            }
frozen imp
tender gust
pale silo
scenic forge
#

It's a bit too broad of a question, it highly depends on what your auth system uses.

tender gust
#

then you will be able to call a URI scheme from the website

#

and the game can parse the request

scenic forge
#

It's for mobile

pale silo
tender gust
#

URI schemes still work in mobile afaik

scenic forge
#

Deep linking has security issues (eg vulnerable to another app registering the same URI scheme and intercept your token)

tender gust
scenic forge
#

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.

midnight violet
#

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

scenic forge
#

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.

pale silo
#

I will see what I can do... I thought it was easy

remote drift
#

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.

scenic forge
#

Yes.

dusty wigeon
cosmic crypt
#

I am looking for resources on how implement mod support to my 2d steam game

upbeat path
sly grove
remote drift
#

class declaration seems to be equal to that

sly grove
#

Not sure how to use generics other than in code ๐Ÿค”

remote drift
sly grove
#

this is not reflection

remote drift
#

when using those, no compilation will happen

undone coral
remote drift
#

so it's not necessary

#

but I am aware of this attribute, yeah

undone coral
#

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>();
  ...
 }
}
remote drift
#

nah, in my case strict class declaration is easier

#

as I will later obtain that type through reflection

undone coral
#

if you do not know ahead of time what the type will be, don't use generics. they are most suitable for collections

remote drift
#

doing so with generics is painful

remote drift
#

I am developing data binding for UITK
And I need those generics to avoid boxing

#

also for fastest delegate usage

#

vs PropertyInfo.GetValue

undone coral
remote drift
undone coral
remote drift
#

but indeed, that would be a good idea if I release it as library

undone coral
#

it's your choice what to do with it

#

the stripping settings do not mean what you think they mean

remote drift
#

their explanation in manual is pretty straightforward ๐Ÿค”

undone coral
#

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*

sage radish
# remote drift generics are simply not compiled unless you call them from code

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/

tawny bear
tender gust
#

yeah I could

#

but I ended up with a simple efficient way

#

for now it's fine

undone coral
tender gust
#

aight

calm mauve
hollow rapids
#

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;
sly grove
hollow rapids
# sly grove > But the constructor of PathNode is like this and will fail.. what can I do? Wd...

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);
            });
hollow rapids
sly grove
#

and compiler error messages

hollow rapids
# sly grove and compiler error messages

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

hollow rapids
undone coral
#

the code is kind of a warblegarble... you haven't said what your issue is

undone coral
hollow rapids
undone coral
#

the way you are doing this is pretty muddled

sly grove
hollow rapids
undone coral
#

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

hollow rapids
#

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)

undone coral
#

pathnode is a bad class

hollow rapids
#

The problem is creatiing those objects

undone coral
#

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

hollow rapids
#

Yeah, and it doesnt care, but PathNode does care about its grid

undone coral
#

okay

#

then you can do

sly grove
#

then you can make a Grid<Node>

undone coral
#
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

hollow rapids
undone coral
#

if you want a 2d array with some extra helper methods called a Grid go for it

undone coral
#

you don't need ipathnode

#

stay focused on what i am saying

#

look at my example

#

this fulfills all your requirements

hollow rapids
#

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

undone coral
#

the problem you are trying to conquer is the same as trying to have multiple kinds of items inside a list

#

it's Bad

hollow rapids
#

And how do I get the PathNode from there, since the struct doesnt implements the interface to get it

undone coral
undone coral
#

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

hollow rapids
#

Not a beginner question, more like im not explaining myself, or I dont understand you

#

But that would not work

undone coral
#

@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

hollow rapids
#

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

undone coral
#

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

undone coral
#

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?

hollow rapids
#

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

undone coral
#

i'm not asking for what you have so far

#

don't tell me anything about how you actually engineered your game

hollow rapids
#

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

errant plinth
#

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.

dusty wigeon
jolly token
#

What you want is covariance, which only supported in delegates and interfaces, not concrete type Grid

ripe kite
#

Hey. Have anyone here implemented mod support for a Unity game?

icy smelt
umbral nimbus
#

hello, anyone good w/ Socket programming?

shadow seal
umbral nimbus
#

thanks

willow sigil
#

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

urban trellis
#

@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

willow sigil
urban trellis
#

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

willow sigil
willow sigil
urban trellis
willow sigil
timber shadow
#

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.

spark oracle
#

Has anyone found a solution for the iOS audio shifting problem when using a voice chat?

#

It drives me crazy

midnight violet
spark oracle
#

You can get to the point with those

#

Whenever you Start using the Microphone the audio is shifting in iOS

midnight violet
spark oracle
midnight violet
spark oracle
#

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

hardy nymph
#

Hi, I want to load an image (.png) from the assets folder and convert it into base64, all through code. How is it possible ?

thin mesa
# hardy nymph Hi, I want to load an image (.png) from the assets folder and convert it into ba...

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

misty walrus
#

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?

midnight violet
regal olive
#

can i add update function to unity's default component?

midnight violet
regal olive
#

can i do that? UnityChanClever

midnight violet
misty walrus
#

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.

midnight violet
stiff swallow
#

is it possible to make y = 0 while keeping the same rotational axis?

#

on a quaternion

crystal galleon
#
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.
undone coral
#

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

gilded palm
#

I have a problem with this when I'm trying to read Rigidbody's property

#

Can anyone help please?

undone coral
undone coral
gilded palm
scenic forge
#

What problem does that code solve? That's a bit unusual way to do things.

gilded palm
scenic forge
#

But why?

gilded palm
scenic forge
#

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.

crystal galleon
# undone coral what are you trying to do

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;
        }```
gilded palm
scenic forge
#

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.

gilded palm
scenic forge
#

Well exactly like it says, those properties are deprecated.

crystal galleon
scenic forge
#

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.

gilded palm
stiff swallow
#

is it possible to make y = 0 while keeping the same rotational axis on a quaternion?

sly grove
#

what is y in this scenario?

#

wdym by "keeping the same rotational axis"

stiff swallow
# sly grove Elaborate on your question - it's very vague

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;
    }
sly grove
#

no idea what that does or what you were trying to achieve but glad you got it working

jolly token
undone coral
#

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

kindred remnant
#

Not sure if this belongs here - but does anyone have any experience with VContainer?

midnight violet
subtle walrus
#

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.

wheat knot
#

any help would be greatly appreciated , the project was almost complete and i was about to pitch it , there is nothing in it now

fresh salmon
#

Don't cross-post

undone coral
wheat knot
subtle walrus
dusty wigeon
#

Having 4 project is a bit suspicious. Maybe you should reevaluate your needs.

#

Also, you can divide by assembly/folder

subtle walrus
# dusty wigeon Having 4 project is a bit suspicious. Maybe you should reevaluate your needs.

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.

kindred remnant
# midnight violet Dont ask to ask, just throw your question in ๐Ÿ˜„

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.

crystal galleon
# undone coral well the error says what it says. it seems like you accidentally did something o...

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));```
undone coral
#

what are you trying to do?

#

big picture?

undone coral
undone coral
undone coral
#

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

formal lichen
#

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?

kindred remnant
#

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.

undone coral
#

it's the same thing

formal lichen
undone coral
#

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

undone coral
gaunt mantle
#

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

kindred remnant
#

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

formal lichen
#

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

kindred remnant
formal lichen
#

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

undone coral
undone coral
undone coral
formal lichen
#

I know SECTR is a tool that does it with scenes, I wonder if there are tools for dealing with one scene

undone coral
#

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

gaunt mantle
#

my content was made in maya, but it's baked in unity

undone coral
#

lights import correctly from maya fbx, and maya can bake

#

well...

formal lichen
gaunt mantle
#

using special shader

#

4 texture splat optimized for mobile

undone coral
#

you are basically doing all this rigamarole

gaunt mantle
#

but no splat it's painted into UV channels