#archived-code-advanced

1 messages Β· Page 85 of 1

flint sage
#

Ad hoc? Enterprise? App store?

muted pilot
#

app store

flint sage
#

So you're publishing this build to the store/testflight to test?

flint sage
#

How are you testing it?

#

I vaguely remember ios being tricky to test since it only works if you click on a link and not when you manually enter it or something silly like that

muted pilot
#

first i have to get back the application url, then send it to the server to include it in onesignal push dialog so when the user clicks on the notification. it directs them to that page indise the application

autumn basalt
#

Anyone got a good tutorial on how to get started setting up a dedicated server in Unity?
Like the actual programming aspect of it, not how to set up the server and get it online & stuff.

inland knoll
# autumn basalt Anyone got a good tutorial on how to get started setting up a dedicated server i...

This one seems promising https://www.youtube.com/watch?v=FjOZrSPL_-Y&t=889s
It came up as one of the first videos when googling "Unity how to set up dedicated server"
Next time just quickly google the question before you ask

πŸ“₯Get the Source CodeπŸ“₯
https://www.patreon.com/posts/82134830

If you liked this video please like and subscribe as it helps me a lot, and consider joining my Patreon or becoming a YouTube Member :)

β–ΊCheck out the Previous Video
The Ultimate Multiplayer Tutorial for Unity - Netcode for GameObjects
https://youtu.be/swIM2z6Foxk

βš™οΈ Set Up βš™οΈ
β–ΊMul...

β–Ά Play video
tiny pewter
#

i think there are existing solutions provided by Unity.
if you want to learn how to set up a server in view of programming, the first thing you should know is server can be written in different language.....you should define the api and how your server handling them (note that the api can be "used" by other front end, the server can have no idea who is sending the requests, you need authorization to solve this)

#

just like how you set up server for other front end applications

autumn basalt
#

I'm looking at Multiplay and Cloud Code right now for example
How am I supposed to choose which one I want without knowing a lot about both of them?

dusty wigeon
autumn basalt
#

I'm making an Idle RPG - the clients never interact with each other, they only interact with the server
all my game logic needs to run on the server to prevent cheating, same with data storage

#

I'm checking the cloud code setup now, it seems like what I need
I just don't know the limitations and it seems pretty hard to find good descriptions of what everything is and does

tiny pewter
#

ie your game is just a display

autumn basalt
#

yup

undone coral
dusty wigeon
autumn basalt
#

it's pretty much all numbers with some fancy graphics on the client side

dusty wigeon
autumn basalt
#

how scalable is cloud code?

gray creek
dusty wigeon
# autumn basalt how scalable is cloud code?

Extremely scalable depending on how you make things. However, as I read, I think Cloud Code is not made to keep connection up and do validation but more for things that are inline with a REST API. You might want to create your own server and only use a service to host you server. Something like Google Cloud, AWS would be more inline with that.

autumn basalt
#

thx a lot for the info πŸ™‚

magic scroll
#

someone checked it?

#

or any idea?

magic scroll
#

Can someone explain why RenderTexture doesn't render colors?

#

on HDRP

#

these cubes should have colors

sly grove
#

doesn't sound like a code issue

undone coral
#

i don't know what i am looking at. on the left, it looks liek the exposure is wrong. on the right, it looks like you have another misconfiguration

magic scroll
magic scroll
undone coral
magic scroll
undone coral
undone coral
#

okay

#

and in the viewport, what are we looking at exactly? experimenting with creating the thumbnail, in a plain scene?

magic scroll
undone coral
#

and you're using hdrp in the editor?

magic scroll
#

yeah because game uses HDRP

undone coral
#

i think you should try to create a camera and render to a render texture first in the editor, at design time

#

so you can see some of the aspects of what is missing

#

you are trying to use built in render pipeline approach code to an hdrp rendering problem

#

which is fine, that can eventually work

#

but there is a lot to do

#

the first image in your screenshot appears to have color, but appears to be incorrectly exposed. it will need a volume; or you will have to find the game's volumes and use them. the image on the right appears to be flawed some other way.

#

you shouldn't be rendering with depth. that can have unintended consequences

#

a render texture can be directly set as a texture for a material

#

you can also read the render texture's bytes later, using an async gpu readback request, and ImageConversion can turn that into a PNG or whatever for you

#

@magic scroll good luck!

magic scroll
#

thanks I will try it

clever widget
#

Hi guys, sorry I'm x-posting this from the iOS channel:
I'm having some issues regarding iOS Universal Links and Unity. I want to open my app and fetch the user id when user clicks on the deep link https://refer.mydomain.com/?userid=123456. I have uploaded the apple-app-site-association file to my domain's https://refer.mydomain.com/.well-known/ directory which contains the following data:

{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "ACBJSD1234.com.mypackage.id",
        "paths": ["*"]
      }
    ]
  }
}

I have validated the above file using https://branch.io/resources/aasa-validator/ and it shows as valid.

I have also added the Associated Domain capability to the entitlement file with the domain: applinks:refer.mydomain.com. Now I have used the event listener provided by Unity to detect the deep link that is used to open the app. Now the thing is, my app is getting opened when I click on the link, but I'm not getting the deeplink data inside Unity. My doubt is that maybe my apple-app-site-association file is not properly set, specifically the paths key. Can anyone help?

undone coral
#

i believe the paths should start with a /

#

and maybe they have to be terminated by a constant string, maybe not

clever widget
clever widget
little sluice
#

Here's my problem and the thing i do not understand.

I got an elevator with the following parts ( see screenshot )
Platform - Empty object, with a Scale of 1.0, which is moved by the elevator script
Platform.Physical - the visible mesh and the ground collider
Platform.Attach - trigger-collider that makes the player a child of itself.

The player is a Unity.CharacterController moved in Update
The elevator script moves the Platform in Update

I got debug lines showing, that the player character while being a child of Platform.Attached is moved by the exact amount that the whole platform is moved.
This works flawlessly while moving upwards, but moving downwards, the player OnTriggerExits the attach-collider.
The player is a CHILD of the collider and has ZERO movement in local space relative to the collider, they are both moved by the parent of the collider. Yet the OnTriggerExit happens.

#

The coordinates after moving both objects in Update logged and then in the next physics tick logged:
a) same coordinates -> TriggerStay
b) same coordinates -> Trigger Exit

what the magic?^^

And yes, it's a repost from Physics, because there is no activity in Physics.

pastel bronze
#

I know ur all busy so dont reply if its lame, but I have this issue of trying to retain the fractured peices in the scene after the second fracture. As you can see the 2nd time around the pre-existing peices just get drawn to the impact point and dont generate a new cluster.

Do i need to make an Entity Pool manager and move the fracture prefab into that and wack it on a separate layer?

Player(prefab)
-cube(Fractured Model)
-- Rigid Body
-- Collider
-cubenice(player model)
-- Rigid Body
-- Collider
-- Fracture Script
-- Movement Script
-MainCamera
-- Look Script

Respawn(blankgame object/rs point)

untold moth
# little sluice The coordinates after moving both objects in Update logged and then in the next ...

I don't know what exactly you're debugging, but it's likely the transform positions. You need to remember that they don't always correspond to the internal physics simulation position. Moreover, moving colliders/triggers/rbs in non physical way(via transform for example) can further amplify the problem.
Lastly, I don't think CC triggers an OnTriggerEnter, so you probably have an rb somewhere, which doesn't play well with CC either.
Lastly lastly, the timing of CC update could also be a contributing factor(talking about it's internal update, not when you call Move), since it could be out of sync with the physics update making it register an exit out of the trigger.

To summarize, there are many factors that could be causing the issue. You can try eliminating the mentioned factors one by one to determine the cause.

untold moth
pastel bronze
untold moth
pastel bronze
#

why when ive got advanced people who are smarter here lmao

untold moth
#

Well, with such an attitude it's easy to get a bad reputation on this server so you might end up not getting any help in the long run or even get banned.

pastel bronze
#

its alright man, with enough head banging / gpt and the available doco ive pretty much learned not to rely on human help anymore. Ill sort this eventually. I always do. Just feeling lazy today cuz i had a big win last night πŸ˜‰

#

I also like to empower other people so they never have to rely on developers lmao

pastel bronze
#

Its beauitful thanks bro

autumn basalt
#

I don't know if I should use JSON or SQL to save my player game states
It will be a single player game that runs on cloud code, but players will find lots of items
The database is needed for trading items between players, sorta like an auction house
I know SQL would be really good for this, but I don't know if JSON is good for this but that seems easier to implement in unity?
I do have a bit of experience with SQL, I also know how JSON works, but never implemented any sort of "database" with it

scenic forge
#

SQL is a data querying language, while JSON is a data exchange format, they are not comparable.

autumn basalt
#

sure they are, I can use both to store my game data

scenic forge
#

What you probably mean is "storing my data in database and querying my data with SQL" vs "storing my data in file as JSON and querying my data in memory"

autumn basalt
#

probably

flint sage
#

Is this some authorative game?

autumn basalt
#

not sure what that means

flint sage
#

Doesn't sound very singleplayer when you can trade

autumn basalt
#

it's an idle game

#

trading is the only multi player part, at least for now

scenic forge
#

But anyways, it mostly boils down to "can I fit all of my data in memory."

autumn basalt
#

I highly doubt that, so I should go with SQL?

scenic forge
#

If the answer is no, then some kind of database is needed (the querying doesn't have to be SQL), otherwise you can choose to have everything in memory (the format doesn't have to be JSON)

autumn basalt
#

does unity have any build in mysql database / sql support?

#

or does it support some other database type?

scenic forge
#

No, but are you going to write your server in Unity?

#

Because the client should never have access to the database.

autumn basalt
#

will be in cloud code

scenic forge
#

No, you'd need to bring in something (and often time you don't want to go raw SQL either if the database has any real complexity)

autumn basalt
#

shouldn't get too complex I think

scenic forge
#

I think you have asked about it before though, I'm not sure what a Unity server can get you since it's not like you can make use of what it gives you, I'd suggest just writing a standalone backend

autumn basalt
#

but cloud code is not a server is it?

#

haven't really figured it out

scenic forge
#

You get much better DX, at the very least not having to confined to Unity's old C# version and all the caveats with NuGet packages.

autumn basalt
#

any suggestions?
I have written a nodejs server before, but had a really really hard time figuring out how to prevent getting ddos'ed
I'm sure I can write .NET as well with some basic tutorials

scenic forge
#

You don't solve the DDoS problem by using a different language/framework, and you don't usually solve it on the application level at all.

