#๐ปโcode-beginner
1 messages ยท Page 750 of 1
then i use a little distance check that way any offsets i use are scaled accordingly..
(the distance text is offset 1/2 a unit above the object @ 1 unit away...)
using that simple conversion i can keep the offset looking good no matter how far from teh camera the tracked object is
so if i were 2 units away it'd be more like .25unit above the object.
if i were 10 units away it'd be like .05 units above the object.
that was really the only issue i had was the indicator would look differently depending on how far from teh camera it was.. so basically just normalized it
@rich adder exposing my math rustiness, whats the best way to find this last number, since i dont want it to be a fraction directly relative to the distance between the two points, i just want it to be close to the player + a couple units
I would just not add an entry to the dictionary in the first place until it has a value greater than 0
I have a problem where I don't get the colors as expected when I draw a line using LineRenderer.
If I use: public Color color1; and select a color using the color picker in the editor, the line doesn't show up.
If I use: public Color color1 = Color.red; the line shows up and is red.
Any ideas?
I think you're looking at a different LineRenderer in the inspector and in the scene
was thinking something along the lines of horizontalPos = Mathf.Lerp(screenPos1, screenPos2, normalizedAngle/value
Interesting
alr lemme try
I'm looking at my prefab which I instantiate ..
You are probably right, I just don't see how
Double check that:
- Your prefab lives in the project window as an asset, not in the scene
- Your code is actually referencing and calling Instantiate on a reference to that prefab, not some other object, e.g. in the scene
this is kinda pesudo code not literal.. screenpos would be the Screen.Width along with some calculations of getting the size of the indicator etc
Also make sure you save the prefab.
yea ik its just a different method so im gonna try it
My scriptable objects reference the correct prefabs, and the prefabs are there and saved and in Assets, not in Scene
mhm I can give a more practical example when I'm at the pc soon, a bit uncomfortable now to do now I'm on the go.
I'm sure you research on this problem there's plenty of modes done the way I suggest (this is how I also done it before)
Never should I needed physics for it / colliders.
that won't scale well especially if you ever decide to expand the viewport/change the size
@wintry quarry Btw, I got it working yesterday with drawing the lines, worked out really pretty. Now I'm building it further with more lines between more objects ๐
That's why I need the color picker
hm ok i see
Maybe show some screenshots and code
Hmm when debugging I actually get the correct colors (?):
Colors: RGBA(1.000, 0.000, 0.000, 0.000) color2: RGBA(0.519, 0.000, 0.000, 0.000)
Wait
That's fully transparent
HAHA
ah- so you were just setting a transparent color in the inspector
Yeah, didn't know it defaulted to fully transparent
Okay, looks super good now
Thanks again
You wanna see it? ๐
back to my previous question
i was a dumbass and added a space to the statename in the editor, making it a completely different item i was trying to call, i love being an idiot
Gotta love strings as keys :smh
imm quite the professional at messing things up in editor
ehh strings very common to mess them up.. If you have multiple places you need it I usually go for a const at least its only changed in 1 spot (can only mess up once and not multiple times / worrying to update each one separate)
think they ment it had a space in the serialized field not in code
so work with a lot of designers and less technical people and i will often just do a .Trim on strings from input
and sometimes also a ToLower
deals with any white space on either side of it
other options are if there is a finate amount of them just use a Enum
ahh okay even worse, the editor input fields are sometimes too small in some screens
that way in editor its a dropdown
yeah would be nice if there was maybe attribute that made the input monospace or something
Hey y'all. Working on a rougelike and need a little help with some UI work. I'm shooting for a Risk of Rain 2 style system to display powerups you've grabbed so it's easier for the player to know what all effects they have. I've seen some "close" guides for it, but nothing quite like what I'm looking for.
Any of y'all have some good resources (videos, forums, etc.) that could help? TIA
you're never going to find a resource that does specifically what you want though, usually you lookup what you will need (breakdown each part into smaller parts) build it up yourself
fair enough, just never hurts to ask
sure but its easier to make suggestions based on a more "generic" topic instead of specific "how to make UI like XYZ Game" etc
what specific features are you looking for ? what is missing in the resources you looked at ? and so on
i cant figure what is wrong with my code
its a pretty obvious one, what does the error say ?
look carefully on how you structured this line
something with transform but ive been looking at it for 5 min now and just feel dumb
It's best to show the error you received . . .
mb
That's always a good start . . .
as far as editor/compiler is concerned you're doing localScaleX * -1 localScaleY that makes no sense for it
Though, you can definitely spot this one . . .
Well, what's a -1 transform.localScale.y and why are you multiplying it with transform.localScale.x
Just look at every character on the error line . . .
idk what yall mean ig im just stupit but i cant figure it out
Well then, can you explain to us what transform.localScale.x * -1 transform.localScale.y means?
not really, flipping it up ig x is like forword and y is it
up
idk man im looking at tut
taps sign
I mean, just looking at it like a math problem. What is a -1 transform.localScale.y? What does that mean?
go down one
transform.localScale.y is a number, so let's just substitute a random number for it, like seven. If you saw a math problem that looked like:
-1 7
Would that make sense to you?
idk 6
How?
there is nothing in between, how would you know (to add subtrace, etc.)
someone plz just tell them its invalid syntax
we have
so has the compiler
and so has the tutorial they copied this from without thinking
ah the old "i swear i did exactly what the tutorial said"
And I figured by asking a patently absurd math question they'd see where the problem is and go double check that exact spot
oh this is from a tutorial too ? that gives you even more easier solution to just compare the two
But patently absurd math problems only work on people who have ever looked at a math problem before
so I guess that doesn't work any more
can you send the tutorial plz
In this video, we're looking at animation basics in Unity. We'll explore how to set up walk and idle animations, and how to flip our sprite from left to right. This video works as a standalone, but is also the second video in a beginner-friendly series where we create an Action RPG in the style of Zelda: A Link to the Past.
Next time we'll get...
ok now. compare these two images
now compare that line, character by character, with what you have
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 197
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2025-10-16
hey only 197 between 3 years, not bad average
Wait a minute you're the same person I've Counter'd at last time
You really need to actually look at the code you're copying. Or, you know, actually take a second of effort to understand it
glad I grew up with those games where you compare two images to find the mismatched/difference in items, comes to good use ๐ช
"They're the same picture" - 197 people since 2022-07-19
what the comma i added that and there is still a problem
what is the new problem
What does it look like now? What's the current error say?
check your spelling
jfc
idk what refrnce im missing
localscale doesn't exist
So, look at the error
you're not missing a reference. you've misspelled localScale
compare it to the thing literally right next to it
and see what's different
I, honestly, cannot understand how you don't see this
The only explanation is that you literally are not looking
I was gonna say troll post but then I tell myself Hanlon's razor...
Please, for everyone's sake, take half a second to look at the thing that's underlined in bright red
and think "Hm... this didn't happen last time I typed this. I wonder what the difference is?"
This is a channel for programming. Not Sesame Street.
another interesting thing... when you type and use the . operator.. you get suggestions on valid things that are part of it, put it to use and select those items... don't just blindly copy something, take the time to see whats happening as you write these things.
understanding basic concepts like . access can go a long way if you're trying to make something as complex as a game..
Hey, I'm very new to this kind of stuff and I've run into a problem twice. I'm attaching a script to a button to increase a value on click, but the only options I'm getting are 'No Function' or MonoBehaviour with the drop-down menu only containing a string option.
Events should have an appropriate Component instance assigned to their object field.
Thank you ๐
Hi guys. I have around 1.2k frames (at most) on a single 2d character. for a much cleaner game making is it better to separate them? (ie. walking North, Flying North,SE,W or just dump them in the sprite renderer and remember their count? I'm planning on using them on a small scale 2d multiplayer rpg. around 5-10 ppl?
Could you elaborate on remembering the count?
Does anyone have any idea how this could be null considering it checks if any of the values are null?
_GridController
Oh, wait, that one is just outside the others
First check is for if it's null
I just forgot that I had a nested check for the playerPawn as well when I made the check for it
Are you sure that's the line the error is on? Show the stack trace
for ex the count on the "walking north" sprite count is frame 100-120 etc.
Can you show us the stacktrace and line numbers for the code
Is whatever running this code the right instance of it?
NullReferenceException: Object reference not set to an instance of an object
GridController.HandlePlayerTileSelection (UnityEngine.Vector3 inputMousePos, CharacterPawn inputPlayer, Mouse inputMouse, System.Boolean overRidePreviousPos) (at Assets/Scripts/Grid/GridController.cs:184)
GameHandler.Update () (at Assets/Scripts/GameHandler.cs:110)
Okay, what's line 184 of GridController.cs?
So that's the line that has a null on it
You put all your null checks on a completely unrelated line
So either GameHandler.instance or GameHandler.instance.playerCursor is null
why is the gravity so bad
its the default 9.81
and i try to play around with the values here
but it still feels like my player is a feather
also i checked something why is it that the cube falls faster than the cylinder?
Are u attaching the script the cylinder?
Well going by the values here one could assume you are a 30kg mass with a jump force of 400N of course you're going to feel as light as a feather (this is assuming you wrote your code nicely) cause at that rate you would have an initial velocity of 13m/s or 46 ish km/h which is insane.
Went on a tangent, for why the cube falling faster no clue realistically it shouldn't
The mass does not affect the falling speed
I know lol it affects the jumping speed though
That's why i said i had no clue why the cube fell faster
Wait huh i might've done some math wrong :/ my bad pretty sure it's an initial acceleration upwards at 3.5m/s^2
this is pretty typical
most platformers/games have quite high gravity compared to irl to make it feel nicer, and there also might be a higher gravity when falling (a higher "down gravity")
try looking up the platformer toolkit by gmtk to play around with some values there
you were right the first time im pretty sure
Idk it's late 
No no i forgot to account for the downward force of gravity so i think i was wrong :/
this is an impulse force, gravity is a continuous force
you can't just subtract them directly i don't think
Fair point
if it's applied as an Impulse force then it's not actually force, it's momentum
Hello,
I have a game concept in my mind and I have never used unity or any engine before or have made any games before
I wanted to ask for your opinion
this game has some unique features such as:
- Needs to have an always on top transparent window
- Needs to be able to change desktop wallpaper of the user(the wallpaper will be dynamic as well like in rainmeter)
- Needs to be an app that should run on "statup"
can this be feasible in unity?
if not if possible please provide me any info about what would fit my requirement
currently i wanna make it in windows 11
thank you very much
have you googled any of these
Sounds like something u can do with Winform. Unity don't have much control over the system like this I'm afraid
c# does
Winform uses C#
So does unity i doubt there is much stopping it if you actually fully knew what you were doing
Cause gravity doesn't play favourites the acceleration you fall from gravity no matter how heavy you are is always 9.81m/s^2 (assuming you are on earth)
hmm interesting
okay now im at the point of making guns
now when i shoot i tried make a rigidbody bullet
but when i shoot it at high speed it just bypasses the collisions
assuming its faster than the game can calcuate the collision
but bullets are supposed to be fast
is rb not a good idea?
how do games use rb or they dont at all?
For what bullets?
yes
They would change the collision type from discrete to continuous iirc
oo let me try that
But again if you want realistic speed bullets us a raycast
wouldnt it be more realsitc when phys is being simulated
yep that worked well thanks
realism isnt usually the initial goal in most games. what feels fun and good is
that makes sense
For the bullet speed? Im sure you could just find the distance traveled and using a set speed for that bullet say (ruudementary numbers) a range of 500m at a velocity of 1000m/s would make it half a second travel time so you just check half a second after they click if the user has a hitbox at the point the raycast first found
Though at that rate you'd need to account for gravity when checking so you'd add (1/2)-9.8*{TravelTime}^2 to the height
Anyone willing to answer a few noob questions on a voice chat? Mostly just very basic stuff so i can understand the concepts without getting into details.. but specifically looking for someone with some experience with Server-Host-Client experience. (Like Server handles the verification and HP, Damage calculations, then sends broadcast back to Clients.. haha im gettin into the weeds here, I guess I need 2 people, one that understand Hierarchy for basic questions in unity, and one that maybe has exp with a multiplayer game, and the Authority for stuff.. idk im new, any help appreciated, thanks!
Sorry i dont think anyone that is skilled enough will willing join a vc
It's kinda a stretch for the multiplayer ask, but i still have questions on like.. "where do you store the GameManager.cs or EventManager.cs in the project? Make a Main Scene that remains open to hold these and then other scenes reference it or do you just add it to all scenes? "
You can post the questions to #1390346492019212368
Multiplayer questions can be asked in #1390346492019212368 but for things that you need to persist across scenes like settings you can either make an object and call DontDestroyOnLoad or you can use a static class which as far as i know keeps data between scenes as it's just one instance of that class
Does anyone have any advice on how I can generate text onto a texture2d in the dumbest way possible?
I don't want to use any of the UI stuff if possible.
U are missing the point. It's trying to find the most efficient solution for a problem.
Yes, u can do pretty much anything with Unity, but then u will need to adopt the Windows API to do the rendering and event work, which Winform already supports.
Technically Unity is overkill for this task, especially for beginner. Winform is way simpler and more lightweight
Technically Unity is overkill for this task
you don't know enough about the task
Besides them wanting a transparent window, changes desktop wallpaper, and it booting on startup which as far as i know is possible in unity we dont lol
Kinda sounds like they wanna make wallpaper engine 2.0 :/
which is fine if they want to
Totally
thanks very helpful
Im shocked you read all that i was just yapping cause im tired but dont wanna sleep
im back to unity after like 4 years this feels refreashing
Then answer my questions on VC lol, I feel like im over-analyzing the basics
They specifically said like Rainmeter which uses Win32 API. U are just assuming things as I do. I already said my points
i didn't assume anything
no vc's on this server, sorry
I know but there is options, if anyone is willing.. im new and just want to ask some basic questions because I did the whole 'watch 15261326 tutorials, and learn nothing' I don't wanna do spaghetti code, just have some basic questions.. maybe ill go to fiver and look for unity dev ha
yea i tried asking some ais and the ans is that unity is good for the game but the features it requires may not be possible to implement in unity
specifically the 2nd point
oh i c
i asked if you googled them ๐
ai is shit
oh ok
also be sure to ask about doing it in c# too
ooo
unity uses c# so stuff done in c# can be done via unity
ooo i c
you see i want to do something like this
so when you are using your pc on a programmed time certain entity comes to your screen
you have an mechanism/interactive way of acquiring this entity
when you acquire this entity you can set it in your background wallpaper
and you know it's that type of cozy kinda game
ok so the entities are in 3d
and the wallpaper is also live so the entities can move in it
so the window should be transparent and always on top for when the entities come
and on the desktop page the window will be behind the folders
i would not recommend Winform then
i feel like a lot of people will feel like that's a virus unless you make reference to the old Tomogachii lol
well it'll be a better choice than trying to make a game from nothing
lol
ooo i c
alright thanks
maybe consider the reference when advertising lol
not sure why but when you said entities i only thought of like cod zombies :/
uhhh lol
ooo ye
but do you mean like they character (say a cat) would be behind everything like in the wallpaper or it would be ontop of your applications?
"demonic entities interactive wallpaper!" lol
the ones you are able to aquire will be in the wallpaper itself so they are not shown when you are using someother app
but there will also be a always on top window in which new entity will come (on a programmed time) for you to catch
ah so like a two window setup where one would be like Bongo cats tiny window with the gifts and the other like wallpaper engines wallpapers?
yea exactly
i mean im not sure how to do it myself but i am fairly certain it is possible
ooo that's great thank you very much
Find out, who is moving your player and from there go through the code to see, what is actually happening
Confused Why This Isnt Working? My Animations Arent Playing?
How can i set a custom spawn location to my network manager in netcode?
Did you already google that?
i somewhat did but was hoping for a simple alt
but anyways ill do it later atp
where does this audio come from i thought it was the GlobalVol
Wild guess, you are creating two cameras somewhere. Just serach for the component AudioListener as it says
ooo its the main cameraaaaaaa
yea
thanks
Okay now the million dollar question i searched online but it seems like I just do the normal instanciate to add objects to the scene but for some reason it doesn't seem to work
Why could that be
And yea the object i try to add has the network object script
#1390346492019212368 might be a better palce to ask if its about the whole setup of the game and not a specific code part ๐
Why does it have to be a post channel ๐ฅน
The Pivot of my object in the prefab and in the scene are correct, but when i try to rotate it with this code:
rb.AddTorque(Vector3.forward * randomZTorque);```
It starts rotating from the feet, instead of from the pivot. why?
or is this a question for in #โ๏ธโphysics ?
never mind - didn't read whole way through
this does fix it so the pivot is at the feet, but doesnt fix the issue that i want it to rotate from the center haha
do i have to import the meshes into blender and reset the pivot?
if you want to rotate it from a different pivot, you could parent it to an empty
then rotate the empty
thats already what im doing, but it doesnt work
Just a little hint that you are not in pivot mode
Top left of your scene view, it says "center"
already put it in pivot mode, doesnt fix a thing
Can you show, where your pivot mode is placing the indicators of the object you want to rotate? But yeh, might not be a code question at all
at the feet, like i said in my post
Also tried placing the mesh location at -1, so the pivot is here, but this does not work in runtime
everything tied to bones is not just easily moved around because the bones and animator control where the mesh should go. #๐ปโunity-talk might be a better place to ask, as this is not a code problem but a setup problem
If I need to add forces to my character in random directions. Should I go with Character controller and program my own force generations or scrap Character controller and go with rigidbody?
What's the best solution for a 3d character? would it be a character controller or a rigidbody?
{
Debug.Log("Ich fahre jetzt los!");
var pos = this.transform.position.x;
pos += Speed * Time.deltaTime;
this.transform.position = pos;
}```
Hey why cant i use that?
i dont find the Problem.
Please explain a bit more, what is not working or what prevents you from using it? where are you firing this code?
You need to create a Vector3 to assign to transform.position, you can't just assign a single float to it
var pos is now a float, not a vector 3
for forces you should use a rigidbody, thats the easiest way to do it
i wantedt that the bus drives forward
transform.position += Vector3.right * Speed * Time.deltaTime;
Easiest way, but the fps movement wont be natural as I bump into colliders right?
That moves it on the X-axis only
its a whole lot of tweaking, but that is what unity gives us...
AHHHHH i see it now, i need to give a Vector3 Position
thank u
I feel like adding custom force methods to character controller would be more natural?
yes it is, but then you will have to create your own custom force methods, which is easier said then done
and AI is not great with making anything physics based
It's pretty easy
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
Feels like you should have gotten errors while typing those lines
i dit but i didnt understand why
but know i know again evertime i want change the Position i need to give him a new Vector
and i have another problem, somtimes my code dont work. Can u guys help me pls
{
// mach was
}
transform.position.x is a float, basically a real number. if you're moving it with some kind of speed, it'll be pretty hard to make it exactly -2.
that's also a really vague question
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #๐ฑโstart-here
you have you give details on how exactly it isn't working
is there an error? is it not doing anything at all? is it doing it incorrectly? etc
okay, sorry
my bad
its common to use a "range"
like if x < -1.9 && x > -2.1
if u use == it'd be super hard to hit it exactly..
like approximation
you could also define an epsilon
like Mathf.Abs(-2 - x) < 0.1f
im sure theres cleaner ways (ie โ๏ธ ).. but just pointing out the difficulty of hitting a number exactly
{
Debug.Log("Hey!");
start = false;
} ``` Thank u i did it like that, i saw a Code Syntax in a Forum
may want to also include the "false" into the condition itself
tha way when it triggers it does it things and waits for something else to reset the flag..
that way ur code doesn't run it more than once at a time
a u mean a bool befor the Movement run, if yes i did that
Is it a bad idea to add a listener to an event inside of the very script it is "firing" from?
I have an event that, when fired, other scripts do their things but there are some methods in this script that also always get called whenever I have to fire them. What I'm doing rn is
MyEvent?.Invoke();
MyMethod1();
MyMethod2();
(multiple times in the script)
Should I be doing
public static Event Action MyEvent;
OnEnable
{
Subscribe to that very event that is in this script => MyMethod1, MyMethod2;
}
OnDisable
{
Unsubscribe and stuff
}
well if its gated somewhere else thats fine too.. just saying.. cuz that condition could run alot if it isn't controlled somehow
-1.9, -1.98, -1.99, -2 <- liek that would run it 4 times (say if u only wanted it to run once when the range is detected)
both of those seem viable
i do it all the time
consider if the MyMethod1/MyMethod2 would change over the course of runtime, if so then you'd be using events sure
For some reason my brain is telling me listeners to events in the same script are a bad idea but I can't tell exactly why
as long as u subscribe and unsubscribe when u need to doesn't really matter if its in the same class or not
Is isGrounded is bugged for CharacterController?
no, make sure you're adding gravity even while on the ground
I feel like the only other way, I can know if the character is on the ground is by doing a ray cast
I did that
how it works is basically it checks if it hit the ground the previous Move
if it didn't move vertically, it'd basically be hovering above the ground and it'd consider that not grounded
I'm applying a slight gravity, while it is still on the ground. But It's still not working reliably
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, 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.
A tool for sharing your source code with the world!
If I do slight movement, isGrounded works. But that is not the solution
Should I just go with a linetrace system, instead of this buggy "IsGrounded" ?
@naive pawn
linetrace? do you mean raycast
you should not have multiple Move calls in a single frame
U should keep the velocity zero when it's grounded instead of negative value
{
verticalVelocity = 0f;
} ```
But why tho?
that's how charactercontroller works/is designed
it expects 1 move call per frame
just combine ur vectors into (1) and pass that iinto the move.
If that's the case, shoudlnt it work if I do not apply any movement? But it's still not working
Move(finalVector * time.deltaTime);```
when you break a system's expectations, good systems will try to cope with the weird input.
sometimes they work, sometimes they don't
garbage in, garbage out
a lot of people have had the same issue
private void ApplyGravity()
{
if (characterController.isGrounded)
{
if (gravitySim < playerSettings.gravity)
gravitySim = playerSettings.gravity;
}
else
{
gravitySim += playerSettings.gravity * Time.deltaTime;
gravitySim = Mathf.Clamp(gravitySim, playerSettings.maxFallSpeed, 0f);
}
}``` its common to use a *small* downward vector when grounded... (constant)
and a accumulative downward vector when in the air so u accelerate when falling
the documentation for SimpleMove also states this
It is recommended that you make only one call to Move or SimpleMove per frame.
https://docs.unity3d.com/ScriptReference/CharacterController.SimpleMove.html
not sure why that isn't in the docs for Move as well
i think thats the first thing i learned ^ bout 4 years ago
finalVector =
(groundVector * finalSpeed) +
(airVector * playerSettings.airSpeed) +
(Vector3.up * gravitySim);
if (jump.magnitude > playerSettings.jumpMagn)
finalVector += jump;
characterController.Move(finalVector * Time.deltaTime);```
really helped learning Vectors as well as a byproduct
(though, since i work in 2d, i haven't used the charactercontroller myself at all. i know the 1 move per frame rule purely from helping here lmao)
combining them.. (modifying pieces of them).. removing some of it etc
and the isGrounded thing
lol, great thing to know ๐
isGrounded gets complained about alot .. but for simple controllers i believe its fine..
i use it all the time (without any additional ground checks)
altho there is a bit of an issue i found. and its probably b/c of what u said earlier Chris..
I had to end up running two groundChecks.. for some reason to get my "Landed" sfx to play..
Tbf I don't see any problem if I'm just moving my character on static environment
But yeah, there should always be a gravity
teh first one couples with the movement code.. and the last one is reassurance i guess.. (its the only way to get my Landing sound to not be sporadic and inconsistent)
i was just pointing out that having a slightly negative force helps..
i would imagine that 0 could cause weird issues
could.. i just dont know how off-hand
it's required to make isGrounded work properly, because it's expected from the cc
^ yea there ya go
u could be ever so slightly above the ground.. and the check would be lying
something something.. maybe skinwidth
you would be 0 units above the ground but not actually touching the ground (which gravity would make you do)
About that, I stopped using cc ground check and just go with a small offset spherecast
totally acceptable.. ^ see thats what i meant
iirc, CC doesn't do physics-esque collision checks
it checks if the previous Move wouldve hit anything
that's why you need to move downwards to detect the ground
since if you don't move downwards you technically don't touch the ground
i like array groundcheck w/ raycasts
can use multiple rays to get a more advanced ground-check
if these rays are grounded but these arent.. i can tell that ur standing on a ledge..
in a certain direction
same w/ slopes and whatnot
Nice! I was thinkingn about implementing slopes. Guess this way is convenient. But 4 linetraces are enough right? Why do we need 6 tho?
u don't 4 would be plenty
or 5 if u want one in the center
๐ note: theres dozens of ways to do Ground Checks.. Raycast is just a single one..
you can do overlapspheres, checkspheres, spherecasts, boxcasts, regular trigger colliders. so on and so on
Thanks!
void Update()
{
if (!IsOwner)
{
return;
}
_moveDirection = move.action.ReadValue<Vector3>();
Debug.Log(_moveDirection);
airDragHandler();
sprintHandler();
}
why is _moveDirection always 0 0 0
make sure it's enabled
also why is it a Vector3
it was working like a sec ago
oh i guess vertical movement, huh
You need to check move or move.action . . .
check the input debugger to make sure input is being recieved
hows that done?
ohhhh no swizzling
open the input debugger from window > input system > debugger, or something along those lines
in general, perhaps?
nop[e
yea found it
sry my bad im cooked
that's not what i'm trying to get them to look at, no
so input is being received, but the action isn't forwarding it - that narrows it down a lot
make sure the action is enabled
hows that done
if the input action asset is set as the default, it'll be enabled
if not, you'll have to enable it yourself
U did not set it in OnEnable(), did u?
How to code for checkpoints and reset car if it flipped or out of the track?
those are quite a few different questions
check them sequentially
break them down into smaller problems, and google the simpler problems to start
saving checkpoints, checking rotation, making bounds, etc
Ok
nope
but it was working perfect like an hour ago
and is it set as the default asset
๐ญ
i refer it like
[SerializeField]
private InputActionReference move;
that's not what i asked, no
is the inputactionasset it's in set as the default asset for the project
you need to have the action enabled, which can be done manually, or by setting it as the default asset
Heh
it's in the inputsystem documentation
Are there any good resources for how to create a custom inspector for beginners. I have been trying but encounter odd errors each time. More noticeably when changing my script to derive from the Editor or EditorWindow i get an error?
I have even added a assembly reference to try and fix the error but no luck. What am I doing wrong?
Very strange, UnityEditor.Editor is correct
I think you dont even need the assembly referenced there, did you click definition on Editor class? where does it take you
btw all the editor resources are pinned in #โ๏ธโeditor-extensions
the core apis are always avaliable to all assemblies so yea not required
What is the correct process to set it up. I'm really lost right now because I have been trying for a week now and doom scrolling for youtube tutorials
As I said first, check the definition for Editor and see where it takes you, it could be another class maybe outside the assembly ?
It takes me to the editor script but it says decompiled
I will try to regenerate the script to see if anything changes but idk
if the error is a compile error it should show in unity, if its not something is wrong in VS
maybe not related or maybe it is but tbh unless you have a specific reason to use asdef I would not use it, just overcomplicates the project structure
I have no errors in unity so it might just be visual studio
yeah its weird maybe you can try regen project files, this is one of the reasons I stuck with VSC on windows as well, I had VS bug out like that for no dam reason
Hi,
Has anyone worked extensively with KCC?
I am building a CharacterController Class, Player Class and Camera class. I am trying to build a full body controller. Basically I have gotten the movement correctly and mouse look around but the camera won't stay infront of the head, I will be implementing a IK solution for spine and head movement at later stage until I have the base fundemental of player controller working.
using UnityEngine;
public class PlayerCamera : MonoBehaviour
{
private Transform _followTransform;
private float _verticalAngle;
private float _horizontalAngle;
private Vector3 _offsetFromFollow;
public void SetFollowTransform(Transform t)
{
_followTransform = t;
// Calculate and store the initial offset from the follow transform
_offsetFromFollow = transform.position - t.position;
}
public void UpdateWithInput(float deltaTime, Vector3 rotationInput)
{
if (_followTransform == null) return;
_horizontalAngle += rotationInput.x;
_verticalAngle -= rotationInput.y;
_verticalAngle = Mathf.Clamp(_verticalAngle, -89f, 89f);
// Apply rotation
transform.rotation = Quaternion.Euler(_verticalAngle, _horizontalAngle, 0f);
// Maintain initial offset from the follow transform (eye level)
transform.position = _followTransform.position + _offsetFromFollow;
}
}
PlayerCamera
I regen the code and got these options now?
Important question. Does the previous example compile successfully in unity? What happens if you write the full name inc namespace?
yeah try doing : UnityEditor.Editor
The build was successful I used both Editor and UnityEditor.Editor to be sure. I just selected all for my assembly reference
not sure the build in VS relates to a unity project, either way it seems something is wrong between the two somehow.. not sure wht it is, have you tried without the ASMDEF ? i thought it makes a difference but worth trying
i just deleted it
huh isnt that something... I just tried it with a test Asmdef but it worked fine
I have a problem whith the player input component โฆ
How can i fix it ?
they are recommending you make your own basically
cause the project wide conflicts with the purpose of PlayerInput
with System wide you don't need PlayerInput and vice versa
Ok so, continuing the talk from #๐ปโunity-talk
var loader = new WWW(url);
yield return loader;
output.text = loader.text;
}```
This is the snippet in the package
var outputText = "";
for (int i = 0; i < urlArr.Length; i++) {
var loader = new WWW(urlArr[i]);
yield return loader;
outputText += loader.text;
}
output.text = outputText;
}```
This one too
what do people recommend using to unit test async methods?
I was using await Awaitable.NextFrameAsync() but since a recent TestRunner update, all tests using that method just stalls forever
something like this basically
private IEnumerator OutputRoutine(string url)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError(request.error);
output.text = "Error: " + request.error;
}
else
{
output.text = request.downloadHandler.text;
}
}
}```
https://paste.mod.gg/edkefefestvl/0
very similiar as you can see
A tool for sharing your source code with the world!
You just fed my family for thr forseeable future
I'll call the wife, job is secured, food will be on the table tonight
hehe yay my work in red cross paid off
i shouldve probably inversed and put Success as first if statements lol
oh well you can always do it that way if you want but no biggie
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Networking.UnityWebRequest.Get.html
unity uses a switch to cover more but yeah
Does anyone know how to remove a specified entry in a table?
lets say i want to loop through a table and remove that specific index if conditions are met.
if you post an answer, do only post the keyword for what i need
Edit mode or play mode?
a table of what exactly? could you give some context
Good lordy that's not the solution
I use unitask because it actually works in edit mode properly
i want to count children in a gameobject. but the count should exclude anything that doesnt have the tag "Target"
don't add it in the first place?
pseudoish
var myList = new List<GameObject>();
foreach (var go in gameobjects){
if(go.CompareTag("myTag")) myList.Add(go);
}
i see,
i just made this myself as well. Altough i've only ever used the keyword list to grab Resource folder items.
private void UpdateTargetCount()
{
//
Transform[] Children = GetComponentsInChildren<Transform>();
print(Children.Length - 1);
TargetCount = Children.Length;
for (int i = 0; i < Children.Length; i += 1)
{
if (!Children[i].CompareTag("Target"))
{
TargetCount -= 1;
}
}
}
sketchy
if it works though you're fine.. though imo the keeping a sepeare list can come in handy if you need to do something specifically with the Targets
otherwise you need to iterate this list again and do the same thing
yeah, i have a hunch my projects other code are like that too
the only thing i'm remotely proud of is my versitile shake script
this one is especially a mes since i've been experimenting alot if certain features. honestly it's pretty bad going through it
sometimes
btw you can also do
foreach (Transform child in transform){
//stuff
}```
<https://docs.unity3d.com/ScriptReference/Transform.html>
and skip GetComponentsInChildren
wait that works too?
That's. i don't know how to feel about it.
it seems amazing. and easy but also kinda cheesy lol.
yea idk skips an extra GetComponentsInChildren prob
first time I've seeni += 1 in a for loop lol
well maybe not in a while at least
are these objects added at runtime ? you can also keep track of them when you do that.
otherwise I just use the inspector and put them in there
it also probably skips the array allocation
and uhh i think it's ordered by child order? whereas GetComponents would be ordered by internal id
i've been avoiding the inspector for awhile now. Trying to learn management
why not? despite what I'm reading, my tests are passing, so it makes me believe it actually does run async
what about Task.Yield() instead?
Also I just realized Awaitable.NextFrameAsync() only stalls in one unit module and not the other, despite being written the exact same way ๐ค
although i'm definitely not so good at it ๐
the inspector is most efficient way in terms of references.
its basically game* compile time dependency injection
I know, and i should definitely use anything that makes my life easier
also yeah i dont use ++1
for consistency, is that weird?
if you do ++ you don't need 1
๐ข
can anyone help me with some animation riging?
but yeah tomato tomato
only if its a code question otherwise #๐โanimation
thanks i was looking for that channel
yes
yeah. i don't use ++ at all..
It's just the order of the calculation
right..pre-increment vs post
huh.
dangit. i somehow feel like that could be something neat to use for counting.
and i don't even use the normal one.
the difference only really matters when you want to use and immediately increment or vice versa
typically with implementing lists/stacks with arrays
ya in for loop they do the same thing I think ?
Odd...
if the value isn't used, then there's no difference, yeah
if the value isn't used they're compiled into the same thing even
optimization ftw
Using Task won't reliably keep you on the main thread
(i++ is actually kinda expensive in comparison, in terms of machine cycles)
yaseem so, just wanted to double check
https://dotnetfiddle.net/wYzLUi
Test your C# code online with .NET Fiddle code editor.
Reminds me of my java teacher that never used Value += Number; and instead always went Value = Value + Number
quick question. how long have you guys been coding?
like in general
anything counts
idk 4 years maybe ?
I started whan I learned unity ๐
Really? What'd be cheaper?
oh really? did you ever try something else?
or you've been commited perhaps. hehe
++i = ADD addr, imm 1
i++ = MOV addr, addr ; ADD addr, imm 1 ; MOV addr, addr
iirc. the last MOV might not be necessary
a little bit of C and C++ but more recently, before that no experience except some HTML and basic JS.
I used to use Game Maker and thought coding was heard ๐
oh damn, like 5 years at this point. time really does go by...
Did u study assembly?
Gamemaker code feels so yucky :/
not formally, i dabble with it a bit
I started learning to code 15 years ago 
i don't really know the actual languages. i can read but not write, but i can write assembly level logic
ive made 2 cpus and working on a third in turing complete (hard recommend)
Though i have the same opinion with python and whatever Godot uses
oh and ive read assembly in ctf puzzles (cybersec)
yeah those pythony languages are my peeve..
There isn't a difference in C#, but iirc there is in C++.
no, the difference is the same
I need my semicolons and swiggle brackets to be happy
That's still pretty impressive. Learning how computer actually works
the differences are optimized out in both languages if the value isn't used
๐ i've seen some c++ code. What did you do with c++ then? like unreal engine? i've seen some people send code of it and it just seems like it's on a another league
yeah imagine your code breaks because you didn't indent ? Im looking for whitespaces now ? fuck all that noise lol
honestly, you always sounded like some veteran that had been coding for a decade..
bro im in first year uni
nah Unreal is too much for me..
mainly doing Embedded system / chips like esp32 nd so on
a little some basic openGL apps to learn some frameworks
๐
Unc
yeah, sorry for the assumption
good.. yeah i know what you mean.
it's like using blender..
but its a game engine
there is just so much C++ boiler (in Unreal) you have to write for simple systems that Im just like "yeah I can do this in c# in a few minutes..." I'm not enticed to use unreal much if I can do the same things in Unity but quicker
so it's like a easier assembly i take it?
I enjoy doing unreal for cinematics and video work
i' was modding with some unreal uassets, it's very interesting how the reverse engineering works with that engine
maybe because I also don't know C++ that well so their engine seemed very opinionated so I gave up on it and use blueprints
that's the visual coding thing right?
yeah
creeping into offtopic here ๐
but yea it gets messy quick and at times you really do tell yourself "I can do this In code soo much quicker (in Unity) " But if I work with someone else I muster through
Visual coding feels quite degrading if you already know code (at least imo)
In Unity/Unreal seems good when working with designers though, instead of doing like 50 custom tools in code ๐
Yeah that's fair i would die if i had to learn shader code instead of have access to the visual shader graph
Hm currently messing with it in SharpLab (for C# tests) and not sure what you mean. Loops end up the same thing, and usage without a loop still gives basically the same instructions (it just flips an instruction order). Got an example of what you mean?
indeed. on that topic how do you feel about the unity's animator thing, i think that also was a form of visual coding?
yeah shadergraph really does open a lot of awesome possibilities when having no shader background.. have you tried VFX graph ? I saw some really cool stuff you can do there
int a = ++b;
I've looked at it 3 times and gave up cause it never worked right
it makes a difference if you actually take the result of the operation
the StateMachineBehavior can come in quite handy at times
Yeah that's my second test and it's the same instructions, just a part is swapped
I have and made quite a few effects for my game, pushed a release and got feedback about how it would crash users computer, which i found kinda odd cause my own pc isnt even that good yet it ran faster than particles systems
my main point being that there's a difference, yes
with VFX graph or particle system ?
I know VFX graph is way better cause it runs on GPU instead of CPU
is it bad practice to use the legacy and modern version of the animator at the same time? I usually use the modern one but theres one specific thing here where it would be very helpful to create an animation at runtime, which it seems the modern version cant do
wdyn "Legacy Animator"
are you confusing it with Animation component ?
Seems like a hassle to. better sticking with coding and sharping that area
while you're at it
oh i wasn't clear with what i said earlier
the machine cycles part was about c++, machine cycles are kinda negligible with interpreted languages aren't they
Used particle system before switched to vfx graph, vfx graph crashed their game particle system didn't
Yeah (in C# at least)
ldloc.0
dup
ldc.i4.1
add
stloc.0
vs
ldloc.0
ldc.i4.1
add
dup
stloc.0
(just throwing out the list for ref)
yeah but the animation component is legacy
Which is why i found it so odd that it would crash them
mhm maybe their GPU was not good at all
so is it bad practice to use the animation component while using the mecanim animation system?
yeah No reason to use Animation imo if you're using Animator
Maybe but even my gtx 1080 had the fps rise like 30 from it
No il colors, so had to use cs colors 
but there is i want to create and play an animation clip at runtiime
thru scripting
hence i asked here instead of unity talk
yeah the GPU can compute faster in some cases, especially graphical stuff like that
source code:
void w() {
int a = 0;
a++;
}
void x() {
int a = 0;
++a;
}
void y() {
int a = 0;
int b = ++a;
}
void z() {
int a = 0;
int b = a++;
}
```C# compilation (IL)
w: `ldloc.0`, `ldc.i4.1`, `add`, `stloc.0`
x: `ldloc.0`, `ldc.i4.1`, `add`, `stloc.0`
y: `ldloc.0`, `ldc.i4.1`, `add`, `dup`, `stloc.0`, `stloc.1`
z: `ldloc.0`, `dup`, `ldc.i4.1`, `add`, `stloc.0`, `stloc.1`
C++ compilation (asm)
w: `add DWORD PTR [rbp-4], 1`
x: `add DWORD PTR [rbp-4], 1`
y: `add DWORD PTR [rbp-4], 1`, `mov eax, DWORD PTR [rbp-4]`, `mov DWORD PTR [rbp-8], eax`
z: `mov eax, DWORD PTR [rbp-4]`, `lea edx, [rax+1]`, `mov DWORD PTR [rbp-4], edx`, `mov DWORD PTR [rbp-8], eax`
at the cost of your particles cannot interact with physics objects like PS can
I dont see how you cant just do the same with Animator though
If only computer cpus could easily talk to each other, wonder wht intel makes these 24 core cpus when most apps cant even use 3/4 of them
a single asm instruction is 4 il instructions lmao
So whats the fastest of these 4 tests?
to be fair its usually APP makers that make them perform better with single cores, its an old school mentality ig
i mean if you actually optimize they're all 0ns because they're all optimized into nothing
also, speed was not the goal in any way
this was a comparison of the work done
ok i googled it and i can do so by creating an animation override controller at runtime and then assigning it the animation
i think thatll work
thanks
Fair was just curious if there would be any effect in a huge loop
Yeah fair point damn Vectors taking ~700ms for 1.2 million calls
I'm so bad at Unity, how to code?
alt + f4 /j
Sigh
It's boring of watching at 20 minutes video
Bruh really should alt f4 then
if you find it boring to learn new skill then what are you even doing then
Gotta get through the boring to get to the good stuff
I was just having dream about making my racing game
Watched a code monkey short video the other day where he brought how people complained that 3 hour simple game making videos weren't simple cause they were too long, could see this guy being one.
programming a game isnt something you learn overnight. there is tons of material you need to learn
Fine
its true though... I find those very long videos are not very good
copyrighted codes?
hes probably one of the worst examples tbh..
he claims "clean code" but a lot of his shit is cringe at best, and not clean code
Yes, the scripts is also copyrighted
what scrips are you talking about? nothing you will learn will be copyrighted
CodeMonkey doesnt give a sh** at all, bad resource 100%
90% of Unity videos are doing WrongLerp so ...
yet he's popular ๐คทโโ๏ธ so must be doing something right
I dont disagree lol (nor do i really watch much of his stuff, like 1 video every 5 months) but it's true that there are people saying that a 3 hour video on making a whole game is too much when most games take months to years to make anything remotely meaningful
I think it's the thumbnails, he uses Synty assets and others
Because of the results people think, wow that looks pretty good!
who knows.. I just know that unity using his shit on their site is ultimate cringe
Manager's choice (person who does not know how to code) type shi
Go in for the concepts, not for the copy/paste 
Same reason AI generated code gets approved in PRs
let's say you have a loop adding 2 10-element arrays of vector3's memberwise
3 instr are for the for initialization
6 instr per loop plus the end, so 65 instr are for the inc and cond
so overall 68 instr of overhead on the for
meanwhile the actual work, 10+28 per loop, so 380 instr for the work
would be more with a list, since there's also the overhead with calling each method too
yeah thats how I extract info from most resources, I never copy . His shit is like brackys tho, beginners mistake it for actual "good code" and end up writing these very over convoluted systems lol
I mean on one of this video he really claim doing transform.Find("TheThing") was "good code" lol
And i assume this ratio of instr for the for loop and the work would drastically grow as the loop gets bigger say 50 10-element arrays. So as you said yeah i guess worrying about the i++ is meaningless for a loop
and this is a very simple loop with minimal work too
I feel like worrying about i++ or ++i is silly as we can probably trust the compiler to optimise this based on usage
I opened a whole can of worms ๐ฅน
which is the opposite of what I learned in my first c++ class where they insisted we use ++i
idk what to believe anymore
they also insist you use C++, so can you really trust them 
wait..isn't C++ just D ๐ค
no that's C##
I call it Bflat but ## would be B?
unless you are using some ancient compiler i doubt it will struggle with such an easy optimisation
godbolt can show you anyway what it will do
โญ hi guys, is it computationally expensive to be passing around parameters like this all the time? This is a static Spring class based on Ryan Juckett's work.
I'm considering to make it non-static and just have an instance wherever I need a Spring. So the values are just there in the instance, not always being passed into functions.
ref tDampedSpringMotionParams pOutParams, // motion parameters result
float deltaTime, // time step to advance
float angularFrequency, // angular frequency of motion
float dampingRatio,
ref float pPos, // position value to update
ref float pVel, // velocity value to update
float equilibriumPos, // position to approach
in tDampedSpringMotionParams springParams)```
value types woo
I see. You really think I wouldn't gain any performance by having instances with member variables instead?
It seems so strange to be passing around 8 variables all the time.
when all the needed variables are all together (such as in the stack) then thats the best case
(we know here most of these arguments will be because they are value types)
the ref float args im not sure, depends on where they are from
I have 1 more question.
If I have some function, is it worthwhile to check if it needs to be called before calling it? Or is it equivalent to check within the function itself and exit if no action needed?
Lots of args and called a lot? better to avoid the call early
So for example with the code I sent.
// Option 1 check before call function
if (currentPosition != desiredPosition)
UpdateSpringStuff( parameters)
// Option 2 check inside of function
UpdateSpringStuff( parameters) {
if(currentPosition == desiredPosition)
return;
...
}
Option 1 is better because we avoid having to pass in those 8 arguments right? And the function call overall
Kinda feels like I just answered my own question ๐ค
In-function "check if any action needed" is so much cleaner and self-contained but. Yeah passing parameters around for nothing just sounds wasteful
I suppose with an instanced class it's possible to avoid the function call and self-contain the check. Idk. That's why I didn't want to use a static class
For something that will be around for the entire game/scene, why would I keep it static? Rather keep all the stuff together in an instance of the utility.
Generally you should return inside a method when it's unable to continue what it's doing. Maybe it creates list, checks the list, and returns early if that list had more than 5 items.
Only that method had any knowledge of the list inside of it, only the method can return.
As for checking before calling it, simplest would be if it's a method to capitalise a string. If the string is empty, you know there's no point calling the method in the first place
aren't they copied around because they're value types though
Excluding ref
well.. reference types would also be copied around
I thought ref just passes a reference (location in memory)
the ref... i guess that would also be "copied"?
it's all just passing a word to the function
Objects are always passed by ref, too, I think
Value types are copied, i think there's exceptions with that too
a ref is just a 64 bit integer that represents an address
a float is just a 32 bit integer that represents a real number
both cases they'd be copied
wouldn't the "bad" case be with copying a large value type?
I'm thinking, to keep the functionality and the variables all together and just have instances. So, the instance itself can decide whether any work is needed, BEFORE it passes 8+ parameters all over the place.
though, it's still a limited amount of copies, so probably not an issue either
Well I suppose pass by value can be faster than.
But it creates a copy of it, so ... Idk
probably not
to my understanding, passing arguments inherently does copying
how much is copied depends on the types
To conclude - the point here being I don't have to keep writing if (springDesiredPosition != springCurrentPosition) every time I need a Spring.
here it's 4 refs (64 bit each) and 4 value types (32 bit each)
i will have to stop myself there because i am now realizing that this is most definitely micro-optimization and absolutely does not matter
design it in a way that makes sense and is easy to use, don't worry about the perf
I used to have 550 FPS now i have like 300-400
I can't keep losing FPS so I need to know these details
Thanks guys for the knowledge
it's not because of your arguments, it's more likely due to the actual work being done
to put this into perspective:
the thing you're worrying about, is going to be like 0.5% of the work your cpu does.
optimizing it won't get you anywhere
You can worry about it when that 300fps turns into 3fps
I've still got tons of game to build so. I need every frame
well, "when" is a little mean ๐
on my cheaper machine, I'm only at 180 FPS. Used to be 280
The triple raycasts probably contribute
But this spring related stuff dropped it further
don't worry about perf until it actually becomes an issue
and when it does, don't worry about these random things. use the profiler to see what's the actual cause
Hey yes but copied into the new stack frame all next to each other which brings benefits compared to a ptr to the heap being copied
otherwise you end up spending 50 minutes for an extra +0.05 fps for something that was already very optimized
I don't need the profiler, I'm looking to write tight and minimalist code.
you most definitely need the profiler if you want to actually make meaningful optimizations
I'll let you know if I need it
For now I've just been cleaning my code and gaining FPS
Except for this Spring crap, passing 8 params around every frame. Nuts
yeah the 8 params are not the cause, man
Will try now
Performance of a build is different to performance while in the editor. If it's running well in the editor, just assume it'll run fine in a build.
When the time comes to actually making the build perform well, that's ultimately a future you problem which doesn't exist atm
cool, sounds like you found heavily unoptimized code and optimized the work
Debug.Log impacts performance, too many of those can tank the framerate (don't not use it because of that)
if you don't have any more obvious stuff (no, 8 params is not "obvious unoptimized code") then you will need to use the profiler to see what's actually going on instead of guessing
Found?
Bold accusation bro
The Spring code, yes. It's from Ryan Juckett i said that
that's literally what you said you did
i'm referring to this part
For now I've just been cleaning my code and gaining FPS
My bad. I thought you meant my entire code
i'm saying you found patches of unoptimized code within your codebase and fixed them
Ohh gosh my bad dude. I'm feeling attacked rn taht's all
... They are though ... Just checked before-function-call and the framerate doesn't dip to 240 anymore
checked... what exactly?
Tried these two options
Donโt worry about ur fps too much lol itโs going to naturally decline as you make stuff
I put in a tile system and my game dropped from 900 to 200
lol
so you're doing different amounts of work
it's the functions themselves
yes
not passing the params
I see. Okay
void X() {
for (int i = 0; i < 1000000; i++) {}
}
void A() {
if (Random.value < 0.5) X();
}
void B() {
X();
if (Random.value < 0.5) return;
}
Got a lot of if (function call required) call function() to do ๐ฅฒ
like, you didn't change the amount of parameters between these 2 cases, so even if the issue was in the params, you wouldn't be able to tell lmao
Unity tilesystem is pretty good you tried that? it doesnt treat each tile a single gameobject so it helps a bit with optmization
Fair, it raised concern because of how many params
tip: guard clauses!
they can clean up a lot of logic if used properly
I never call a function with params, I just use instance variables always
What?
You mean checking in-function?
R u talking to me or vengeful
// normal conditional
if (x) DoY();
// guard clause
if (!x) return;
DoY();
Okay so... This
helps if x is an exception rather than a requirement, it makes it easier to read
no, these 2 have the same behavior
x is checked before calling DoY there in both cases
it's just a styling thing that can make it easier to read when applied correctly
Ah ok, that's what they call it huh.
could someone explain why is this an error?
In an Update loop with many function calls, can't just return so.
Maybe if they were all separate but anyway.
you said "tilesystem" no ?
read the error what does it say
extra ) by canFire
(sorry nav yes he should learn on his own)
Uh yeah Iโm just confused cause u said to put in a tile system and I already did that
Oh you mean unitys built in one?
yea
I used unitys yeah
ohhh ok
dw i didn't understand it
because you closed statement early for it == true doesnt make sense
not quite
Oh whoops didnโt see they posted code above
i thinks you wanted to do if(canFire) { //stuff so adding == true after a closed statement confused it ๐
instanced class that has all the data available at any time > passing data around to static functions every frame ๐คทโโ๏ธ
My programming teacher taught us to say (bool == true) instead of (bool) and I nearly lost it lol
I guess itโs way more obvious that way in the beginning. U get to know better the longer u code
My teacher technically said โmake me a game in C++โ for the mid-term
I keep on getting an error when I try to add my array to my custom editor?
if (dialogueSettingGroup)
{
EditorGUILayout.PropertyField(dialogueText);
EditorGUILayout.PropertyField(dialogueArray);
}
EditorGUILayout.EndFoldoutHeaderGroup();```
its good to be explicit some times but its preference
mainly for == false
cause (! myBool) can be less legible/clear to some than (myBool == false)
I basically never see explicit boolean comparisons apart from beginner code
once you understand that the bool itself is sufficient then you can stop
Hey guys, I'm trying to make a procedural generated hospital with basic modular assets, a plain wall, wall with door and wall with window (1m x 3m). I also have a floor that works as a ceiling at the same time (1m x 1m). I want to create a script that will procedurally generate a building out of these assets with following room groups:
Corridor (A main corridor connecting one or two other corridors for example 12m long, that also can attach the two other groups of rooms)
A "patient" room (2 types: 8m x 4m and 3m x 4m)
A "examination" room (4m x 4m, spawns less then the patient room)
All these rooms need to contain different assets, but that will be added later.
Anyone knows where I can find a good tutorial about this or paper to read on? Or anyone who can help me on my way on how I should start with this?
break down your issue into a more generic thing you will find it easier
there are a couple of procedural algorithms you can use BFS etc.
the rooms themselves are easy to randomize tho, you can have different prefabs that spawn in random, the room with different layouts
maybe even easier to use "snap points" at the door of each part then use some pathing algo to connect them doing some physics overlaps (a bit more brute force but works)
@odd radish http://pcg.wikidot.com/category-pcg-algorithms this site helped me greatly when I did a few procedual things
I can't recall why this is, but I have a canvas and canvas scaler, and whenever I recompile it defaults to portrait - if I change tabs to game mode then back, it resizes properly. What the heck am I forgetting?
You were right. I switched to using a SpringInstance, no more passing parameters to static functions - no performance gain.
I did gain the convenience of all my data being within the class instance though. So I can add a new Spring with only 5 lines of code rather than 10+ and no if statements (the instance checks before it does any work.)
It often does this if the game tab has not tried to render yet in editor
Probably why it fixed itself when you went to the game window
I've fixed this in projects in the past though.. but forgot how. It's kinda driving me batty
It's such a minor annoyance :p
can triple nested for loops themselves cause performance issues? its probably mostly their content right?
yes, depends on how often you call them and how many elements they have
no, and yes
triple nested loops are very important at times
for (int i = 0; i < 1; i++) for (int j = 0; j < 1; j++) for (int k = 0; k < 1; k++) // 1 operation
for (int i = 0; i < 1000; i++) for (int j = 0; j < 1000; j++) for (int k = 0; k < 1000; k++) // 1b operations
especially working with multidemensional arrays
each going from 0 to 32 and they are called once per second. there are multiple instances though but the have ann offset at which they are called
okay thanks
What about when it's unnecessary? Is it eating performance - having that nested branching?
depends on what you're doing in the bottom, if it's just math then it's probably pretty fast
its more about what operations you are doing
I read somewhere to avoid code branching - and try to use Math as much as possible.
32k operations per frame is trivial for x ++ and game killing if it's something else
Like Lerp between 2 different "modes" of camera follow for example, rather than if (camFollowMode == ...)
I'm not sure which is more expensive.
cinemachine ๐ฟ
Love Cinemachine. I only use Hard Look At Target though.
Don't like their 3 ring orbit crap. Deoccluder is great
ohh you're missing some really cool shit, cinemachine can do wayyy more
๐คทโโ๏ธ
again, it's a matter of scale.. if eat a grain of rice 32k times per day, you'll live.. if you eat a chicken nugget.....
Mostly what I've avoided is the built-in aiming, the "offset", and the orbit rig thing
ive noticed that updating every chunk of my terrain algorithm once per second increases my frame time from 3 to 700ms which isnt good im pretty sure. im looking through my code rn and looking at every line and trying to find my massive performance loss. probably the best way would be to rewrite my algorithm as a compute shader
Can't say I have any complaints. Unity's built in stuff is just ... Code anyway, so
Excluding complex stuff that uses Jobs like IK, I found writing my own implementations is just better
"better" in a "i can get the exact result i want" way
yeah if its tailored to your need ofc.. I just trust engineers that know way more than me making all the solid implementations , Cinemachine is one of them
the damping alone takes away so much bs with doing custom Tween
dont even get me started on Blends without cinemachine
Really? I hated how the damping felt
I use my own camera smooth following code
Vector3.SmoothDamp didn't give me the customization that using Curves did, so. I even avoided that
You gotta tune a bit but eventually you get really nice cameras, depends on your needs. I mostly use it for cinematics and their awesome spline / tracking
oh and the camera shakes makes things really nice.. Recoil, Hand-Held feel all that crap you have spend time making Algortihms for noise.. in CM is just 1 component , dont even get me started on the Obstacle Avoidance (basically its just a bunch of physics queries xD)
It can do recoil?
I've seen so many bad tutorials on IK (procedural) recoil.
should i set my terrain chunk to static if its mesh can change/update?
yeah because the impulse noise you can add it in a specific pattern or do randomized
Bout to try right now. thank you
if you want specific/predictable patterns per weapon, ala Counter-Strike and such.. Check out TheKiwiCoder he has some on that (maybe there are newer ones but he had them when i was looking into it years ago)
This video uses the Unity Animation Rigging Override Transform Constraint and CinemachineImpulseSource component to achieve a weapon recoil effect. The Impulse source listener is used to add camera shake effects, while the Override Transform constraint is used to animate the character and the weapon.
โบ Previous Video: https://youtu.be/HZuaz...
Ohh ok. So it is Override Transform
But the camera shake is from Cinemachine
yeah it just basically moves the transform for you
so you can basically make your own patterns with ease
can someone help me optimize my code? i get like a solid .4 fps
i dont think thats really great
yeah.. sure what you got going on
how do you know its the code ? have you used the profiler
profiler?
but its def. the code thats for sure
got a single one
confirm assumptions with facts. Also deep profiling will tell you which function is costing most
how much code is there total happening at runtime?
but my terrain is really expensive i fear
So if you remove terrain and run around on a flat Plane, what's the FPS?
you'd be surprised some times, for me it was always some URP thing or PostProcessing in the graphics
my code was doing 1kb at most
its the function updating it once a second. without it i get 300fps with ease with 50 instances of it
Updating what once a second? The terrain?

yes
i already split it up in smaller chunks tho
dont want to get .1fps haha...
https://paste.ofcode.org/377XKzxMAnwRpDsLU7rnqgR thats the code
i feel like marching cubes is quite expensive
Well. That's a lot of code.
SetHeights() shouldnt be a problem. SetMesh() and MarchCubes() might be the cause tough
i dont really know what most of this means but it does look horific
thats why we learn the tools , so we can learn how to use them and make them less intimidating ๐
also you want to check out the "hierarchy" mode too. Both have their uses
and "Deep Profile" to see code
though its recommended you do these in a build because in editor there is still some overhead to keep in mind
i think thats not my biggest problem sadly ๐ฅฒ
mhm try heirarchy, a lot of it also seems to come from rendering / physics too ๐ค
wait a sec i think my unity is dying right now
look at your gc allocations as well in the heirarchy
bro these are a lot of kb i dont like this
unity uses 97%of my 32gb ram btw
wait
thats 35gb
you using deep profiling?
if so yeah it needs a crap ton of ram
best to figure out what you need to deep profile first and run it as little as possible to get the info you need
my spotify crashed because of it
did you put an infinite loop lol
even know i mostly develop from my laptop, i will often deep profile builds from my desktop since the laptop only has 48gb ram
how you eating so much ram
i created a blackhole probably
am assuming the ran deep profiler o nthe editor for a decent amount of time
sounds like it lol I run like 7 instances of unity and one uses 5 max
its usage gets high quick
oh yeah possibly the profiler
but code that probably creating trash sounds likely too
my editor is still frozen its been 10 minutes now
i would not use deep profiling till you narrow down where it should be used
also would profile builds not editor
common bro .4 fps is insanely bad but not THAT bad
though for me deep profiling was useful narrow specific function
the spikes in your graph above look like garbage collection to me, so good chance you are making alot of allocations per frame
yeah i think so
I hate that they made Rendering and Garbage so close in color...
I always mistake them
i can never tell the difference
bruh couldnt picked a purple or some shit
but its easy to confirm in the hieharhcy view
true
if you sort by gc allocs
but also consistient spikes like that often just mean you are allocating too much a frame
rendering shouldnt be that expensive im rendering on a low resolution and i dont have any expensive shaders or post processing
yeah the frequent cleanup will def slow your shit up
i think it killed my shit on the spot
there is almost always a way to not allocate per frame
should i just terminate unity and restart it? code is saved and didnt make to many changes. its been frozen for 17 minutes now
probably a good idea to conclude you made sludge and should end it
i would
corporate hate this one simple trick
if you need to force quite and things are unstable afterwards. just close unity and delete your projects library folder and let it reimport it all
what should i delete??
ahhh okokok thanks
while unity is closed
its not even that bad just 1.7gb
it could still be full of bad cache
Hello there,
I have a "vehicle type 1", I want to be able to switch to "vehicle type 2" mid game.
what do you suggest the best way to do that?
Like I have other scripts like camera follow script that requires the transform component of the player vehicle.
and vehicle type 1 type 2 are different from eachother so I prefer not to combine them into a single gameobject.
I tried making a vehicle manger gameobject that can switch, it worked but the issue is the current vehicle transform data when I try to access it from the scripts like the camera for example.
if its gone Unity regenerates this when you open a project
cant delete it it says files in there are open but i have unity and even vs code closed
make a Cinemachine camera per vehicle, use something like Cinemachine Brain to just change between the two, remove belnding if you dont need it . Each camera has their own follow target so no conflicts
restart the pc first then you have something lingering somehow
Do you mean replace the exact object - like a character select?
issue is it's not just camera other scripts, I don't want to re-write other stuff
Like I thought about making player proxy transform gameobject but I figured it could cause issues later on.
wait now it works
Or fully switch to a different object - different location on the map etc
I'd go with activate / deactivate GameObject ...
you dont have to rewrite anything, dont they both use the same controller ?