#archived-code-general

1 messages · Page 319 of 1

vapid lynx
#

oh burh 😭

heady iris
#

I don't know what rotation will result

#

although I also don't know what "doesnt work" means

vapid lynx
#

it just goes into the mesh ☠️

heady iris
#

yeah, switch the rotations

vapid lynx
#

al

heady iris
#

oh, and

vapid lynx
#

alr

heady iris
#

you don't want -surfaceNormal

#

that would, indeed, send you flying directly into the object

#

the normal points out

opaque forge
#

what do you mean? I can't rotate it before instantiating it

vapid lynx
heady iris
#

Switching the multiplication order may still affect the result

#

but that wasn't making it go entirely backwards, I don't think

edgy stump
#

Anyone????

sleek bough
#

@edgy stump Don't spam, and this is not a code question

vapid lynx
#

@heady iris

edgy stump
sleek bough
edgy stump
heady iris
vapid lynx
#

idk this the code my teammate wrote so im not really sure 100% how it works 😭

heady iris
#

RotateRocket is running after AvoidObstacles

#

that is not helping

#

i think you need to compute a single "goal" vector and rotate towards that

#

always try to go towards the player

#

then turn away from obstacles

#

also, a few Debug.DrawLines would help to visuzlize what's going on

vapid lynx
#

I tried doing Debug.DrawRay

#

and i coudlnt see the rays

#

so i gave up

#

wait

heady iris
#

DrawRay would be appropriate here.

#

DrawLine draws a line between A and B

#

DrawRay draws a line from A to A + B

vapid lynx
#

like that?

heady iris
#

this would draw a line that lasts for 10,000 seconds

#

but yes, that's otherwise reasonable

#

If this runs every frame, either pass nothing (so it lasts one frame) or a small number (so you see a few lines)

vapid lynx
#

uhh 😭

#

oh wait

naive swallow
#

Depending on scale, you might need to zoom in? It's only 1 unit long, I have no idea how big this missile is. If it's not there, then either this code isn't running or the script it's on isn't actually here

heady iris
#

you also need to have gizmos enabled

vapid lynx
#

OH

robust elk
#

To those with experience, if you have a script that let you pickup an object, and show a ui when you hover over it، and an method that let you pick it up, so would you use unity eventa to run this method or run directly inside the code??

brisk knot
#

Hey everyone! I've been working on creating a volleyball game with ML-Agents, and I'm making some progress. Right now, I can control the agents manually using heuristics, but I'm having trouble getting them to move autonomously. Any assistance or advice would be greatly appreciated!

leaden ice
shrewd fog
#

what is the best alternative ? use a list<myStruct> and use a field in the struct as index to keep track when adding / removing item from the list ?

leaden ice
#

What's the best alternative for what to achieve what?

#

What are you trying to do

shrewd fog
#

true .. no context sorry

livid loom
#

I have Question why is this returning every enemy in the scene for some reason?

Collider[] colliders = Physics.OverlapSphere(transform.position, range, 1<<LayerMask.NameToLayer(Tags.enemy));

leaden ice
livid loom
#

I copied from prototype and it was working now it's not?

winged hare
#

Hey, I'm using unity's latest input system and I want to add an event in the dropdown from another gameobject using only code, since the gameObject the input component is attatched to is a prefab

tried to illustrate it better in the image above

leaden ice
#

what behavior are you expecting

livid loom
leaden ice
leaden ice
#

Remember we have no context about how your game works or how things are supposed to work in your code

livid loom
leaden ice
#

if it's returning every enemy in the scene they must all be in that range

#

Did you check what range you're using?

livid loom
#

yeah 5 m

leaden ice
#

perhaps range is not what you expect or perhaps your enemies are not where you expect

livid loom
#

even have gizmo

leaden ice
#

So how do you know it's "returning every enemy in the scene"? How did you verify that?

#

It's time to do some debugging

leaden ice
#

Did you log it?

livid loom
#

yeah course

leaden ice
#

So if you've done some logging etc please share what you logged and what the results were

#

So we can all get up to speed

livid loom
#

the tower at the beggining of teh level is shooting at a target from far away even thoug it's like 20 m away and the racast is giving enemies of 8 total enemies on hte field is 8

#

its copied and pasted code from prototype project that it was working fully

leaden ice
#

You are really stunlocked on this idea that you copied the code from somewhere

#

it's not really important

#

you have to debug it

#

Something is set up differently now

#

we will find it through debugging

livid loom
#

number of enemies spawned = X and Raycast return the same number always

leaden ice
#

Again how do you know? Can you please show log statements you tried and what they're printing.

#

in the context of the full script ideally

cold parrot
livid loom
#

its about 500 lines of code al interwoven

leaden ice
#

that's nothing

livid loom
#

or more

leaden ice
#

share it

#

!code

tawny elkBOT
livid loom
#

Solved

#

nevermind

leaden ice
#

My guess is range was set wrong in the inspector

livid loom
#

Sometimes just talking about points it out lol and no

#

I would not make that mistake just lines switched up

#

plus i have visual for range i would know fast also everythng is debugged and fail safed anyway

#

I run eveything in editor as well i have code written for testing things in the editor

#

WHqy id on't share code it's my secret sauce to fast production

leaden ice
#

Sure but you have to recognize it's hard to help with a problem if we're going in blind

cold parrot
#

do you even want to help in cooking a secret sauce?

naive swallow
#

even then, this is Unity. Your code is pretty much plainly available with every build you make

rigid island
#

bro writing Nasa code

livid loom
#
#

Made few games and yeah how I have built in safety systems that run in the editor essentially idiot proofed and i have to never add any compnent into any object i wrote code to do it all based on classes I assign to objects. I never have to hit play to test any code I hit run in edit and it works!

cold parrot
livid loom
#

ok you are not getting it out of me

#

ok whatever moving on now going back to work here

cold parrot
#

i wonder what toy problems you are working on that this statement can even be close to the truth

rigid island
rigid island
livid loom
#

yeah i rea that book 20 years ago

#

read that book 20 years ago

#

almost 20 now

rigid island
#

pretty sure most of the folks here would have 0 use for your code lol

#

anyway just weird asking help in a code channel then not share code..

hard viper
#

tbf, I am going to take his code for VectorList.cs, and make a fortune licensing it out to people for $10/mo subscription fee, to access the .cs file

livid loom
#

ok cool why are we arguing and being toxic I don't wan't to give away the gameplay more then anything that is a seret new game idea never done before, I described my whoe system im sure good programmer already fiured out how I did it anyway.

#

its the idea I am protecting till its copyrighted

rigid island
#

ideas dont get copyrighted

#

what you imply is patent

hard viper
#

you can’t patent ideas either

rigid island
#

exactly just something that does something

hard viper
#

patent = description of how to do/make something technical

livid loom
#

yeah people can beat you too it and spend more on advertising andsell more copies though

#

lol really

#

this is hilarious I am having a blast watcing you guys feed on yourselves lol

hard viper
#

we’d love to talk about your code

#

oh wait 🤡

livid loom
#

I have hd tons of interest in it already with limited info and a screenshot

#

till next weekend when early access gets released

rigid island
#

cool goodluck with that then

hard viper
#

what you describe is like going to a mechanic, describing your problems, and demanding he solve them without being allowed to inspect your car

livid loom
#

its dealth with its fixed lol

#

it was lines being switched I made tiny typing mistake when i was adding features

rigid island
#

no need to continue this

livid loom
#

exactly i make atypo everyone rips me a new a butthole

hard viper
#

so… something we’d only know… if we saw the code? 🤡

livid loom
#

cool why do you need to see it it's fixed

cold parrot
hard viper
#

truth

livid loom
#

great I love my attitude optimistic helpful caring loving adventerous experimental

#

People are reading into much into they are projecting

hard viper
#

he’s like a goldmine of entertainment

livid loom
#

yah it's called having boisterous happy personality

#

that is how depressed the world is anyone is happy and content they jump all over them lol

#

sitting here working on games jamming deathcore I am in really good mood and happy

cold parrot
#

you're not content, you're here bragging about how amazing you are, so we wonder why that is

livid loom
#

no i am not I just said i have systems in place to minize errors

#

what is everyne else in game design doing same thing

shrewd fog
livid loom
#

I learn by watching and learning from John Carmack and John Romaro I watch them work on games live

livid loom
#

I prefer stuff over other things therfore i think I am great I can smell who is under 25 here lol

rigid island
teal delta
#

man this guy keeps on giving isn't he

shrewd fog
livid loom
#

John Romaro just made one and John Carmack still is the manager of ID software and still codes and for Bethesda as well now they had amerge like a while ago.

teal delta
livid loom
#

We talking now lol

#

what?

shrewd fog
#

im lost, bye

knotty sun
rigid island
teal delta
livid loom
#

Yeah only eople under 25 get mad because you don't do things theirway or schizophrenics which my mom has

teal delta
#

what

rigid island
#

should probably get off the #offtopic

shrewd fog
#

I think he have an issue with his mum and most likely some mental issue too.

teal delta
#

yeah like. this started with code problem and now somehow changed to schizophrenics

knotty sun
livid loom
#

