#π»βcode-beginner
1 messages Β· Page 843 of 1
Or just do similar logic in awake, because this happening 3 times isnt gonna do shit to your performance. Although its not pretty
doing it in OnValidate isn't a great idea here. I doubt itll matter for your performance either but this shouldn't be something that constantly needs to run
it's happening like 10 times but for sake of doing less I guess I ll leave it there
ll put in Awake for now
half questions I ask here is I am realizing I made a poor design this game so I gather some info how to make next game better
relatable
Yea the better design here is just spawning them at runtime via code, you'll avoid scenarios where an existing object in a scene is outdated because you never went back to update it after updating the prefab. Or maybe im misremembering how that works but Im pretty sure that'll be an issue in your current setup
it's somehow fairly easy to make something which works but to make it look like something I don't want to cringe looking at is harder
i don't think that'd be an issue? the stuff saved in the scene is just overrides
it's helpful other way around tho, I can easily tune those prefabs for each scene, like if I want player to start with different items I can just change them in scene version of prefab
this one's also an option btw, i find it helps with linking singletons or whatever
if you drag a prefab into a scene, then change the prefab, does the object update? I havent opened unity in some time actually to remember this
yes
additive scene sound like... bad for performance? but I don't really know how it works
that's the point of prefabs
additive scenes just let you load/unload objects in groups
Something about this sounds wrong, but idk I could be thinking of something else
you are free to override prefab on the disk by the scene one and the other way around any time
there are other ways to handle it but yea that's one way. I havent found a great design either around having specific setups per scene, when the objects need to be spawned via code
I suppose that would be a scriptable object with alot of info and a script overriding stuff using it
I see, yea not sure what I was thinking of then. Maybe unpacked prefabs which obv wouldnt work
It's been too long
performance is an issue you worry about when you notice lag. loading/unloading a scene containing a prefab will always be slower than just loading the prefab but it just depends on what you want
I never used additive scenes much because you also need to design around it for anything involving scenes
Can't really compare the performance either because you'd be using it in different ways. Like if you have the same pause screen UI exist in every scene, that's being instantiated everytime you load the scene
If you load it additively, it's not tied to your gameplay scenes anymore
I don't understand the attitude of caring about pefromance only when it starts lagging
computers are faster than you think
unless you absolutely know it's going to be a problem, or it already is a problem, don't worry about optimization - you have better things to worry about.
compilers are really good at optimization, too.
I guess the right way to put it would be to say if it's not big performance hit it's not worth caring about
yeah
and a lot of the time, that nasty stuff is bad for other reasons, too
Find is fragile
i can't think of other examples off the top of my head
doing GetComponent for every access reduces maintainability and readability
don't worry about perf unless a) you start having perf issues, b) you are working in the millions of iterations, or c) you are working with extremely limited hardware, like an arduino or an NES
I had ALOT of tolerable overhead by overusing navigation api for example
but yeah anyways in many cases, preemptively/prematurely optimizing for perf can reduce readability or maintainability, for relatively little gain
many raycast checks and stuff I have got cooldown timers but they could as well not have it
what is a good way to find what gameobject is closest to a specific other gameobject?
public AggressionTarget RequestTargetClosest(AggressionTarget requester, Vector3 where_from_seek)
{
if(targets == null)
{
Debug.Log("No valid targets");
return null;
}
AggressionTarget candidate = null;
float shortest_distance_square = Mathf.Infinity;
if (requester.team == Team.player)
{
Debug.LogError("Why does player request a target");
return null;
}
else
{
for (int i = 0; i < targets.Count; i++)
{
if(targets[i] == requester) continue;
if (targets[i].is_visible_to_attackers && IsValidTarget(requester.team, targets[i].team))
{
float distance_to_target_square = Vector3.SqrMagnitude(targets[i].coords - where_from_seek);
if(distance_to_target_square < shortest_distance_square)
{
candidate = targets[i];
shortest_distance_square = distance_to_target_square;
}
}
}
}
//Debug.Log(requester.target_position + " attacking " + candidate.target_position);
return candidate;
}
I use that
I was going to ask about this method
on profiler I see how the most expensive things are apparently... getting transforms positions?
look through the other gameobjects and check which is closest
you should reduce the scope of the search though - what gameobjects are viable targets? only go through those
perhaps keep a set of those viable targets for this purpose
would that make more sense to maintain a list of Vector3-correspondingTransform structs each frame
oh okay i am using tags but i didnt know how, but i think i just found the method Distance() bcs i am lazy to do it from scratch
so in the long run if same frame I get many requests each would only iterate once
to replace which part? i'm not seeing a transform access there
oh well yeah targets[i].coords is a property for getting transform position
well, it's 2 method calls that crosses into and out of native code, so i would expect it be at least a significant chunk of this method, i guess.
but it being "most expensive" doesn't really mean anything. is it expensive enough to be an issue?
how many targets do you have, and how much cpu time is it taking?
for now it's not an issue but I want to see how hard I could push it
I remember till I added cooldowns it was on 1-2 place on CPU time with like... dozen of ms or something?
along most frames
dozen of ms? i don't think that's right
Something something transform job https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Jobs.IJobParallelForTransform.html
me thinks this isnt beginner stuff too
as for the amount it's tens for now and at this game and hundreds in my dreams
I suspect I would have to go to the different architecture
I forgot how does that Unity package called
non OOP components
ecs?
yes
anyways i don't really think this is gonna be an issue at hundreds
how did you profile it? In editor or build? Deep profile or not?
Deep profile exaggerates the cost of small method calls a lot
π€
π€
(Also if you profile editor you should try standalone profiler, though might not matter here)
Sorry bout the ping, had misclicked your name earlier and it was @ in the text field π
Nah just waking up xd
in his defense i have misspelled a word so bad i just typed a different word while i was completely awake XD
oh also it's not the question of this channel but why when I increase Minimum Region Area I get more tiny navmeshes
but not the other way around
no wait it... looks random
I just want one big navmesh
it keep baking me tiny ones too even if I type in absurd 9999999999999999999999999 in min region area
cool Unity docs saying "Note: some regions may not get removed"
Minimum region area wouldn't merge separate navmesh regions.
It decides if an area is being enough to have a navmesh or not.
I know
by I just want one big navmesh I mean I want everything else culled away
sounds trivial enough but unachivable without fiddling with colliders manually it seems
seems like a #π€βai-navigation question
I don't think there will be a solution anyway
guys does void means function?
you should learn basics of C# somewhere
to answer the question it means it does not return anything
im learning it and i want to understand not just copy do you have a source to learn from? likeyoutube channel or smthng
you may read this
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods
but rather get a basic learning course or something somewhere
try to learn from the official learning materials from microsoft first π (linked above)
it's kinda hard to learn by just learning Microsoft docs or something because to to know what is A you need to know B and to know what does B you need to know A kind of thing
on second thought not really but it feels like it
is InvokeRepeating a good way to repeat voids instead of timers?
yeah i hate docs 2 pages for 1 information
it's a thing which works but ugh
it's annoying to debug
not ideal for performance
And you have less control so id avoid it
ok then how to repeat with ease
is there a built in timer like godot? i hate doing timers
coroutines are the closest
timer at Update is the most annoying but most manageable
I mean what if you want to stop the timer or scale it or something
you can stop coroutines?
you may also forget to disable coroutine
yeah i agree but when i read it my brain get fucked
How to acces the store
online, but not a code related question
no I mean not permanently but to halt it
yes you can do that
and a lot of variables for 1 timer not worth it
it's 3 variables
if you need many variables to do something then you need them
outside bool or something?
"can you communicate without communicating" no, obviously
but you would need that in Update regardless
depends on the context
most stuff you can put in Update, you can also put in a coroutine, they run on the same cycle
ok like 1 timer for every thing i need to repeat in a certain time
yeah I know I mean coroutine is an extra step those cases and for what
for oneshot things I d go coroutine
for something bit complex I am not sure it's worth it
you need 1 thing for configuration and 2 things for tracking state kinda regardless of how you do it
using InvokeRepeating just hides the latter ones away - you don't have to manage it, but you also can't manage it. both a pro and a con.
hold up bro its my first day in cs
yeah coroutine and invoke have timers internally
could be for better readability and/or separation of concerns, depending on the case. obviously coroutines don't make sense for everything
im getting rage baited
coroutines don't. WaitForSeconds for example does, and you could use that or your own timer in coroutine as well
the variables end up being locals rather than class members
right, they only have timers if you use them with timers
they don't have timers, you can use a timer with them
guys i have a question : how does cs script act in unity like every script its for 1 object or i can use it in another
oh yeah I havent' thought that I could just +=Time.deltaTime inside Coroutine
a component is a instance'd version of your script that many be on many objects
1 script
x "live" versions of that script
"script" is kind of a nebulous term. pedantically it refers to a file, but that's often not how it's referred to in a lot of resources
so for clarity, i'll avoid that term in this explanation
- the .cs file contains a class definition, this tells mono (the runtime, the thing running code) what the class is
- the class can be "instantated" into a component
- a component lives on a gameobject
the component is a version of the class that can be run by unity, the class is a blueprint for the component/instance
Sounds like learning about object oriented programming will help!
let me read again
yeah and with that you have fine control like you would with an Update timer, and also the encapsulation of a coroutine
like the class is a blueprint i can chnage on it for every object i put the script in?
@random sigil have you played minecraft
yeah..
you can't change the blueprint for each object, no
oh man, very interested to see where this analogy is going lmao
your script is like, how a grass block is defined in the code
a component/instance is a grass block placed in your world
ok so its a script the same act for every object or what
it has the same instructions, but each object can have different values set that result in different behaviors
you might make a skeleton script
then you would spawn instances of the skeleton at night time
ok like if i created a spawning script and put it in zombie creeper and skeleton they will spawn if they can and spawn in the time i put in thier metadata or smthng
there's a couple things off there in a literal sense but vibe wise your on the right path i think
sure, and you could have 2 instances of the spawning script where one is set to spawn chickens at daytime and one is set to spawn zombies at night.
same script, different inputs, they can act differently using the same instructions
like the object will act on hes act like if the code contain color changing the object will chaneg it color if he had a color and if he can
like if a wikipedia page was a .cs script, it might look something like this
thats your script
then this crafting table would have 3 instance's of your Cobblestone script
because they are three different "objects" that all come from the same script
ok i understand know
most of programming has very direct comparisons to minecraft
like the breaking script will act on the hardness for the block and if the pickaxe can break it , like something liek that
well, minecraft is a program lol
especially with AE2 mod
especially with OpenComputers mod
the breaking code would probably be in the Cobblestone block script directly
and every block
yup
there's abit more to it for that (called inheretence) but thats a little more advanced then what we are talking about
also composition - in reality there probably wouldn't be a class for each block, you would have a class for all blocks, then each specific block would be a "scriptable object" that holds the data for each block, like the infobox batby sent above
(that's also outside the scope of what we were talking about though. this will come up much later)
i saw a video that said the class is like a factory and the functions are the machines is that a right concept because i understand this concept
that is right but also like
the scale of that comparison isn't always 1:1 with reality
eg. if your making a printer (like something that prints paper), that would probably be a class, not a function
but it might contain functions like
Scan()
Print()
Copy()
Refill()
etc.
yess
the printer have a scan machine print machine etc
oh its easy now
when i first heared of classes i thought like a real class
thats fair lol
but also if you were programming a school that would probably be right π
laughs in terraria
how is it with multiple nav mesh agents on one nav mesh surface? It doesnt work for me
perhaps ask #π€βai-navigation
Surely they do not do this
More lines of code in this one file than i've written in the last 2 years π
they don't, items/blocks use the same class with specified ids, as inferrable through the item generation glitch
also terraria is closed-source so if this is from a decompilation it's probably marked up or done in a more sensible way in the source code, but that's just a guess
Surely they arent insane enough to write these by hand, and instead have a helper script to write it for them
compiler optimizations be wilding sometimes
im pretty sure it is like this
how can you be sure though
i dont have a direct source so take it how you want but used to do modding stuff and im pretty sure one of the devs confirmed it
huh, interesting
i know for a fact one of them told me they don't have any documentation
like for design stuff either
i mean, undertale and balatro have similar things (and are kinda well-known for it)
so i wouldn't doubt it
my AI code is close to 9k lines
where base class is like 3k and chilrend are like 1-2k
it works but I feel like
I made a grave mistake
so the structure is
I got a bunch of Action s for SFM
where without any incapsulation it's just alot of methods
SomeStateStart
SomeStateLoop
{
SomeStateCheckEmergencyExit
ActualCode
SomeStateCheckNormalExit
}
SomeStateCheckEmergencyExit
SomeStateCheckNormalExit
I am not sure what to do about it
I need some kind of FSM I guess
I thought of making it like at FEAR maybe
i have a project using the muip library to do some animation effects like sway on hover over etc
where it's a list with priorities
I gonna ask
I want to make an architecture where I can easily add and remove states
where like I can ugh
...yeah I should think for some time to figure out what exactly I need and then go from there
Helelo, guys! By the way, I found a way to create my own PLayerPrefs.SetBool() XD. I mean why Unity doesn't have PlayerPrefs.SetBool in the API and its really interesting.
{
PlayerPrefs.SetInt(key, value ? 1 : 0);
}``` thats how we do it right ? I mean it was so hard to write these lines of code?
Becuase i am trying to save some values and was searching for SetBool().
A bool is just a number, so there's no need to have it otherwise.
main issue is imagine I have a system of 9 states and then I add 10th one
and now I have to manually specify transition into 10th state and transitions from that state to all other states
Was it really "so hard" to write?
Same amount of lines = so hard to write. π¬
I guess if we're nitpicking based on character count, you might be breaking a sweat, yeah.
how does sway work?
this project i'm on uses the muip library to implement icon sway on hover over
the bug is that in a partuclar mode
the sway is too much
Are you asking how sway works or how to change the intensity of it in a specific library that you're using?
both
What does sway mean in this context? The icon just rocks back and forth/up and down on hover? It would just be using a simple Mathf.Sin to oscillate it back and forth.
yeah
right now the behavior in one mode is that the icon just flies away
but in the other mode the sway is fine
and i'm unsure what property to look for that's different
I don't know this library so who knows
Maybe it's a scaling thing, is the bad scaled larger? Could be that it's multiplying the effect?
Or it could be that it's restarting the effect each time and it's just going off in one continual direction
it seems to be scaled the same?
when you have sway
how does the rect transform play into that?
It shouldn't do much, other than moving the position of it
Hi, if I want to pass through a variable as a reference in an Action, what is the syntax for it? I tried Action<ref type> but it says invalid token
you'd have to use a custom delegate for that. but what are you trying to pass as reference, and why? that seems like it would be a bad idea
i'm working on another issue
the thing is to literally move lights so that they're on top another asset
but i do the copy and paste and it doesn't work. the light's dont appear on the new asset
does unity allow interface method implementation bodies?
yes
how else do you implement them?
Or do you mean default interface implementation?
Yes I mean default implementations. I heard c# allows it. Struggling right now implementing it.
doesn't seem like a #π»βcode-beginner issue. if the lights are there but not rendering, ask in #1390346776804069396
if the actual GOs aren't getting moved, ask in #π»βunity-talk
and probably provide some more context as to what exactly you're doing, not sure what you mean by "on top another asset"
They are only usable if using the interface type as is, otherwise the real type must provide the definition
e.g. FooBar.InterfaceThing() wont work but IInterface.InterfaceThing() does
and ofc (FooBar as Interface).InterfaceThing) can be used to do that but a little cursed
yes thats exactly what i found out in this moment and yes it looks cursed lol
basically stop trying to use it like multi inheritance
tried that but unsuccessfully
it sucks but this is not what this feature is meant for
no no my example is not implying its magically static π
you misunderstood their example, IInterface there is the type of the instance, not referencing the class type directly
best to not do this overall and fix your design
huh so you can't practically (ab)use this for multiinheritance the way you could with java's version
some of the newer c# stuff lets you get a little more weird with it
also i think with generic extensions you can get it down to just this.InterfaceThing()
doesnt save the cast but looks slightly cleaner kinda
I don't have that much experience with default interface method implementations but it sounds better than starting inheritance. guess in my case i might just do a static?
no just start inheritance
if you are making large interfaces with lots of default implementations you are likly reaching for the wrong tool
if its a small 1 or 2 method thing then sure makes sense
did OP explain usecase here? I feel like something is missing..
one sec
also why the need to cast to call it?, just implement them publically
its a small one. I'm creating something that will need multiple UI Controllers and each of them controls which Screen (VisualElement here) is visible and which are not. So I want to make sure each of those controllers will have the same functionality and implement methods that can't be implemented via default method
Reason I need multiple UI Controllers is that I will have multiple scenes which are almost isolated from the actual game
and since i will need to implement multiple ui controllers i want to make sure each implements the same functionality. But 1 method can have a default implementation since it will be the same for all ui controllers.
so thing is with default interface implementations is they can only access what is exposed in the interface its self
depending on how this is structured maybe a abstract class as the base might be more correct
I suppose you could combine interface with abstract class
yea i was thinking that too. abstract classes and interfaces with all those extra features kinda start blending together
public interface IUIController{
void ShowScreen(string screenName);
void HideAllScreens();
}
...
public abstract class UIControllerBase : MonoBehaviour, IUIController
{
public virtual void ShowScreen(string screenName){
etc..```
thanks! I'll check what I will do
also i feel if something is named IUIController really it a class not a interface
yea think i remember usually its class = what it is and interface = what it can do
hmm yea you can probably just do this with the abstract class since unrelated items have no reason to implement interface anyway
yeah more a is a vs can do
most of my interfaces tend to end in able so like IDamageable for example and often are very small quite often only 1 method
IDamageable, IHealable, IInteractable, IRuntimeDamageModifier (hmmm, screwed the pooch on that one) . . .
i have often used it for modifers as well
but sometimes i just do that with just basic named delegate types instead
oh, i haven't done the named delegate types. i heard it's good for intellisense bcuz you can actually what's it's for . . .
yeah can help signatures docement themselfs more vs seeing a Func<T1, TR>
heya! does anyone know how I can pass in an IEnumerator into a dictionary? right now I get this error with this code:
public Dictionary<HitboxType, IEnumerator<>> funcs = new Dictionary<HitboxType, IEnumerator<>>();
I also did try passing in IEnumerator as ..., IEnumerator> funcs... but that still caused an error
there are 2 IEnumerators, a non-generic one and a generic one. they're in different namespaces. if youve imported the generic one, you have to supply a generic to specify what's in the IEnumerator. if you want to not specify that, you have to import the non-generic one
what's this for exactly? if you're storing coroutines you can also just store the Coroutine itself (but also seems like a weird thing to store in this way in general)
you didn't provide the type for the IEnumerator . . .
i kinda planned to have a coroutine for every attack in my game and I'd pass an enum to the gameobject so that it could access its coroutine within the dictionary (if that makes any sense)
and all the coroutines would be active at the same time?
would you not want to start the coroutines later?
gotta mentally separate the method that defines the coroutine, vs a coroutine that's actually running
ahh okay thank you, im very new to c# so is there a different way you would recommend to do what im trying to do instead of this?
you could store the methods that define the coroutines
would be like, Func<IEnumerator> i think
(your coroutines should be using plain IEnumerator and not the generic one, as i've found)
yeah, that's what Unity is expecting anyway
IEnumerator<> by itself isn't a valid type; it's something you can construct a valid type from
(you do see this notation occasionally, but it's uncommon)
Hello! I am currently trying to view a decompiled cuphead project but when I try viewing it it unity it says 'unexpected symbol 'ref' ' , looking at the code, due to my lack of C# knowledge, I can't seem to find anything wrong & the stuff I've seen is talking about C# methods & all that fancy-pancy stuff but I just want to get these errors fixed so I can compile it
- ref doesn't make sense there. In fact the whole line doesn't make sense. It's likely a decompilation artifact.
- This server prohibits discussing modding and decompilation, so can't help you beyond that.
its a reference variable, iirc not all C# versions support it, also yeah we don't talk about modding and decompilation here
Oh, didn't know that was valid C#. What version was it added in?
iirc it was 7
they only work local to the function, but more or less lets do some pointery stuff with value types
Interesting
i do not think i have ever used the feature
almost always a other way that is more readable to others
Hi everyone, if you can help me with this code, the car moves forward and everything, it has the handbrake, the normal brake that makes it move forward, go in both directions and everything, right? But when it moves forward, there's a kind of delay if I release the key that makes it move forward or backward, and also the rear wheels spin as soon as I press the button instead of moving as the wheel colliders are moving. Almost part of the code was done by an AI, those two errors were done by the AI, but it made it worse than it already was.
You need to learn to read and debug your code. Don't expect people to fix Ai generated code for you.
Regarding delay, the issue could be with the input or the way velocity is accumulated. You can investigate both with debug logs or debugger breakpoints.
I've no clue what you're trying to ask.
nvm
in c#? i vaguely remember c# just not doing this when i was checking this out coming from java
yeah, it's super rare to see it, but unbounded generics can be used in some places. like the typeof operator, and nameof in c# 14. i wanna say i've seen it in asp.net as well? maybe with dependency injection or something, but it's been a while since i used that
interesting
yeah i've used it in typeof for some custom editor scenario iirc
-# turns out the dependency injection related stuff i was remembering was still just the typeof operator so really it's just those two operators
Any idea why limiting FPS stopped working for all my projects?
I'm running Unity 6000.10f1, but was not coding for a while. Yet I updated unity for all projects in the meantime due to the security issue they had.
I checked other projects and they also ignore the FPS limit of 60 now and instead use VSYNC at 144 Hz.
Also, if using vSyncCount = 2, it still uses 1x.
Also, if using vSyncCount = 0, and target frame rate -1, it still uses 1x VSYNC, ignoring my code entirely.
But I can see Unity recompiles when I change the settings.
I did not change my code at all.
Might want to explain how you're verifying this, what platform you're compiling to and if it's VR or whatnot.
Just the statistics overlay in Unity editor.
Also, I use URP 3D, in case that matters. No VR.
Let me check an actual build...
OK, actual build has same behavior (checked with MS Game bar). So ignoring my code as well, using only 1 blank VSYNC.
Also Ignoring Project Settings -> Quality -> VSync count setting.
Same a in Unity Player.
Oh. Never mind. Problem between chair and keyboard. It's a great idea to actually use that script in a game object
if you wanna have it do anything. Where is my coffee mug?
Me only copied the code from an existing project and forgot to assign it. Sorry. 
It works not in the actual build, but Player still caps at 144. Weird, but can work with that.
I'm trying to change emission source position for particle system thru code but i can't figure out how to access it's transform.
I tried using "ParticleSystem.shape.postion =" but it says that ".shape" is read only. I tried using "ParticleSystem.transform.position" but it moves object instead of just particle emiter.
Any tips for how to set particle system emission source position properly (thru code and not editor)?
You need to get the shape module into a local variable first and then modify it. Particle modules are a bit weird since they are structs that act as wrappers for the functionality
ty
Iβm kinda confused about what caused the error. Does anyone know how to fix it?
!code
π Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
π 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.
and look through the stacktrace to see which script and line it's coming from
modelItem = Instantiate(modelItem) seems wrong
typically you want to keep a prefab for the argument for Instantiate, and then receive an instance of that prefab as the return value
these 2 things should be kept separate
so ive got an issue with one of my scripts where i want to make it fire in bursts (i got that part down) but i want to make sure i can start another burst while one is already active. how would i fix that?
you havenβt described something that is broken
we would need to see code and know what you donβt understand
if you want to be able to do several things simultaneously, you almost certainly need to either:
- explicitly store information about each activity in a list
- start a coroutine for each activity
i have it so that on every right mouse button click it fires a small burst, but my issue is that i need to make it so that right clicking while a burst is running doesnt trigger another burst while the other one is still firing
have a variable to store the state that you're currently burst firing, then check for that being false before you fire a new one
would recommend using coroutines over invoke here, so you can have the logic flow contained in a single method, just gives you more control
you wouldn't need eg bulletsFired to persist across method calls, it'd just be a local inside the coroutine method
so like this
no, that immediately sets firingBurst back to false
InvokeRepeating just says to call that thing later, the code after still runs immediately
i think this works better?
could just have firingBurst = true in the "fire bullet" part, and also you could use !firingBurst instead of firingBurst == false, but yeah, 
i'd recommend looking into coroutines though.
also, seems like you'd keep firing the burst fire even if you run out of ammo, is that intended?
it'd go into the negatives lol
no i didnt even notice that
also note that this would also wait before firing the first bullet in the burst
if that's not intended, well, there would be multiple workarounds each with drawbacks, but the proper solution would just be to use coroutines or similar lol
i have no idea what those are
they're basically a tool to manage doing work over multiple frames, they make waiting and such easier to read and write by keeping stuff together in a single method rather than being scattered into class members
Hi! Im very new to Unity and was going to add Animation Layers to my Player Character, however when doing a quick test it ended up messing up the ground check and making the character extremely floaty
I didnt know where else to put this but some help would be greatly appreciated!
So I've been trying to tinker with my player's attack animation and noticed that some frames of animation won't appear on screen sometimes. Like my character's active hitbox is about 3 frames but when I slow down footage. It would be 2 frames of active hitboxes instead of three. Its inconsistent and Im not sure on what could be some potential causes for this
Anyone have potential ideas as to why?
Its 2D sprites in unity 3d so idk if theres something Im not really do properly
Oh I didnt see that one thanks!
@gusty briar if the issue arose from messing with the blending you should probably ask here as well
c# kinda hard tbh
the first language is always the hardest
I don't think c# is particularly hard. Every language is daunting at first, you will get quickly going though. Start from the basics and it will quickly start making some sense
Its in the middle id say
c# best language
first language is always hardest, to me C# was very easy, but i also knew multiple other languages before coming to it
Hi, how can I move the boolean checkboxes to the right so that the names aren't obstructed in the inspector?
is it using a custom inspector/drawer?
No, just a regular struct with [SerializeField] variables
You see the unity inspector is trash by default so you don't without add-ons like editor attributes (free) or Odin inspector
I quit working on AI for a month to just stall with doing architecture work (Which has mostly dried up now). Its been 1 day and Im already drowning. Do professional developers in this situation just hire a specialized AI dev or what.
how do even expect someone to answer this..
Industry people who get hired solely for AI jobs?
can your budget permit hiring someone -> yes -> hire someone
no-> simplify the implementation / scale down the requirements
Part of me feels this AI stuff is just so hard that I find it hard to believe people here are just chilling through it
and i also dont think u guys are hiring people so
define what you mean by AI, its a pretty overloaded term in game dev
Like u have 500 units roaming around in a section of the map. And then have to path 60 people through it while not losing any fps
I think they mean like NPC not gen AI thats abused
it really depends on the type of game, the path finding part there are multiple ways to do it, but how its handled for large groups like in a RTS game differs alot from a regular A* on a navmesh
more complex system can require more performance centric approaches like ECS / Multithreading
Yea i have literally no AI systems on the asset store that are compatible with my game style. It really is driving me insane
the behaviour of the NPCs really depends on your game, but the pathfinding part generally you can shove that off to its own thread
Yea like see multithreading messes with the very strict determinism of the game so id have to be a literal god steam programmer to do it right
well how you approach literally everything in your game changes based on if you need total determinism or not
i need to research more into it. What u said sounds like multithreading but idk maybe i can make something work on different threads somehow
not just stuff like this
multithread is great of offsettings calculations so you don't bog down the main thread for other stuff
So far so good on that end, its just not been working well with AI
Maybe its because i never really messed with multithreading but do u know how realistically how hard it would be for some to do it with absolute determinism?
yeah for example at my old job, yeah it took a few frames from a NPC to calculate its path, but it did not matter much since people would not notice that delay and it does not hold the game up since pathfinding had its own thread
the determinism comes from how you are writing something not so much thread themselves
put the proper checks to avoid hitting the same objects at the same time to avoid race conditions
Yea i chose a tile game because i thought it would be easier and now im starting to think its actually harder lmfao
when you say determinism I think more of something like physics, where at least I think Entities / Unity Physics provide things like determinism in that case
how you pathfind on a grid or a 3d mesh is the same for both
A* and stuff like that does not care what dataset it operates on, it just needs a node (that is a convex space) and its neighbours
Would be so cool if unity would've actually provide a standalone A* component
last time i wrote my own, the part doing the work could be applied to grids, a bsp or just a navmesh and worked
we have NavMesh which is essentially A*. They should've abstracted that into seperate component so you can also use it on grids / 2D
the navmesh built in is good enough for most cases especially if 3d
its mostly only a problem for something like a rts game
yeah true , the navmesh agent. Another different story but there are workarounds
last job i built my own soultion used for the whole org, but it was due to fitting the needs of the type of game they make
current job i am just using the builtin stuff since what is needed is way less specialized
I used free version but Aaron bergs A* pathfinding project has some decent stuff too. I bet by now its highly optimized compared to when I tried it last 4 years ago
yup thats why i had it
i kinda hate how the free version is just an older version though
like i dont mind having less features on the free version
even for 2d something that is a octtree or navmesh can work better then a grid, results in way less nodes
but at least it could be kept up to date for some other issues
Not sure if this is beginner but
Im working on the system to save my game, its already working.
I have a shop where you can buy items, currently the items available are filled in inspector with a list<Item> (Item is a scriptable object)
but im trying to think of the best way to save that data. Also to save which items have been bought already.
I was thinking a Dictionary<Item, bool> ?
but i wanted to ask other ways people accomplish this?
learned octtrees the hardway when I had to make flying / swimming enemies.
the navmesh was just unfeasible even offsettings only mesh itself
yeah flying throws wrench in things
you will notice in something like a RTS game everything flys at the same height from ground
since they more or less just used a 2nd grid of mesh for the sky
if its offline, why not just put purchased items in a list directly ? not sure you need a bool
if they are in collection, they are bought
yeah true in simple cases this is fine, sadly not if you have air obstacles to traverse up and down
yeah i would not want to figure out how to do one for a game like decent
pushed navmesh to its limits xD
at first I had an "air" base platform navmesh would navigate then use raycast to shift the mesh/collider up and down while keeping nav agent glued on mesh, it was not pretty lol
but yeah either way to the OP, this is all stuff that can be learned, just might take a week or 2 of a deep dive to understand it then start building. But i would first lean on established things like the built in system or the pathfinding project if they suit your needs
i found creating good NPC behaviour that feels good for your game and doing good steering and stuff was harder then the pathfinding aspects of things
Yeah i suppose i could, in my shop i just wanted to show already purchased items with a "SOLD" sticker on them
so was thinking the bool could be for if it was bought already,
You're right i could just add bought items to a list and compare the availible list to the purchased list?
You could do it so many ways, thats just one of them
but yes you can def compare two lists, you also have functions in LINQ like Intersect() etc,
you can compare for example an ID etc.
basically You don't need to compare an enitre Object, an ID should suffice
foreach (ShopItem item in shopItems){
bool owned = IsPurchased(item.itemID);
if (owned){
Debug.Log($"{item.itemName} is already owned");
// buyButton.interactable = false;
// ownedText.SetActive(true);
etc.
}```
async
what's the issue you're referring to here exactly
I used a box collider to check if it was on the ground, and then it malfunctioned like this: the jumps were jerky, and when I entered another section of the track, it got stuck.
why do you have both a capsule collider and a box collider
yeah no i shouldve been clearer. why are they both non-trigger colliders
it seems like half the issue could be that your tilemap is not using a composite collider
do you have a composite collider on your tilemap
and the tilemap collider is set to use the composite?
!code
π Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
π 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.
Instead of using a actual collider for ground checking you can use a box cast
https://docs.unity3d.com/ScriptReference/Physics2D.BoxCast.html
This would arguably be better
ok thanks
Bro, I checked my settings and it's like this, so it's something else.
Project Auditor might complain anyway as this option is expected to be removed in 6.8
So what should I do?
You can probably turn the rule off in Project Auditor settings. Could also change the code.
2022
Yoo, I'm trying to make it so when I turn the mouse left or right it rotated my character accordingly
I'm using cinemachine to follow the mouse movements, and I have the mouse locked
but I want a code that'll actually move my character so I turn when the mouse moves, I can't for the life of me find a way to do it
My "move" do you mean rotate? Is this your own character controller/movement?
Sanity check here, is there anything that can suppress an OnDIsable call?
I keep getting NREs from events that I should have safely unsubscribed from
in the OnDisable class
seems to happen on scene switching
Use OnDestroy because on disable has some additional dumb rules
But only other thing I can think of is its virtual and overwritten
Yeah rotate my bad, I'm using an old input control script to move it. I'm superrrr new so bare with me if I didn't understand you lol π
you dont want cinemachine to rotate your camera(s)? would be less coding for you
No worries. Regardless of how input is read you can rotate the transform/rigidbody using X mouse:
Vector2 lookInput = look.ReadValue<Vector2>() * LookSpeed; //New input system action
rigidBody.rotation *= Quaternion.Euler(0f, lookInput.x, 0f);
Cinemachine can handle the camera movement to follow the player for you so you can just worry about the player movement
I could call On disable through On destroy? just make sure
I've made sure to call base
on overwritten methods
but tell me this, why OnDisable?
do you actually disable this and need it to unsub then be able to resub on re enable?
I just call subscribe on enable and assumed the convention was to unsubscribe in ondisable
this happens between scenes
so when I leave a scene, then come back
To me unless you actually want to do this specifically on enable/disable you should use Awake/OnDestroy
there are missing things
Then i re direct you to my question again and ask if you actually need to do this on enable/disable?
sounds like no
I always do Awake/Start + OnDestroy myself
Or Init() + OnDestroy
i'd like to mention: Awake+OnDestroy, or OnEnable+OnDisable
ops that was a mistake, i mean Awake + On Destroy
@stuck palm tl;dr swap to Awake/Start/Init + OnDestroy if you dont actually need this to happen on object enable/disable state change.
okay will do. thanks
there are some instances where onenable / disable is required , such as a settings menu that is enabled and disabled but for others it makes sense to use the other
such as scene swaps
hmm does it really? does this settings menu exist always?
but you know better than we do what your stuff needs
it's like a game object in a scene
does not persist
what actually is the difference between awake and start? they both only call once right?
Go read the monobehaviour lifecycle page to see why I have said everything I have...
And then hopefully realise the difference
I might be dumb but I have no idea what the hell this means
so it's only called before onenable??
but I see that awake is the very beginning and on destroy is the very end
Awake is called once for a monobehaviour, same for on destroy.
On enable and on disable is for when the game object is enabled and disabled and each time that changes after.
Meaning awake and on destroy inform you of creation and destruction once as they should
*OnEnable and OnDisable happen when the specific monobehavior gets enabled/disabled, both including its own enabled state, and the activeInHierarchy state of its gameobject @stuck palm
so basically, whenever its isActiveAndEnabled state changes, which requires it to be enabled, and its gameobject and all parents to be active - if any of these become false, that triggers OnDisable, and once all of them become true, that's OnEnable
also note that Awake for scene objects also requires the GO to be activeInHierachy, so an object may never have Awake called if it's never active before it gets destroyed
I have it rotating my camera but I want my character to rotate across the y axis as my mouse moves also
I'll try this when I get home and let you know ty!
cinemachine obviously rotates all axis's, idk what you mean π€
hey guys so ive been really frustrated with trying to even get my player to move right and i genuinely want to know how to even learn this thing. cuz every tutorial i watched uses a different system and i have no idea which one to even use
i might be stuck in tutorial/course hell so id really really appreciate if someone gave tips or something on learning this. i did 2 courses on unity learn (roll a ball and haunted house) so i tried referencing the script for my own player movement. but i genuinely dont know how to add jumping like call me a dumbahh but ive been stuck on this for 3 hours ππ
this is the original script that i took from the haunted house course, and the one that i tried modifying. i kept trying to add a jump MoveAction based on the original script but i kept getting errors. like if anyone could just point me in the right direction or resources id be so so thankful. 
That'd be rotating the camera tho, I need the object the camera is on to rotate with the mouse
oops i just realized the error image is cropped
!code
π Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
π 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.
oh sorry!! it was my first time asking and posting code ill make sure to use those next time π
No prob, it's just easier to look at the code from a link . . .
lemme send them as links real quick! thank you for the note :>
https://pastes.dev/csXu3PfyxD (original script)
https://pastes.dev/MWTS3M5dnx (modified cuz i wanted to add jumping)
im still trying new things rn but yeah i think i keep going in circles or end up writing incomprehensible code
sorry if its confusing im confused too
is there any way to use get and set accessors on a ScriptableObject?
such as:
public class SomeClass : ScriptableObject
{
[SerializeField] public float MyVariable
{
get {...}
set {...}
}
}```
you can use properties on a scriptable object just fine. but you can't serialize them directly, you can only serialize their backing fields
props aren't fields, you can't serialize them. instead, serialize the automatically generated backing-field, [field: SerializeField]
My answer is their two answers . . .
[field: SerializeField] public float MyVariable
{
get { ... }
set { ... }
}
if i do this i get a CS0657 warning
that only works for auto properties. if it has an explicit backing field then just serialize that
oh you actually have custom accessors?
yes
serialize the backing field you have instead then
value inside accessors isn't supported in unity yet, right?
you might be thinking of the new field keyword that isn't supported yet
It is . . .
so just
[SerializeField] float my_variable
right?
and i put my accessors on this public one
oh, yeah probably.
i tried to use [field: SerializeField] and i'd get a warning
value is the input value for setters, but field refers to an automatic backing field and that one isn't serialized, did i get that right?
that's not what i'm referring to
[field: SerializeField] works for autoprops
[SerializeField] works for fields
the unsupported field i'm referring to is inside accessors, to refer to the automatic backing field
okay
got it
public float MyVariable
{
get { ... }
set { ... }
}
[SerializeField] private float my_variable;
so I can use this yes?
i h ave this game and the ONLY script i have is my movement script. i have no animation triggers
my player gets deleted after 5 seconds of me not moving. even if i actively move into an object as long as my character is not moving it just gets deleted
i have no idea why this is happens
im attaching my script just in case (https://pastes.dev/rGd3hnHIP5)
!code
π Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
π 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.
@heady pagoda use a pasting site to share your code
dont send us the .cs files directly
oops mb...
And you have no other scripts in your project?
not attached to anything i have ones from brackeys like 2d basics but theyre not attached to anything in the scene
do any of them reference destroying the player game object in any capacity?
this is my scene setup
as far as i know no...
also it could be your train renderer as well
it is your trail renderer...
youre setting it to autodestruct, its destroying the game object when all of the points are removed
omg thank you so much i love you omg....
Hello guys. I'm a beginner in Unity and I'm trying to develop a simple AR. Well, here I want to ask how to add AR maker information in Unity but the button content displays the information. AR is scanned > click the information button > the information description of the marker appears. Can anyone help me provide a tutorial?π₯Ήπ
compute shaders make me depressed π
Dont crosspost
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
β’ ** Collaboration & Jobs**
what's it?
read the bot message
I did it, but no result
what
Im talking about this. Read what it says
specifically the very first sentence
I have this "funny" bug, when I select multiple Area Lights and then I try to extent the Light component my editor closes. Can some try this, So I know that it is only on my system, so I don't have to report it as bug at unity
sounds like an editor issue
what do you mean extent the light component though?
I show you
On the right the light comp.
Also happens when I select 2.
what version of Unity are you using?
I dont realy need a fix though, I was just wondering if someone has this problem too
6000.3.9f1 (The 6.3 LTS version)
64GB, so it should be enough
Hello ! Again, i have question about the the Raycast system.
So, basically, i want the A point to touch the C point no matter what, and return :
- False if there is a wall (In the layer : LevelTiles)
- True is there is no wall
Here's the code : https://pastebin.fr/019e3732-88d3-728b-a6b9-f376b40b0ef1
with the main line being if (!Physics.Raycast(PositionA, positionB, 20f, excludedMask))
But for some reason, it appear that the player is always seen...
The "LayerMask" only contain le Layer LevelTiles, and the wall is on that layer...
Am i doing things the wrong way ? If someone can help me, i would be glad. Thanks ! :)
excludedMask
the layermask passed it what layers it can hit, so might want to check that naming
anyways, yeah check the signatures of the stuff you're using
Raycast does not take 2 positions - it takes a position and a direction
Well, thanks for giving me some explications. It surprise me tho because it does work when i give two positions, am i doing something wrong ?
And alright, i'll check..
because it does work when i give two positions
that's by coincidence then.
just being the right type is not enough, it also needs to be semantically correct - points and directions and etc all mean different things and have different meaningful operations.
The visualization is not the same as the actual raycast
Ok I tried that code and I couldn't get it to work.
I tried using this code and it just made me rotate to the right (positive of the y axis) slowly no matter the speed I gave it. Is it maybe because I locked the camera or am using play mode in the engine?
[Header("Settings")]
public float LookSpeed = 1.0f; // How fast the object rotates (default: 1)
void Update()
{
// Get mouse deltas via Input.GetAxis()
float mouseX = Input.GetAxis("Mouse X"); // Horizontal movement
float mouseY = Input.GetAxis("Mouse Y"); // Vertical movement
// Rotate around the Y-axis (left/right) and Z-axis (up/down)
transform.Rotate(Vector3.right * mouseX * LookSpeed * Time.deltaTime);
// Hidden just in case I wanna try it
// transform.Rotate(Vector3.up * mouseY * LookSpeed * Time.deltaTime);
}
Debug.DrawLine has different parameters than the raycast
Oohhh β that's why, i thought it worked, while it didn't
lines and rays are different semantically! rays have an origin and direction (and maybe a length), lines have an origin and an endpoint
Alright, im checking on the documentation then, i do have to say i don't understand how im supposed to do now :(
you have a position, you need a direction
you have 2 positions, you need a direction from one to the other
"how to get a direction from a position" would be next question/step
you can get the direction by subtracting 2 positions
(you need 2 positions)
Wait it does ring me a bell..
I think i've already studied that one day
You don't need to include delta time for this and I presumed world Y would be the axis rotation but here you are using X?
I asked a friend who knows a bit more then me I dont really think he understood me though. I figured out something on the unity forums but its still kinda eh
public float horizontalSpeed = 2.0F;
public float verticalSpeed = 2.0F;
void Update() {
float h = horizontalSpeed * Input.GetAxis("Mouse X");
float v = verticalSpeed * Input.GetAxis("Mouse Y");
transform.Rotate(v, h, 0);
I set the vertical speed to 0, and it turns left and right. but its delayed with my mouse and kinda iffy
Oh I thought the vid was send here I guess its too big
I'll see if I can compress it rq
Thanks ! I now do
direction = PositionA - positionB;
And i've changed :
if (!Physics.Raycast(PositionA, PositionB, 20f, excludedMask))
to
if (Physics.Raycast(PositionA, direction, 20f, excludedMask))
I still have the same issue of player always detected tho... But at least now i understand how to do things properly
size won't be an issue, the issue is that discord doesn't embed mkv. send it as an mp4
this will be backwards
you need positionB - PositionA
Here we go,
Oh euhm yeah that is actually right TwT
i apparently am too tired to write up a coherent explanation of why it needs to be B - A
look up a vector tip-to-tail thing or something
Dont worry about that.
As long as it work, im fine with it xD
nah, understanding this stuff will make it easier to work with
This should work and is actually close to unitys example for how to use GetAxis()
https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
Oh, alright, i don't have this mentality, so having this kind of suggestion is really useful !
I do have a line correctly drawed from the AI to the player now... But it always return "true" (player IS seen) no matter what, this is weird and i need to investigate it.
Hello everyone, I am trying unity and ive come to an issue. I've imported easyroads3D (free version) and everything is pink . I did windows-rendering-Rendering pipeline converter and didnt fix the issue. Is there any good road assets or is there an fix to this?
does unity support record class types?
not yet!
you can't easily convert something if they have custom shader
conversion usually only works on unity birp shaders
So i should swap to something else like unitys splines?
use something built for URP if thats what you're using or you'd have to make your own in splines sure, that can get quite complex depends wat you're doing
oh, so i should replace my record types with a class or struct type and modify my code to fit it?
For those who knows a bit of RayCast, ima going to be honest :
I've followed the Unity documentation regarding RayCast & layers and now i am dead lost. Like everything is... Broken.
Here's the new code : https://pastebin.fr/019e3788-d5b1-719c-8f51-a755c4d9282c
Here's how it looks...
If someone is okay to explain how wrong i am, i would be happy to listen to it.
thanks !
you have no other options rn so yes
is the yellow line supposed to be representing the raycast?
your direction is backwards
ah well not backwards. certainly wrong though
it needs to be B - A, you have -B - A
Oh damn i-
No, it's just gravity related π !
i mean, you have 2 of them, one of which seems to be coming from the raycast code
Yes, the line going in the direction of the floor? it's just an old Raycast, ill remove it..
i was asking about the other yellow line
Oh yeah, this one is supposed to represent the raycast, and now it does work. Thanks !
But still, i have this issue that i now have to fix..
Does any1 have any good ways to create roads that are free? Or any good tutorials. Thanks
Ill look for that and ill try to figure it out myself, thanks Chris and iAmBatby for the help already ! :)
Fairly good actually
what issue? you wrote this log man
The problem I had with unitys road system was that when I placed the road it didnt set into the terrain. If i put it abit lower it would ofc dissapear since it would go underground. If i put it higher it would be to high to drive on. So there was no way to get the perfect setting
I did ! But the player is NOT supposed to be detected by AI through walls...
It prints the same message if it detects it or not
So the player is supposed NOT to be touched
i hate myself, i really need to be more careful when i copy/paste things... Thanks...
Does anyone know how to tie gamespeed to in game fps?
Do you mean the opposite ?
Im aware this isnt exactly a good thing and thats why unity keeps them seperate
Yeah oops
It depends on what your doing
I want them tied together so if the fps drops. The game speed drops too
why would you want that?
Its prob a solution that would solve an issue Im having
and the game is locked at 60 fps for balancing reasons anyways
Why not ask about that issue

this smells like an xyproblem
no esport game does this
fighting games?
Well I dont wanna go super deep into it. Is there a way to implement this into a unity project?
instead of trying to force some hacky solution that nobody would enjoy, why not address the underlying problem
sure, google how to not do that and just do the opposite π
nevermind
Thats not the case but if theres not a way to this then thanks for all the help I guess
We would need more specific info for a more specific answer
what you're asking is going to make someone running 30fps have a slower game than someone running 60fps which makes no fucking sense. why would anyone want that?
you should actually address the actual issue, and if you want help with that then you need to describe it.
you're trying to force a shitty solution that will make the game actually worse
bit of a weird vibe
Relax and thats up to me to decide whether I want to do that for my game
If you don't want to help thats fine but no need to get so aggressive about what is a bad decision for my game
Sorry for not providing enough context
You would need to alter the timescale all the time based on the current framerate as modern engines are designed to NOT have this flaw
your own logic can do this easier but yea its not a desirable thing hence it being weird to use this as a solution...
it's literally introducing a different problem that makes the experience worse to solve some thing you won't even describe because you're dead set on this bad solution
Oh okay
what is the actual problem anyway
Ill try to describe best I can
If the game fps slows down from 60 to 59 or anything lower. The animation of the 2d sprite would tend to skip or extend certain frames to keep it consistent with the game fps. Which would be fine in most cases but since Im making a fighting game. If a player animation gets extended this could result in the active frames of an attack to be extended
or it could skip a frame and make the active frames of when an attack could hit shorter
is your animator using unscaled delta time?
and my thought process was that if the fps was tied to game speed, when the fps drops. The framedata of attacks stay consistent
If framerate is capped and advancement of this simulation uses frames then that would produce the result you want
but things like the animator and anything else needs to be fudged with timescale changes
advancement of this similuation?
Sorry but can youclarify what you mean by that
e.g. your own animation system that you "tick" forward using Update()
Oh the sample rate?
if you animate and advance this game state yourself then easy
e.g.
float duration = 1.5f;
float time = 0f;
const float FrameCap = 60f;
const float FrameTime = 1f/FrameCap;
void Update()
{
time += FrameTime * (FrameTime / Time.deltaTime);
}
So I use a state machine. WOuld I basically put this inside each state script for each animation?
if designed badly i guess but lets hope not
a better design would have a singular update with a custom delta that is then used to update everything pertaining some object
pertaining some object? Like as in this doesnt affect everything in the scene but per object?
Id recommend some master manager to tick everything with this custom delta and then go from there
Okay thank you
It means you need to properly organise your objects however as you can no longer rely on magic Update(). I recommend dependency inversion and good use of interfaces
https://en.wikipedia.org/wiki/SOLID
The statemachine that calls each state is running through Update(). Would I not be able to do this?
Okay, unity handles calling Update on our scripts for us. So my recommendation is your own manager to do this but instead provide the custom delta
Or you need to re calculate this everywhere/inherit from a type that does this for you
Ohhh okay lemme try something then. I think I can do that
at this point do what you can manage but try to make use of shared constants for the important values like the framecap
I wondered a little bit ago but I want to find the closest enemy to an object using overlapSphere, alot of forums use stuff like using the sqrMagnitude of the distance and all that
but i wondered if it would be more optimal to just increase the size of the hitbox over time and return the first thing it hits, is it more expensive to constantly change the hitbox data of a sphere or to just use some distance math in a preallocated list
not in a sort of conundrum about optimization I was just curious lol
the physics thing is most likely more expensive, but also note that it's a different operation with different results
checking distance gets the closest by pivot of each object
checking with physics gets the closest by collider bounds
though note that the physics thing alone won't guarantee getting a unique result anyways
bottom line is, consider how exactly you want it to behave. i did say the physics thing would be more expensive but if you're not doing overly tiny increments then it probably won't be super significant
Hey guys, I am new to Unity 3D and was having some trouble with cinemachine settings, I would really appreciate it if someone could help me out.
Basically I wanted to know if there is a way to set cinemachine freelook camera an equal distance away from the player no matter where the player is looking? (Screenshot is what I want to avoid, I want the player character, in this case the capsule in the center of the rings)
the freelook camera has always been kinda wonky to use imo i usually just use a regular cinemachine camera attach it to an object on the players head and rotate that object via mouse inputs
Regular cinemachine camera? If you don't mind could you tell me the exact name... π
i think its just called virtual camera or cinemachine camera
its gonna require some extra coding but it will be better since youll have better control of the camera anyways and dont gotta deal with the freelook cameras wierd numbers lol
yea i was jus wondering if messing with unitys hitbox detectoion stuff was flexible like that
but i think it would cause problems later down the line anyways if it hits 2 objects at the same time or sum
wonder if its possible to make hitbox detection without relying on unity physics engine and probably having some unessesary calculations not go thru
that would be making your own physics engine and it will be slower
real lol
If I move code files in GIT that counts as a file remove and a file add, which removes the change history for that file.
Is there any way to get around this? What do other programmers do here?
git can track history through renames
is there any good tutorials on how to set up Git for a Unity project, I want to use Sourcetree as that is the only thing I have experience with but if needed I can switch
source tree is a git client, it has no bearing on what projects it can be used with
go get the unity gitignore, set up the repo at the project root and work with git as you would normally
if you have large assets you could use lfs for them
Hello, guys! How to get reference to a specific Audio Mixer Channel, because I have to do something with the channel and I am not sure how to get a reference to it?
Basically, I have a mouse hover sound effect on my UI buttons and when the sound effect / SFX Mixer Channel reaches -80dB for one reason at the end I hear frequencies that are annoying for the player experience, so if I do hover many times and the sound effect will play 5 times lets say I hear this disturbing frequencies at the end, when it reaches -80dB.
I think you have to add exposed parameters for anything you want to change
So my gitingore seems to not be removing the library folder even though its in there
Once comitted you have to explicitly untrack assets. Git ignore changes wont affect already tracked things
i havent commited anything yet
Then something is wrong such as your unity project not being the root of the repo
that is probably why
Ill check
If its Foobar/Library, Foobar/Assets then thats why!
foobar?
example name
ohhhhh
That fixed it thank you!
How should I start with the coding, I'm an upcoming BSEMC student without any knowledge about coding
there are beginner resources pinned in this channel
Hello everyone, I am trying to set roads since i found an good asset, I am wondering is there a way to find a middle to this mesh so I can set the anchors correctly? ty
MeshRenderer.bounds.center probably
Yes, thats what I did, but I dont think I can get reference to a specific channel with exposed parameters. Basically, what I want to do is to set the dB instead of -80 to be -79.9 because I think thats the problem when it reaches -80dB
Yes so you need an exposed parameter for that specific channels volume
I have 4 btw
exposed parameters which are constants on my script settings maanger and they are used for my volume sliders
But what I want it to do is on event to set the dB to -79.9 basically
Let me show you my scriopt
so do that?
Yea unity does not provide a way to modify any channel specifically apart from the exposed params
no idea why its so black box but hey ho
using UnityEngine.EventSystems;
public class UIButtonAudioEvent : MonoBehaviour, IPointerEnterHandler, IPointerClickHandler
{
private AudioManager audioManager;
private SettingsManager settingsManager;
private void Start()
{
audioManager = ServiceManager.GetService<AudioManager>();
settingsManager = ServiceManager.GetService<SettingsManager>();
}
public void OnPointerEnter(PointerEventData eventData)
{
audioManager.PlaySFX(SFXType.Hover);
}
public void OnPointerClick(PointerEventData eventData)
{
audioManager.PlaySFX(SFXType.Click);
}
}
{
float masterVolume = masterVolumeSlider.value;
float dB;
if (masterVolume <= 0.0001)
dB = -80f;
else
dB = Mathf.Log10(masterVolume) * 20f;
audioMixer.SetFloat(MASTER_VOL, dB);
PlayerPrefs.SetFloat(MASTER_VOL_KEY, masterVolume);
uiEvents.RaiseUpdateSliderValue(masterVolumeSlider, uiManager.MasterVolumeText);
}```
So here I have my settings manager and UIButtonAudioEvent class.
but slider has nothing to do with it I dont know why I send it XD
im confused what the issue actually is
oh sorry
if you dont want it to go below a value then clamp/correct the slider min
my bad yes you are right I can do it with exposed parameters with an out value I thought there isn't a method to GetFloat and there was only to SetFloat
Oh right yes if you want to read back the current value then yes.
However if you always control the value set you shouldnt need to
because I cant really remember what the out keyword does?
it is a way to return more than 1 values from a function?
Basically, yes
if you do need to return multiple related things from one method call you typically would want a struct containing that data though. the out keyword shouldn't really be used as a replacement for returning related data
It is most useful in cases where you want your function to return a "status", and if that status is that the function failed, the out parameter isn't ever used anyway. This is how it's used in things like TryParse or TryGetComponent
They don't want all their data at once, but a sort of two-tiered system where the out only matters if the return is something specific
Hey guys I'm using Unity InputActionMap and have a question, I have a PlayerInput.cs, and IControllables, and was wondering If its possible to do something like ```c#
public interface IControllable
{
InputActionMap inputActions { get; }
Vector2 OnMove();
Vector2 OnLook();
void OnKeyPressed();
}
private IControllable controllable;
foreach (var action in inputActionMap)
{
action.performed += controllable[action];
}``` The general idea is just naming all my map actions the same as the function they should be activating in IControllable
This is PSEUDO code btw, not functional, just to get the general idea across
controllable doesn't seem to be an array and the interface doesn't seem to implement the indexer operator. Not sure what your pseudo code is trying to illustrate.
i mean, technically it's possible but definitely not good practice. honestly you could just implement a default method on the interface that takes in the action map and manually subscribes to the actions using the relevant methods and it would be much better than setting up an indexer that compares actions and returns the relevant method group
What if Im using multiple InputActionMaps though? For example, I currently have two different control schemes, one uses Mouse(Delta), the other Mouse(Position), If I add more, I feel manually subscribing will bloat user control, especially when I need to subscribe every time the IControllable changes for example if I want the player to control to a vehicle
either way you're still going to be getting the relevant method groups manually somehow. i'm just saying that you can put it all into a single method that is implemented directly in the interface
then you aren't duplicating the code anywhere and it isn't a mess of trying to determine what action was passed to it and which method is relevant to that action
Oh wait, so you mean I can manually subscribe in the interface implementation?
I think im overcomplicating this, I could probanly just pass the InputObject lol
yes, unity supports default interface methods which you can do here. or you can use some static method in some static class that handles it (that would require passing both the interface instance and the action map)
interfaces can include events in their definition but no idea if default implementation works here
the interface wouldn't need the event, they would just be subscribing to the existing events on the action map passed to a default method
So essentially Id just detect if the player needs to change the IControllable object (From say a car to a plane), pass the InputObject to the new IControllable, then just subscribe in the implemented IControllable
oh right just bridging from event -> some instances
basically just this:
public interface IControls
{
void OnSomeInput();
void SubscribeInput(InputActionMap map)
{
map.FindAction("SomeInput").performed += OnSomeInput;
//etc
}
}
Excellent thanks alot
I'm creating timeline assets programatically, but I keep getting warnings spammed saying "Empty track found while loading timeline. It will be removed." What am I doing wrong here? I am creating assets and putting them in the track
How to address cinemachine freelook through code?
Or how to toggle between two different cinemachine cameras?
If both cameras have the same priority, whichever one was enabled most recently will take focus, so you could just enable the camera you want to switch to
And then disable it when you're done with it, and it'll go back to the old one
And do the cinemachine third person follow and freelook cameras have the same priority by default?
You could just look at their inspectors and check
what do you guys use for this now?
tried the dropdowns
didn't work properly
currently in learn unity
Check the IDE suggestions for the replacement method
the "dropdowns"?
oh, interesting: they're getting rid of the sort mode option
(i always found it extremely annoying to have to specify that, especially because it came after the "inactive" parameter in the two-argument versino)
what
what exactly is the warning/info message
it tells you that you can use the method without the SortMode
oh nvm I got it, that wasn't the problem
what was the problem then
got a bit confused cause of the dropdown, so I tried doing the suggestions first, completely ignoring the other code
It's a popover, not a dropdown (which is why people didn't know what you were talking about)
yeah mb
using System.Collections.Generic;
using Unity.ProjectAuditor.Editor.Core;
using UnityEngine;
public class InventorySystem : MonoBehaviour
{
[SerializeField] private GameObject InventoryUiParentObj;
public Dictionary<string, string> Items = new Dictionary<string, string>();
}
Why is the dictionary not visible?
Dictionaries cannot be serialized by default. You'll either need an editor extension or use a different data structure
oh ok ty
i am surprised that Unity hasn't implemented that
oh yeah, there have to be a dozen SerializableDictionary implementations in random packages
because it's such a common desire
And yet they decided on "Shittier Claude" to be the selling point of the latest release
i am genuinely unable to explain why it hasn't been done
list serialization is a "special case", as I understand it
they put general improvements, new terrain system, behaviour graph package and ai shit on spinthewheel.com
Dictionary serialization is coming, presumably in 6.8
curious does this include the ability to turn Dictionaries to json without annoying wrappers?
JsonUtility supports whatever serialization Unity supports
roundabout way of saying yes ~_~
Got tired of manually setting up Animation Rigging IK for every weapon so I made this lol
Right click character
Right click weapon
Attach
Done
Might clean this up + open source it for free if people are interested.
Feel free to DM me.
im trying to put tf2 style rocket jumping into my game but im having some trouble
i saw a post on reddit that got it working using a modified version of the fragsurf github (which i already downloaded) but i cant figure out how to reproduce the post; could anyone help me?
https://www.reddit.com/r/Unity3D/comments/1e6g2lt/rocket_jumping_in_unity/
hey everyone, just want to say thanks in advance just in case i can't get back asap. but i do have one question;
Does anyone know of any good alternatives on the ''pity'' randomizer?
I'm looking for a solution that:
- after 'x' amount of rolls, this item has been selected ''at least once''.
important! *specifically not saying this:
- after ''x'' amount of rolls, all items have been selected ''at least once''.
i also need this to be true for all individual items
Alternatives to what?
a Pity System. it's a system that takes psuedo random and tries to make it 'feel' more fair for looting items.
becasue in a loot pool a rare item might have a 4% chance to appear. but it's possible for you to roll 200 times and still never see it even though that situation has approximatly an average of being picked twice.
the idea of a pity system is to make that rare item always be obtainable after '200' amount of rolls.
anytime you use a random number, it's always pseudo random. which i'm assuming you already knew, so i'm confused by what you are asking
"it's a system that takes psuedo random and tries to make it 'feel' more fair for looting items"
yes? what's confusing about that
yes i know. but why does it matter what the 'something' is. that doesn't matter wether im talking about cows or numbers or chairs?
bags?
i specifically don;t want to use bags because that means every item is picked exactly x amount of times after n rolls... i want their to be a randomness to it but exclude the super unfortunate cases..
you can randomize the bags
the bags don't have to be fixed
this only works if you only have 1 of these constraints though (or the constraints are all for the same x)
and it doesn't have the same "gets more likely with more misses" that typical pity systems have (at least i think they have? i don't have much experience with these systems)
i understand this.. but let me give you an example with numbers:
say i have 5 unique items. all with a 20% chance of being picked.
i create a bag that is twice it's size and every unique item is placed in the bag twice.
then it's shuffled.
the problem is if the first two rolls are (i.e.) item 1, then i can expect to never see that item again for at least 8 more rolls. <- this is predictable
and the constraint here is that each item needs to appear at least once in 10 rolls?
i mentioned randomizing the bags specifically to reduce this predictability
idk what the constraint is for this exact example. all i know is i want each item to be picked at a minimum of once after 10 rolls. not all being picked twice
ok so you said both yes and no lmao
i see where you are confused.. this is why i'm reaching out because google is confused to and so is Ai..
so in this case, you could have a bag of 10 elements where 5 are fixed, and the other 5 are randomized from that original 20% distribution
i can clearify that there is a difference in what i am saying
yes something like this sounds right..
im not confused about the content, only about you saying "idk what the constraint is, but it's this"
oh right, i was trying to figure out why i didn't want to do it this way.. and it's because i don't want to preconstruct a seeded bag..
how come?
(also disclaimer - this is just my spur-of-the-moment idea, idk if it's been used in real scenarios, there may be caveats that i haven't thought of)
because it iterferes with some of my other systems..
what i came up with in my head is something to do with individual item percentages that fluctuate when they have reached a maximum misses.
isn't that what the pity system does
so from what i can tell.. a pity system is used for items that are of different percentage values?
what you were describing is a function to bias the probability to make it more common over time
or just to give you the item after a fixed amount of tries
a pity system makes it more likely for rare stuff to hit if it hasn't been hit in a long time
so yes and no.. i guess maybe i'm not fully understanding what you are saying because i'm being dumb. but a pity system is like this:
4 common items at 24% each, 1 rare item at 8% = 5 total
after every roll that 1 rare item % is increased, and all common items are % decreased.
after 10 rolls, the rare item is garenteed to drop if it hasn't yet.
that is what i just said yes
yes so i want this system but every item is common, no rare items. or if it makes sense,,, every item is rare, and their are no common items.
so hopfully this will make it really clear.
every item in my game is rare. and lets say there are 25 items.. they all have a 4% chance to drop. all items are rare. not just one
so i need to garentee that every rare item is rolled at least once after 30 rolls for example.
without using a bag system
yeah pretty sure you just need a bag for that
otherwise you'd need a really convoluted system basically to emulate a bag
so i need [..] every [...] item [...] once after 30 rolls
So it's just a normal random system?
unfortunatly this is what i need...
no, just make a bag
very low max rolls and very similarly-sized pool, just make a bag for this, man
well actually the "bag" would be much bigger than this. probably near 400 items total but with multiple bags. so about 5 bags of 75 items
75 is still very low max rolls
isn't pity used for stuff in the thousands of rolls lmao
the problem isn't the size of the bags it's the time between rolls.
that isn't an issue
subnautica uses bags for its ore loottables
3200 extra bytes for a save file all things considered is not that much
so respectfully lol my game is not subnotica. and it's a very unique kind of game that is similar to an idler game mixed with rpg elements. but most of the game is waiting around. specifically on a major time scale similar to real life. one of the fundamental pillars of the game is actually closing the game and coming back tomorrow to see whats happened. it plays itself offfline.
i didn't say your game was subnautica
i just brought that up as an example of a long-lived bag
what's the issue with saving a bag here
i see, my bad.
ummm not sure it's 100% an issue. i need to think about it for just a minute..
becasue the idea of have a full bag that is mixed.. plus 1/4th of a bag might be a good idea.. but i actually don;t know if this will work..
forgive me as i'm just jumping in randomly (i did read above) but what's bag mean in this context?
i had a very good reason for not using a bag earlier today. i can't remember what it was. i think i need to just impliment a bag system and test it out.
a bag is a loot system that takes all possible items and makes them equally likely to roll at least x times in n amount of rolls.
an alternative to generating a new item randomly each time you need one
you generate a "bag", a list of items, and shuffle it, then each time you need a random item you grab from the bag
it helps manage results over time
not equally likely
you are right.
i see thank you
forgive me. a bag is a pool of items and when one of those items is selected randomy, it is removed from the bag. once the bag is empty it refills a starts a new.
eg in tetris, there's a randomization option called "7bag" where the set of 7 tetrominoes is put in a list and randomized, so you guarantee all 7 for each set of 7, but in a random order
Ideally but it could restart prematurely if need be.
or in subnautica as mentioned previously, there's a drop chance for each item, but using a bag so it guarantees you don't get unlucky and get starved for a specific resource
didn't know subnautica did this
i didn;t either but yes it's a good quality of life for players to 'feel' like the game is random but not fully random.
thanks to all the people who helps with my options for randomizing items. i implimented the bag idea. it's working well
is it okay to ask here about canvas/ui element issues?
Hey guys, I tried making a 3D boss fight game. But I've realised that I lack the skills to make it a reality for now but I don't want to give up, almost every tutorial I follow I just end up copy-pasting, not really understanding why I am doing what, and I'd usually just end up following step-by-step instructions from ChatGPT.
I don't want to do that anymore, could anyone recommend some resources (whether it be youtube videos, sites, books, courses, preferably free since I am a student from a third world country so I don't have too much disposable income) so that I can learn Unity from the basics and have a strong foundation which I can build upon
Any help appreciated β€οΈ
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
also, google is your friend!
instead of just copy-and-pasting, start researching the parts you don't understand
I tried, but I couldn't make sense of most of it. It just taught me that I was in over my head π
well, that's still something valuable to figure out lol
don't worry. take your time, and break down each line. the biggest thing that helped me is typing everything line-by-line, word-for-word, and looking up every term along the way.
public int curHealth;``` i would make sure i understand what `public` is and does. what is an `int`; why use that? then why we're calling it `curHealth` and not just `health`
`public` is an access modifier that specifies how much access (or how visible) the field is to the rest of you code (other types). there are other access modifiers like `private`, etc. `public`, specifically, allows access to all of your objects or types
`int` is a value type that stores signed whole numbers
`curHealth` is the name of the `int` field. we're using it to represent the current health of an object.
------------------------------------------------------------
it's a simple example, but if you do this for every method, calculation, and assignment, you'll understand what each line is doing and why . . .
That's a really good way of going about it. Thank you for the help.
Best practise is to just sit to code, and try different things.
it takes time, but the more eager or enthusiastic you are about learning, the quicker the process will be . . .
Wdym? Just sit to code?
Just open the editor, your new script and try things like,
Vector2
Vector3
Lerp
Unity Events
.....etc..
Cant give any other details besides this?
What sotrage type is it on, how long do you have to wait before it compiles? Does it even finish compiling, 1:36s isnt even that long to compile
Also just to say not really a code question
I can't find the correct channel to post it
You answered none of the questions i asked, and restarting should only lose unsaved scene data nothing else
though, make sure you don't have any infinite loops in your code
Is it good to split logic across multiple components?
Example: I am splitting Character movement and Character camera logic
These two could just be combined into one component
Are there any reasons not to, except clean composition?
Single responsibility I guess
In general, the more individual files you have the better, until you hit a threshold at which you, the human, are unable to understand the function of something
So, do as many as you're comfortable with dealing with
Hi, im new to unity and i wanna make a game, i know how to use blender. I want some advice (like wich language should i use or where i can find the best asset website (for free and paid)β¦) and i also wanna know if the unity ai is good or not. And like i just want know everything i need to know to get started π thanks
Not the channel to ask such questions but for the one that's valid, unity only works with c# nothing else so the language to use is c#.
Yeah. If you are using unity to make games, you have to learn either C# or visual scripting.
You can find great assets or models on sketchfab.
I really wouldn't recommend visual scripting at all there's really no upside to it
learning logic, components & in some cases quick prototyping for designers has its benefits
check resources in the pins in this channel
O alr thx and sorry but were is tge channel for such questions
Okay thx π
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
I booted unity today and my player suddenly is super floaty whenever I jump. Maybe the night before theres a hotkey I just dont know about or something. Does anyone know what could be the cause of this?