autumn basalt
#

that's why I'd like to use the unity cloud code service, I assume they have something built in?

scenic forge
#

It's typically the job of what sits in front of your backend application, eg the reverse proxy (like nginx) or DNS (like Cloudflare)

autumn basalt
#

I'm also not a big fan of having to work with Javascript and C#, makes things a bit confusing

scenic forge
#

It doesn't matter what language the backend is in.

#

If you like C#, then sure go for it.

autumn basalt
#

can you write a server in C#? or is that .NET?

#

or is that the same πŸ€”

scenic forge
#

.NET is a runtime, C# is a language.

#

And yes you can write a backend in C#, the most commonly used is ASP.NET Core.

#

(Backend specifically ASP.NET is probably what C# being used the most, rather than game dev)

autumn basalt
#

ah that's what I meant, ASP

#

this is why I hate programming lol
I just love writing code, I hate everything else

scenic forge
#

Well if you are making a multiplayer game, you will have to deal with infrastructural stuffs sooner or later, so might as well now πŸ˜„

autumn basalt
#

yeah 😦

scenic forge
#

Cloud stuffs are basically "paying for convenience."

autumn basalt
#

my game has gotten to the point where I need to save the player data in order to continue working on it
but I need to figure out this server stuff to save player data, wanna do it right the first time

#

could I just save the player data in files with json instead of a database, since that seems to be a lot more logical for unity?
and then save the tradable items for multiplayer in an sql database?

plucky laurel
#

you can use sqlite locally, setup interfaces to exchange with pluggable db, and then the server db exchange would be abstracted

autumn basalt
#

that is a lot of words 😦

plucky laurel
#

you can also setup local server on your machine and work with it as if it was a remote

autumn basalt
#

yeah the issue is not the database management, I know how that works, at least the basics

#

I just don't know how well it works with unity

#

for example my items are scriptable objects, how would I save that to a database?

plucky laurel
#

write code that handles exchange at specific points

#

scriptable object is just a bunch of fields/properties, those can be mapped to columns, for example

#

there are most likely assets/github repos that do that with reflection

scenic forge
autumn basalt
#

no on the server, not locally
but I guess I won't have a server if I use cloud code

scenic forge
#

I mean if your server is already going to have a database for tradable items, you might as well just make one more table and store other player data there.

autumn basalt
#

true lol

sly palm
urban warren
#

I have a series of compute shaders (And Graphics.Blits?) that create and modify textures that I need to run in sequence (output of one is input of another). I was wondering what a good way to do this would be?

For additional context it is basically a Photoshop layer system, or a substance designer node graph, each layer creates a texture and has filters that modify it, and has blending modes.

sly grove
urban warren
sly grove
#

I'm not really sure this stuff is kinda voodoo to me

#

Whenever I use a compute shader I'm kinda 😬 😬 🀞 that I won't have scheduling issues

urban warren
#

All good, I appreciate the link!

flint sage
#

Can you do a write up once you figure this magic out lol

sly grove
urban warren
undone coral
# urban warren I have a series of compute shaders (And Graphics.Blits?) that create and modify ...

if their work can be parallelized, use cmd.CreateGraphicsFence with GraphicsFenceType.AsyncQueueSynchronisation. pass the returned GraphicsFence object to cmd.WaitOnAsyncGraphicsFence of the dependent graphics job. if their work cannot be parallelized, its better to model their work as void ApplyComputerShader1(CommandBuffer cmd) and ApplyComputerShader2, then submitting a command buffer with all the ordered calls as needed.

undone coral
urban warren
#

Ahh looks like CommandBuffer.RequestAsyncReadback might be what I want

undone coral
#

there are a lot of nuances though

#

the callback will occur on the main thread, but they don't tell you which player loop 🫒

urban warren
undone coral
#

the jobs api will have a way of expressing a dependency on an async graphics job aka a computer shader that will allow you to start work early in a frame and have it ready in time for rendering

#

if you know exactly which scene state you need for it

urban warren
undone coral
#

okay

#

probably premature lol

#

chatgpt gpt4 does an OK job on one-shot hlsl code. it will make logical mistakes but it will show the right syntax.

#

having just done this, there are a lot of pitfalls - everyone writes their matrices row major, for example, even though hlsl and glsl are column major, but write vector * matrix instead of matrix * vector, which makes it all work out in the end in the strict context of the shader

urban warren
#

Oh I ain't touching matricies haha

#

I am just working with textures

tawdry ferry
#

hi I was wondering if this was possible? my application creates a directory with saved scree captures of my project. I would like this folder to be synced with a dropbox directory and organize all the cpatures in there? Is it possible or has anyone done something where you connect dropbox api within unity

#

so that when it creates the folder it automatically syncs to the same dropbox directory

tiny pewter
tawdry ferry
#

yeah I dont presume there is an existing solution and ive been reading docs just wondering if someone did anything remotely the same

tawdry ferry
#

ok it looks like I need to setup the http API i have no clue how to start doing this in unity

#

ive been scouring online too is there any SDK or something that supports this

tender crest
#

Hello, does anyone know any reference code that works for computing the correct rotation and position of a parent gameobject, respective to a child's (an anchor), which I want to position on top of another connection anchor?

#

The quaternions and inverse transformations are getting me very confused, I thought I had a working implementation until I expanded my set of example prefabs. It'd be nice if I could tell if there is Gimbal lock happening or something alike

#

This is what I had that was working:

            Quaternion anchorTargetRotation = _connectionAnchor.Transform.rotation;
            Quaternion rotationCorrection = anchorTargetRotation * Quaternion.Inverse(connectionAnchor.Transform.localRotation);
            instanceRoot.transform.rotation = rotationCorrection;

            Vector3 anchoredPosition = Transform.TransformPoint(rootAnchor.Transform.InverseTransformPoint(rootWorldPosition));
            instanceRoot.transform.position = anchoredPosition;
bleak citrus
#

In my case, I needed to figure out where to position a ragdoll's root so that one of its bones would have a certain position and rotation

little sluice
# untold moth I don't know what exactly you're debugging, but it's likely the transform positi...

Hey, thanks for the answer! Yes. I assumed that the position does not always correspond because the visual position of moving physics objects is not exactly their real physics position. In my case, i am using Physics.SyncTransforms() which sounds like it serves the purpose of syncing movement done in code to the physics engine.
CharacterController does execute OnTriggerEnter, OnTriggerStay and OnTriggerExit.
The problem i have is that the CharacterController is inside the Trigger Zone with a distance of X between their centers and then i move them both and next frame its OnTriggerExit with the distance being the exact same.

I do not know how to further eliminate factors. I tried different variations of Update, LateUpdate and FixedUpdate and each of them has different flaws. Moving an object in UpdateFixed and having a first person camera as its child leads to horrible visual stutter for example. I tried different physics refresh rates, from 60 fps when the games runs at 60 fps to 100fps for physics and more of less for frames, it doesn't make a difference, the effect is still the same.

tender crest
scenic forge
tawdry ferry
#

ok i can give that shot as well

#

and see if that works

untold moth
# little sluice Hey, thanks for the answer! Yes. I assumed that the position does not always cor...

Again, there are still many unknown factors. Especially for someone that doesn't have access to your project/code.

While sync transform might've been useful I'm not sure if it has any effect in your case since you don't have any rigidbodies involved it seems. All moving objects need to have rigidbodies in order to comply with physics.

Perhaps try giving your platform an rb and moving it with MovePosition or something as well as replacing your character with a simple capsule collider with rb and OnTriggerEnter/Exit callbacks and see if you can reproduce the bug with that setup. Obviously, both rbs need to be kinematic if you want the parent-child relationship to control positions.
That being said, it might actually be contributing to the problem, as it implies that the child objects is moved outside of physics. So, if that doesn't work, might want to make the capsule rb dynamic and maybe use MovePosition for it as well.

keen temple
#

hey guys i try to make a ability system so i did a list of abilitybehavior but i cant add different class that Inherit from abilitybehavior so i try to play with thee editor and make this so i can chose what type of abilitybehavior i can add but evrey time i change same scripts its return it back to abilitybehavior and not the class i add heere the code :

https://paste.ofcode.org/7zKwCCGVvqnmgra9DRRvD4

thorn flintBOT
lament salmon
#

You would add that attribute to the behaviours list

keen temple
#

hooo ok ty ! you saved me

sterile meteor
#

Can you recommend a tool or solution for managing dependencies for a large Open World project that may be ported to the latest consoles? One that will allow you to keep the architecture solid. I've tried Zenject, VContainer and Reflex, but I feel like I'm fighting Unity more than doing something simple by using them.

undone coral
dusty wigeon
sterile meteor
sterile meteor
undone coral
#

you can sort of do anything with enough time. so it really depends on what your goals are

#

is there a pre-existing code base of a working game?

sterile meteor
#

Most likely yes, plus future maintenance and ports to other consoles. I would like to make the right decision now so that I don't have to rewrite half of the codebase later, we are currently in the third month of production, and the code base is growing quickly.

#

I'm concerned about solutions like Zenject due to performance and future debugging on consoles due to AOT.

dusty wigeon
# sterile meteor How do you manage scaling your solutions and keeping project organization withou...

I meant, without using fancy architecture for the reference aspect of it. My bad, I should've specified it. Obviously, we have some sort of architecture such as UI, GameState, Sound, VFX, etc. However, we do not rely on dependency injection or any reflection base/code generation architecture because they are confusing, hard to debug and invasive. Fortunately enough, Unity has already an abundance of tool available such as Editor Serialization, ScriptableObject, GetComponent function, etc. Then, you have the Singleton pattern and the Service Registry pattern if needed. With all of that, you are more than able to always get the requiring reference where you need it.

In my opinion, dependency injection is great mechanism in Web development or other software development but does not have the same value in a Video Game. This is particularly due to the serialization nature of a game and the non-existent Unit-Test in a game. It is worth nothing that dependency injection solution favorize the creation of highly coupled class which is exactly what evangelist warn against the usage of Singleton. Also, in the optic that you are going to develop on multiple platform, dependency injection could be a massive irritant due to the fact it is important to control what reference is acquired and when it is acquired. By example, you would most likely use AssetBundle for low end platform. This is something that is not though of in most DI I've seen or it is overly complicated. You cannot just grab a reference, you need to load the AssetBundle before.

cerulean wasp
#

Decoupling code is extremely useful in videogames, bro

dusty wigeon
cerulean wasp
#

how

dusty wigeon
#

People acquire reference to things they shouldve at place they shouldnt

#

You need to keep things enclosed as well

cerulean wasp
#

dependency injection is to just make A=>C<=B instead of A=>B

dusty wigeon
cerulean wasp
#

as opposed to?

dusty wigeon
#

At the end of the day, if you destroy A, C is not longer valid isnt ?

cerulean wasp
#

C would be a more long lived mediator

#

or at least coded as such

#

or just a generic point of contact for A and B

#

so B doesn’t need direct knowledge of the A it is tied to

#

it’s not rocket science

dusty wigeon
cerulean wasp
#

mediator is maybe not the right name for it, since that has a more specific meaning. interface is more correct

#

interface, but not actually an interface

dusty wigeon
#

If you have A that inherits from C, if A is destroyed, then C is no longer valid. Making your reference invalid. When you work with singleton or service registry, it is obvious that does reference will never be in such states. The implicit contract in a singleton makes it clear of that.

cerulean wasp
#

but inheritance is not necessary for dependency injection

dusty wigeon
#

However, the principle issue I has with dependency injection (in the architecture side of things), is that it favorize the acquisition of reference through the wrong channel.

dusty wigeon
cerulean wasp
#

false

#

you can easily make C a class that takes in input/output using a class shared by anything trying to work with C

#

C can have input methods that take in D from B. And call actions that output maybe D or E, which is a format that A can use

#

like, I have a collision class that can take in collision data (in one format), and outputs a new struct with a processed form of that collision data, then calls an event action.

B can tell C to go in with incominthg collision data.
A can subscribe to C’s events to know.
C knows it can cancel the request if no one is subscribed, but has no knowledge of B nor A.

dusty wigeon
#

We aren't talking about dependency inversion anymore and you are implying a whole set of pattern that has nothing with dependency injection and would not be enforce what so ever with that. What you have done would be the same as using an interface be more complicated. It has its advantage, but still end up as filling the role of an interface.

cerulean wasp
#

how is this not dependency injection? The alternative without C is to have B directly get a reference to A, and try to start calling methods.

#

B now depends on C’s methods, as does A.

dusty wigeon
#

Instead, you just have a reflection base/gerenation code tool gives you a reference to C.

cerulean wasp
#

everyone has a direct reference to C

dusty wigeon
#

The point of dependency injection tool is to fill that reference

#

Whatever C is, does not have anything to do with dependency injection

cerulean wasp
#

with the thing you put in the middle, which is C

sterile meteor
#

I have similar feelings, @dusty wigeon but dependency Injection frameworks clashes with MonoBehaviour lifecycle here. However, by abandoning it and using singletons and locators, components 'ask' for references, instead of references beign provided to them, creating a tighter coupling.

dusty wigeon
#

No, you are the one that decide what you want.

cerulean wasp
#

C is not technically needed, as A could directly depend on B

dusty wigeon
#

Yes, and if you want to have better architecture you use C.

#

We agree

#

However, it has nothing to do with dependency injection

dusty wigeon
#

At the end, you still gonna have a reference to the component. If you want flexibility in acquiring the reference, serializefield and scriptable object does more than that.

#

Also, you can use a reference on a more broad concept such as a player to retrieve a component that he owns.

#

This, wouldnt be possible in most web framework.

#

Hence, the usage of dependency injection is a good thing in my opinion in those scenario.

sterile meteor
#

It seems to me that there is no silver bullet here, but what you're describing is probably the most natural in Unity and just straightforward.

#

anyway thank you guys for your point of view πŸ™‚

dusty wigeon
#

@sterile meteor, I do not accept any DMs.

sterile meteor
#

oh, that's a pity, so thank you again here πŸ™‚

undone coral
sterile meteor
#

It is more like Minecraft Dungeons with coop mode but in open world in listen server architecture.

undone coral
sterile meteor
#

Yup, Netcode for GameObjects. I looked at the BossRoom sample architecture, but it seems a bit spaghetti there.

undone coral
# sterile meteor Yup, Netcode for GameObjects. I looked at the BossRoom sample architecture, but ...

okay. my opinion is you're in a pretty good place. my experience is pretty limited, while i have worked with ~10 engineers on a game before, only 3 were ever touching the unity scene. in my opinion, all the dependency injection choices are bad for Unity. dependency injection generally is poorly suited for games, because all the stuff you spend the most time writing is tightly coupled anyway. the best thing you can do is to give ownership of the tightly coupled stuff to specific people. for example, the player controller, and therefore the way you architect movement in your scene, and therefore the multiplayer, must all be done by the same person

#

you can make this easier by using ECS, which if your game doesn't need 100% of all the latest rendering features, you will be able to decouple a lot of the networking from everything else.

#

ECS is "decoupled networking for gameplay." netcode for gameobjects is fine, but since ordinary, non-ECS networking is coupled to everything, you are, in disguise, forcing your game to be authored by 1 person, even though you have 6 😬

#

that's why i say 3 years

#

"spaghetti" is just saying, "one person came and made a ton of changes to other people's stuff."

#

boss room was authored by at least 6 engineers over time.

#

it is true that fernando-cortez had to touch everything, but i don't think he authored the bulk of the sample

sterile meteor
#

Big thanks for the response! I wonder why they changed their custom DIScope to the VContainer.

steel snow
#

in a scriptable object how do you automatically create and manage assets when you create an SO ? I tried something like this :

        private void Awake()
        {
            if(_meshTemplate == null)
            _meshTemplate = LoadAsset<ThemeMeshTemplate>();
            if(materialTemplate == null)
            _materialTemplate = LoadAsset<ThemeMaterialTemplate>();
        }
        private T CreateAsset<T>() where T : ScriptableObject
        {
            Delete<T>();
            var asset = ScriptableObject.CreateInstance<T>();
            asset.name = typeof(T).ToString();
            AssetDatabase.AddObjectToAsset(CreateInstance<T>(), this);
            AssetDatabase.SaveAssets();
            var path = AssetDatabase.GetAssetPath(this);
            return AssetDatabase.LoadAssetAtPath<T>(path);
        }

        private T LoadAsset<T>() where T : ScriptableObject
        {
            var path = AssetDatabase.GetAssetPath(this);
            var result = AssetDatabase.LoadAssetAtPath<T>(path);
            if (result == null)
                return CreateAsset<T>();
            return result;
        }
#

but it was causing the error Calls to "AssetDatabase.RemoveObjectFromAsset" are restricted during asset importing

#

same for AddObjectToAsset

#

if i use OnEnable i get an exception about some infinite import loop

#

so there does not seem to be an ideal method for doing it in a scriptable object

grizzled stag
#

What's the best way to handle multiple external factors on a target script with a one way relationship:
Say I have a player controller which has a "CanJump" boolean, I would like this boolean to be the intersection of factors involved in other scripts such that CanJump = ScriptABoolean && ScriptBBoolean...

My issue is that I'd like to not reference these in the script which has CanJump but to append them in some way from scripts A and B. I know I can do this with a list and just change my get from CanJump to resolve this list, but wanted to check if there's a better approach than this solution

sly grove
#
public bool CanJump => ScriptABoolean && ScriptBBoolean;```
tiny pewter
#

i think this is fine as long as the canjump is synchronized

grizzled stag
sly grove
grizzled stag
#

I'm using two in this example but it should be expandable to however many

sly grove
grizzled stag
grizzled stag
tiny pewter
#

when you update the scriptABool the canjump will be updated

sly grove
#

something like this?

grizzled stag
grizzled stag
sly grove
tiny pewter
#

permanently, so you have to reset jump

grizzled stag
sly grove
#

yes if you do b = false; b becomes false

#

naturally

#

there's no magic here

grizzled stag
sly grove
#

why would a become false?

#

there's no spooky action at a distane here

grizzled stag
#

I think I've misunderstood &= nevermind

sly grove
#

if you don't do a = something; a will not change

tiny pewter
#

&= is a=a&b

sly grove
#

a &= b is just a = a & b;

grizzled stag
#

yeah yeah

tiny pewter
#

after assignment b will not change a anymore

grizzled stag
#

so I need to call append after each adjustment of b for a to update properly

grizzled stag
sly grove
tiny pewter
#

actually i may have a semaphore approach but you need to know how many bool are here so you dont need to call ResetJump

grizzled stag
tiny pewter
#
public int ready;
public int number_of_bool;
public bool can_jump{return ready==number_of_bool;}
grizzled stag
grizzled stag
#

I suppose if I kept a total that'd work fine

tiny pewter
#

you need to keep the total number of bool, but it allows you update ready from anywhere

sly grove
grizzled stag
#

do you pass in the child script's booleans as a parameter each to an append-like method you mentioned before?

grizzled stag
#

and have the other scripts add it to a delegate of AllAppends or something alike?

sly grove
#

yeah then the other scripts A, B, C, etc call AddJumpSource to add themselves to the list

#

so for example in script A it might be:

bool IsReadyToJump() {
  return fuel > 5;
}

void Awake() {
  playerController.AddJumpSource(IsReadyToJump);
}```
grizzled stag
grizzled stag
#

obviously one less line and you don't have to define a delegate type but curious if anything else

sly grove
#

defining your own delegate type would be fine

#

it would replace Func<bool> though

#

you still need a HashSet or List

grizzled stag
tiny pewter
#

func is action but it has return type

sly grove
#

Func<bool> means " a function that returns a bool"

#

it's equivalent to:

public delegate bool BoolSource();```
#

So you could do HashSet<BoolSource>(); here just the same

grizzled stag
#

right

#

I'm still not super confident with delegate return types as of yet, I thought only the last delegate Invoked returned its value?

grizzled stag
#

ahh

sly grove
#

that is true if you try to shove them all into one multicast delegate

#

instead I have a collection of many delegates

#

and am evaluating each one by one

grizzled stag
#

yup yup makes sense

#

hang on I'll type up an alternative proposition if you'd care to give it a glance, I'm sure it'll be less efficient though

sly grove
#

if it makes it easier to think about you can replace HashSet with List here and it will work the same

#

If the number of elements is small (less than 10 or 20) it probably won't make any noticeable performance difference either

grizzled stag
#

oh wait nevermind I was in lala land

#

completely misinterpreted delegate parameters for some reason

grizzled stag
#

sorry for the bombardment of questions btw, lmk if you're busy or whatnot

tiny pewter
#

hashset is O(1) for add/remove but around O(1.4n) for iteration (suppose reallocated if 70% space is filled, maybe slower in real life)
list is O(n) for both add,remove,iteration

earnest helm
#

I have a question. So I have been experimenting lately with the Netcode for gameobjects. I am stuck trying to make a player reset to his base position on map reset, any ideas how could this be done?

#

Like so when the map is reseted using the other network command, the players get teleported back to their base positions too.

undone coral
undone coral
# earnest helm No.

hmm. what is your game? it should be pretty straightforward to set the player position

#

even if you just blubbed it

earnest helm
#

I thought there was a special netcode function for reseting Netobjects position tho.

undone coral
#

this is simple enough that GPT4 can author it for you

tall ferry
earnest helm
undone coral
terse oyster
#

Any idee how can I change player name in cloud code unity?

undone coral
plush pier
#

how do you preserve aspect ratio regardless of resolution (Unity 2022, URP)

dusty wigeon
mighty latch
dusty wigeon
mighty latch
#

If it can be done through scripts, there's Screen.SetResolution

dusty wigeon
#

You need to set the viewport of the camera.

#

To keep the same aspect ratio

#

Something like:

public Rect GetViewPortSize()
{
    return GetViewPortSize(Screen.width, Screen.height, referenceSize.x, referenceSize.y);
}

private Rect GetViewPortSize(float screenWidth, float screenHeight, float referenceWidth, float referenceHeight)
{
    float screenRatio = screenWidth / screenHeight;
    float referenceRatio = referenceWidth / referenceHeight;
    float scale = screenRatio / referenceRatio;

    if (screenRatio > referenceRatio)
    {
        scale = 1 / scale;
        return new Rect((1.0f - scale) / 2.0f, 0.0f, scale, 1.0f);
    }
    else
    {
        return new Rect(0, (1.0f - scale) / 2.0f, 1.0f, scale);
    }

}

pastel bronze
#

Yo im doing Custom Pool Managing now am i advanced enough yet?

#

Starting to study ECS

fluid totem
#

Hi, I am making a health bar system that make use of one canvas (screen space) and the canvas is a child object of a UI camera. I want the health bar to follow the enemy but I dont know why all the health bar is stuck in the middle of the screen. Here is my code:

private void Update()
{
    if (objectToFollow != null)
    {
        Vector2 ViewportPosition = _camera.WorldToViewportPoint(objectToFollow.position);
        Vector2 WorldObject_ScreenPosition = new Vector2(
        ((ViewportPosition.x * _myCanvas.sizeDelta.x) - (_myCanvas.sizeDelta.x * 0.5f)),
        ((ViewportPosition.y * _myCanvas.sizeDelta.y) - (_myCanvas.sizeDelta.y * 0.5f)));
        _rectTransform.anchoredPosition = WorldObject_ScreenPosition;
    }    
}

_myCanvas is the RectTransform of the canvas. ObjectToFollow is the enemy transform. Is there any solution? Thank you.

plucky laurel
#

you can just pass the viewport position, maybe with flipping one axis

fluid totem
#

not working, it doesnt move

#

can you explain more about " just pass the viewport position", my understanding is change the code like this

Vector2 ViewportPosition = _camera.WorldToViewportPoint(objectToFollow.position);
        
        _rectTransform.anchoredPosition = ViewportPosition;
plucky laurel
#

yes, already should produce results

#

because full screen canvas matches 0-1 to viewport

#

i may have confused anchoredPosition with anchors themselves

#

try anchorMin = vp; anchorMax = vp;

fluid totem
#

trying

#

ok it works, but the health bar is "shaking" when the enemy move

tropic vigil
verbal knoll
# fluid totem tried. Still shaking

I used this as a starting point, and none of my HealthBars Shake !
https://www.youtube.com/watch?v=_lREXfAMUcE

BMo

The main difference between a Player's Health Bar in the HUD vs an Enemy's is creating the Health Bar in WORLD SPACE.

In stead of overlaying UI on the Camera, the Enemy or Game Object itself has a Canvas attached to it as a child object, and the UI is a part of the Enemy GameObject.

The benefit of this is the Health Bar follows the Enemy aroun...

β–Ά Play video
#

its 2d diablo style too

fluid totem
#

I am in 3D

verbal knoll
#

it works in 3d

#

I am using the same code in 3d

fluid totem
#

how do you make the health bar face the camera? transform.lookat?

verbal knoll
#

just make sure its WORLD SPACE and make sure to have the bars face the cam

fluid totem
#

I have tried to use transform.lookat but it makes the health bar look bad (the frame is kind of broken in some angle, like its not completely round)

verbal knoll
#

on HealthBarSCRIPT in UPDATE try ...

#

transform.rotatino = camera.transform.rotattion;

#

serialize camera variable, and drag cam ( inspector

#

You game looks sick ATM BTW, I love Diablo 3 and 2

fluid totem
#

yea, I tried before, the health bar frame will become kind of scratchy like this. So, I decide to swap to screen space

#

Thank you

dawn oriole
#

if the healthbar is on canvas, you probably don't want to rotate it too much as it will "skew" the bar just like that

regal lava
#

I think I've suggested it to you before, but using a screen position shader for this stuff cuts down a lot of work

fluid totem
#

yea. I asked yesterday and I have google it. But if I use the shader I cannot make a custom health bar, like adding the skeleton and adding the gold frame in this example.

#
fluid totem
#

After watching the video and the comment, I try changing the rotation of the canvas rather than the health bar and use world space canvas and it works.

#

Thank you everyone for helping

lament salmon
#

Otherwise it will use world up vector which can look a bit off at some angles

regal lava
regal lava
#

just some minor optimization since they're already doing a lot of work with the shader so might as well just do it all

fluid totem
#

yea, it looks good at performance. I am considering using it in "normal" monster, and use the world canvas in "elite" monster.

verbal knoll
fluid totem
frozen imp
#

@ionic ivy Don't cross-post. Pick one channel

cerulean wasp
#

I want to run by a system to help my physics system keep things grounded along changing slopes. Looking for feedback:

  1. At start of fixed update, one script calls GetContacts on anything that can be grounded to learn current grounding state and slope normal it is on.
  2. Most scrips run to call velocity changes etc. These scripts also tell physics system if something should stick to ground (bool).
  3. End of fixed update, during custom physics simulation:
    3a) Whenever we move something, if stickToGround, then change the vector for how we plan to move to be along the slope (using normal from part 1)
    3b) Right before end of similation, for everything that can stick to ground, cast down to check for floor. If find floor, move down.
#

And assume anything that is ground cannot stick to ground.
Good plan? Bad plan?

torpid jolt
#

Hi, I need some help.
So I have a 2D array of nodes (Node[,]). Let's call it "arr1"
I have another array. The array is of the same type (Node[,]). Let's call it "arr2"
I want to combine them into one large node.

Both arrays aren't jagged. Both arrays have unique elements, meaning that an element from arr1 won't appear in arr2 and vice versa.
Is there a way to do so without loosing too much performance?

dusty wigeon
torpid jolt
#

I see

dusty wigeon
#

Your best option is to find an alternative to not have to do that.

torpid jolt
#

Okay, thanks for your help

dapper cave
#

which version of Unity added delta compile in IL2CPP? 2020 seems to recompile entire project even on scene change.

runic tendon
#

If I replace a 100x100 tilemap with prefab tile gameobjects(10,000 spriterenders+colliders, no update() calls) how badly would it perform compared to a tilemap?

Going the prefab route makes some calculations easier for my mechanic. But I'm not sure how big the perf hit will be.

tiny pewter
#

profile it, though the memory usage must be huge if you use 10000 gameobjects and the rendering cost

undone coral
#

you might consider ECS

runic tendon
#

@undone coral
It's hard to explain. Basically, the player can move tilemap columns. Like columns 3...100 is moved to cols 1..98 . This requires repainting 80x100 tiles. If every tile was a prefab, I could just move the gameobjects. I'm not sure if that's faster. However, the ability to have monobehaviors on each prefab makes somethings easier.

I think ECS would be overkill for this. I also have the option of using multiple, smaller tilemaps as chunks of the map. That way, the repainting would be limited to current chunks and I would simply move the other chunks.

regal lava
runic tendon
regal lava
#

You'll have to update it afterwards

dusty wigeon
dusty wigeon
# runic tendon <@247793168056057857> It's hard to explain. Basically, the player can move tile...

Have you profile the games on the targeted device ? Same if it seem inefficient, you might be correct. Also, note that moving 80x100 GameObject would also be considerable slow. However, your real lost would come from losing the batching that comes from a tilemap (and the ease of use of a tilemap).

Also, note that instead of moving column, you could offset all your time map and only modified 1 column or 2 if you want to cleanup the extra each time.

runic tendon
regal lava
#

I guess it comes down to how much is being rendered at the time too as spriterenders do actually batch quite well (with a sprite atlas at least), but if you're viewing whole tilemap it would probably be a problem.

verbal knoll
abstract folio
#

hi all! I've got a small project (SerializableDictionary): I've got the project itself up on git hub, and on my own system, I’ve created a unitypackage with the project. But I’m missing the last step in order to make the package installable from git… anyone know where to find those docs? no luck in my searches.

fickle mango
abstract folio
fickle mango
#

did you forget the .git at the end?

abstract folio
#

I just dont know what SHOULD be in that repository, should it be the package file I made, or the source project?

abstract folio
half swan
fickle mango
#

You need to click the green "Code" button and then copy that. or just add .git at the end. No matter though, I tried and there is still another bug

#

you need a package.json file in your git repo

abstract folio
#

should the package I created be in there? or just the source project

fickle mango
#

just the package

abstract folio
#

AH! ok, lemme tryu a new repo with that. thank you!

fickle mango
#

You can take a look at how one of my packages looks like:
https://github.com/Gruhlum/Basics
Coincidentally, that packages also includes a tool to create packages with one click

abstract folio
#

I see the folder I exported my package into contains ONLY the file" SerializableDictionary.unitypackage" will I need to geretae that package file manually or sothing?

abstract folio
thin mesa
#

the unitypackage file is only necessary if you want to manually add the package. it is not necessary for adding a package via git

fickle mango
#

I am not 100% sure if the unitypackage can actually be installed via git. You might have to do a "regular" package

abstract folio
#

AH, ok cool. thats clear things up alot! so this package.json file appears tobe what I'm missing. not sure how to generate that.. do I do it manually?

#

(Imma try just modifying the one I found in your repo @fickle mango

fickle mango
abstract folio
#

ah, that's why you wrote it? cool, thanks again !

fickle mango
#

ye, there should be a tools button at the top once you add that script, generate it from there and drag your package scripts into the Runtime folder, or the Editor folder if they are Editor scripts.

abstract folio
#

@fickle mangoalso- cool tool!

fickle mango
#

yes you need the meta files as well

abstract folio
#

just copy em over?

#

to the folder your tool made?

fickle mango
#

yes

abstract folio
#

not having much luck. Now it wants .meta file for files that don't even exist in my main project... (just in the package folder the tool created) What a nightmare this is! And no unity docs for this?

fickle mango
sturdy roost
#

Hey guys,
I had posted in #archived-code-general but wasn't sure whether it was better suited to here and didn't want to repeat text across channels

I've been having this problem for well over a week now and have yet to receive any advice on it, so it made me think to post in here just in case the people who frequent here would be able to better spot my problem.

Here is the link to the thread I made in general if anyone would be willing to take a look.
https://discord.com/channels/489222168727519232/1172973780633665556

fickle mango
abstract folio
#

alright. thanks fo the help bud.. mch further than I would have got without it! gnight @fickle mango

zealous summit
#

is there a way to add custom log types? For example: Debug.LogCustom("customized log")

abstract folio
zealous summit
#

i'm writing a custom in-game console and wanted some error messages to display with stack trace and some not (or with even more customization). Currently I'm just subscribing to "logMessageReceived" event from "Application" and using a switch statement for handling different log types

abstract folio
#

neat! well, you cannot add to the Debug class itself, but you can certainly make your own Logging class to call Debug.Log in some ...particular... way. As far as different "types" of log, I assume you mean like normal, warning, error? As far I know, NO: there is is no way to add another type like that. However, you COULD prepend some kind of "logType" text when your custom class calls Debug.Log.. then when displaying the logs in-game, check for such text in the log message itself.

zealous summit
#

that's a great idea actually. I could define a phrase like "[no stack trace]" and look for in the "logString" to determine how it should be displayed. Thanks!

dusk pike
#

I can't figured out, tried a lot things. Used chatgpt, nothing works.

I just want a ball that bounce around between two walls left and right with a floor.
It's a 3d world, but the ball will move only in a 2d direction. The ball should move between those two walls and have always the same height unless it collides. The problem is that I can't freeze X or Z because the walls are not always placed in a X or Z direction.

If the ball can ignore the parents rotations (walls & floor) and keeps moving in the X direction, that would be also a solution for me.

#

Not sure if that is possible

tall ferry
dusk pike
#

I understand, I moved it to the beginner channel

keen temple
#

hey guys so i work on ability system when i can add alll type of thing and then create endless abilities do you think its good to Continue with this or is it a waste of time? its for my new game i working on

dusty wigeon
keen temple
dusty wigeon
#

Why, instead of doing your own behavior system did you not use a prefab ?

#

A prefab already has the capacity of adding component.

keen temple
#

I think because it's more convenient for me than going through every prefab and change, and the behavior act like mono but they are not i create new list of the behaviors so i can change stuff in real time

#

something like this

{
    [SerializeReference] private List<AbilityBehaviour> _behaviours = new List<AbilityBehaviour>();
    private HolderAbility _holder;
    public void Init(List<AbilityBehaviour> behaviours ,HolderAbility holder )
    {
        _behaviours = new List<AbilityBehaviour>( behaviours);
        _holder = holder;
        OnStartAbilit();
    }



    private void Update()
    {
        ActiveAbility();
    }


   


    public void Destroy()
    {
        OnEndAbilit();
        Destroy(gameObject);
    }

    public void OnStartAbilit()
    {
        foreach (AbilityBehaviour item in _behaviours)
        {
            item.OnStart(_holder,this);
        }
    }

    public void ActiveAbility()
    {
        foreach (AbilityBehaviour item in _behaviours)
        {
            item.Active(_holder, this);
        }
    }


    public void OnEndAbilit()
    {
        foreach (AbilityBehaviour item in _behaviours)
        {
            item.OnEnd(_holder, this);
        }
    }


dusty wigeon
#

In my opinion, you are just rewriting the wheel and additing unnecessary additionnal step

keen temple
#

the component im adding its mor like add force change transform add box colider in the time the attack do dmg and stuff like that

dusty wigeon
keen temple
#

ye i know but its in Play i need to add thos scripts anyway

#

its not for the before the game this in the game

#

i have prefab in i just give it Behaviour like range , force , new child

dusty wigeon
keen temple
#

or active animation

keen temple
#

i think i know what you try to say

#

to add thos on the prefab and not form my editor

dusty wigeon
keen temple
#

no its not like transform its use to move with transform

dusty wigeon
#

Same for the force

keen temple
#

why is that?

dusty wigeon
#

I mean, what is the difference between both ?

#

Why not use what you already have

#

At the very least, you should have a component to take on the responsability of moving.

keen temple
#

using transfrom.positon += new vector 3()

#

and the force to its just behavior to use to move

dusty wigeon
#
public class TransformMover {

  public void Update()
  {
    transform.position += velocity * time;
  }
}
#

If you need an Awake, a Start, an OnDisable or an OnEnable you do not have anything to do extra

#

If you have multiple variant you could do:

public abstract class Mover : MonoBehavior 
{
  ...
}

public class TransformMover : Mover 
{
  public void Update()
  {
    transform.position += velocity * time;
  }
}

public class ForceMover : Mover 
{
  public void Awake()
  {
    rigidbody.AddForce(...);
  }
}
keen temple
#

and if i want to move only in the start or in the end or chnage the rot to ?

keen temple
#

ye its doing the same i did

dusty wigeon
#

As I said, it is the same. You are reinventing the wheel

keen temple
#

i have here something that call to start end and update on evrey behavior

public class HolderBehaviours : MonoBehaviour
{
  [Space]
  [HideInInspector]
  [SerializeReference] public List<AbilityBehaviour> behaviours ;

  private HolderAbility _holder;
  public void Init(HolderAbility holder)
  {
      _holder = holder;
      OnStartAbilit();
  }
 

  private void Update()
  {
      ActiveAbility();
  }


  public void Destroy()
  {
      OnEndAbilit();
      Destroy(gameObject);
  }




  public GameObject InstantiateObj(GameObject obj, Vector3 startPos, Quaternion startRot, bool isChild)
  {
      GameObject prefab = Instantiate(obj, transform.position, transform.rotation, isChild ? transform : null);
      prefab.transform.localPosition = startPos;
      prefab.transform.localRotation = startRot;
      return prefab;
  }


  public void OnStartAbilit()
  {
      foreach (AbilityBehaviour item in behaviours)
      {
          item.OnStart(_holder, this);
      }
  }

  public void ActiveAbility()
  {
      foreach (AbilityBehaviour item in behaviours)
      {
          item.Active(_holder, this);
      }
  }


  public void OnEndAbilit()
  {
      foreach (AbilityBehaviour item in behaviours)
      {
          item.OnEnd(_holder, this);
      }
  }

}

dusty wigeon
keen temple
dusty wigeon
#

And you know, you can use sub object to class them if you want.

#

Ability

  • Movement
  • Collider
  • VFX
  • SFX
  • Animation
  • etc.
keen temple
#

ok

#

i dont see the different from what i did

#

i just use one mono and not for evrey one

dusty wigeon
#

The major difference is that you are essentially recreating what a MonoBehavior is. It has multiple impact:

  • A new user most understand the system you have created
  • Your system has more risk of not being robust
  • Your system does not integrate as well as using component. Feature such as CustomEditor, Prefabs override, Nested Prefabs, Tag, Layer will not be part of your behavior.
#

Note that I'm not saying that it won't work.

lament salmon
#

Non-component behaviours is not a very complicated thing for the "user to understand"

lament salmon
dusty wigeon
keen temple
keen temple
dusty wigeon
keen temple
#

and its for me to create an interface that i can easy create ability

keen temple
dusty wigeon
dusty wigeon
#

That being said, having move the actual data that deals with the world to a prefab is definitely better. This way you would be able to easily edit things such as collider/trigger, VFX, SFX, Animation, etc.

cerulean wasp
#

I'm still looking for a way to determine multiple points of contacts between two colliders, which is not tied to the timing of the physics update

#

specifically, I move red ball from old position to new position, and I want to get those 3 points of contact between the red and blue colliders. But GetContacts tells me what it was at start of the previous physics update (eg the 1 contact for the old position)

regal lava
#

Can't use spherecast at all to, right?

cerulean wasp
#

.Cast methods all seem to return only 1 hit per collider

regal lava
#

Because that also gives all contact points I think

#

well, the override version does

cerulean wasp
#

I'm in 2D, btw

regal lava
#

Circlecast probably has it too

cerulean wasp
#

wich argument/setting is it?

#

maybe I can find a related one in physics2D

regal lava
#

circlecastall may return all intersection points

#

doesn't actually say on the documents but I'm pretty sure spherecast does or maybe I'm thinking of another method

#

but it uses the physics2D library if that matters

cerulean wasp
#

it looks like CircleCastAll just retrieves hits for all colliders allong the path, as opposed to multiple hits per collider

#

I have an idea, but this might need some hammering out:

  1. Cast, get hits normally.
  2. For each hit that hits a CompositeCollider2D/PolygonCollider2D, then:
    make a new ContactFilter2D that tries to ignore that contact normal.
  3. Cast again. Check for double hits.
#

actually, normal filter does't work....

regal lava
#

Could just fan out some rays even not the ideal solution

cerulean wasp
#

that... is going to be a problem

#

Raycasts are weirdly similar in cost to casting my whole box collider

hallow elk
#

Hello, I am building an asset store asset and I need to check if TextMeshPro is installed (for compatability with other versions). There doesn't seem to be a define symbol for it and the only thread I can find remains unanswered. Any ideas?

#

It appears back in 2018 Unity, there was a define called TMP_PRESENT but this does not exist in current versions.

cerulean wasp
#

if hashcodes are 32 bit integers, how does a hashset/dictionary not cost 2^32 bytes each, just to hold empty buckets?

sage radish
tiny pewter
#

you mean you need an array of size 2^32 for the "buckets"?

devout hare
#

A hashset doesn't reserve an empty bucket for every possible hash. That would just be a normal array. Typically there's one bucket reserved for each element in the set

tiny pewter
#

it will modulo the total number of buckets, usually a prime number

cerulean wasp
devout hare
errant halo
#

hello, does anyone know why this compiler error is here? This happened afterI pressed connect to unity cloud in the unity hub, I then disconnected it but its still showing this

#

I cant play the game or anything now because it just says theres a compiler error

regal olive
#

What if compiler didnt liked the space in path C:\Users\dynam\Co-op Survival because it does not seems a bug that comes from your project

errant halo
#

what should I do about the space to try and fix it

regal olive
#

Copy the project into another folder and rename the new one without spaces. Open new one and try it
Also get rid of the "-" in path

errant halo
#

is there any other way? the project is 77GB

regal olive
#

Wow dude

errant halo
#

Like install something for the post processing stack?

errant halo
regal olive
#

I dont think so man you should try the easiest thing before trying the hardest

errant halo
#

ight fair enough

regal olive
#

Do not forget to Regenerate the project files from Edit>Preferences>ExternalTools again in newly copied project

errant halo
#

@regal olive im trying but i dont have the space to copy the project

upbeat path
regal olive
errant halo
#

im on a laptop unfortunately

#

Im sorry Im trying to follow your guys instructions i just have a bad situation lol

upbeat path
#

So you have no USB drives?

errant halo
#

I dont have one big enough

upbeat path
#

The Library folder will be very large. How big is your Assets folder?

errant halo
#

43 GB

upbeat path
#

do you have 43 gb space?

errant halo
#

here ill just uninstall something real quick

#

Im deleting some old projects, hopefully that will clear enough space

#

okay so what should i copy over @upbeat path ? the whole project?

#

i have 128 GB space free now

upbeat path
#

No, just the assets folder

errant halo
#

okay

#

copying now

#

how about library folder?

upbeat path
#

No, delete the Library folder

errant halo
#

from my main project?

#

will that mess anything up?

#

will i lose anything?

upbeat path
#

no, I would not tell you to do it if there was a danger of losing anything

errant halo
#

okay πŸ™‚

#

so in my main project, deleting the library folder rn?

#

and I have the assets folder backed up

upbeat path
#

perfect. Now in the project folder delete all .csproj and .sln files

errant halo
#

all of this?

upbeat path
#

yes

errant halo
#

.vsconfig?

#

or nah

upbeat path
#

did I say that? No I did not

errant halo
#

okay sorry

upbeat path
#

I thought you had deleted the Library folder, I still see it

errant halo
#

im deleting it now

#

sorry i had it backed up and i forgot to delete after

#

okay i have that deleted now

upbeat path
#

Now rename your project folder to remove the -

errant halo
#

So the old name was Co-op Survival - Built-in, should i just rename it to something else, like the games name UndeadHorizon ?

upbeat path
#

CoOpSurvivalBuiltIN will do or you can just call it Fred, it's up to you

errant halo
#

sweet

#

alright i renamed it

upbeat path
#

ok start Unity Hub, you will need to remove the old project name and Open->Add from Disk the new one

errant halo
#

okay im opening it now

upbeat path
#

Ignore

#

It should not contain compilation errors if you were doing a build

errant halo
#

wdym

errant halo
#

like it wouldnt let me go into playmode because of it

upbeat path
#

Open will take some time as it needs to rebuild the Library folder
Even so, you should not have been able to enter play mode if you had compilation errors

errant halo
upbeat path
#

Always fix compilation errors before you do anything else, not doing so can cause problems

errant halo
#

okay

#

getting there..

#

@upbeat path its probably going to take another 15-20 mins i think

upbeat path
#

I would expect so, at least. But once you clear your compilation errors you should be good to go

#

Oh, dont forget to change the Product name in ProjectSettings->Player if needed

errant halo
#

okay πŸ‘

#

so this should just regenerate everything back to normal ?

upbeat path
#

yes

#

that is the plan unless you did something really bad

errant halo
#

okay πŸ™

#

@upbeat path

#

i just opened a scene i had, i havent edited anything but it looks like untiy isnt importing the scripts properly

upbeat path
#

Not it's not, it looks like it's generating an invalid .csproj file

errant halo
#

oh ok

#

what do i do

#

is it bc the compile error hasnt gone away

upbeat path
#

is this HDRP or URP?

errant halo
upbeat path
#

In the Package Manager remove and re install the Post processing stack

errant halo
#

okay i did that

upbeat path
#

if you're not using post processing just remove it

errant halo
#

i uninstalled and then reinstalled it

upbeat path
#

Regenerate project files

errant halo
#

where do i do that

upbeat path
#

Project Settings->External Tools

errant halo
#

okay

#

also i saw this idk if this is something but yeah

upbeat path
#

Sorry, Preferences->External Tools

errant halo
fresh salmon
upbeat path
#

why is it being used as a file name?

#

wow, where did that come from?

errant halo
#

compiler error is cleared

#

awesome my project is back to normal

#

thanks a lot @upbeat path I really appreciate it

#

is there anything I can do for you for helping me out?

upbeat path
#

yes, implement and use version control on your projects

errant halo
upbeat path
#

yes

errant halo
#

okay

#

Also, Am i good to delete that backup of the assets folder?

upbeat path
#

yes

errant halo
#

πŸ‘

upbeat path
#

Also get yourself some external drives so you don't run out of disk space

errant halo
#

real quick one last thing

#

I dont know if you can see it but that particle trail

#

It looks like the color changed from before

#

do you think theres some post processing stuff messed up or nah

upbeat path
#

no idea, not my area of expertise

errant halo
#

okay nevermind this is a simple little thing ill mess with it

#

thanks again, ill get Git working with my project ASAP

upbeat path
#

perfect, enjoy the rest of your evening, I'm off to bed

errant halo
#

you have a great evening aswell!

rancid hinge
quiet dragon
#

I know there's an #↕️┃editor-extensions channel but I'm not sure if this necessarily fits... I'm generating some GameObjects with a script and running SaveAssets after, but I've noticed that specifically after adding some code that manipulates RuntimeAnimatorControllers, every time I "regenerate" my scripts, I get some odd errors interacting with the generated objects until I manually recompile the main component I'm editing

#

I guess my question is that I know there are some SetDirty and other interactions when editing/manipulating gameobjects with editor code...

Is there something more I need to do with a GameObject I've generated with an editor script in order to correctly "update" its variables when interacting with a RuntimeAnimatorController?

olive cipher
quiet dragon
#

@olive cipher do you SetDirty before editing or just right before saving the assets, or does it matter?

olive cipher
#

So right before saving

undone coral
undone coral
#

it is a misconception that they are "O(1)"

undone coral
cerulean wasp
#

and it theoretically should not. the overhead is supposed to be the cost for quickly knowing exactly where in memory you are supposed to go (in theory)

tiny pewter
#

amortized O(1) just like List.Add
when you add some elements until the list capacity becomes n=2^k, the time needed for each insert is n/(4+8+16+...+2^(k-1))=n/(2^k-1-1-2)=2^k/(2^k-4)=1 when lim k->infinity
(if the current capacity is 8, an array of length 4 is copyed, 16->8+4 (previous copy), 32->16+8+4....)

undone coral
#

it's not about the capacity alone. it's exactly what i showed in that expression

#

hash collision chances can be very high for many kinds of game data storage

cerulean wasp
#

yes, it would be amortized O(1). not trur O(1)

tiny pewter
#

idk why c# list's capacity start from 4 btw, i feel it is quite small

cerulean wasp
cerulean wasp
undone coral
#

you can read it and reason about it carefully

tropic vigil
undone coral
#

i don't know what you are trying to do specifically

cerulean wasp
#

given your data’s structue

#

like if you have a hashset of Vector3, but all the z values are 0, your hash function is probably going to give you a lot more collisions

undone coral
#

you should consider using ECS if you need something sophisticated in terms of performance or control, especially if you are trying to author performance sensitive CPU code

#

you can also use burst and native collections

tropic vigil
upbeat path
#

if you dont like the initial capacity, change it, it's a parameter in the constructor

cerulean wasp
#

what is the best way to handle collections for using non-allocating methods?

#

like when ray casting, results get populated into an array or list.

#

is it best to go for List vs array, and static vs non-static?

abstract folio
regal lava
#

I should probably start swapping my stuff to NonAlloc

cerulean wasp
#

mostly focus on methods that get called a lot, and would thus create lots of garbage

abstract folio
regal lava
#

Really should just be the default behavior considering how much these methods are usually used

frozen flax
honest stirrup
slim fulcrum
#

Hey guys. I'm creating a DB using Sqlite and I'm trying to delete the database. File.Exists returns false even though I'm 100% sure the file exists at that location and I'm 99% sure the permissions are fine.

#

Does anyone know what might be up?

fresh salmon
#

Path concatenation should be done with Path.Combine() instead of string concatenation!

slim fulcrum
#

Ok ill give that a go but i dont see how that could change the outcome, if the string im logging is identical and if i paste it into finder it goes there to that file

#

I'll see what happens

fresh salmon
#

Just code safety and IO standards. So you don't end up with a // or no directory separator at all, if you change one of these contstants

slim fulcrum
#

Ok ill change that thanks for the tip

cerulean minnow
#

What's the best way to go about storing a string with an int? Right now I have a list of strings and I want to associate an int with each.. I could do a list of ints and each time just get the correct index , I could do a multidimentinal array , maybe a dictionary that'll have a string , int or a scriptable object... I'm also thinking of ease off data entry as I will have 40,000+ entries.. maybe a json with string , int and convert to dictionary?

#

Any constructive thoughts/help is appreciated

fresh salmon
#

A class or struct?

#

Why make it complicated

tall ferry
cerulean minnow
#

Struct would be easy and take json data .... i have an example of this in another project actually , and i made it load data from firebase into a struct for a while .

cerulean minnow
cerulean minnow
small hinge
#

Dictionary <string,int>

slim fulcrum
#

@fresh salmon I got one more related question for you

#

Do you know why, in this case, the "Database.DB_PATH_PREFIX" does not get added to the path?

fresh salmon
#

Doesn't seem like a valid path to me. = and : might be invalid path characters

slim fulcrum
#

It works before I changed to "combine"

#

It's to connect to a sqlite db

#

Oh.. maybe i dont use path combine then

#

LMAO

fresh salmon
#

Yeah Combine checks the paths you feed to it

#

Path.GetInvalidPathChars() will give you the list of chars that are invalid for the current platform

slim fulcrum
#

Itneresting ok, but it works when it's just a string.

fresh salmon
#

Yes because Combine checks the paths you feed to it

#

If it contains invalid characters, pretty sure it's ignored, or you get an exception

slim fulcrum
#

But if they're invalid, why would they work when it's just a string

#

is what I don't understand.

fresh salmon
#

Because string concatenation does not use Combine???

#

Therefore the strings are not checked for invalid path characters

thin mesa
slim fulcrum
#

I figured out my issue

#

and i will also look into that thanks for the link

#

thanks guys

errant halo
undone coral
sand iris
#

I'm making a custom C++ game engine, and I'd like to do something similar to what Unity does by auto-serializing public members of MonoBehavior classes, which subsequently allows for the member to be drawn in the editor.

My question is: how does Unity actually do this auto-detection? It seems like this feature is closely tied to reflection, but at least with the C++ reflection libraries that I've looked at, it seems that you have to manually "register" your members for iteration later on.

How does Unity do this without the user of the class having to do any manual registration?

I've researched C++ reflection libraries, specifically RTTR and Meta. Both of them require manual registration of class data members.

sly grove
#

Unity uses reflection, full stop. C# happens to have a virtual machine with a fully fleshed out type system running the show. C++ doesn't have this. The metadata about function names and such simply doesn't exist in the compiled binary by default. So you're at a huge disadvantage if you want to do things the Unity way.

I recommend just abandoning "the unity way". Anyway this isn't really a Unity related question...

sand iris
#

Thank you.

olive cipher
#

I would give it a shot to go through their source, as its open source, maybe you can find what you want

half swan
# sand iris Thank you.

TechGeek on the Unity Developer Community discord worked on Unreal and develops engines, you may want to ask in that server for suggestions

I know they're working on something wild right now

sand iris
# olive cipher Also the reason unreal uses the UPROPERTY macro

That's a good tip, thanks. If it can be done with a macro that's a pretty close second. I just don't want to force the user to type this ugly statement every time

RTTR_REGISTRATION
{
    registration::class_<MyStruct>("MyStruct")
         .constructor<>()
         .property("data", &MyStruct::data)
         .method("func", &MyStruct::func);
}

Anyways, I'll stop posting on here now since it's no longer Unity related.

sand iris
half swan
olive cipher
#

Dm'd you an invite

sand iris
#

Thank you both.

warped pasture
#

For those who knows about the Probuilder API, is there a way to change the UV scale automatically on creating a mesh?

frozen flax
unique basin
#

Hey people, so DOSember is coming up fast. It's an event where poeple play old DOS games on Twitch during the month of December. I'd like to build a virtual room with a computer that I could play the games on in Unity. The site Good Old Games has a tone of old DOS games on sale and they mostly use DOSbox to emulate them. I know that you can run emulators through Unity but I'm not sure how. Any advice would be appreciated.

small hinge
#

Welcome to Arcade Paradise, the 90’s-fuelled retro arcade adventure. Rather than washing rags for a living, you decide to turn the family laundromat into the ultimate arcade. Play, profit, and purchase new arcade machines, with over 35 to choose from, to build your very own Arcade Paradise!Take the laundromat business made up of dull chores from...

Price

$19.99

Recommendations

798

β–Ά Play video
vagrant basin
#

Hi all, I've seen 3 different ways to do event handlers..
Make the event a ScriptableObject and drag and drop it on the Listeners/Callers,
Make it a static class and subscribe/call that
Make a Singleton to handle all the events
Is there a consensus on which one is the better approach? or is there one I'm missing which is better?

sly grove
vagrant basin
#

yeah sorry, I mean like OnEnemyDie, OnTakeDamage, etc.

#

I've just been throwing event Action<T> on my GM, but it seems messy as the project grows.

sly grove
plucky laurel
#

as an example of one, dumb, direct approach

sly grove
#

If you need them to be "global" you can make them static

#

there's no good reason to put all your static events in one class

plucky laurel
#

there are plenty of ways to go about it, but general idea is to create a middleman between subscribers and dispatchers

sly grove
#

yes a global event bus / central dispatcher is an approach as well

#

This would involve making topics as data basically - e.g. eventBus.Subscribe("enemy-death", listener);, eventBus.Publish("enemy-death", params); as a quick dirty example

vagrant basin
#

yeah, this is something like what I'm looking for. Thanks!

hazy epoch
#

Anyone have any idea...how a Capsule Collider's bounds, can move away from where the collider actually is?

dusty wigeon
#

Not exactly sure what you mean by move away

sly grove
#

What are you seeing that makes you say/think that?

hazy epoch
#

Gizmos.DrawCube(bounds0.center, bounds0.size);

#

During runtime it's gradually going further down.

#

The Gizmo is...yet the GameObject and the Collider are not moving.

sly grove
#

oh sorry I see it

#

where did bounds0 come from?

hazy epoch
#

Bounds bounds0 = GetComponent<CapsuleCollider>().bounds;

dusty wigeon
#

Does your capsule has a rigidbody ?

hazy epoch
#

Yes

sly grove
dusty wigeon
#

Do you do something with it ?

sly grove
#

the full inspector

hazy epoch
hazy epoch
#

Sorry was in Debug mode when I grabbed that shot. Dunno if that matters.

hazy epoch
sly grove
#

including the top bit

#

and any other components

#

also try disabling some things like the animator

dusty wigeon
#

Oh and you might want to add the transform.position of the object

#

The bounds are in local space arent they ?

sly grove
#

you've got Animator, NavmeshAgent, and Rigidbody all on this thing - those things will often conflict

sly grove
#

not for COllider

hazy epoch
dusty wigeon
#

Oh I see

sly grove
#

well is the object marked as static?

hazy epoch
sly grove
#

try disabling some of these other components

#

to test

#

NMA, Animator

hazy epoch
#

Looks like it's the Nav Mesh Agent causing it. πŸ˜•

#

Or if I Freeze Position on the Rigidbody's Y axis it also stops "sinking".

sly grove
#

right because it's just falling

hazy epoch
#

Okay. So I'll have to add/remove the RB based on whether or not it's a player controlled (does or doesn't have Nav Agent) version of the GameObject.

#

Since it's not happening on the player controlled prefabs that have a RB but no NMA.

sly grove
#

making it kinematic should also work

tired fog
#

How can I profile a shader so that I know which instructions are taking so much time? I made a custom terrain shader and is taking around 6ms to run (which doesn't make much sense since it's quite simple)

patent bear
#

You'll also probably want to make sure shader debug symbols are being generated if you want to get as much info as possible. Defining the environment variable UNITYSHADERCACHE with a value of a folder location to put the debug symbols will force them to be generated, iirc.

echo stream
#

Problem About Adding Modifiers

cerulean minnow
#

How can i sort/filter a dropdown list options?

half swan
cerulean minnow
half swan
cerulean minnow
#

here is where I serach th list after its added to the options

// Iterate over each string in the itemList
        for (int i = 0; i < itemList.Count; i++)
        {
            // Check if the current item in the itemList contains the searchText (case-insensitive)
            if (itemList[i].ToLower().Contains(searchText.ToLower()))
            {
                Debug.Log($"{searchText} Exists in {itemList[i]}");
            }
            else
            {
                Debug.Log($"{searchText} Does Not Exist in {itemList[i]}");
            }
        }
half swan
#

Ok, so you look to be mostly there for what you need

cerulean minnow
#

I thought about searching the list then only add whats being searched

tiny pewter
#

why not just using a hashset then you dont need to iterate the list

#

oh i misunderstand

#

you must iterate the list since you cant simply store all substrings

#

you may conside using Trie if you really want to store the substring and search it efficiently

echo stream
#

When I call GetValue() it returns the basevalues. Not the modifiers added.

obsidian glade
#

Hey, I have a question about UniTask, or more generally timesplicing -
I'm working on a project (2021.3 LTS) which has a bunch of separate async UniTasks being started while loading the game. They are started in different places from different objects and are doing a lot of work with Unity objects so likely need to stay on the main thread, collectively exceeding 1000-2000ms a frame. Since each task doesn't know about what other tasks are currently executing in a given frame, throwing in various await UniTask.Yield() seems a bit cluttered and random

My goal is that I can centrally stop continuing all tasks if, say, more than 50ms has elapsed since the last frame, and defer those continuations until the next frame. Anyone have insight on if this is possible & how to go about it, or if this is approaching it the wrong way?

scenic forge
#

Depends on what's actually in each task

#

But a simple way is to just check Time.realtimeSinceStartup - Time.time.

obsidian glade
#

a few things but it largely follows a similar pattern: 1. load a text file, 2. parse the text file for various strings & data, 3. create objects for each line, populate fields on those objects, create child objects, etc, and finally 4. some additional processing/interaction between the objects

scenic forge
#

Have you profiled it to see what's taking most of the time, the reading + parsing part or the object setup?

#

Because if reading and parsing are the bottleneck, they can be offloaded to a separate thread.

obsidian glade
#

it's mainly in the parsing of text and allocation of objects, so could probably move some of the parsing to a background thread

#

but each step individually already exceeds an acceptable frame time, hence looking for a central solution

obsidian glade
scenic forge
#

That's basically what you have to do for work that must happen on main thread and they are exceeding your frame budget.

#

Move as much work as possible to background threads so they don't hang your main thread.

#

(Keep in mind moving work to background threads doesn't speed things up, if reading a file takes 100ms it will still take 100ms, it just won't freeze your game in the mean time)

obsidian glade
#

yeah, it's just to keep responsiveness in the loading animations

scenic forge
#

Yeah just extract that while into a utility function and insert it everywhere, don't think there's any better way.

#

There's no auto magical splitting your code, because that's just not possible.

echo stream
#

can someone take a look at my thread

nocturne raft
abstract folio
# obsidian glade I have something along the lines of this https://hatebin.com/wfbccfyuqa pseudoco...

You could "register" each UniTask you launch with a custom class that will make note of their start times. This class can have it's own aync process that, checks these times to see if any have exceeded some maxRunTime, and/or if they have been completed, and should be de-registered. You could even wrap UniTask in custom class that will do this registration automatically when a task is created, launched.

grizzled stag
#

I have a hitbox system which currently uses OnTriggerStay to detect hits and requires their attached script to determine whether they're active or not if they can hit stuff but was curious if anyone's done any implementations before which don't require each hitbox to be a separate gameobject per actor, whether it's because it uses pooling, instantiation (which I presume isn't a good choice) or overlapspheres.

I'm asking this as it'd be nice to just be able to say to any actor use x hitbox from a large library rather than having to have the desired ones each be setup as their own gameobjects per character

regal lava
#

Sounds like you just want to cast yourself instead of using the unity collider methods, is that right? Overlapshere isn't gameobject dependent and you can pretty much cast them via a manager/singleton GO if you wanted to.

grizzled stag
#

Yeah, as I've made sure all colliders right now are just sphere colliders I was thinking it'd work fairly well and all my hitbox data is SO based so it would be pretty feasible

regal lava
#

You get more control over casting yourself anyway, but usually you do want them in your fixed update.

grizzled stag
#

I'm presuming coroutines to time how long a HB is active for isn't a good idea though if it's going to happen constantly, would keeping track of my own timers within update (or fixed update) per hitbox be better? or would the difference be negligable?

grizzled stag
regal lava
grizzled stag
regal lava
#

I use them quite a lot for minor timer systems like character buffs/debuffs which I've also created similar systems by instead polling them through a single update system. I can't say I noticed much of a difference testing with about 2000+ coroutines running at the same time compared to polling. There's probably some optimization unity does under the hood for coroutines for when they are awaiting, but I'm not entirely sure. Maybe someone else has more insight for that ;p

grizzled stag
regal lava
#

Coroutines for the most part are single-threaded, and they do probably have some overhead compared to polling them yourself through a single system, so it comes down to if awaiting does reduce the amount of polling each coroutine does per update I'd presume.

grizzled stag
regal lava
#

polling meaning that you're checking if the routine is sleeping or not per update

grizzled stag
#

ahh right right

half swan
grizzled stag
#

i'll do a little digging on coroutine performance for my case then, but presuming it's going to be insanely negligable as i doubt i'll have more than 20 hitboxes active at once ever

hazy epoch
#

Anyone know of a tutorial or detailed explanation anywhere out there for the Package Manager, that will help me to use it in the way described in the image?

#

I don't want to go the .dll route, because I'll be sharing more than just scripts between the two projects.

#

I also can't use the folder junction route, because I'm going to have this up on Plastic for collaboration and version control.

mellow sail
#

Excuse me, do any of you know how to make record and share clip feature in game?

#

I want to make a feature so player coukd record a short clip of their gameplay and share it through

#

either download it

hazy epoch
mellow sail
#

So there's no API where unity could do it?

dusty wigeon
#

You could probably find a 3rd party API that does it.

#

Or try to make it yourself, but as stated it is not something you usually do in the game itself.

mellow sail
#

Okay thank you so much

mellow sail
#

Can anybody help me on this, i tried to screenshot in editor using this code, but each time i took another screenshot, somehow it shows the previous picture, not the new one:

    void Start()
    {
        // Ensure the recording folder exists
        System.IO.Directory.CreateDirectory(photoFolder);
        screenshotPanel = screenshotImage.gameObject.transform.parent.gameObject;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && ableToSS && PauseHandler.ableToPause && !PauseHandler.isPaused)
        { 
            string screenshotPath = Screenshoot();
            StartCoroutine(DisplayScreenshot(screenshotPath));
        }
    }

    public string Screenshoot()
    {
        string screenshotPath = photoFolder + "/screenshot.png";
        ScreenCapture.CaptureScreenshot(screenshotPath);
        return screenshotPath;
    }

    IEnumerator LoadTextureAsync(string imagePath)
    {
        // Load the screenshot into a Texture2D asynchronously
        byte[] fileData = System.IO.File.ReadAllBytes(imagePath);
        Texture2D texture = new Texture2D(2, 2);
        texture.LoadImage(fileData);

        // Wait until the texture is fully loaded
        while (!texture.isReadable)
        {
            yield return null;
        }

        // Assign the Texture2D to the UI Image component
        screenshotImage.sprite = null;
        screenshotImage.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));

        Debug.Log("Texture loaded successfully");
    }
regal lava
#

Is the image being overwritten in the directory?

mellow sail
#

yes

fickle mango
#

what happens in the DisplayScreenshot() coroutine?

mellow sail
#
    IEnumerator DisplayScreenshot(string imagePath)
    {
        ableToSS = false;
        Time.timeScale = 0f;

        Debug.Log("DisplayScreenshot coroutine started");

        // Load the screenshot into a Texture2D asynchronously
        yield return LoadTextureAsync(imagePath);

        screenshotPanel.gameObject.SetActive(true);
        screenshotPanel.transform.localScale = new Vector3(0, 0, 0);
        screenshotPanel.transform.DOScale(new Vector3(1, 1, 1), 1f).SetEase(Ease.OutBack).SetUpdate(true);

        Debug.Log("DisplayScreenshot coroutine finished");
    }

    public void ExitScreenshot()
    {
        screenshotPanel.transform.DOScale(0, .3f).SetEase(Ease.InBack).SetUpdate(true).OnComplete(() => {
            screenshotPanel.gameObject.SetActive(false);
            PauseHandler.ableToPause = true;
            Time.timeScale = 1f;
            ableToSS = true;
        });
    }
}
regal lava
#

Are you calling ExitScreenshot() at all in between SS?

mellow sail
#

not its for a button

regal lava
#

It's changing the timescale to 0 which is interesting

mellow sail
#

the button supposed to show afte Dsiplay

#

so when in Play Mode and i pressed space, i want the game to pause. Thats why i made it to timescale 0

regal lava
#

Ah, I see

mellow sail
#

even though i removed the scale, it doesnt matter

#

it still shows the previoue picture

#

not the new one, even if i take another picture it stills the same

#

in the directory folder the file is succesfully ovewrite, but somehow when in display it didnt show the same? i dont know if its delayed or not

regal lava
#

Well, you have it working async, so make sure the coroutine is resolving completely

mellow sail
#

so ive tried to not use coroutine, its even funnier, it just keep taking picture for small period of time. Somehow its delayed and not synced with the input from keyboard. I already made a flag for this

mellow sail
#

nevermiind, ive found the solution

#

thank you elder

undone coral
#

this isn't how you load textures in unity from the file system

sly grove
undone coral
#

ChatGPT GPT4 does indeed give the wrong answer if you phrase the issue the way you did

#

also, what exactly is your goal @mellow sail ? there are better ways to get an image that represents the last rendered frame.

mellow sail
# undone coral this isn't how you load textures in unity from the file system

Could you show me the correct way? Actually i already solved it . I still uses the same script but the reason it didnt work out well because it seems after i called Screenshot(), it still try to write the file in the directory but i already called the DisplayScreenshot(). I solve it by adding a yield return new waitforsecods to wait the image to save in the destined path

undone coral
mellow sail
#

Most of it, except the load part

undone coral
#

okay

fickle mango
#

it's from a tutorial, "how to take a screenshot in Unity"

mellow sail
#

Yup

undone coral
#

okay, and why do you need the screenshots?

#

what is your goal

mellow sail
#

For debug perpose and for a presentation on how i achieve screeshot feature that could be save to directory. The real target was to capture in build version not editor, but since i havent found the way for that, this is the closest to achive. Its for demonstatrion purpose in my college

#

The screeshot is a gameplay that player could somehow share one day from the game itself

undone coral
#

okay

sly grove
undone coral
#

it does math on words. you can use it to help overcome a parade of tedious obstacles. you can't use it to query documentation that it wasn't trained on, like the unity docs.

#

the answer it gives in the chat isn't even 100% correct, because it doesn't understand static IEnumerators apparently

#

by the way, if you're turning this in as an assignment, i can tell you now, everybody recognizes ChatGPT's commenting style

#

record a clip is also a different problem. there are actually al lot of APIs for this, such as the ones that are built into iOS that unity exposes.

#

that are far and away the best approach

mellow sail
#

I see, its not for an assignment. I just wanted to share the abilty and brute force my way out using AI hahaha πŸ˜…. I realized its not the best way, but it really does confuse me. Thank you for the help

mellow sail
fickle mango
#

if you are loading from file you can just use this:

#

unless you are using an old hdd or taking huge screenshots it will be instant

undone coral
real blaze
#

hi. anyone knows how to redirect all unity Debug logs to console in Linux? (not headless. normal windowed build)

#

i've used this but it doesn't work

public static class RedirectToStdout
{
#if LOG_STDOUT
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    private static void StartRedirectToStdout()
    {
        Application.logMessageReceived += Application_logMessageReceived;
        Application.logMessageReceivedThreaded += Application_logMessageReceived;
    }
#endif
    private static void Application_logMessageReceived(string condition, string stackTrace, LogType type)
    {
        switch (type)
        {
            case LogType.Error:
            case LogType.Assert:
            case LogType.Exception:
                using (new ConsoleForegroundColor(System.ConsoleColor.Red))
                    Console.WriteLine($"{condition}\n{stackTrace}");
                break;
            case LogType.Warning:
                using (new ConsoleForegroundColor(System.ConsoleColor.Yellow))
                    Console.WriteLine($"{condition}\n{stackTrace}");
                break;
            case LogType.Log:
                Console.WriteLine($"{condition}\n{stackTrace}");
                break;
        }
    }
}```
#

(ignore the using lines)

real blaze
sly grove
#

isn't it &1 or something

real blaze
#

thanks . that's a good lead, will look it up

#

ok didn't find the stdout file handle (was above my grade), but I found out in Linux there's tail -f command, so
myUnityGame -logFile ~/log | tail -f ~/log (be sure to touch ~/log for the first run)

sly grove
#

well yeah that's the roundabout way

undone coral
#

does this make sense?

#

if you double click on the game in Ubuntu, i'm not sure if it attaches a tty to the process it does not attach a tty, so -logFile - would be meaningless, i.e. standard out doesn't go anywhere

undone coral
#

./myUnityGame -logFile - is what you should use

real blaze
#

I still don't understand why Console.WriteLine doesn't work though. that's odd (building with mono)

undone coral
real blaze
#

but well, that doesn't matter now anyway, because -logFile - works fine

muted pilot
#

hi, i have a very unique problem which i don't understand why it happens, i have two scenes login and game scene which the player go back and forth between them

#

i have a list which i add items to in game scene, it works fine when i login and open game scene and add items to that list

#

but when i go back to the previous scene and open game scene again it duplicated the atem in the list, it adds to it twice

sly grove
#

Sounds like you have data persisting between scenes, due either to static variables or DDOL objects

muted pilot
#

i think it has some proble with loading scene or the scene is loaded twice

sly grove
#

When you use such things, you are responsible for managing your data yourself

muted pilot
sly grove
#

then you're adding twice

#

without further details I'm not sure what else you want me to say

#

You have some state hanging over from a previous scene

#

either a static variable, a DDOL object, an event subscription you never unsubscribed from, etc..

#

as mentioned already

muted pilot
#

i start the game for the first time, i go to game scene and add item to the list it only adds one ( no duplicates ) then i go back to login and open game scene again, it adds duplicate

sly grove
#

You said that already

sly grove
#

Without seeing your code etc. it's not possible to be more specific

muted pilot