sorry keyboard is old and I have problems with dry skins which get into the keyboard I am buying new one in like aweek

#

how?

rigid island
#

kid is probably 12, failing to troll. Just move on

livid loom
#

im 39

hard viper
#

just block and move on with your life

teal delta
#

good for you i guess

knotty sun
livid loom
#

we talking why are you guys acting 12 I asked for help then I said nevermind I solved it and dropped it

rigid island
shrewd fog
hard viper
#

i believe it has come time to ping <@&502884371011731486>

livid loom
#

go ahead

hard viper
#

it was time to do that a while back tbh

livid loom
#

I said nothing rude or off topic

#

we talking about coding techiniques

vagrant blade
#

Please move on, if you have a question ask it, if you solved your issue then don't post.

livid loom
#

I am always looking to learn!!!

#

I was not the one starting it I asked I solved it I said nevermind I solved they jumped on me for solving my own problem

vagrant blade
#

Again, move on. That includes you and everyone. I'm not going to dig into the whos and whats.

livid loom
#

ok fair enough thank you!!!

hard viper
#

Closing note: I know people have reservations against pinging mods because it can be obnoxious, but we also shouldn’t wait so long to ping them when we actually need them.

shrewd fog
#

@cold parrot so basically I should just use ENUM for finite value such as traffic light ( red / green, orange ) or direction ( north , east, etc .. )

cold parrot
hard viper
#

enums are a way of encoding category information, but really as an integer

rigid island
cold parrot
hard viper
#

traffic light, and cardinal directions are both great times for enums

shrewd fog
#

thank you both

hard viper
#

you can change enums all the time. it effectively ties a “category” to a number

cold parrot
#

generally dont use enums for things that are subject to design changes

hard viper
#

the definition of the enum should not change

eager yacht
#

Just be wary about removing an enum value from the middle if they aren't assigned explicit values, as it will shift everything after it

hard viper
#

instances of the enum can change

#

like if you have public enum Cardinal { North, South, East, West }, and you start coding around that, then it is going to be awkward if you later add NorthWest etc in

#

because you may have done numerical calculations that depended on how the enum was structured before

cold parrot
#

but those should also not be type-objects

shrewd fog
#

ho yeah .. it happened 😄

cold parrot
latent latch
#

worst part is unity's serialization when changing enums

#

make sure you always have value gaps

shrewd fog
#

ho yeah I read about that , like use 10 100 1000

hard viper
#

it depends on what you do tbh

eager yacht
cold parrot
latent latch
#

my flag enums are always changing :)

cold parrot
#

instead of messing around with serialization workarounds

hard viper
#

and then it is awkward

cold parrot
#

flag enums in the wrong hands are also evil

hard viper
#

flag enums effectively assign each “category” to a specific binary digit

hard viper
#

so 0001 being north, and 0010 being west, then 0011 would be northwest

cold parrot
#

yeah, but some people like to use flags for things that arent masks, and thats wrong

latent latch
#

I use them sometimes just to prevent users from selecting multiples of the same entry of the enum

cold parrot
#

just like people like to use interface default implementations to get some cursed form of multiple inheritance

hard viper
#

if you define an enum like that with powers of 2, it is effectively a mask: one number that actually encodes a crapton of booleans, that can be separately true/false

#

(i’m trying to use more simple language on purpose)

shrewd fog
#

thanks for the explanation

cold parrot
hard viper
#

if I had public enum PowerupState { SmallMario, SuperMario, FireFlower}, you wouldn’t want this to be a flag enum, because it doesn’t make sense to have SmallFireFlower mario

hard viper
heady iris
#

flag enums are funny because you can have valid enum values that are not part of the enum declaration

#

scary

hard viper
#

I strongly recommend you become familiar with the Enum class in the System namespace. It has many tools to know about what is defined in your enum

#

such as Enum.IsDefined, which tells you if a given number actually has a named definition in a given enum type

#

(which you can use to know if you fucked up)

#

or Enum.GetValues, which goes and grabs all defined values for your enum, which is good if you plan on your enum to get more values in future

cold parrot
hard viper
#

that’s just awkward

hard viper
#

and cursed

heady iris
#

i've wound up using scriptable objects in place of enums in many places

hard viper
#

you should use both

heady iris
#

sometimes they're literally empty

hard viper
#

do not fear them. just know them, and use them well

heady iris
#

just a "key"

hard viper
#

and don’t use enums when it’s an ass-backwards solution to your problem

cold parrot
heady iris
#

i guess you could do a flags enum with less than, greater than, and equal

#

all eight combinations are meaningful

cold parrot
#

yes, but thats still silly

heady iris
#

It's too clever for its own good

cold parrot
#

just extra brainwork to read

#

also whats Greater || Less supposed to mean?

#

basically never

heady iris
#

not equal!

#

it's "or", not "and"; otherwise Less | Equal would also be useless

hard viper
#

you might need an enum to get out a categorical result from a function

cold parrot
#

yes, but thats just silly to read

#

like you're trying to make a riddle

hard viper
#

i have one function that gives an enum, like data state. Which is like “Good”, then separate enum values for different types of failures. I forget

#

it was a pretty specific scenario. not a normal situation

cold parrot
heady iris
#

NOTE: Here comes the weird part of the article. This is where I pull out the black magic

hard viper
#

bitmasks are really good when you need to go fast

heady iris
#

lol

hard viper
#

when you need to do a specific sort of thing a fuckload of times, bitmasks are good

cold parrot
heady iris
#

i just wish there was a nicer way to interact with bitmasks. i wonder if you could write some extension methods for integers

hard viper
#

my whole game uses a flag enum Cardinal to do rotations, collisions, logic, etc. Literally everywhere many thousands of times per frame. The bit math helps a lot

cold parrot
#

if you like to juggle bits your co-programmers will hate you

hard viper
#

i already hate myself

#

i fear nothing

livid loom
#

Yeah me neither I fear nothing lol

knotty sun
livid loom
#

IM sitting and learning right now

knotty sun
hard viper
#

we need an emoji of a dog being hit with a squirt bottle of water

cold parrot
#

what can you do, post C nobody is touching bits anymore

heady iris
#

you can take 10 minutes to explain it to them

livid loom
#

yeah is Unity LayerMask system bitmask or am I wrong on that

heady iris
#

LayerMask is a bitmask, yes

cold parrot
#

explaining is just words out of your mouth that will collide with a wall that does not care

knotty sun
hard viper
#

LayerMask is a type that is a bitmask, where each bit corresponds to a different collision layer

cold parrot
livid loom
#

so why use it, seems well not user friendly at all and unstable right. Becasue trying to use it is a pain in the butt. seems easier and faster to just sort a list or order an array

hard viper
#

bitshifting can do some things pretty smoothly

heady iris
cold parrot
#

also bitmasks are just the peak of the iceberg

heady iris
#

if every single thing in your game has a layer mask on it, you'd rather not have hundreds or thousands of extra arrays or lists floating around

knotty sun
hard viper
#

like, the cardinal enum i was talking about earlier? If you want to rotate, that is just a bitshift

cold parrot
#

there is so much black magic in the bits of ints and floats

hard viper
#

i don’t need to do all this shit about moving north to west and west to south etc

cold parrot
#

like the fast sqrt is just a bit-shift trick

hard viper
#

whenever I do bitmath, i comment the shit out of it

knotty sun
hard viper
#

because otherwise you won’t know where bits currently are, or what you are doing

livid loom
#

Yeah I keep list small or one list of all enemies in the game got a better solution though? Dictionaries seem even more insane to use resource wise right.

hard viper
#

dictionaries require lookup, and management, and the ability to access etc. But in some cases, you can just bitshift

#

a bitshift is rarely the right tool, but when it is, it is the best tool by a lot

livid loom
#

ok

naive swallow
hard viper
#

for every single collision check

#

which is O(n^2) checks where n is the number of colliders

#

or rather, n * m, where m is the number of colliders near a given collider

#

so if you put 1000 objects in a ball, that is 1M checks

#

per frame

#

without a bitmask, it would be O(layer count * total colliders * neighbor count)

dusk apex
hard viper
#

my general rule of thumb is that bitmath requires at least one comment per line.

#

because bitmath is notoriously hard to read

knotty sun
hard viper
#

legibility is important for long term maintainance for any coding project

knotty sun
#

yes, and how often have you made a game and done any maintenance on it what so ever?

hard viper
#

literally every bug fix

#

literally every time you have to go to an old class and add a feature

knotty sun
#

after release?

hard viper
#

dude, do you even code? this is like, beginner level shit

knotty sun
#

Child I was programming before your parents were born

hard viper
#

this is the sort of commentary i’d expect from someone who’s never worked on a codebase for longer than a college semester

#

then act like it

knotty sun
#

How many games have you made and released?

naive swallow
#

Seems like this channel just woke up and chose violence today

eager yacht
#

Useful book full of bit stuff and black magic math

heady iris
#

it's only magic until you understand it (:

eager yacht
#

