#archived-code-general
1 messages · Page 319 of 1
I don't know what rotation will result
although I also don't know what "doesnt work" means
it just goes into the mesh ☠️
yeah, switch the rotations
al
oh, and
alr
you don't want -surfaceNormal
that would, indeed, send you flying directly into the object
the normal points out
what do you mean? I can't rotate it before instantiating it
oh right
Switching the multiplication order may still affect the result
but that wasn't making it go entirely backwards, I don't think
Anyone????
@edgy stump Don't spam, and this is not a code question
Where do I send a message?
It's a general #💻┃unity-talk question. Also write it properly describing what happened so you can get an informed answer
Idk what properly happened 🥶
show me your current code.
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
lik ethis?
DrawRay would be appropriate here.
DrawLine draws a line between A and B
DrawRay draws a line from A to A + B
Debug.DrawRay(transform.position, transform.forward, Color.red, 10000f);
like that?
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)
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
you also need to have gizmos enabled
OH
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??
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!
hello , is this still relevant for enum ? Thanks
yes
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 ?
Why do you need an alternative?
What's the best alternative for what to achieve what?
What are you trying to do
true .. no context sorry
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));
I guess all of the enemies in the scene are within that range of this object.
BTW to make a layermask you can just do LayerMask.GetMask(Tags.enemy)
I copied from prototype and it was working now it's not?
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
It's unclear what you mean by "not working"?
what behavior are you expecting
yeah it was not working and yeah it's not working still yah you would think it was working in protye of the roject where i was building code why i am confused
myPlayerInput.actions["Player/Pause/Resume"].performed += MyListener;```
Though I wonder if the slash in the name of the action will break it
You still haven't explained what "not working" means
Remember we have no context about how your game works or how things are supposed to work in your code
read my original post it says it's returning every enemy in the scene not in range
Reaqd my original response
if it's returning every enemy in the scene they must all be in that range
Did you check what range you're using?
yeah 5 m
perhaps range is not what you expect or perhaps your enemies are not where you expect
even have gizmo
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
yeah course
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
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
So show what log statements you added and what they printed
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
number of enemies spawned = X and Raycast return the same number always
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
Generally enums that are likely to change should be replaced with type-objects, in unity those can be "empty" ScriptableObjects https://gameprogrammingpatterns.com/type-object.html
its about 500 lines of code al interwoven
that's nothing
or more
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
My guess is range was set wrong in the inspector
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
Sure but you have to recognize it's hard to help with a problem if we're going in blind
do you even want to help in cooking a secret sauce?
If you're specifically asking for help on why it's not working it's unlikely anyone would even want to steal the code
even then, this is Unity. Your code is pretty much plainly available with every build you make
bro writing Nasa code
No it's not using unity code rally i can port to any engine at anytime I use unity as visual interface basically I learned form this book really good one
https://www.google.com/url?q=https://www.amazon.ca/Beginning-NET-Game-Programming-C/dp/1590593197%3Fsource%3Dps-sl-shoppingads-lpcontext%26ref_%3Dfplfs%26psc%3D1%26smid%3DA3DWYIK6Y9EEQB&opi=95576897&sa=U&ved=0ahUKEwjTjdP4zYOGAxU4GjQIHQWnBDkQrzwIFA&usg=AOvVaw2JZcgVmNaoXnkkCfYlR57_
The authors use a very friendly voice, and cite several well-known games as exhibits of the fundamentals they describe throughout the text. /a /p /blockquote p id='quoteAuthor' - Jason Salas, Microsoft MVP, ASP.NET /p /div p This long-awaited title provides a clear introduction to game programmin...
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!
nasa doesn't have secret code 😛
ok you are not getting it out of me
ok whatever moving on now going back to work here
i wonder what toy problems you are working on that this statement can even be close to the truth
I'm picturing some secret air force joint venture department lol
classified
you posted a book about beginning c# so you worry about your code being copied ?
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..
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
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
you can’t patent ideas either
exactly just something that does something
patent = description of how to do/make something technical
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
I have hd tons of interest in it already with limited info and a screenshot
till next weekend when early access gets released
cool goodluck with that then
what you describe is like going to a mechanic, describing your problems, and demanding he solve them without being allowed to inspect your car
its dealth with its fixed lol
it was lines being switched I made tiny typing mistake when i was adding features
no need to continue this
exactly i make atypo everyone rips me a new a butthole
so… something we’d only know… if we saw the code? 🤡
cool why do you need to see it it's fixed
by now people are just entertained by your attitude
truth
great I love my attitude optimistic helpful caring loving adventerous experimental
People are reading into much into they are projecting
he’s like a goldmine of entertainment
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
you're not content, you're here bragging about how amazing you are, so we wonder why that is
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
thanks @cold parrot , @leaden ice , my use case is easy, I work on a editor tool and wanted to use enum as its easy to get the text representation. I will just use scriptable Object, it will be easier to use / extend if needed, safer 🙂
I learn by watching and learning from John Carmack and John Romaro I watch them work on games live
thank you very much for defending me lol I love enum lol
I prefer stuff over other things therfore i think I am great I can smell who is under 25 here lol
when is the last time those two ever had to make a game..
man this guy keeps on giving isn't he
@livid loom ? im sorry i dont follow
really?
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.
he is leonardo dicaprio
im lost, bye
Pretty sure if I expressed my opinion I would get banned
Yes I'm aware of the history, I was probably around before you were a thought.
Still doesn't answer which and what game did they live code..
yeah i know, me too. Just saw a goofy comparison
Yeah only eople under 25 get mad because you don't do things theirway or schizophrenics which my mom has
what
should probably get off the #offtopic
I think he have an issue with his mum and most likely some mental issue too.
yeah like. this started with code problem and now somehow changed to schizophrenics
Sorry, but you are totally deranged
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?
yeah, maybe
kid is probably 12, failing to troll. Just move on
im 39
just block and move on with your life
good for you i guess
maybe 3.9f
we talking why are you guys acting 12 I asked for help then I said nevermind I solved it and dropped it
I'd feel sorry for your mental developmental skill if that were true
thanks , I did not know we can 🙂 ( I mean .. block people)
i believe it has come time to ping <@&502884371011731486>
go ahead
it was time to do that a while back tbh
Please move on, if you have a question ask it, if you solved your issue then don't post.
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
Again, move on. That includes you and everyone. I'm not going to dig into the whos and whats.
ok fair enough thank you!!!
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.
@cold parrot so basically I should just use ENUM for finite value such as traffic light ( red / green, orange ) or direction ( north , east, etc .. )
true, but it was fairly good natured, those usually pinging were all participating, so we could have just stopped on our own
enums are a way of encoding category information, but really as an integer
to be fair both sides doing unecessary back n forth
got it thank you
generally for stuff that you dont expect to change over the course of the life of the component, simple things like operational modes, comparion behaviour, finite number of values (when using flags) etc.
traffic light, and cardinal directions are both great times for enums
thank you both
you can change enums all the time. it effectively ties a “category” to a number
generally dont use enums for things that are subject to design changes
the definition of the enum should not change
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
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
but those should also not be type-objects
ho yeah .. it happened 😄
if bad design breaks, thats intended though 😄
worst part is unity's serialization when changing enums
make sure you always have value gaps
ho yeah I read about that , like use 10 100 1000
it depends on what you do tbh
enum Cardinal {
None = 0,
North = 1,
South = 2,
East = 4,
West = 8,
NorthWest = North | West,
NorthEast = North | East,
// etc
}

make sure to not use enums if they are likely to change!
my flag enums are always changing :)
instead of messing around with serialization workarounds
indeed
that’s how I defined mine, but I just gave an example to show what happens if you don’t define it as a flag enum, and need to change later
and then it is awkward
thanks thats useful
flag enums in the wrong hands are also evil
flag enums effectively assign each “category” to a specific binary digit
NorthSouth 
so 0001 being north, and 0010 being west, then 0011 would be northwest
yeah, but some people like to use flags for things that arent masks, and thats wrong
I use them sometimes just to prevent users from selecting multiples of the same entry of the enum
just like people like to use interface default implementations to get some cursed form of multiple inheritance
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)
thanks for the explanation
yes, but clever people will use the non-powers of 2 to make multi-selects, like the hideFlags on GameObjects
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
he will get there when he gets there. let’s just teach him the basics of how to drive before he goes to Nascar
flag enums are funny because you can have valid enum values that are not part of the enum declaration
scary
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
This is also an example i don't like
[Flags]
enum Comparison
{
Always,
Never,
NotEqual,
Less,
LessEqual,
Equal,
GreaterEqual,
Greater,
}
that’s just awkward
Because it is stupid
and cursed
i've wound up using scriptable objects in place of enums in many places
you should use both
sometimes they're literally empty
do not fear them. just know them, and use them well
just a "key"
and don’t use enums when it’s an ass-backwards solution to your problem
type object
now that's just goofy
i guess you could do a flags enum with less than, greater than, and equal
all eight combinations are meaningful
yes, but thats still silly
It's too clever for its own good
just extra brainwork to read
also whats Greater || Less supposed to mean?
basically never
you might need an enum to get out a categorical result from a function
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
NOTE: Here comes the weird part of the article. This is where I pull out the black magic
bitmasks are really good when you need to go fast
lol
when you need to do a specific sort of thing a fuckload of times, bitmasks are good
yes but mind your usecase, an enum with the explicit name is equally fast, also that enum is in UI code so that doesnt matter
i just wish there was a nicer way to interact with bitmasks. i wonder if you could write some extension methods for integers
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
if you like to juggle bits your co-programmers will hate you
Yeah me neither I fear nothing lol
Why? Because you are exposing their lack of skill/knowledge?
IM sitting and learning right now
tough shit
we need an emoji of a dog being hit with a squirt bottle of water
what can you do, post C nobody is touching bits anymore
you can take 10 minutes to explain it to them
yeah is Unity LayerMask system bitmask or am I wrong on that
LayerMask is a bitmask, yes
explaining is just words out of your mouth that will collide with a wall that does not care
wanna bet? Bitshifting is perfect for saving and comparing a board game state
LayerMask is a type that is a bitmask, where each bit corresponds to a different collision layer
i agree, but i mean thats a generational thing, people today don't need bits anymore, so it takes a special interest to dive into that
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
bitshifting can do some things pretty smoothly
lists and arrays are both reference types that live out on the heap.
also bitmasks are just the peak of the iceberg
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
they do need them, they just don't know enough to use them so they implement less efficient solutions
like, the cardinal enum i was talking about earlier? If you want to rotate, that is just a bitshift
there is so much black magic in the bits of ints and floats
i don’t need to do all this shit about moving north to west and west to south etc
like the fast sqrt is just a bit-shift trick
whenever I do bitmath, i comment the shit out of it
indeed
because otherwise you won’t know where bits currently are, or what you are doing
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.
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
ok
It uses bitmaksing because it takes up 1/32 of the memory and compares against an arbitrary number of elements in 1 CPU cycle instead of O(n) time
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)
Yes but your future protege might not like it with today's (or tomorrow's) emphasis on readability (by the common folks) over performance 😔
my general rule of thumb is that bitmath requires at least one comment per line.
because bitmath is notoriously hard to read
then they will be no protégé of mine. This is game dev. performance is everything. if they want readability go and do app dev
legibility is important for long term maintainance for any coding project
yes, and how often have you made a game and done any maintenance on it what so ever?
literally every bug fix
literally every time you have to go to an old class and add a feature
after release?
dude, do you even code? this is like, beginner level shit
Child I was programming before your parents were born
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
How many games have you made and released?
Seems like this channel just woke up and chose violence today
Useful book full of bit stuff and black magic math
it's only magic until you understand it (:
learns fireball
understands fireball
now I just have a really hot hand :(
the better you get at casting fireball, the better you get at not hitting things with it
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
i'd guess you need to "re-initialize" something after the permission is granted
but i don't see anything like that
me neither... the place I call Microphone.Start()/End() is totally separate from the permission granting section
That's what usually causes problems like that (not waiting for the player to grant permissions before trying to use them)
hmm after more googling i'm guesing it's a specific quirk w/ the oculus/meta quest runtime.. i'll dig into it more
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?
it's an editor error. clear it and move on
Report it as a bug!
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
Pretty sure that was fixed in a newer Unity version unless it came back in 6
i haven't seen it in 6 (yet), but i have seen it in pretty much every other version i've ever used 🤷♂️
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
why are you using unity 5? 🤔
because 6 is not out yet not unless it just released
5 is also 9 years old
unity switched to being named after the release year a while back
are you sure you aren't using like 2022 or something?
they are going back to sequential numbers
unity 6 is being released 2024 summer
also, it is out. the unity 6 preview just recently released. and despite the confusing name, it's a tech stream version, not a beta
it's just not the LTS version yet
much like 2023.2.x was a tech stream release
i'm thiiiinking about upgrading from 2023.2.20f1
I'm still on 2022.3 
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.
one reason for switching back to plain numbers is to make it more obvious which versions are LTS vs. Tech Stream, I imagine
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
yeah
tying yourself to yearly releases means you're just Shipping Stuff
(or, conversely, Not Shipping Stuff)
Oh nice.
I tested that my project behaves properly in the 6 Preview, but I think I'll give it a few weeks
i just bumped to .20 because of a very annoying bug https://issuetracker.unity3d.com/issues/when-multi-editing-gameobjects-with-seriliazed-enum-fields-changes-are-not-reflected-if-the-the-last-selected-gameobject-in-the-hierarchy-has-a-different-value
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 

would have made the release much more major imo
and maybe a few itty bitty breaking changes
(please throw out the goddamn rigidbody property)
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
they still exist as obsolete properties
iirc those should be removed Eventually™️
a carrot to go along with the stick (:
Not having readonly record structs in Unity constantly makes me sad
i keep poking at record and then realizing i can't do anything cool with it in this version of C#
It is 2024 summer
it sure FEELS like summer right now
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
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
You're waiting 1 second, then removing 1 frame of time from duration
Meanwhile, you're adding 1 frame to duration every frame
I'm waiting 1.014666 before next code execution, and want to fix the duration by this 0.014666
what are you trying to do exactly ?
deltaTime is not going to be the same every frame
Also yes, what is the use case here
Fix the duration considering WaitForSeconds margin
to do what with ?
It will be physically impossible to get the exact time to match up with the value you pass unless your framerate is always an exact diviser of the time you wait
Time between render frames in a game literally does not exist
Ok, thanks
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
better answer is this instead
float timer = 0;
float interval = 1;
while (true) {
timer += Time.deltaTime;
if (timer > interval) {
timer -= interval;
Debug.Log($"{interval} seconds passed!");
}
yield return null;
}```
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
just don't use WaitForSeconds at all if you want accurate periodic timing
(works in Update too)
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
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?
how would the latter work?
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
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.
Ah, I see. I thought you were saying you wouldn't have any inheritance at all!
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.
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.
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.
Yeah, I do this personally it works WaitForSeconds() is well not that useful code above runs endlessly code below only runs after wait condition finished if I have that correct.
`// I prefer using Update
float time = 1;
float timer;
void Start()
{
timer = time
}
void Update()
{
timer -= Time.deltaTime;
if(timer <= 0)
{
timer = time;
}
}`
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
those are functionally the same, except praetor's accounts for extra frame time
Coroutines slow down the system so bad
completely untrue
ah yeah close enough looks smooth too so meh Ill take it for most things
This is barely a sentence but wtf no
it's a sentence why do i have to write out in text message full sentences what am I writing a book?
It's basically ineligible past the first 5 words
Ah Yeah, is Canadian for Yeah your right, eh is ? meh mean it's ok. there you got some Canadian lingo and venacular!
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
That's the problem with them exactly I can find Jason Weinman video and link it.
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
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.
jason weimann, while fairly knowledgeable, is not infallible. and has some fairly strong opinions about things that don't actually matter
coroutines create garbage though which is the takeaway
which is where unitask picks up
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
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.
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?
true, you could always pool coroutines too if you wanted to
it's like you didn't even bother looking at the test results
use an array of bar objects, you won't have an easy time doing what you've just described without reflection which isn't going to be very performant anyway
Link to a game then please and thanks and lets test this, because 80% of Unity games I play run like garbage.
mate, i linked you to an actual benchmark test that showed the performance was almost exactly the same
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
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.
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
congrats, that is not a measurement of the performance of a coroutine versus update
if you're doing collisional/casting in each of those coroutines it's probably related
Sounds like a good made up statistic. Anyways you're literally ignoring the tests someone provided you and just going with what you assume is right because someone else made a video on it.
I could make a video and claim the opposite, what then, do you freeze in an eternal paradox?
This surely must be a troll
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.
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 😆
you can always do a manager type systems that handle similar routines instead of distributing to each gameobject
1 update loop vs multiple coroutines
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
wat
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
Living near smart people doesn't make one smart. You can also just test it objectively and know for yourself.
Your Objective evidence gets trumped by Programmers with 30 years experience that have consistently made good optimized games.
Can you stop this nonsense already?
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
Ok you made your point. You're professionally equipped because you asked professionals some questions. We can move on.
fine coruotines are amazing I'll shall use them now ok happy
If it keeps you quiet, yes. Thank you.
You're the best ok
I mean if we all wanted optimal performance we'd take advantage of compute shader and async but im too lazy for that
I will stop loving my heroes and now worship you
If the next thing you say on this server isn't productive, you're getting muted.
I was a productive we discussing the times to use Coroutines and not that was discussion
The array is what I was missing, thank you.
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?
if that were possible, it would be using decompilation tools that are not allowed to be discussed in this server
Are you not using version control also?
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
The discussion ended when boxfriend brought out actual data. The rest of that conversation was your temper tantrum
Dont believe so
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
that was it
Thank you I just lost a weeks worth of development, hopefully version control can prevent it in the future
This is partly what it's for. A lot of people go through the same thing, then start using it
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
I know
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?
You can install the hlsl extension, but that would only help with the basic types and macros. To enable intellisense for all the unity stuff, you'll need to add all the relevant unity headers to your project and #include them in your file.
All the real shader programmers code without intellisense💪
Ouch
i should really figure that out
so far i've just written shader code with literally no IDE support
same. where's the bot command to configure your IDE for shaders lol
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Line ten is the list I want to be able to edit.
show the definition for StateDataPair and BaseState, if these are all abstract classes there really should be no issue using SerializeField here.
I ended up fixing it by just making them all derive from ScriptableObject instead of Monobehavior.
Sounds questionable, especially if you have any mutable data going on
If need be, I'll just make the statemachine construct a new list of components that are duplicates of templates stored on ScriptableObjects
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?
Are you trying to Destroy the .transform?
Yeah that is a transform. You should add .gameObject
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
depending on your version, there might be a breaking change https://docs.unity.com/ugs/en-us/packages/com.unity.services.cloudsave/3.1/changelog/CHANGELOG#changed-1
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?
I do basically stuff like OnHit, OnExpiration
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
I think there isn't a specific pattern to projectiles, it depends on your structure and what you want to do. But check the Template Method,it is a bit more extended than using just a Interface to avoid being always repeating the same lines of code. This is my point of view as a generic programmer, not a game developer, I'm just making my first game
Also take a look of object pooling for making it efficient, instead of just creating and destroying an object each time you shoot
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)
yeah I plan on doing that, just haven't gotten around to it
everything else is object pooled but projectiles havent caused any lag issues so ive left it for last
you think like me but it's so easy to overscope this haha
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
what holds the triggers? the ability?
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
and is that a general thing defined for your base ability or specific to an ability that has triggers
fire ball projectile -> hit anything -> explode aoe at location
each of my abilities are SOs that contain ability SOs
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
okay, interesting, thanks
fireball that procs a fireball that procs a fireball, fun
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?
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
i see what you mean, ill try. Although this will definitely miss cases if i did var but i can just go through that one manually i guess
im decent enough at regex to do it, doesnt have to be perfect
Im 33 and literally call my dad when I need a regex 🤣
i just go on regex101 and guess until it works on some input lol
Thats what I do too
😅 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.
You can overload == operator, and then find all reference on it.
After you done all the clean up, remove the overload.
how do I make wheel collider less slippery? At higher speeds steering barelly works, Wheels turn left and right but the car barelly turn
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
😮 thanks a lot
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)
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.
I remember having to configuring something in an omnisharp.json file back when VSCode required you to install the analyzers separately
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.
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
Yep, that's what I'm suspicious about.
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.
I turned off two warnings by adding a file named csc.rsp to my Assets folder containing...
-nowarn:8524
-nowarn:0618
I wonder if you need to put something in here to enable warnings or errors
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.
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
I don't even know if you can configure individual rules via compiler arguments, all I've seen is via .editorconfig.
I used .editorconfig to kill these warnings in my code editor
Yeah getting IDE to do things is pretty easy, getting Unity to do things on the other hand...
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!
alright, making a third person controller is acutally pretty hard.
- Do you add a focus point and rotate the point so that the camera rotates around it, or
- Add cinemachine and have the camera rotate around the focal point??
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
The root rotates both left/right and up/down
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.
ah, did a forward slash work too?
Yeah /switch and -switch both works it seems.
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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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?
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.
StateHolder is a scriptable object.
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.
I'm trying to drag the Monobehavior file for UIState into it, because I want to replace the BaseState with a UIState instead. UIState derives from BaseState.
A script asset is not an instance of the component.
It's a MonoScript object that doesn't even exist at build time.
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?
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]
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?
If you remove MonoBehaviour, it will no longer be a unity object, so you won't be able to drag and drop it anywhere
You can pass a scriptable object to Instantiate to copy it.
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.
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.
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
I mentioned this because it kinda sounds like these BaseState-derived classes don't actually need to be MonoBehaviours. They don't meaningfully exist in the world
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?
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)
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?
You also have to destroy them yourself then
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()
{
}
}
📃 Large Code Blocks
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ur missing a ()
aka "call"
you should probably configure your IDE if its not underlined in the code editor
ohhh thank you i didn notice.
Whats IDE?
ideally the Application you're using to edit the code
Oh
Integrated development environment
An integrated development environment (IDE) is a software application that provides comprehensive facilities for software development. An IDE normally consists of at least a source-code editor, build automation tools, and a debugger. Some IDEs, such as IntelliJ IDEA, Eclipse and Lazarus contain the necessary compiler, interpreter or both; others...
Aside from that () u are missing, you should start your coroutines at the end of the void Start() since your variables doesn't have a value at the beginning
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
I went on unity version control once now I can’t get rid of it, how do I get rid of it?
ask about this in #💻┃unity-talk . this is not a code question.
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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Here is a video of the issue: https://streamable.com/ywtmy1
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
yes, use Application.persistentDataPath as your base folder and Path.Combine to make sub folder paths
thanks, I think this is exactly what I was having a hard time finding
Wasnt able to look extensively but one thing I notice is you arent storing the coroutine, meaning you cannot stop them. You should store it and then stop the coroutine if it's not null to do either the fade in or out.
Right now it's possible that both are running at the same time
Those bools also look a bit questionable
Storing the coroutines would also avoid those 4 bools you have.
Huh? I've never heard of being able to store coroutines. How could I go about that?
Also, the bools are used to detect when the player just started looking at the object, and just stopped looking at the object.
Start by reading the StartCoroutine documentation
Yes, and what I said still applies. Storing the coroutine will allow you to avoid this. As Steve said look at the docs
If the stored coroutine is not null that means you've already started it
You need to ensure you also set the coroutine to null when it finishes or you stop it.. it doesn’t happen automatically
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.
Don't I need coroutines to make the text fade in/out?
No
Something like this? cs hitUpgrade = Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out RaycastHit hit, 5, layers); if (hitUpgrade == true) { coroutineRunning = StartCoroutine("FadeIn", 1.0f); } else { if (coroutineRunning != null) { StopCoroutine("FadeIn"); } }
You can, sure. You don't need to.
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);
I don't understand what to do with this information?
That wasn't meant to answer your question, just a side tangent.
oh
This would be my answer.
How would I fade in/out without coroutines?
Animation is nothing but a series of changes happening frame by frame.
coroutines just make it easier to remember variables from frame to frame, without having to create a bunch of fields on your class
that's a really neat way to express something that'd otherwise be in Update!
Yeah and all of that logic in mere 5 lines of code, it's so much more powerful and expressive than procedural code.
I wound up adding "changed" events to all of my settings objects, which has been very convenient
basically nothing polls for settings
So I add a or subtract a small amount of opacity from the objects every frame?
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
You don't really need to, let me ask you this, given the following information:
start time = 1234
end time = 1234.25
start color = clear
end color = white
What color should it be at time 1234? 1234.125? 1234.25?
1245 its clear; 1234.125 its half transparent; 1234.25 its white.
Good, and there you go, you have a fading animation.
Use those 4 information, + the current time, and you can calculate the current color.
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
This is iterative.
Mathf.Lerp(oldValue, newValue, transitionTime); // where transitionTime goes from 0 to 1 over time
This is explicit.
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.
I would prefer the iterative method here.
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
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);
}
}```
this would instantly fade the text in
oh right
this is not a coroutine; you are not yielding anywhere
also time is untouched
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.
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;"
They want a fading animation, not just toggle.
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
Actually, I've just discovered a problem with this code. For some reason when the fadeTime is less than 1 the text just doesnt fade out at all.
Does it fade out pretty much instantly or super slow
It doesnt fade out at all if the fadeTime variable is less than 1
It stays fully opaque
hmm that's weird
just very slowly?
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.
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)
Yeah, that doesnt work. That results in the super slow fading issue.
Wouldnt I need a coroutine to change transitionTime from 0 to 1 or 1 to 0 over time?
no, because you can just change it by a little each frame
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?
Divide deltaTime by the duration you want
Time.deltaTime * rate;
Time.deltaTime / duration;
both of these are valid
multiplying by a duration is wrong
What am I doing wrong here? The text is currently fading in and out instantly. cs float alpha = text.color.a; alpha = Mathf.Lerp(startAlpha, endAlpha, Time.deltaTime/fadeTime); text.color = new Color(text.color.r, text.color.g, text.color.b, alpha);
Is there a way I could use seconds with the explicit method?
Well
Lerp gives you a value between the start and end values.
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
If startAlpha is 0 and endAlpha is 1, this is giving you a value that is very close to startAlpha.
yup
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?
so basically put it
yes
if startalpha is 0, endalpha is 1 and your interpolation value is 0.5 then your value that you get is 0.5
I know that
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
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.
pretty much that
For example:
text.color = Color.Lerp(new Color(1, 1, 1, 0), new Color(1, 1, 1, 1), fadeProgress);
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
Are you able to use the IPointerHandler interfaces on regular objects? Or is it limited to UI?
They must go on components.
Ah, you mean non-UI things
but still MonoBehaviours/etc
Well ya obviously they need to be on GameObjects.
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)
Alright cool.
In your case, you want an alpha between 0 and 1 anyway, so the last step is not necessary. you can just use fadeProgress directly.
If it COULD do that I'd be concerned.
How would unity do that. Where does it think these things are located >_>
✨magic✨
convert memory locations to 3D space
what is visible?
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)
I've already replaced the visible bool with what you would get it from here
a liittle while ago
I just used a boolean variable there beacuse it does not matter how you decide if the text is visible
true
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);
}```
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
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.
you mean fadeProgress, not targetProgress, that would just make it toggle.
hmm, what is fadeCurve?
oh wait
nvm, I get it
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!
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?
i would have to see the code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
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?
If I understand, you should move it using the AddForce method : https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
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
try with something like this: https://hatebin.com/vesqnlnmlh
ah thank you.
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.
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?
Which part are you struggling with? What you said is exactly what you need to do, change the texture on the material of the renderer.
Why is your SO referencing a scene object? This isnt about object persistence but that assets cannot reference objects in scene.
if I have two instances of the prefab and change the texture of the one, the other's material changes too
cause they are referencing the same material
Changing it at runtime should be fine
When you access the material, it will make an instance of it
like from code rather than dragging and dropping
Yes code, you arent gonna be dragging and dropping it on the users pc
okay i see
Using prefabs might just be easier here though.
Especially since you'll already need some lookup for the textures
like each card with its own material and texture is a prefab?
Dont think you would need a unique material for every single card
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
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
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)
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
smart
thanks for your help
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
now worries i found this, https://discord.com/developers/docs/game-sdk/getting-started
This is completely possible
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
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
i dont think there are vectors for corners as far as i know
only x and y, you can make more checks to avoid corners that's all
you want to avoid hitting corners??
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.
modularity for its own sake is a fools' errand -- if things need to be coupled, let them be coupled and your life will be simpler for it
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
people have different feelings here, but I would say that ideally you should always be able to generate the scene from a given gamestate, at which point what's in the inspector at runtime can be whatever is easier for you to manage
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
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
This is a good goal -- one way data flow and keeping clear dependencies are always good things. Some pieces like 3d player movement are always going to be complicated and highly coupled, but splitting it into input frames -> game actions helps keep things managable for sure
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
}
}
Great name with IPattable, that's hilarious
that's not what that does
Converts an object to byte. What else is required?
they want to serialize some value as an array of bytes. not try to get the equivalent byte value of some object
this would be more along the lines of what they want if they were just trying to get a single primitive object as an array of bytes https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter.getbytes?view=net-8.0
you will need to be more specific about what exactly you are trying to achieve if the above method isn't what you were looking for
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
The first one's fine.
I'm just trying to get around Unity's limitation for inability to serialize an unknown type by making a field name value pair.
Obviously I'm using a custom editor.
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.
You'd have to show more of the setup, which objects are storing these references and to what. How you're loading the scenes etc.
Objects are destroyed if you are loading another scene in single mode
Having an SO reference a specific transform sounds like a bad idea though
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
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
Basically yes. I want it to say if u hit a corner register that as a bottom hit (if corner is near bottom) or top hit if corner is near top
sigh sometimes the easiest fix is right in front of your face and you don't realize it... ty that did it.
Can someone link me the latest visual studio code build?
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
there's not some secret location to get the latest version. you just get it from the official sources just like everyone else
Ik bro I was just asking you don't gotta be smart about it thanks for the link keep it moving
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
👍
If its such a big deal you wouldn't have done it for me lol
But anyways have a good day
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"
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?
I usually create a script that automates these things already in the editor so I dont have to do anything runtime for no reason
eg you can separate by suit
then have different arrays
oh i see
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
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.
How is this going to help me?
you're meant to read it
then surely you see what is wrong with your path
Are you goign to say cause i have .png in it?
yes, absolutely
i took that out and i have the same issue?
Note that the path is case insensitive and must not contain a file extension.
show the full path for that asset
and if you look at the second material for the MeshRenderer you are modifying, does it show that texture on it?
Not on the created instance
what do you see on that MeshRenderer?
for the instantiated object or the prefab that is being copied?
the instantiated object, obviously. the prefab wouldn't have run that code
and you have the component with this code on it attached to that object?
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 😂
holy shit, what an asshole. i was verifying information to try and help you but now i definitly won't
bro is onto nothinbg
gn bro
get some sleep
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
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
Hahahaha
Bro linked the documentation when I asked for clarification on the documentstion
Some people just can’t help
yes because the documentation told you why your path was incorrect
or did you do it wrong on purpose?
Tip: just say the path is wrong
tip: learn to read
Tip: go outside
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
Brooo 💀 💀 💀 😂 😂
<@&502884371011731486> racism
surprised thats not auto filtered out
and yet that's still racist and against server rules. 👋
anyways if you're expecting actual help, which you likely wont get after the above, you should likely be posting in the #💻┃code-beginner channel.
Okay why bro had have to be racist
!ban 1126368364911141034 racism
honest_panda_49009_25434 was banned.
Real.
crazy
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.
Do the arms have to rotate in the direction of the cursor?
while I'm holding left mouse button arm onthe left will rotate and right when I'm holding right. They dont have to rotate I just want them to follow cursor
"will rotate", "they don't have to rotate" ?
what do you mean by have to
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:
-
- [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.
-
- 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
2ndheader to make it work.
- 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
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
Does anyone know how load a texture from the program files to be shown by a sprite render?
Resources.Load and
Sprite.Create
Found a forum post from what you said. Thanks for the help
better to read the documentation for those 2 API cals
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
Why on earth would you have textures there?