learns fireball
understands fireball
now I just have a really hot hand :(

hard viper
#

the better you get at casting fireball, the better you get at not hitting things with it

rocky basalt
#

anyone dealt with Microphone permissions on Android/Oculus? For some reason the microphone input never works on the first run of the app after permissions is granted. It works fine from the 2nd onwards. Not sure why. It's the Unity microphone class btw

heady iris
#

i'd guess you need to "re-initialize" something after the permission is granted

#

but i don't see anything like that

rocky basalt
#

me neither... the place I call Microphone.Start()/End() is totally separate from the permission granting section

mellow sigil
#

That's what usually causes problems like that (not waiting for the player to grant permissions before trying to use them)

rocky basalt
#

hmm after more googling i'm guesing it's a specific quirk w/ the oculus/meta quest runtime.. i'll dig into it more

livid loom
#

Ok, I have been getting this error a lot lately what am I doing never seen it before last month thanks, and now I get it 3 times a day?

somber nacelle
#

it's an editor error. clear it and move on

leaden ice
#

Report it as a bug!

livid loom
#

ok well it's annoying thanks seems to be the only answer yeah I did a long time ago I was hoping for a fix or at least when it can be fixed window

naive swallow
#

Pretty sure that was fixed in a newer Unity version unless it came back in 6

somber nacelle
#

i haven't seen it in 6 (yet), but i have seen it in pretty much every other version i've ever used 🤷‍♂️

livid loom
#

I am in 5 still

#

ok makes sense thanks 6 is out already don't you have to pay for it now?

#

not that i am going to upgrade mid project but next one for sure

somber nacelle
#

why are you using unity 5? 🤔

livid loom
#

because 6 is not out yet not unless it just released

somber nacelle
#

5 is also 9 years old

heady iris
#

unity switched to being named after the release year a while back

somber nacelle
#

are you sure you aren't using like 2022 or something?

heady iris
#

they are going back to sequential numbers

livid loom
#

unity 6 is being released 2024 summer

somber nacelle
#

it's just not the LTS version yet

heady iris
#

much like 2023.2.x was a tech stream release

#

i'm thiiiinking about upgrading from 2023.2.20f1

eager yacht
#

I'm still on 2022.3 CH_DogDance

livid loom
#

yeah preview I just won't till I start a new project after full release I will play in it do little things in it till its fully done and released then I will create new project based on that, which I have a project i want to use for that a Tim Burton-esque world.

heady iris
#

one reason for switching back to plain numbers is to make it more obvious which versions are LTS vs. Tech Stream, I imagine

somber nacelle
#

it also allows them to stagger releases more than they have been recently, so they could potentially do releases every other year or every few years

heady iris
#

yeah

#

tying yourself to yearly releases means you're just Shipping Stuff

#

(or, conversely, Not Shipping Stuff)

heady iris
#

I tested that my project behaves properly in the 6 Preview, but I think I'll give it a few weeks

somber nacelle
#

oh god, i was going to lament the fact that unity 6 isn't including the .net modernization (which yeah, i'm still super bummed about), but i went to the forum post about it and josh peterson has left unity why

heady iris
eager yacht
heady iris
#

and maybe a few itty bitty breaking changes

#

(please throw out the goddamn rigidbody property)

eager yacht
#

Didn't they remove a few of those

#

Or were some just made obsolete

somber nacelle
#

it really would have. i understand why they didnt do it that way, there's still quite a bit of work left on that project, but it definitely would have been a refreshing change to the engine with the new pricing model, naming change, and .net modernization all in one

heady iris
#

they still exist as obsolete properties

somber nacelle
#

iirc those should be removed Eventually™️

heady iris
eager yacht
#

Not having readonly record structs in Unity constantly makes me sad

heady iris
#

i keep poking at record and then realizing i can't do anything cool with it in this version of C#

naive swallow
heady iris
#

it sure FEELS like summer right now

livid loom
#

yeah I guess technically I do live in Canada though and spring getting later and later every year, we just got trees budding leaves. Also, Easter just passed like 2 weeks ago.

#

we had rain in the middle of winter right near the north pole as well super weird

#

If Iived BC less weird it rains all winter long there in the Prairies no never it's usually snowing week of Christmas not raining lol

hollow hound
#

How can I calculate WaitForSeconds time margin?
Simple example:

    float duration;
    
    void Update()
    {
      duration += Time.deltaTime;
    }

    IEnumerator Test()
    {
      duration = 0;
      for (;;)
      {
        yield return new WaitForSeconds(1);
        Debug.Log($"duration before = {duration}");
        duration -= Time.deltaTime;
        Debug.Log($"duration after = {duration}");
      }
    }

I expect duration after = 1, but got less (screenshot below).
I believe it's because
on the frame n time is 0.98
on the frame n+1 time is 1.02
So deltaTime is .4 not .2.
And I need to find this .2 margin

naive swallow
#

Meanwhile, you're adding 1 frame to duration every frame

hollow hound
#

I'm waiting 1.014666 before next code execution, and want to fix the duration by this 0.014666

rigid island
naive swallow
#

deltaTime is not going to be the same every frame

#

Also yes, what is the use case here

hollow hound
rigid island
#

to do what with ?

naive swallow
#

Time between render frames in a game literally does not exist

hollow hound
#

Ok, thanks

thick terrace
#

yeah even if you pass in exactly 1.0 - nextDeltaTime, WaitForSeconds is only an instruction telling unity to resume on the next frame after that amount of time has elapsed, which might be any amount of time later

leaden ice
naive swallow
#

It basically keeps an internal timer like the one you put in Update, and when it is over 1, it continues. So, what you're doing is just getting the value that internal timer was last frame, which would be just a smidge below 1

leaden ice
#

just don't use WaitForSeconds at all if you want accurate periodic timing

#

(works in Update too)

heady iris
#

You can still use it as long as you properly track how much time has passed

#

you just can't keep doing yield return new WaitForSeconds(0.1f) -- the errors will pile up

#

yield return new WaitForSeconds(delayTime), where delayTime gets calculated in each iteration of the loop, works pretty darn well

indigo verge
#

So, I'm working on a modular Finite State Machine and am currently designing the base abstract classes.

Currently, how it's set up is that there is a StateController, which holds a list of States, and those States have a list of Actions, an OnEnter, OnUpdate, and OnExit method.

Assuming each frame, a State runs all Actions in its list during OnUpdate, should I use classes that inheret from Action to handle OnEnter and OnExit actions, or should each Action have its own OnEnter and OnExit behavior packaged with it?

heady iris
#

presumably you have a List<Action>

#

If there is no abstract base Action type (or an interface, I guess), you would not be able to store a list of actions

#

you'd have to have a List<FooAction> and a List<BarAction> and so forth

indigo verge
#

In the latter case, each Action asset (which derives from the abstract BaseAction) could have an UpdateAct, ExitAct, and EnterAct method associated with it.

#

In the former case, each Action asset would only have an Act method, and I would make EnterAction, ExitAction, and UpdateAction as seperate classes that derive from BaseAction.

#

But I'm unsure which is more common or expected.

heady iris
#

Ah, I see. I thought you were saying you wouldn't have any inheritance at all!

indigo verge
#

No, I'm def using inheretance. Right now, I have the Abstract Classes for BaseStateController, BaseState, and BaseAction

#

and I'll be using those as foundations for the derived classes that will actually implement unique properties and behaviors.

heady iris
#

The latter is aesthetically pleasing..

#

but I'm wondering if you will need to have actions that know when they start and end

#

suppose you have a state that wants to display some particle effects

#

I guess you could have two actions: one on enter, one on exit. Both would refer to the same particle system.

indigo verge
#

Yup, that was my thought as well. I plan on making another class explicitly for holding output data, though, so I think I can jank it either way.

#

so a State might have something like an "Output List" which holds outputs, and Actions would have a variable which determines which entry in the Output List they request, defaulting to the same ID as their index in the Action List.

livid loom
#

Coroutines slow down the system so bad really bad Unity is not true Async system according to jason Weinman of course he would know he is the father of modern games

somber nacelle
#

those are functionally the same, except praetor's accounts for extra frame time

#

Coroutines slow down the system so bad
completely untrue

livid loom
#

ah yeah close enough looks smooth too so meh Ill take it for most things

lean sail
livid loom
#

it's a sentence why do i have to write out in text message full sentences what am I writing a book?

lean sail
#

It's basically ineligible past the first 5 words

livid loom
#

Ah Yeah, is Canadian for Yeah your right, eh is ? meh mean it's ok. there you got some Canadian lingo and venacular!

lean sail
#

Anyways the main point was supposed to be that the sentence is not true, on top of it being difficult to understand

#

If a coroutine is slowing down your system, you've likely started way more than you think

livid loom
#

That's the problem with them exactly I can find Jason Weinman video and link it.

somber nacelle
#

i tested it in september and the difference in performance between Update and a coroutine doing the same thing was so minor that it is literally not even worth thinking about in any capacity #💻┃code-beginner message

livid loom
#

Yeah, becsuse you are more right then Jason Weinman lol that is funny and huge ego so you guys I here are better then the best lol I'll stick to learning from guys who built good popular games that run like butter.

somber nacelle
#

jason weimann, while fairly knowledgeable, is not infallible. and has some fairly strong opinions about things that don't actually matter

latent latch
#

coroutines create garbage though which is the takeaway

#

which is where unitask picks up

somber nacelle
#

but that is easily mitigated. and usually it's a one time cost if you aren't generating any garbage within it

#

and the performance impact of garbage generation comes from when the GC runs, so a long running coroutine won't really suffer from that

livid loom
#

Yes, thanks exactly also running more then one at a time bogs the whole system down can't use coroutines on 100's of objects all at once. It's good for one instance running it and need precision/ Pretty sure that is it's intended use.

waxen blade
#
        for (int i = 0; i < foos.Length; i++)
        {
                bar(i).foo = foos[i];
        }

The (i) after bar is what I have wrong, but not sure what the solution is.

I have 9 bar classes. bar1, bar2, etc. How do I make this for loop put the number into the name of the class so I can set all 9 of them using the for loop?

latent latch
#

true, you could always pool coroutines too if you wanted to

somber nacelle
somber nacelle
livid loom
#

Link to a game then please and thanks and lets test this, because 80% of Unity games I play run like garbage.

somber nacelle
#

mate, i linked you to an actual benchmark test that showed the performance was almost exactly the same

latent latch
#

my crappy tower defense game has some stacking effect feature with (poison, burning) and im pretty sure I've had like 20k coroutines running at a point

livid loom
#

How many of each are you running one or more because one your right more then one it's a no way it's running smooth. Because I got a game running 100's of projectiles on the screen with explosions a really flashy game I get 120 fps on a system that is old as crap.

somber nacelle
#

you aren't going to get accurate results by playing some random ass games because firstly, you won't be able to properly measure what is a coroutine and what is in update. second, you won't actually be able to get any real data from that, as it will mostly just be a measure of your framerate at best which will naturally vary based on what is being done. the test i linked to, which i performed myself was doing the exact same thing in both Update and a coroutine. testing one object and 1000 objects at the same time

somber nacelle
latent latch
#

if you're doing collisional/casting in each of those coroutines it's probably related

lean sail
#

This surely must be a troll

livid loom
#

What makes it made up you will see lol releasing it very soon, taking what I learned in classes at the Library, school, taking extra classes on Unity.

lean sail
#

What games are u even playing that you see it's not running smooth, then decompile it and see that they're running a coroutine 😆

latent latch
#

you can always do a manager type systems that handle similar routines instead of distributing to each gameobject

#

1 update loop vs multiple coroutines

livid loom
#

yeah, I just listen to people who know better objectively. I live in a city where one of the biggest game companies exist and give classes at the Library. Unless Bioware is crap now I guess, and Beamdog, and IronHide, essentailly I live in a city where Video games are life and part of the culture even.

#

I live 5 mins from two of them as well

#

@latent latch Just do what your doing it's fine lol

latent latch
#

wat

somber nacelle
#

no offense, but i think it's clear that in this instance I know better objectively, considering i've provided objective evidence and you've provided conjecture with no verifiable data and guesses at best

vagrant blade
#

Living near smart people doesn't make one smart. You can also just test it objectively and know for yourself.

livid loom
#

Your Objective evidence gets trumped by Programmers with 30 years experience that have consistently made good optimized games.

vagrant blade
livid loom
#

If you can aske them questions and get access to their knowledge first hand it does

#

They have classes at the downtown Library every week every Wenesday

vagrant blade
#

Ok you made your point. You're professionally equipped because you asked professionals some questions. We can move on.

livid loom
#

fine coruotines are amazing I'll shall use them now ok happy

vagrant blade
#

If it keeps you quiet, yes. Thank you.

livid loom
#

You're the best ok

latent latch
#

I mean if we all wanted optimal performance we'd take advantage of compute shader and async but im too lazy for that

livid loom
#

I will stop loving my heroes and now worship you

vagrant blade
#

If the next thing you say on this server isn't productive, you're getting muted.

livid loom
#

I was a productive we discussing the times to use Coroutines and not that was discussion

waxen blade
lucid cape
#

I recently saved over a scene where I deleted my player, there is no way to undo in unity. But before this, I did build the game and was wondering if theres a way to see the object structure and script values attatched?

somber nacelle
#

if that were possible, it would be using decompilation tools that are not allowed to be discussed in this server

lucid cape
#

Shit alright

#

Weird they cant be spoken of, people know they exist

lean sail
#

Are you not using version control also?

somber nacelle
#

discussion of tools that enable piracy and asset stealing just isn't allowed

#

and yeah, if you aren't already using some sort of version control (like git) now is a good time to start

naive swallow
lucid cape
naive swallow
#

!vc

tawny elkBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

naive swallow
#

that was it

lucid cape
lean sail
#

This is partly what it's for. A lot of people go through the same thing, then start using it

lucid cape
#

Yup lmao

#

Spam saving is great until this happens lol

lean sail
#

Tbh you also wouldve not lost much had you used a prefab for the player. Accidentally removing one object from a scene shouldnt result in weeks of lost work

lucid cape
#

I know

indigo verge
#

Is there a thing I can install for Visual Studio to make it compatible with all of Unity's HLSL syntax, for the intellisense stuff?

cosmic rain
#

All the real shader programmers code without intellisense💪

indigo verge
#

Ouch

heady iris
#

i should really figure that out

#

so far i've just written shader code with literally no IDE support

somber nacelle
#

same. where's the bot command to configure your IDE for shaders lol

indigo verge
#

https://hastebin.com/share/bezukuqifo.csharp

I'm having an issue. I want to have things that derive from BaseState, and drag them into the list in inspector, but it's not letting me drag my stuff into it. I tried using SerializeReference, but it's still not recognizing my derived classes

#

Line ten is the list I want to be able to edit.

lean sail
indigo verge
lean sail
indigo verge
swift falcon
#

recently imported a package that has a script that uses

using DrawingImage = System.Drawing.Image;
apparently this isnt compatible with Unity anymore, anyone know how to fix?

hexed pecan
#

Are you trying to Destroy the .transform?

#

Yeah that is a transform. You should add .gameObject

solar thunder
#

Hi, I'm trying to save player data using unity cloud save service by following this doc here: https://docs.unity.com/ugs/manual/cloud-save/manual/tutorials/unity-sdk#Save_Player_File
But I got a problem that the value "Files" in "await CloudSaveService.Instance.Files.Player.SaveAsync("fileName", file);" does not exist, it only call CloudSaveService.Instance.Data
So I want to know if the doc is out of date or something like that? Cause I'm trying to save player data using file but the only thing I able to google is this doc, everything else is using dictionary

mossy snow
merry stream
#

so I'm building out my projectile system right now and am wondering the best route to go to allow for distinct projectiles while keeping the code generalized. right now I have a general projectile monobehavior that gives it basic functionality (piercing, chaining toward nearby enemy, etc) things that all projectiles might need. Then ontop of this, I have a projectile c# class that has a builder to give it damage, capacity to explode, etc. All just data. However, if I want more specific things, such as a projectile that shoots out ice shards on collision it feels weird to pack all of this into a general projectile class. I feel this kinda fits the strategy pattern but i am unsure how to implement it. https://gdl.space/xusuyocaxe.cs https://gdl.space/ukoqedinoy.cs

#

I could also do an inheritance tree, but that feels very unnecessary.

#

perhaps I could create an IProjectile interface that has some functions "OnSpawn" "OnHit" "OnDespawn" and then create different projectile types through that and run that code through my Projectile monobehaviour. Is that basically the strategy pattern?

latent latch
#

effects -> OnInterval, OnExpiration

#

for chaining and piercing I just use bools

#

as they are just common functionality for all projectiles

#
void TriggerAbilityOnExpiration()
{
    if (ability is not PrimaryAbility castableAbility) return;

    HashSet<Guid> id_set = TriggerExclusions(castableAbility.PrimaryAbilitySO);

    foreach (AbilityTriggerOnExpiration trigger in castableAbility.AbilityTriggersOnExpiration)
    {
        GameManager.Instance.AbilityInitializer.Initialize(new(
            new AuxiliaryAbility(trigger.AbilitySO, ability.Caster),
            transform.position,
            id_set));
    }
}
#

You can also just use enums as identifiers but I like making sibling classes for these triggers to hard restrict their type

#

because I've crashed my unity multiple times because of recursional triggers

neon zinc
neon zinc
merry stream
# latent latch I do basically stuff like OnHit, OnExpiration

so i was planning on building the projectile system sort of seperate from my ability system but am now considering maybe integrating them. Right now my abilites just act as payloads for effects which solely change some Stat in some way. For something such as projectiles causing ice shards to spray out, I could define a seperate ability that could be cast as normal from the player position but instead have it be cast from the projectile's position when some conditions are met (hit an enemy)

merry stream
#

everything else is object pooled but projectiles havent caused any lag issues so ive left it for last

latent latch
#

my system I do define if I cast at my location or the enemy location, but the trigger stuff mixes it up and just creates so many more options

#

I handle triggers such that they act from their location without target, so stuff like splash abilities work well for them, and like a barrage of abilities in the general direction

#

otherwise you got options like, do I cast from the hit location or the player location or the enemy location? If the trigger is a expiration trigger, that implies no specific target so now need specific logic for that

merry stream
#

what holds the triggers? the ability?

latent latch
#

Right, my abilities just hold abilities

#

so when it gets to that point in code such that I hit someone -> if there are hit triggers use those now

merry stream
#

and is that a general thing defined for your base ability or specific to an ability that has triggers

latent latch
#

fire ball projectile -> hit anything -> explode aoe at location

latent latch
#

well, I make them into a subclass of ability trigger because of what I mentioned previously that I dont want recursive abilities so I need to know if I am using a primary ability that can trigger

merry stream
#

okay, interesting, thanks

latent latch
#

fireball that procs a fireball that procs a fireball, fun

lean sail
#

is there any easy way to find all lines where I do something like this? specifically the (varname) == null

Character someRandomName;
// later on
if (someRandomName == null)

Im refactoring my Character class now so its not a monobehaviour, and now comparing it to null doesnt make sense. Issue is throughout scripts I named these variables different things. Am i just stuck finding all references and looking through each one?

west lotus
#

Pretty sure you can use RegEx in the search field

#

Im not sure how to construct the regex but it should be possible to capture the var name matching the pattern Character …. ; and then use that to find it in a == null pattern

#

But you need a regex wizard for that and I am not one

lean sail
#

im decent enough at regex to do it, doesnt have to be perfect

west lotus
#

Im 33 and literally call my dad when I need a regex 🤣

lean sail
#

i just go on regex101 and guess until it works on some input lol

west lotus
#

Thats what I do too

lean sail
#

😅 welp that search sent my cpu to 100% somehow, maybe i just scream test this and override the equals operator

#

I realize find all references also just shows me each line i use Character and not where i actually use the variables so that might not even be an option.

chilly surge
#

After you done all the clean up, remove the overload.

teal delta
#

how do I make wheel collider less slippery? At higher speeds steering barelly works, Wheels turn left and right but the car barelly turn

indigo saffron
#

hi, I have a rigidbody on the blue ball, upon colliding with the white balls a few times its shading turns flat and I cant figure out why, I dont change the balls material in any way when it gets hit

#

nvm I had recieve shadows on on that ball which I didnt want

heady iris
#

I'm replacing a GUILayout.VerticalScope with a GUILayout.ScrollViewScope. However, it looks like the scope does not shrink to fit its content, so it always takes up its max height.

scope = new GUILayout.ScrollViewScope(debugState[debug].scrollPosition, GUILayout.MaxHeight(300f), GUILayout.MinHeight(0), GUILayout.ExpandHeight(false));

I tried throwing all of the relevant options at it.

#

I want it to grow vertically until it's 300 pixels tall, then start scrolling

#

I also stuck GUILayout.ExpandHeight(false) on the enclosing scope

#

(which i do not think is relevant, after reading some more)

chilly surge
#

How would I go about getting Microsoft.CodeAnalysis.CSharp.CodeStyle to work in Unity?
There are some very valuable IDEXXXX rules (Add missing cases to switch statement (IDE0010)) which I'd like to become compile errors and block Unity from building.
I've tried the usual of downloading the NuGet package, putting in the dlls and mark them as RoslynAnalyzer, set up .editorconfig, and it doesn't seem to work (no errors are reported in Unity and builds are not blocked). Whereas in a plain C# project, adding the analyzer and setting up .editorconfig would work.
Is there something I'm missing? I'm suspicious of the need of .editorconfig and if it gets picked up by Unity.

heady iris
#

I remember having to configuring something in an omnisharp.json file back when VSCode required you to install the analyzers separately

chilly surge
#

That's not relevant, IDE can pick up and read .editorconfig just fine, but errors showing in IDE is not a strong guarantee comparing to blocking compilation altogether.

heady iris
#

oh, the IDE is getting it, I see

#

you've done all of this

#

I don't think unity cares about .editorconfig

#

I know that I've had to separately configure warnings for Unity

chilly surge
#

Yep, that's what I'm suspicious about.

heady iris
#

in that very mysterious csc.rsp file

#

or was it smcs.rsp...i have both in my project

chilly surge
#

Presumably the analyzer needs to take in .editorconfig for it to know what rules need to be reported as error, and Unity wouldn't normally pass that to the compiler and thus analzyer is not getting it.

heady iris
#

I wonder if you need to put something in here to enable warnings or errors

chilly surge
#

I'm thinking yeah.

#

Need to know what CLI arguments to pass to csc though, and there doesn't seem to be any documentation on this.

heady iris
#

It looks like this is just a list of arguments to pass to the compiler

#

yeah, it's very...opaque

#

searching for it gives you a 5.3 doc page

chilly surge
#

I don't even know if you can configure individual rules via compiler arguments, all I've seen is via .editorconfig.

heady iris
chilly surge
#

Yeah getting IDE to do things is pretty easy, getting Unity to do things on the other hand...

heady iris
#

it looks like the syntax would be -warnaserror:####

#

i'd try doing that with a warning you know already works

#

I'd also try using that "ErrorProne.NET" analyzer mentioned in the instructions

#

since it has clearly worked at some point, at least!

wicked river
#

alright, making a third person controller is acutally pretty hard.

  1. Do you add a focus point and rotate the point so that the camera rotates around it, or
  2. Add cinemachine and have the camera rotate around the focal point??
heady iris
#

Cinemachine has a third person follow component. In my game, I have it follow a "third person root" object, which is an empty object parented to the character.

Normally, I keep the root pointing in the same direction as the character, but I allow it to rotate freely when the character isn't moving.

#

so closer to option 2, but it's not rotating around the "focal point" (that'd be where the camera is looking!)

#

for aiming, it's just matching the rotation of its follow target

#

"Rotate With Follow Target" in CM 3.0; "Same As Follow Target" in CM 2.0

heady iris
chilly surge
# heady iris it looks like the syntax would be `-warnaserror:####`

I created a minimal C# project and build it with dotnet build -v diag to look at the command line arguments, there's a /analyzerconfig:path/to/.editorconfig which I tried to add to csc.rsp but that didn't work.
I tried /warnaserror:IDE0010 and that worked. It's not ideal because now I have to sync them up manually, but eh, I guess it's better than nothing.

heady iris
#

ah, did a forward slash work too?

chilly surge
#

Yeah /switch and -switch both works it seems.

heady iris
#

we do love documentation

#

💥

indigo verge
#

Okay, I've reached my wits end here.

https://hastebin.com/share/yiquqojuxo.csharp

In the following four scripts, (Which are in different C# scripts), I want to take the UIStateHolder, and in the inspector, drag the UIState Monobehavior into the slot which is explicitly for it, but I cannot. I can't figure out what I'm doing wrong.

#

UIState inherets from the abstract BaseState, and UIStateHolder inherets from the abstract StateHolder class, for context. And StateHolder has a default variable which holds a BaseState, so it should let me drag any derived BaseState into it, right?

chilly surge
#

Welp, now that I got it to work in Unity, time to checkout all of Code-style rules and see which ones I want to turn on.

#

Nice.

heady iris
#

You are probably trying to drag a scene reference into the inspector for an asset.

#

This is like trying to reference an in-scene object from a prefab. It does not work.

#

You can drag a BaseState prefab into a StateHolder's state field, though.

indigo verge
heady iris
#

A script asset is not an instance of the component.

#

It's a MonoScript object that doesn't even exist at build time.

indigo verge
#

Okay, well, it won't let me use "new" to create a new instance of it, and it asks me to use AddComponent instead, but I can't use AddComponent for ScriptableObjects?

heady iris
#

yes, because you cannot construct a MonoBehaviour

#

it must be attached to a game object

#

Since BaseState is a MonoBehaviour, you can create prefabs and then Instantiate them as needed

#

If BaseState has no business being a prefab, then just make it a plain old C# class

#

so that it's not a unity object at all

#

Although, at that point, you would need to be able to select which kind of state you want to put in your "StateHolder" scriptable objects

#

which would require [SerializeReference]

indigo verge
#

So basically, all I'm wanting to do is to encapsulate my BaseStates inside a ScriptableObject, then clone them inside my statecontrollers, so each Statecontroller has its own BaseStates, and overwriting variables on those BaseStates does not mutate the original ScriptableObject, which is just a template.

#

So just remove Monobehavior from my BaseState class and it should work for dragging and dropping?

heady iris
#

If you remove MonoBehaviour, it will no longer be a unity object, so you won't be able to drag and drop it anywhere

heady iris
#

Alternatively: if each BaseState is a mono behaviour, you can instantiate them to create copies for your StateController to work with.

#
public void Setup(StateHolder holder) {
  foreach (var state in holder.states) {
    Instantiate(state, transform);
  }
}
#

You would probably want to put the new instances into a list in the state controller.

indigo verge
#

Yeah, I wasn't sure I wanted to Instantiate actual scriptableobjects, because I heard that creates garbage, but it looks like I'll have to.

heady iris
#

instantiating anything creates garbage

#

You should worry more about continuous sources of garbage

#

I've been working to cut how much garbage my AI system allocates per frame

#

But I'm fine with allocations that actually live for a while

#

i'm actually getting my "money's worth" from those

heady iris
indigo verge
#
    public void OnEnable()
    {
        foreach (var state in stateTemplates)
        {
            var _newState = Instantiate(state);

            states.Add(_newState);  
        }

        foreach (var data in dataTemplates)
        {
            var _newData = Instantiate(data);

            datas.Add(_newData);
        }
    }

So something like this should work, if my states and datas are made into ScriptableObjects?

heady iris
#

You could turn BaseState into a ScriptableObject as well. That sounds reasonable.

#

And yes, you'd be able to do that

#

This does make it harder to do references between states, though.

#

(if that is needed)

indigo verge
#

Yeah, that was my original plan, until I ran into the issue of "I want my States to be able to have per-unit variables"

#

And yeah, I have a plan for that.

#

Each State has an associated StateData, and States can modify the StateData in the list of StateDatas inside the StateController

#

or that's my plan at least.

#

so each State's "input" will always be a StateData, but that itself can be modified and abstracted into whatever is needed.

#

so if I have a "wait for UI input" State, it can be set to output the result of the UI input into the next state's StateData.

#

Does that sound reasonable?

lean sail
naive summit
#

Yo guys, im working on my game and ive had this problem with my BiologyScript ( The script that contains all the player's health, hunger et cetera.
And i have this problem on line 91 with the error "Only assigment, call, increment, decrement, await, and new object expressions can be used as a statement.
Could i get some help here is the script. Also for notice Line 91 is the where it says Die; in the two brackets on the if function.

#
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class BiologySystem : MonoBehaviour
{
    public int Hunger;
    public int Thirst;
    public float Health;
    public int HungerReduction;
    public int ThirstReduction;

    void Start()
    {
        StartCoroutine(WaiterHunger());
        StartCoroutine(WaiterThirst());

        Health = 100f;
        Hunger = 100;
        Thirst = 100;
        HungerReduction = 7;
        ThirstReduction = 5;
    }

    // Thirst and Hunger Reduction
    IEnumerator WaiterHunger()
    {
        while (true)
        {
            Hunger -= 1;
            yield return new WaitForSeconds(HungerReduction);

        }
    }

    IEnumerator WaiterThirst()
    {
        while (true)
        {
            Thirst -= 1;
            yield return new WaitForSeconds(ThirstReduction);
        }
    }

    // Thirst and Hunger reduction end 
    // Void Update Start

    void Update()
    {
        // If Conditions
        if (Hunger == 0 || Thirst == 0)
        {
            Health = 0;
        }

        if (Health > 100)
        {
            Health = 100;
        }

        if (Thirst > 100)
        {
            Thirst = 100;
        }

        if (Hunger > 100)
        {
            Hunger = 100;
        }

        if (Input.GetKeyDown(KeyCode.LeftShift))
        {
            HungerReduction = 3;
            ThirstReduction = 2;
        }

        if (Input.GetKeyUp(KeyCode.LeftShift))
        {
            HungerReduction = 7;
            ThirstReduction = 5;
        }

    }

    public void TakeDamage(float amount) 
    {
        Health -= amount;
        if (Health <= 0) 
        {
            Die;
        }
    }

    public void Die() 
    {

    }



}
tawny elkBOT
rigid island
#

ur missing a ()

#

aka "call"

#

you should probably configure your IDE if its not underlined in the code editor

naive summit
rigid island
naive summit
#

Oh

rigid island
#

Integrated development environment

neon zinc
heady iris
#

yes -- calling an enumerator method does nothing, but StartCoroutine will then run it until the first yield statement

#

so this would subtract 1 from hunger before it gets set to 100 in Start

zenith bear
#

I went on unity version control once now I can’t get rid of it, how do I get rid of it?

heady iris
dense estuary
#

I am making text fade in when the player looks at an object, and fade out when the player looks away. But I have a problem where when the player looks for a split second, then looks away, it fades in and doesnt fade out, this causes it to just be permanently visible. This is my script: https://hastebin.com/share/payepofeni.csharp.

turbid lark
#

I'm trying to setup a save/load system, starting with creating a folder to put the saves in with System.IO.Directory.CreateDirectory(), but many folders are read-only, and give an UnauthorizedAccessException

#

Is there a typical way to deal with this?

#

since I've played Unity games that save data, I assume there's some way to save in a folder other than right under C:, but clearly I'm not doing it right

knotty sun
turbid lark
#

thanks, I think this is exactly what I was having a hard time finding

lean sail
#

Those bools also look a bit questionable

#

Storing the coroutines would also avoid those 4 bools you have.

dense estuary
#

Also, the bools are used to detect when the player just started looking at the object, and just stopped looking at the object.

knotty sun
lean sail
calm echo
#

You need to ensure you also set the coroutine to null when it finishes or you stop it.. it doesn’t happen automatically

chilly surge
# dense estuary I am making text fade in when the player looks at an object, and fade out when t...

Since you already have an Update, you can get rid of the entire coroutine fade in and out.
You need to store 4 pieces of information: start time, end time, start color, end color. In Update, simply changes the current color based on those 4 pieces of information.
Remove your old code where you start fade in/out coroutines, and replace them with logic that changes those 4 pieces of information, and that's it.

dense estuary
#

Don't I need coroutines to make the text fade in/out?

vagrant blade
#

No

dense estuary
vagrant blade
#

You can, sure. You don't need to.

chilly surge
#

No, your update can do it without coroutines.

#

(These types of state management is so simple to express in a reactivity system, for example in my project the entire logic can be expressed as:)

Reactive.Time
    // Whenever time changes, check if upgrade is hit
    .Computed(() => Physics.Raycast(...))
    // Whenever upgrade hit status changes, calculate target color
    .Computed(isHit => isHit ? Color.white : Color.clear)
    // Whenever target color changes, calculate current color by tweening
    .Tween(0.25f)
    // Whenever current color changes, set it to text's color
    .Watch(color => text.color = color);
dense estuary
chilly surge
#

That wasn't meant to answer your question, just a side tangent.

dense estuary
#

oh

dense estuary
chilly surge
#

Animation is nothing but a series of changes happening frame by frame.

heady iris
#

coroutines just make it easier to remember variables from frame to frame, without having to create a bunch of fields on your class

heady iris
chilly surge
#

Yeah and all of that logic in mere 5 lines of code, it's so much more powerful and expressive than procedural code.

heady iris
#

I wound up adding "changed" events to all of my settings objects, which has been very convenient

#

basically nothing polls for settings

dense estuary
heady iris
#

Right.

#

You can use current = Mathf.MoveTowards(current, target, Time.deltaTime * rate); to express this in one line.

#

this will make current constantly move towards whatever target is

chilly surge
dense estuary
#

1245 its clear; 1234.125 its half transparent; 1234.25 its white.

chilly surge
#

Good, and there you go, you have a fading animation.

#

Use those 4 information, + the current time, and you can calculate the current color.

heady iris
#

yeah -- there are two ways to think about it:

  • an iterative method, where you use the current value to calculate a new value
  • an explicit method, where you directly calculate the value
heady iris
#
Mathf.Lerp(oldValue, newValue, transitionTime); // where transitionTime goes from 0 to 1 over time

This is explicit.

chilly surge
# heady iris basically nothing polls for settings

Yep, procedural code is typically pull based (I ask you if you have changed so I can do something), whereas reactive code is more push based (you tell me if you have changed so I can do something), and push based makes it so much easier for state related things.

heady iris
#

imagine it takes one second for the text to appear

#

if you briefly mouse over something so that it gets to 10% opacity before losing focus, you want the text to quickly disappear

#

it shouldn't take one second to go from 10% to 0%

#

it should take 0.1 seconds

#

MoveTowards gives you that behavior for free

dense estuary
#

So, something lke this then? ```cs
if (hitUpgrade)
{
float time = 0;
float fadeInTime = 1f;

while (time < fadeInTime)
{
    float alpha = text.color.a;
    alpha = Mathf.Lerp(startColor1.a, endColor1.a, time);
    text.color = new Color(text.color.r, text.color.g, text.color.b, alpha);
}

}```

heady iris
#

this would instantly fade the text in

dense estuary
#

oh right

heady iris
#

this is not a coroutine; you are not yielding anywhere

rigid island
#

also time is untouched

heady iris
#

oh yeah

#

so it just kills your game :p

dense estuary
#

yeah, I forgot to do time += Time.deltaTime;

#

I've got something working ```cs
float fadeTime;
hitUpgrade = Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out RaycastHit hit, 5, layers);
if (hitUpgrade)
{
endAlpha = Color.white.a;
fadeTime = 1f;
}
else {
endAlpha = Color.clear.a;
fadeTime = 0.25f;
}

float alpha = text.color.a;
alpha = Mathf.MoveTowards(alpha, endAlpha, Time.deltaTime * fadeTime);
text.color = new Color(text.color.r, text.color.g, text.color.b, alpha);```

#

I change the fadeTime so I can make the text fade out in more or less time than it takes to fade in.

pulsar elm
#

I feel like this could be made into 1 line (it can be made into 1 line)

#

but I feel like 2 lines would be better but this could be made shoort

#
float endAlpha = Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out RaycastHit hit, 5, layers) ? 1f : 0f;
text.color = new Color(text.color.r, text.color.g, text.color.b, alpha);``` I think this should work (but I wrote it in discord and it utilizes ternary operations)
#

How ternaries work is just "something = condition ? true : false;"

chilly surge
#

They want a fading animation, not just toggle.

pulsar elm
#

I made it into a toggle in order to not flood the chat

#

but a fade is possible with a ternary, it's not just for toggles

dense estuary
pulsar elm
#

Does it fade out pretty much instantly or super slow

dense estuary
#

It stays fully opaque

pulsar elm
#

hmm that's weird

dense estuary
#

Oh wait!

#

It does fade out

pulsar elm
#

just very slowly?

dense estuary
#

Just REALLY slowly

#

I didn't realize that the fadeTime didnt work as seconds.

#

I was hoping to make it take 1 second to fade in, and 0.25 seconds to fade out.

pulsar elm
#

For 1 second you would have to do 0.1*Time.deltaTime i believe for the delta

#

unless that's simply 100ms off of length idk

#

eitherway, if possible you should make long functions into ternaries as it makes it easier to debug (atleast for me)

dense estuary
dense estuary
heady iris
#

no, because you can just change it by a little each frame

dense estuary
#

But how can I make it fade in with seconds?

#

If I want it to take 1 second to fade in. How could I make the transitionTime change from 0 to 1 in 1 second?

heady iris
#

Divide deltaTime by the duration you want

#
Time.deltaTime * rate;
Time.deltaTime / duration;

both of these are valid

#

multiplying by a duration is wrong

dense estuary
#

Is there a way I could use seconds with the explicit method?

pulsar elm
#

Well

heady iris
pulsar elm
#

That's because the interpolation value in the lerp function (which is Time.deltaTime/fadeTime for you) makes it so that the higher the value it is the faster it lerps it and the lower it is the slower it lerps it

heady iris
#

If startAlpha is 0 and endAlpha is 1, this is giving you a value that is very close to startAlpha.

pulsar elm
#

yup

heady iris
#

If startAlpha changes every frame, then it will still move towards endAlpha pretty darn quickly

#

If startAlpha is a constant, then it will just jitter around near startAlpha as Time.deltaTime varies.

#

If you want to use Lerp, the third argument needs to steadily increase from 0 to 1 over time.

#

Of course, that's pretty much what you're trying to do in the first place, isn't it?

pulsar elm
#

so basically put it

pulsar elm
#

if startalpha is 0, endalpha is 1 and your interpolation value is 0.5 then your value that you get is 0.5

dense estuary
#

I know that

pulsar elm
#

if you rather do something like alpha = Mathf.Lerp(alpha, endAlpha, [dynamic value that you change]); then it would still work but it'll take a lot of time to reach 1 fully or 0 fully so MoveTowards is the better way to do it I believe

heady iris
#

I usually wind up doing this:

float targetProgress = visible ? 1 : 0;
fadeProgress = Mathf.MoveTowards(fadeProgress, targetProgress, Mathf.deltaTime / fadeDuration);

I can now use fadeProgress as an argument to Lerp, or SmoothStep, or whatever.

pulsar elm
#

pretty much that

heady iris
#

For example:

text.color = Color.Lerp(new Color(1, 1, 1, 0), new Color(1, 1, 1, 1), fadeProgress);
pulsar elm
#

so literally just float targetProgess = Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out RaycastHit hit, 5, layers) ? 1f : 0f; for you

dawn nebula
#

Are you able to use the IPointerHandler interfaces on regular objects? Or is it limited to UI?

heady iris
#

Ah, you mean non-UI things

#

but still MonoBehaviours/etc

dawn nebula
somber nacelle
#

as long as your camera has a Physics Raycaster and the object has a collider, then the event system interfces do work on world space objects (and obviously an EventSystem in the scene)

heady iris
#

I thought you meant plain old C# objects

#

which would be very weird (:

heady iris
dawn nebula
#

How would unity do that. Where does it think these things are located >_>

heady iris
#

✨magic✨

dawn nebula
#

convert memory locations to 3D space

heady iris
#

a boolean

#

in your case, you would set it to true if the raycast hits the upgrade

#

(so you'd literally just use the return value from Physics.Raycast)

pulsar elm
#

a liittle while ago

heady iris
#

I just used a boolean variable there beacuse it does not matter how you decide if the text is visible

pulsar elm
#

true

dense estuary
#

This code works perfectly. Exactly how I want it to!! ```cs
private void Update()
{
float fadeTime = 1f;
hitUpgrade = Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out RaycastHit hit, 5, layers);
if (hitUpgrade)
{
endAlpha = Color.white.a;
fadeTime = fadeInTime;
}
else {
endAlpha = 0;
fadeTime = fadeOutTime;
}

float targetProgress = hitUpgrade ? 1 : 0;
fadeProgress = Mathf.MoveTowards(fadeProgress, targetProgress, Time.deltaTime / fadeTime);

float alpha = fadeProgress;
text.color = new Color(text.color.r, text.color.g, text.color.b, alpha);

}```

pulsar elm
#

Remove the float alpha line from there and just do text.color = new Color(text.color.r, text.color.g, text.color.b, targetProgress); as it uses less variables meaning ever so slightly less GC and the file gets barely smaller too

heady iris
#

Locals do not produce garbage.

#

Something neat to try: you can add an AnimationCurve to let you control how the fade looks.

[SerializeField] AnimationCurve fadeCurve;

...

float alpha = fadeCurve.Evaluate(fadeProgress);
#

I use this quite a bit.

dense estuary
dense estuary
#

oh wait

#

nvm, I get it

heady iris
#

unity's curve editor makes me kind of sad (i yearn for blender's graph editor)

#

but it's a handy way to reshape the fade effect

#

for example, if you make a curve that goes from [0, 0] to [0.5, 1], then the fade will hit full opacity after half a second

#

and you'll get half a second of lag before it starts fading out when you look away

#

since fadeProgress has to get down to 0.5 before the alpha starts to drop!

old sigil
#

has anyone here had any issues before with when your player uses a key to paint the terrain it gives a weight of 0 instead of anything else?

heady iris
#

i would have to see the code

old sigil
#

basically my grass is indexed at 0 on my texture layers and soil is indexed at 1. it seems grass always has a weight of one regardless if i remove the weight of it and replace it with soil in my script

#

i can manually paint soil in the unity editor and get a weight of 1 but that doesnt really help when i need it to happen on a keybind

compact carbon
#

how would i go about doing a spline, but i can control when the train stops and goes and i want it to gradually gain speed instead of it looking like a snappy thing?

compact carbon
#

yes but how would i move it along the spline whilst adding this motion?

#

because i have tested and if i add force it will not snap to the spline in the slightest it will just fly away

compact carbon
#

ah thank you.

fallen lotus
#

Can anyone give me some advice? I'm making a multiplayer card game for fun as a way to do anything but study for finals (😭).

I need advice on how I should implement this system. I have a Playing Card model I made, which has a front and back texture. I want to make a modular system that allows for each card to have data associated with it. I also have a folder full of textures for each face of every playing card, including the Joker. Then, depending on the card when it is instantiated, I want to assign the corresponding texture to the material of that instance of the playing card. Can someone help me figure out what I should do to make this happen? Let me know just @ me.

ruby nacelle
#

Does anyone know much about object persistance between scenes? I've lost all references of many gameobjects with dontdestroyonload, whats the best practice for finding these for instance a 3 recttransforms in an array or data within an SO?

lean sail
lean sail
fallen lotus
#

cause they are referencing the same material

lean sail
#

Changing it at runtime should be fine

#

When you access the material, it will make an instance of it

fallen lotus
lean sail
#

Yes code, you arent gonna be dragging and dropping it on the users pc

fallen lotus
#

okay i see

lean sail
#

Using prefabs might just be easier here though.

#

Especially since you'll already need some lookup for the textures

fallen lotus
#

like each card with its own material and texture is a prefab?

lean sail
#

Dont think you would need a unique material for every single card

fallen lotus
#

Wait so what do you mean then when you say using prefabs might be easier?

#

cause my plan is to have a prefab that i instantiate changing the values

lean sail
#

Staying with your current way is probably good tbh, ignore the prefab bit.

#

But yea really should just be fine if you change the texture through code, at runtime

fallen lotus
#

what do you think should be attached to each card

#

like a card monobehavior that holds data?

#

and then other scripts can reference and instance of the card, get the component, and then access the coorisponding value?

#

(sorry just trying to talk through how ill do this)

lean sail
# fallen lotus what do you think should be attached to each card

whatever you wish to attach. ideally in this system, you wont need to really GetComponent all that often because you really should just have access to all the cards. You arent getting them through Physics messages for example. Sure, you'll need some script which ideally has some SetupCard method or whatever you wanna name it. Then give it the values and assign the texture

fallen lotus
#

thanks for your help

ripe ember
#

Does anyone know is it possible to connect discord bot with unity. And how if it is. I want to make something that will be started with discord commands

fallen lotus
#

you can have the clients directly submit data (not reccomended as you have to expose things like your bot token to clients) but if you integrate your bot into a backend service such as playfab you can do this

thorn stirrup
#

Can anyone help me understand what are the vectors from the normals on a corner of a box collider?

#

i have a circle collider 2D on my character and when he hits the side of a box collider (i compare the normal to see if its a Vector2.Right) he should snap on.

#

however, sometimes he hits the corner edges

ripe ember
#

only x and y, you can make more checks to avoid corners that's all

thorn stirrup
#

that makes sense

#

what kind of checks do you reckon?

ripe ember
vivid halo
#

How do you guys manage a very complex GO with dozens of scripts on it in the inspector? I'm opting for modularity and development is continuing but it's getting a little tedious to sift through my 20-some scripts attached to my player GO.

wicked scroll
vivid halo
#

I use MVC for my inventory management and it definitely helped, but they almost exclusively interact with one another. PlayerController and PlayerMovement are similar, and isolating the controls from the movement makes the input/output very clear to interact with. *<-- You are free to bring up any points regarding my desgin choice here

My main concern is the inspector becoming vertically burdened / not being able to categorize scripts attached to a GO in the inspector

wicked scroll
#

the scene should be only the VIEW of your MVC architecture and the game itself should exist as C# objects independent of unity (as much as is reasonable, at least)

#

if the 'design time' representation of your entity is independent of the 'runtime' representation of your entity, it matters much less how each of them presents

vivid halo
#

Interesting. I was always curious if there was any significant difference in runtime by changing the design via combine two components into the same script component but keeping the classes separate to help make it extensible

#

I am aiming to avoid spaghetti without overengineering my components, and keeping clear I/O between each component

wicked scroll
vivid halo
#

What is your opinion on using event-based architecture to decouple modules? I read that it is considered generally good practice, but I'm not sure if I'm overcomplicating it needlessly.

Example:

public event Action OnPlayerMoved;

public class PlayerMovement
{
    // The implementation
}

public class AttackHandler
{
    private void OnEnable
    {
        if (TryGetComponent(out PlayerMovement playerMovement))
        {
            CancelAttack += playerMovement.OnPlayerMoved;
        }
    }
    private void OnDisable
    {
        // The inverse of OnEnable
    }
}

loud wharf
#

Hi peps.

#

Is there a way to serialize a value as string of bytes?

vivid halo
#

Great name with IPattable, that's hilarious

vivid halo
#

Converts an object to byte. What else is required?

somber nacelle
#

they want to serialize some value as an array of bytes. not try to get the equivalent byte value of some object

somber nacelle
#

for example, if you were trying to serialize some data to send across a network or something, i'd personally recommend MessagePack which can serialize and encode to a byte array

loud wharf
ruby nacelle
# lean sail Why is your SO referencing a scene object? This isnt about object persistence bu...

It might have been a misunderstanding of persistence on my part. I'm mostly just trying to better understand what can and can't be taken between scenes and if I can grab something like an icon previously assigned in another script. For instance I have an SO functioning as an ability database and I was wondering if when I carry between scenes if I could just use those previously stored variables.

#

I've mostly lost things like object transforms which I was hoping to potentially grab onsceneload again, but even if I do something expensive like fingameobjectwithtag it wasn't working.

lean sail
#

Having an SO reference a specific transform sounds like a bad idea though

waxen spruce
#

I'm using NavMeshSurface.BuildNavMesh(); and its creating a surface that extends beyond the script's parent object (which is terrain) and includes meshes that don't have colliders. I'm struggling to understand what is happening.

#

or even how I could properly share what is wrong

somber nacelle
#

sounds like you need to check the settings on your NavMeshSurface component, and look at the documentation pinned in #🤖┃ai-navigation to learn what those settings do

thorn stirrup
waxen spruce
crimson pelican
#

Can someone link me the latest visual studio code build?

somber nacelle
#

does your google not work? 🤔

crimson pelican
#

Unnecessary Comment but thanks and yeah it does I just wanna make sure I get the latest version because it hasn't been working recently

somber nacelle
#

there's not some secret location to get the latest version. you just get it from the official sources just like everyone else

crimson pelican
#

Ik bro I was just asking you don't gotta be smart about it thanks for the link keep it moving

somber nacelle
#

i mean you should at least try being smart about it next time. you would have gotten your result much faster had you bothered to just type "vs code" into your web browser's search bar

crimson pelican
#

But anyways have a good day

somber nacelle
#

oh fuck off with that. that's such a cop out excuse. "i'm too lazy to do it so i'm going to get someone else to do it then complain when they say i could have done it myself when i definitely could have, but i prefer wasting other people's time instead"

fallen lotus
#

So i have a bunch of card textures that I want to apply to different instances of a card model prefab that gets spawned in
how do you guys reccomend that I handle this
i read something about loading the texture from the resources folder but is there a better way?

rigid island
#

eg you can separate by suit

#

then have different arrays

fallen lotus
#

i think im gonna do the resources trick right now and revisit this system later. im making it modular tho so it shouldnt be a pain

#

just need to do more research

fallen lotus
#

Can anyone tell me why this isnt working?

// Loads the texture
Texture2D cardFaceTexture = Resources.Load<Texture2D>(path);
Material cardMaterial = new(Shader.Find("Universal Render Pipeline/Lit"));
cardMaterial.mainTexture = cardFaceTexture;

Debug.Log("Path to card: " + path);

// Sets the material to the new material
gameObject.GetComponent<MeshRenderer>().materials[1] = cardMaterial;

The path to card prints something like this picture. which is correct.

fallen lotus
somber nacelle
#

you're meant to read it

fallen lotus
#

I did?

#

and im having an issue with my implementation

somber nacelle
#

then surely you see what is wrong with your path

fallen lotus
#

Are you goign to say cause i have .png in it?

somber nacelle
#

yes, absolutely

fallen lotus
#

i took that out and i have the same issue?

somber nacelle
#

Note that the path is case insensitive and must not contain a file extension.

#

show the full path for that asset

fallen lotus
somber nacelle
#

and if you look at the second material for the MeshRenderer you are modifying, does it show that texture on it?

fallen lotus
#

Not on the created instance

somber nacelle
#

what do you see on that MeshRenderer?

fallen lotus
#

for the instantiated object or the prefab that is being copied?

somber nacelle
#

the instantiated object, obviously. the prefab wouldn't have run that code

fallen lotus
somber nacelle
#

and you have the component with this code on it attached to that object?

fallen lotus
#

yup

#

do you know why it isnt?

#

bro doesnt know how to fix the issue but still likes to be a dick in a discord server LMAO 😂

somber nacelle
#

holy shit, what an asshole. i was verifying information to try and help you but now i definitly won't

fallen lotus
#

gn bro

#

get some sleep

somber nacelle
#

lol fuck off. you don't know what the fuck you're doing clearly. you didn't provide enough context so i was trying to get the necessary context from you

lean sail
#

youve shown literally 4 lines of code and a cropped screenshot of the object, not even showing the material itself...
some people just cant be helped

fallen lotus
#

Hahahaha

#

Bro linked the documentation when I asked for clarification on the documentstion

#

Some people just can’t help

somber nacelle
#

yes because the documentation told you why your path was incorrect

#

or did you do it wrong on purpose?

fallen lotus
#

Tip: just say the path is wrong

somber nacelle
#

tip: learn to read

fallen lotus
#

Tip: go outside

somber nacelle
#

this is a unity server mate.

#

probably where ever "finger painter badge" is actually relevant. a quick google search shows it's probably a gorilla tag thing, so go find their discord server

fallen lotus
#

Brooo 💀 💀 💀 😂 😂

somber nacelle
#

<@&502884371011731486> racism

lean sail
#

surprised thats not auto filtered out

somber nacelle
#

and yet that's still racist and against server rules. 👋

lean sail
fallen lotus
#

Okay why bro had have to be racist

quartz folio
#

!ban 1126368364911141034 racism

tawny elkBOT
#

dynoSuccess honest_panda_49009_25434 was banned.

loud wharf
#

Real.

cloud harbor
#

crazy

stark sun
#

I have a character like this. How can I make his arms rotate with my cursor? I had a plan like putting arrows at the end of each arms but dont know how to do. I'm trying to make a system like the game Bloody Bastards if you know.

gray mural
stark sun
gray mural
stark sun
#

what do you mean by have to

gray mural
#

Anyway, to rotate the objects in a direction of the cursor, you'll have to calculate the angle, which then should be applied to the object's z rotation

#

@stark sun
Some time ago I wrote some scripts about this logic, so you can check them out:

    1. [Explanation about rotating different camera types](#💻┃code-beginner message). I don't explain how to rotate the object here, as the person, who asked the question, had already implemented it by themselves. The code provided rotates the object in the direction of the mouse.
    1. Rotate the weapon in the mouse direction. It's a full guide with the explanations and code provided on how to implement it. You only need the 2nd header to make it work.
gray mural
# stark sun thanks

Make sure you simply implement the methods, which rotate the different objects, and apply them to your arms if a certain condition is met in the Update

#

This condition is a key pressed, in your case

torn dome
#

Does anyone know how load a texture from the program files to be shown by a sprite render?

knotty sun
torn dome
#

Found a forum post from what you said. Thanks for the help

knotty sun
torn dome
#

Ok

#

Looking at docs its going from the asset folder but I would like it from the program files (on the C: drive)

#

C:\Program Files

knotty sun
#

Why on earth would you have textures there?