#💻┃code-beginner
1 messages · Page 804 of 1
Programming is creative work
the inputs themselves might be partially standardized, but how they work in code to actually move the character absolutely is not
What is walking
What is jumping
What is looking
come on, you tell me after 40 years or so, game engines need code to know what jumping is?
@sour fulcrum what do you mean by that reaction? i thought that was marking crossposted questions 
yes
Yes
Twitter retweet equiv
oh, ive usually seen 👍 💯
☝️ etc for that
Mario Bros
Hollow Knight
Celeste
VVVVV
Metroid Dread
Donkey Kong Country
These are all 2d platformers that have very different implementations on a “jump”
They share fundamentals but games need to be specific
Code defines these specifics
hows that, other than maybe jump height and gravity impacts its all the same. so the base should be the same
there are several, several ways to implement jumping, depending on the game.
some games don't have jumping at all.
some have force-based jumping, simulating a real-life parabolic arc.
some have more snappy jumps, for more precision in parkouring/platforming.
some games let you control the height by holding the button for longer, some don't.
some games have double-jumps, some don't.
some games have wall jumps, some don't.
some games have coyote time or input buffering, some don't.
some games make you move faster when you jump, some don't.
some games give you less control in the air, some don't.
some games have hovering or flying, some don't.
the physics are absolutely not the same (VVVVVV doesn't even have this notion of jumping at all)
coyote time, physics potential, wave dashing type stuff, sliding, diagonal support etc etc
This is a really handy intractable game that helps get this point across https://gmtk.itch.io/platformer-toolkit
getting over it
just for trying things out. If i want to recreate all those jumping variations of the games you named. there would i start looking? googeling "mario bros jump code for unity" ?
Sure
if you're starting out, sure
According to this logic, you can be outraged why your game does not become ready at the stage of installing the engine
as you get more experience, you can adapt resources that are less specific
you might be able to adapt results from googling "mario bros jump physics" into your game
no because i still have to model the characters, the environment, create the cutstenes, come up with a story. the coding part just slows everything down
you have to design and implement the mechanics. that's what coding is for
movement is one such mechanic
model the characters, the environment, create the cutstenes, come up with a story.
if you don't have interactivity, this is just a movie or a visual novel
The code is the game, previously, games generally existed mainly in text format and without a plot
Well, at the stage of conception
Well, the pc
previously, games generally existed mainly in text format
wouldn't the first video games be like, arcade games?
So I said pc
I get that but those interactions (speaking with NPC, picking up Items, etc.) should be components build in in unity if you ask me.
ah, i didn't know what you meant by that addendum
that wouldn't work, because every game does that differently
consider how minecraft, terraria, pubg, and apex legends handle item pickups
or how hollow knight, minecraft, terraria, skyrim handle npc interaction
if you want to follow some particular well-known style, then you could probably find existing assets/resources to do so
but unity can't cater to everyone simultaneously
maybe im just to dumb to understand it yet but for the NPC talking example. how does every game doest it differently? you walk twards an PPC which is a game object. if you are in an certain radius and press a specific key, they play an animation, stop your movement and display a text or sound. thats the same in every game I can think of
How those things are specifically done are things programmers want control over
What you want is totally valid, it’s just not really unity
Dreams on ps5 is something a little closer
in some games you have to be looking directly at the interactible, in some games not
in some games you might need an overlay, some you might need a menu
how the dialogue is presented, how the sound is configured (2d vs 3d?) etc - these can all be vastly different
Not to mention saving
the overall concept is the same, yes. it's the details that are different, it's the details that you want to control
how would I know how to code that for example? where do I start?
hard to controll the details if you cant even code the concept 😄 I mean I can code the pseudo code and then chatGPT converts it but you guys sudgest me to NOT use AI for gamedev
start by disregarding code entirely - consider the design
see how other games do it, see what feels right for your game
you would identify what elements you need, then you would design how they lay out, and then you'd get to implementing it
I can code the pseudo code
you're already a good chunk of the way there then
have some patience and do it yourself, that way you can actually learn
"see how other games do it" is there a way to "see" how for example DMC5 does its doublejump?
ChatGPT very consistently provides people with very poor code that either breaks their projects in the short time or slowly in the long term
by "see how other games do it" i mean the mechanics, not the source code
all right, my bad 😄
nah i was vague there, that's kinda on me
btw, every step here involves researching, to utilize the available resources
if you see someone doing it without researching, that's because they've done it before
or if you see someone doing it without designing, that's because they have enough experience to do it in their head for that task
research and design are crucial to giving yourself an easier time
would you sidgest starting bigger with what I have in mind (recreating the first level of super mario 64) and expanding my game from there? or starting low with a 2d platformer or stuff like that
it's easiest to learn 1 thing at a time, but often that's not possible. if you minimize the things you have to figure out at the same time, that's going to be easier
start very small, and once you understand and are comfortable with the tools introduced there, move on to using more tools
I think it's better to start with minecraft, it seems to look simple 
(tools being components, features, different chunks of logic, etc)
Think the oasis from ready player one is easier
just went trough that toolkit. exactly something like that: a tool that already has a controll mechanic but lets you change that with handles and values and not code. IS there anything alike?
plenty, probably
but generally you want more customization than that. this is more of a physics demonstration
the source code for that is available btw
Possible 
Happy Sunday to everyone! Im learning lifecycles which Is overdue and is very important I think. My question is do I initialize self contained variables in the Awake method or OnEnable method? Lets say for example I will reuse this object after death and when its going to be enabled again its health will restore to 100, so health initialization in Awake isnt quite needed I suppose since when the object will be enabled its health value will be 100 and when its going to be disabled and reenabled later health will be reinstated to 100 once again. But lets say the object dies once and is not reset again, where does it make sense to initialize the health variable? I read the self component references and variables are best to be initialized in Awake? Want to hear some explanation from actual people rather a GPT or a documentation. Thanks
```cs
public int health;
private void Awake()
{
health = 100;
Debug.Log("Object is Awake!");
}
private void OnEnable()
{
health = 100;
Debug.Log("Object is enabled! Current health is " + health);
}
private void Start()
{
Debug.Log("Object is starting to die!");
}
private void OnDisable()
{
Debug.Log("Object has died!");
}
And this is a simple Coroutine im running in a " game manager " object.
```cs
private IEnumerator Test()
{
if (!playerController)
{
yield break;
}
yield return new WaitForSeconds(5f);
playerController.enabled = true;
for (int i = 0; i < 10; i++)
{
yield return new WaitForSeconds(1f);
playerController.health -= 10;
print("Player health: " + playerController.health);
}
playerController.enabled = false;
yield return new WaitForSeconds(5f);
playerController.enabled = true;
}
Just to view the life cycles in console
What I understood the most is Awake and OnEnable is best used to initialize self contained variables and references and only then start cross referencing other scripts in the Start method once the Awake and OnEnable are done for all game objects.
So Im just wondering where is the best place to initialize variables used in the same script, or it just depends how is it used?
But lets say the object dies once and is not reset again,
what do you mean by reset?
Awake is only going to run once, so if you need reuse the object and restore some state, Awake doesn't make sense
So the object dies, it gets disabled, its position reset, health reset and it gets enabled again
yup thats why I said since the object will be reset I can initialize the health variable in OnEnable, but if the object wouldnt be disabled/enabled its best to initialize all self coontained variables in Awake correct?
or like reference other same object components like transform etc.
Awake and Start are for initializing stuff that make the component usable, they run once
OnDestroy similarly runs once, for cleaning up stuff that was done in Awake or throughout the entire existance of the component
OnEnable would be for setting up the object when it, well, becomes enabled and active
OnDisable would be for cleaning up stuff that was done in OnEnable or throughout the active operation of the component
"best" is probably impossible to define, there's a lot of factors, but overall consider the design in how the object/component can be used
ultimately that was my assumption
if everything uses the assumption of being resettable, then no need to make an exception in this one case because it's "unneeded"
so both onenable and awake is fine to initialize self contained variables, just depends how the object will be used
i miswrote in the previous message, should be "how the object can be used"
not necessarily only how it's currently being used
And lets say I create references to other scripts in "Start" and the object gets disabled "not destroyed" will it still have that reference in memory even if its disabled and would be re-enabled again?
only when it gets destroyed they lose the references?
If you reference other scripts even if they're disabled. They'ill still have the reference in memory.
That's the whole point of disabling and enabling objects. Everything in the scene currently is in memory.
If you wanna save memory or split your games into sections without consuming memory, you'll have to destroy and instantiate objects appropriately.
Thank you. So enabling / disabling rather than destroying and instantiating objects makes more sense
this is close to object pooling i think? Im yet to learn that concept as well
but I will stop asking here, since this place is more for coding questions
I got the idea
Sounds like you want object pooling. I'd have a method called Initialize that sets up the object, and call it after retrieving the object from the pool . . .
Likewise, I'd have a Deinitialize or some type of reset method to call before returning it to the pool . . .
Just set the variable to null when you disable the object
!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**
sounds like a bot
```cs
using System.Collections;
using UnityEngine;
public class HoverBullet : BaseBullet
{
[SerializeField] public GameObject enemy = null;
[SerializeField] public bool isHovering;
[SerializeField] Vector3 moveDir;
// Start is called once before the first execution of Update after the MonoBehaviour is created
protected override void Start()
{
base.Start();
moveDir = transform.forward;
}
void FixedUpdate()
{
if (!isHovering)
{
transform.position += moveDir * bulletSpeed * Time.fixedDeltaTime;
} else
{
transform.position = Vector3.MoveTowards(transform.position, enemy.transform.position, 2f * Time.fixedDeltaTime);
}
}
}
why does my bullet immediately teleport to the enemy? i want it to follow him instead
place a log in each case of the if statement to see which one runs. that piece of code is teleporting instead of what you expect . . .
yea i want it to just move towards the enemy, thats all
speed is too fast maybe?
tried with 0.1f still teleporting
okay, but which code in FixedUpdate is running?
isHovering
ill try using a rigidbody instead
so, the MoveTowards code is running? how are you doing collisions? if you're using colliders, you shouldn't move using transform.position . . .
use velocity or force to move the bullet . . .
```cs
using UnityEngine;
public class HoverTargetEnemy : MonoBehaviour
{
[SerializeField] HoverBullet hoverBullet;
[SerializeField] bool hasTriggered;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Enemy") && !hasTriggered)
{
hasTriggered = true;
hoverBullet.enemy = other.gameObject;
hoverBullet.isHovering = true;
}
}
}
i have a big on trigger collision around the bullet with this script on it
what's a good way of referring to prefabs in a dictionary without instantiating them?
just store the path to each file in a string?
do you mean instantiating or loading them?
if it's just instantiating, you can just store a prefab reference there and use it
if it's about loading, then you should look into addressables
instantiating, to get the prefab references I was just going to store the file names in a dictionary
but then how are you loading those files?
that happens in the next scene, I'm making a character selection and I'm passing the information about which character to load to the game scene
so I wanted to store the references in a dictionary with an id to make it easier
yes, but how are you actually loading the assets? using the resources folder?
this seems to be a pretty good use case for addressables any way, you just need to store an asset reference and forward it however you want, no need to deal with path strings
ah yes that looks like it'll do the trick, thanks
hi im having an issue with unity version control so basically i made an alt account owner and tried to commit code but it says i dont have permissions even though im an owner of the project
not really a code question
do yourself a favor and save unecessary headaches and use Git. UVC is a dump
school blocked it
Git, not to be confused with Github
we need to make a group project and uvc was the only thing which wasnt blocked
iirc you can upload/commit to github directly from the browser
unless they blocked the site itself
they did
what about codeberg or gitlab
how does a school block the git software
iirc you need admin permission to install anything on school pcs no 🤔
yeah
even git
no idea we never got pcs where i went to school
it just says i have to request permission to download smth
yeah idk that thing is always bugged
you might have better luck asking on Unity Discussions site and maybe those VC devs might see
ahh alright thanks
whatever is left from all the layoffs
its all ai now, they removed humans from the forums 
/r/totallynotbots moment
I suppose I don't even need the dictionary if I can just use the addressable address string directly
but then its string comparison again
I suppose there's no way around it
Hm? string comparison? context?
I made the character prefabs Addressables so I can tell the next scene which prefab to load, but the way that is done is by using the Addressable address string
That's fine to pass the address but why do you think there is string comparison? They are likely hashed to do a faster lookup.
You could also pass some unique id for these characters so you can look up the address.
I see
yeah I was going to make a dictionary but that actually makes it worse
vs. using just the character name as address string
A great way for beginners is to use scriptable objects to store configuration for stuff like this:
```cs
public class CharacterConfig : ScriptableObject
{
public AssetReferenceGameObject prefab;
public int health;
public string displayName;
}
You can load many into a dictionary:
```cs
Dictionary<string, CharacterConfig> characterConfigs;
//...
//Load them all from a resources folder and add to a dictionary
var assets = Resources.LoadAll<CharacterConfig>("CharacterConfigs/");
characterConfigs = new(assets.Length);
foreach(var asset in assets)
{
characterConfigs.Add(asset.name, asset);
}
```
Yea give it a go. I used AssetReference in the example as that lets you assign an addressable asset and does not create a direct dependency (so you still LoadAssetAsync() but via the asset reference instead)
https://docs.unity3d.com/Packages/com.unity.addressables@2.8/manual/asset-reference-intro.html
Not sure if this is even possible to fix but whenever I move in my first person camera while fixating on an object, I can kind of see the object vibrate instead of move smoothly. I know this is kind of an issue with every first person game but it feels a little strong in my project.
My camera is a child of my player although I think thats irrelevant because the actual camera moving looks fine, but looking around with my mouse is the issue especially when combined with moving around. Here is my camera movement code that is being called in update:
```C#
Vector2 mouseDelta = Mouse.current.delta.ReadValue();
float mouseX = mouseDelta.x * mouseSensitivity;
float mouseY = mouseDelta.y * mouseSensitivity;
//rotate body left/right
transform.Rotate(Vector3.up * mouseX);
//rotate camera up/down
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -maxLookAngle, maxLookAngle);
if (playerCamera != null)
{
playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}```
Where is this executed? Update?
yes
How is the player moved then, physics?
yea linearvelocity
Do you have interpolation enabled?
yes
You probably should be rotating the rigid body with physics too or you need to lock physics rotation
You can also try assigning to rigidbody.rotation instead if doing this
Example of some basic movement I did a while ago:
```cs
private void FixedUpdate()
{
//Movement
Vector3 input = inputs.gameplay.move.ReadValue<Vector2>();
//Change speed
input *= MoveSpeed / Time.fixedDeltaTime;
//Make local
input = rigidBody.rotation * new Vector3(input.x, 0f, input.y);
rigidBody.AddForce(input, ForceMode.Force);
I rotated in late update:
rigidBody.rotation *= Quaternion.Euler(0f, lookInput.x, 0f);
hmm ok i have some developments
i did the following code and it COMPLETELY got rid of the vibrating, but now general mouse movement feels slightly choppy as if its like 30fps
```C#
if (rb != null)
{
Quaternion yaw = Quaternion.Euler(0f, mouseX, 0f);
rb.rotation = rb.rotation * yaw;
}
else
{
transform.Rotate(Vector3.up * mouseX);
}
i can try fixed update again although that wasnt good before
Hey, im making a proceedural spider leg system and im confused on how instead of lerping the legs, they would start at the starting position, and go to the end position while lifting up in the process like a spider, and if anything in my code is badly optimised?
Dont read input in FixedUpdate
Why not?
for pressing/releasing edges sure, but for reading values it's fine tbh
badly optimized i think is what he's trying to say
hmm no
no, that's not relevant
For important inputs like jumping yes its not a good idea as we may miss them
ohh okay
it will only reads the movement every so often which is a longer stretch of time than your FPS so it feels like lower fps no?
input is framebound, it gets updated every frame
detecting the rising or falling edge of an input should be done on the update loop
but for getting the current value of an input, it can be done anywhere, just that it'll be updated in the update loop
Thats why I had this in LateUpdate
```cs
if(!shouldJump)
{
shouldJump |= inputs.gameplay.jump.WasPressedThisFrame();
}
Read the input more frequently to then use in FixedUpdate to add force
even if you move the input to update, the actual action would only be updated every fixedupdate as physics gets simulated
yea i realized that
so yes, there's some delay, but just moving the input wouldn't change anything
which is why it still feels bad in update
but it does look better so im torn what to do
yeah personally i like having input in update for organizational reasons, but no technical issue with this
I replicated my input delay problem I had last week, where sometimes the rigidbody object moved with delays and saw that I was reading my Input in the same method where the movement was applied inside FixedUpdate. So my thought process was 0.005s is four times faster than 0.02s of the fixed time step, I moved the input to update and it started working fine?
Maybe a coincidence
could be, but (without any further info) my next best guess would be you were moving with the transform
no was moving the whole rigidbody.position like advised here too ^^
oh hm 🤔 that's meant to be a teleport without simulating physics, maybe that gets applied immediately?
is it not more affected by physics lag if in fixed or no?
```cs
private void FixedUpdate()
{
Move();
}
private void Move()
{
Vector2 verticalInput = move.action.ReadValue<Vector2>();
Vector2 finalInput = verticalInput * (movementSpeed * Time.fixedDeltaTime);
Vector2 targetPosition = myRigidbody.position + finalInput;
targetPosition.y = Mathf.Clamp(targetPosition.y, -yAxisBoundary, yAxisBoundary);
myRigidbody.MovePosition(targetPosition);
}
If using Update/LateUpdate: rigidbody.rotation
If using FIxedUpdate: rigidbody.MoveRotation()
The docs mention which is best for what situation: https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.MoveRotation.html
since the docs do mention using this to help with updating the physics scene
(why are you moving with .position though, that doesn't simulate physics)
aren't these just different things
Its moving with the MovePosition no?
.rotation = is a teleport, MoveRotation is a sweep
im currently using .rotation in update and it still feels kinda low fps or like not as smooth as before
.position = and MovePosition are not the same thing
not sure what you mean by that
oh so you are using MovePosition, that would be bound to the physics tick then yeah
like he said he saw delays when his movement was in fixed update but could just be lag
yeah but what lag are you referring to by "physics lag"
Yes but just wanted to point out the difference explicitly
idkkk like the fixed update tick coming late
I dont know why but with this code I sometimes got delayed input and even when I released keybinds the rigidbodies still were moving by themselves
Its either change rotation without physics but update physics or rotate with physics and interpolation
your message sounds like it's trying to say they're the same for different messages 😅
I moved Input to Update and I didnt get the same problem
But I have to say I changed the batteries to my keyboard that same time, so that couldve been the culprit too haha
FixedUpdate executes on the main thread when enough time has passed and we want to update physics so reading translation movement input in update/fixed makes no difference.
another option couldve been that the input was being read incorrectly, maybe after the rb move
i will try moving it back to Fixed Update again, as now Im thinking about it that input should be better off in sync with the rigidbody
If we just want to get the current state of WASD/controller stick for physics movment then Update/FixedUpdate will do the same because both get executed on the frame it happens on the same thread.
But thats for reading input it would be the same regardless I think yes, but the response we get gets slower in FixedUpdate the higher FPS we get no?
It will be better because fixed update may get executed a tad sooner because more frames means better precision to hit the desired physics update time step.
Gurble
Isnt it reversed? More FPS means more Update to FixedUpdate calls.
Update
Update
Update
FixedUpdate
no
Update
it would be:
Update
Update
Update + FixedUpdate
And according to the unity docs FixedUpdate may even get executed multiple times per frame:
https://docs.unity3d.com/6000.3/Documentation/Manual/execution-order.html
Resulting in double input
Which is bad?
not sure but what function we read input from didnt cause that did it?
Input system also polls devices at a fixed rate too so that would also affect the input data we read
my beginner expertise ends here ^^ need to do further studying and experimenting
yea it can be confusing but me and others are here to offer advice again in future
Appreciate it really!
Just trying to think with my own head while im learning
LateUpdate for camera movement and rotations makes sense to wait for Update to finish moving the object itself first then fire the lateUpdate for the camera to move to the last position. I had jittery camera movement before when I had it follow the "player" in Update loop.
well, that's definitely several steps in the right direction 
LateUpdate is very useful. If we want to follow a transform (e.g. UI) then thats the place for that too.
Hey, im making a procedural spider leg system and I'm confused on how instead of lerping the legs, they would start at the starting position, and go to the end position while lifting up in the process like a spider?
```cs
void UpdateLegPosition()
{
CalculateLegTargets();
for (int i = 0; i < LegIKTransforms.Length; i++)
{
float step = legLerpSpeed * Time.deltaTime;
LegIKTransforms[i].transform.position = Vector3.MoveTowards(
LegIKTransforms[i].transform.position,
LegTarget[i].position,
step
);
//LegIKTransforms[i].transform.position = LegTarget[i].position;
}
}
Might want to describe what you're trying to achieve and what you're getting instead.
I'm assuming the problem is that everything happens instantly
Could you expand a little what you being by following UI elements? I dont seem to understand what you mean by getting UI element positions?
in the same vein as the camera following some target, sometimes you want non-child UI to follow some target
There's no error in my code, but instead of lerping, so moving smoothly from one point to another, I want it to start at the starting position and jump to the end position, like you lift your legs while walking, heres a visual demonstration if that may help
You mean the UI which isnt fixed on screen like health but a 3d like Ui following the player?
sure, in my case i have tutorial text inside a level where i want it to follow a player around
Yea if we want some UI element to follow/move to match some world position
If the element is actually in screen UI then we need to do WorldToScreen conversion
Would you not just lerp the local height variable up and down and then plug that into the A to B lerp?
you'd probably have to keep track of the whole movement instead of a movetowards, an actual lerp might work. gotta first figure out what trajectory you want and then find a mathematical way to represent that, a parabola would probably be easiest (while also giving a reasonable result)
What about those "Press "E" to interact" when you come by a door. Do those work the same like you mean?
I'm not sure what you're doing but your current interpolation isn't Lerp. It's using move towards and the speed is linear (a fixed rate per second)
oh wait i wrote that at 5am i thought i was using lerp
Yea they sure can. Some system detects the interactable object is "in reach" and then shows the UI and has it track some world position
Thank you!
If you want non linear motion like the image shown, you could probably use slerp or some other non linear interpolation
Thank you! :)
I'm assuming you want the "jump" line and not the "lerp" line, from the image shown #💻┃code-beginner message
Yeah
@strange jasper on a side note, i'd also recommend opening some document in draw.io/powerpoint/canva/miro/etc and try drawing out different scenarios, and see what you'd want for each scenario, and then you can find a solution that matches that
maybe a parabola doesn't look nice with a short distance for example, you could then maybe try a circular arc instead
would help you figure out what constraints and inputs you want too, which would make the implemenation easier
Thanks, I might experience with the distance threshold before the legs move if that is the case
I have a question that's probably better for general, but I'm not really sure how to ask for what I want.
I'm trying to figure out how to transition from walking up to a wall, to climbing that wall and vice versa
I'm stuck with how to switch between the ground movement and the climbing movement and how to do that without locking the player to either the ground or wall and needing them to jump to either.
in terms of design/interaction, or implementation?
implementation
i have the climbing movement and walking movement, but idk how to transition them in code
(the linear in linear interpolation doesn't mean it goes in a straight line btw. slerp is also linear, the output is linearly proportional to the input t aka a linear function
your message kinda sounds to me like it's suggesting that linear interpolation = straight line, so just in case you weren't aware
)
right now, i'm just checking if there's a wall directly in front of the player and then setting movement to climbing
well, you would just change whatever value distinguishes those movements?
it's kinda sounding like you're more stuck on design/interaction
how it is now means I have to either jump off the wall to move back to walking, or I have to jump onto the wall to climb, I can't go directly from walking to climbing or back again
and what should the intended flow be?
If I'm climbing down the wall, I should start walking when I hit the ground, or if I walk up to a wall, I should be able to just start climbing.
It should be a smooth transition. I shouldn't have to jump to get it to work
ah, ok. i misunderstood what you were trying to say in your initial message
well, start with design, you'd want to detect the ground (when climbing)/a wall (when walking) within some distance and direction
could probably use raycasts for that
rn I'm using a spherecast for both. A sphere at the players feet detecting the ground and one directly in front of their center detecting walls.
both always active?
The ground check is always active and the wall check is only active when the player is moving
The ground check is always active
well then you'd never be able to leave the ground
hey! thanks for this I just managed to figure out how to convert my inputs to the rb movement but it still goes through the object (whilst its in the bounds of the object it shakes about) was just wondering if you knew a method as the last line of this message seems promising haha.
i'm about to go so can't look into this further, but i'd guess something like this might help?
in grounded state:
if walking forwards and raycast hit wall:
-> climbing
in climbing state:
if going down and raycast hit floor:
-> walking
```so it only transitions with player input
Okay, I'll give this a shot
Can you share how you are moving the object? Perhaps open a thread in #1390346827005431951
of course one sec!
I found slerp to be what I want but I am not really sure which parameters to pass through, the docs are not really clear to me
im sure ive fucked it up
```cs
LegIKTransforms[i].transform.position = Vector3.Slerp(
LegIKTransforms[i].transform.position,
LegTarget[i].position,
stepHeight
);
where do i even start?
its 0.5
wdym?
Read the docs
Lerp abuse!
i cant understand them
Linear interpolation is not to be used to "move towards some value by a constant rate"
im trying to get it to move from one point to another in an arc motion
Vector3 Move towards can do this however
Then some function to do this using sin should do
oh you'd need to sample a bunch of points if you want to do it this way then
curve or sine is an idea too yea
how would sine be used
like in what way
animation curve gives you a bit more editor control for big steppy
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/AnimationCurve.html
These things. Y would be the arc and x would be time
thank you :)
Wait, hold on. That would be a rate. Let me think about this
Ideally just make the curve normalize from 0-1 too
yeah i just tried and it didnt work
didnt know itd be this hard to make a transform move in an arc trajectory 
Throw me the code you're moving on the x/z axis
```cs
void UpdateLegPosition()
{
CalculateLegTargets();
for (int i = 0; i < LegIKTransforms.Length; i++)
{
float t = Time.time * legLerpSpeed;
float y = Curve.Evaluate(t);
Vector3 currentPos = LegIKTransforms[i].transform.position;
LegIKTransforms[i].transform.position = currentPos + new Vector3(0, y * stepHeight, 0);
}
}
i dont think im doing something right to be honest
```cs
public AnimationCurve Curve; //0 to 1
public float HeightMulti = 3f;
public void MoveLeg(Vector3 target, float duration)
{
StopAllCoroutines()
StartCoroutine(MoveRoutine(target, duration));
}
IEnumerator MoveRoutine(Vector3 target, float duration)
{
Vector3 start = transform.position;
Vector3 end = target;
float elapsed = 0f;
while (elapsed < duration)
{
elapsed += Time.deltaTime;
float t = Mathf.Clamp01(elapsed / duration);
float height = Curve.Evaluate(t) * HeightMulti;
Vector3 pos = Vector3.Lerp(start, end, t);
pos.y += height;
transform.position = pos;
yield return null;
}
transform.position = end;
}
Something like that. The only problem I'm thinking of is if the coroutine can get interupted. Haven't really done one of these projects yet
Actually duration wouldnt make too much sense if you want to step closer. So you want to make a rate from distance and a speed
how would I write a check that sees if a boolean becomes true?
Thank you! about to check if it works
invoke an event?
```cs
void Update()
{
CalculateLegTargets();
for (int i = 0; i < LegIKTransforms.Length; i++)
{
float distance = Vector3.Distance(
LegIKTransforms[i].transform.position,
LegTarget[i].position
);
if (distance > legThresold)
{
MoveLeg();
}
}
}
public void MoveLeg()
{
StartCoroutine(UpdateLegPosition());
}
IEnumerator UpdateLegPosition()
{
CalculateLegTargets();
for (int i = 0; i < LegIKTransforms.Length; i++)
{
Vector3 start = LegIKTransforms[i].transform.position;
Vector3 end = LegTarget[i].position;
float elapsed = 0f;
while (elapsed < legLerpSpeed)
{
elapsed += Time.deltaTime;
float t = Mathf.Clamp01(elapsed / legLerpSpeed);
float height = curve.Evaluate(t) * stepHeight;
Vector3 pos = Vector3.Lerp(start, end, t);
pos.y += height;
LegIKTransforms[i].transform.position = pos;
yield return null;
}
LegIKTransforms[i].transform.position = end;
}
}
not entirely sure whats gone wrong
Hmm, actually I am just appending a height but I should be sampling from the base height
Actually, it does look correct. I have to try it out when I get home.
thank you so much it means a lot, i don't want to stay up until 6am coding spider legs again 
Really looks fine to me. I'd double check if it's something setting your values elsewhere
Oh, remove your update
Shoudl just be calling the coroutine
Oh, ok maybe you're calling the coroutine multiple times
Like, for testing purposes just throw what I gave you onto a random gameobject and make sure that works
i’m gonna take a shower and then i’ll check, i might be calling it twice since it’s a distance check, thank you :)
Ye, this way should work fine assuming that the leg always completes the destination, but otherwise you may run into issues if you need to interupt them which will require more logic.
I have a C# question. I have a few void methods that are going to be called in the Update() method of a MonoScript. Should they be positioned before or after Update()? Does it matter?
makes no difference
Thank you. For future reference are any of the other built in methods like LateUpdate() or OnDisable() sensitive to void method positioning?
The order of functions in a class does not affect functionality at all
c# is a compiled language
the entire class is read first
and then it starts to care about method calls
It may in C and C++ but thats due to how that gets compiled compared to more modern languages
in python for example the order does start mattering
because its not compiled but interpreted or whatever
Oh that's cool! I come from Java/Typescript where we have to worry about that sort of thing. Good to know!
I meant JavaScript/TypeScript
ah
The order doesn't matter there either
you sure? im pretty sure js is interpreted and not compiled
nvm i checked
it matters for function expressions
but not declarations
That doesn't really factor into it, the interpreter parses the entire code before executing it
It goes line by line in function declarations unless you're using async
in c and cpp it matters because compilation is done in a single pass (which is why forward declaring is possible and sometimes needed)
c# does multiple passes to avoid the issue
Function declarations are hoisted in JS
yes and expressions are not
there's people who dislike headers
I mean it's exactly the same in C#, class methods in JS -> order doesn't matter, expressions (delegates/lambdas) -> order matters
haha well it solves a real problem, defining symbols ahead of time
same for forward declaring. Its "trust me compiler this will get defined soon 🙏 "
i see what you mean, thinking about it i know it’s called a few times, a random thought but if i created an array of boolean’s and used those as a flag would that work?
since the behaviour is obviously different i think your logic does work
the problem is that if the leg starts in the air then you arc from the current position mostly
you can interupt it fine, but you need to figure what the idea is to reposition the leg mid transition
in that case you may not want a coroutine and just reuse the current progress in update
I don't know how I did it, but I did it
so i put the logic in update?
sure, but logic needs to change a bit since you cant yield from update like that
what do i do?
Sorry im very stupid, forgot you had to set the curve, tysm for all of your help
slight problem
edit: just needed to change the preciseness of the curve
What's everyone's favorite keyboard shortcuts in Visual Studio?
Ctrl + R + G
Alt + F4
Alt + hold power button
Sorry. I can’t have a favorite child.
Is there something better than visual studio
The only other choice similar is jetbrains rider
VS code exists too but is not as feature complete
Better in what way?
Idk I’m a complete beginner, just wanted to know if there is better options
Say I have 6 vectors, how would i average those out to get a rotation of an object?
Are you referring to the type Vector3?
Yes, I'm trying to calculate body position for a spider based on where the leg targets are, you probably saw it earlier
Average would just have to add up the values and divide by the number of values
If you're referring to the centroid, you can simply look that up.
do the unity devs ever plan to add support for custom enum parameters and more than one parameter for unity events? theres soooo much more i could do easily if i didnt have to find a workaround for everything not supporting the useful stuff.
i could make the 160 wrapper functions, but would the dropdown even support that?
Probably not no
hey im new here and need some info, i have the go from a DEV to mod the new game and i have problem finding the right tools. the game is Burglin' Gnomes
you'd have to ask in that game's modding community, we can't help with modding here
oooh thanks
Kinda stuck here, I have a spider with six legs, and it has six IK targets, I want to use centroids to calculate the bodys rotation using the IK targets but I'm not too sure how, right now it's like 2, but I want it to be like 1
better explanation
Set the up direction of transform relative to the normal of the floor.cs transform.up = floorSurface.normal * distance;
Where distance would be how far away you ought to be from the floor (the average of your leg heights relative to the surface of the floor)
But say two legs are higher than another, I want the body to face those two legs like the screenshot (yellow line is what i want for bodys orientation)
Probably determine if both legs are on the same floor. If not, elevate body relative to higher floor. Where distance would be some offset above the average height of each leg on the higher floor.
What if I want more legs
You'd have to accommodate for whatever you're wanting to do
well make a spider
Probably determine if all legs are on the same floor.
so only quaternion have slerp right and using lerp for this will have a built in dampening effect and slerp isnt? is this how i should use lerp and slerp? damp and no damp?
Slerp will treat the values as directions. Lerp will treat them as numbers. Slerp will get you a value between two directions, the point some percent of the way along an arc between the two directions on a unit sphere. Lerp will get you that point along a line drawn between the two
📏Lerp vs Slerp⭕
• Lerp interpolates in a straight line
• useful for interpolating positions
• Slerp rotates around (0,0)
• useful for interpolating directions
#unitytips
lerp goes in a direct euclidian line, slerp goes along the surface of a sphere/circle
idk i dont see any vector.slerp
are you only looking at Vector2?
this look like slerp should have the damp thing rather than lerp ?
because Vector3.Slerp absolutely exists
Neither of them have anything to do with damping
Neither of them even have a concept of damping, it just gets you a value some percent of the way between two others
literally the only difference between the two is spherical (slerp) vs linear (lerp)
sl is spherical linear
the linear means the output changes linearly, not that it's a straight line
why the first lerp (linear) have the damp thing
What damp thing
rotate with the first lerp slow down when near 180 and speed up again
One of them will be linear. One of them will be spherical. As demonstrated in the gif
oh, yeah
guys the difference is not spherical vs linear, it's spherical vs direct 
they're both linear
Well, one of them is eculidian linear, one of them is non-euclidian linear
but that's a bit more confusing to explain
they're both linearly proportional
the "linear" is about the function, not the geometric result
How would I make this core rotate based on the position of the legs? kinda stuck and im not really sure what to do or what steps to take
sure, but when explaining it to someone who clearly can't tell the difference between the two, is it not just easier to point out the "linear" vs "spherical" (even though the latter is still linear, just in a different way)
i feel like it misleads about the l in slerp but fair enough
The most important thing is to impart that it is not "Do a thing over time"
it's a discrete mathematical function that produces exactly one value at the time you run it
at the very least let me use 2 ints. i keep hitting roadblocks in logic just because i can only use one single basic type parameter. this is going to make my code unreadable if i take any breaks from this before im done. all that money they got and they cant even give unity events some love -_-
i mean, that's really only a limitation for passing specific values via the inspector. you absolutely can use unity events with multiple parameters if you are passing the data dynamically (i.e. in code)
if there was at the VERY least a way to use an editor script to make your own support for two basic type parameters id be happy. now i might have to make a 4th scriptable object script
that's actually the workaround for it anyway
https://unity.huh.how/unity-events/method-requirements-workaround
i made a spawn function that uses 3 enums and an int value and a float value.
okay, and do those things need to be assigned to the listener via the inspector or can it be passed directly to the event?
because for the latter you don't need any special workarounds
im using scriptable objects to be workaround cuz unity events absolutely wont serialize that
you should show what you actually have, because from the sound of it you don't really need this workaround. unless you have multiple subscribers to the events that each need different data passed to them for whatever reason
this is the one im trying to call from the timelines unity event. the 24 is an index for the list of 160 scriptableobjects i used to hold the 3 enum values with all combinations.
the grid is something i have spawned at runtime using the blue squares you see in my first ss
i think ill restart everything from scratch except for the scriptableObjects now that i know more of the limitations i have to deal with because unityevents has to have complicated workarounds.
because the timeline signal can only be a UnityEvent and not one of the generic versions that can pass more data you are limited to the same values that a UnityEvent can pass. this is not something that would be easily changed without a lot of complex logic that allows you to specify which generic UnityEvent type you would like to use. so you are restricted to using those workarounds, but the link i sent before gives a good way to work around that limitation
however, if you already have the data set up in a scriptable object then really what you're doing now is probably going to be easiest
literally what would that accomplish? i already told you that you need to use a workaround and why. you've found a workaround that seems to work for your workflow, but if you don't want to use that moving forward i gave you a perfectly valid option that works just fine. but no matter what you will need more code for each different type of event you want to support, that's not really something you can avoid for it
alright. can unityevents have scriptableobjects as parameters?
since i cant even use gameobject i will just keep the int for presetIndex and im making another scriptableobject and using Gameobject.Find in SpawnNote to do a very long workaround
why can you not use GameObject?
why would I be getting an error on other? is it the unity system im using?
you are using = instead of ==
oh, thats my mistake but its not that
the error should be telling you that you can't do = on other.gameObject
it says "other does not exist in the current context"
am I missing an import?
what is other
I'm trying to refer to the other object in a collision
what is the actual name of the parameter there?
what parameter?
the method parameter that you are trying to use
like collision?
yes
just to be clear ur talking about the Collosion2D passed through the method?
cus its just called collision
yes, notice how it isn't called "other"
right now I'm trying to get a teleportation system working between two points, and it does work however only when the player is moving on an object and pressing a button, I want it to work when I player is just on a pad and pressing a button, how could I fix this?
you shouldn't be using GetKeyDown inside of OnTriggerStay because that runs only on FixedUpdate frames, however GetKeyDown only returns true for the very first frame that a key is pressed which is unlikely to be a FixedUpdate frame. either check the current state of the input, or flip a bool inside of OnTriggerEnter/Exit and check for the input (and the relevant bool) in Update
also you should ideally serialize the reference to the desired target object rather than using FindWithTag
thanks it all works better now
also I checked this with a counter but it seems stayed only gets called when u are moving in the object, I thought it would be called if u were just standing in the object
provided the relevant rigidbody does not go to sleep it should continue being called
oh, ima try to fix it but basically when I move inside the object my counter goes up but when I'm just standing in the object it doesn't go up
Not sure if rigidbody sleeping is still a thing, where your rigidbody will get inactive/sleep, while not being moved/used
Can you describe specifically what do you need?
ok guys I am almost done with the beta of my game and all I need to do is make it so that audio can get saved when you close and open the game again. I am so done, I have been working on this SINCE YESTERDAY, and for some reason FOV and sensitivity work absolutely fine BUT NOT THE AUDIO
hell I used chatGPT and tried to get it to help me but all it gave me is my code that I did myself but cleaner
this code is like 210 lines long, can I just paste it here for help?
!code for pasting code, especially 210 lines. And maybe describe, what you want. What you mean with saving audio? Whats the game about that you need to save audio? give some information
📃 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.
read the bot message for instructions to post code properly please
specifically the section on large code blocks
what do you mean by saving audio anyways? do you mean volume settings?
OK here is the code, I just want to be able to save the audio settings so that the player doesn't have to reset them each time, the variable for audio can get saved and works fine but mister audio mixer is being a bit problematic and doesn't want to set the audio after starting the game
yep, volume settings, the variables and playerprefs work fine but the audio mixer doesn't set the volume after starting the game while the sliders are set, for example if I set the music volume to zero, then stop and start playmode, the slider is set to zero while the music still plays, but the music does get set when I change the slider once again
Set the volume to 1.0 at scene start? You need to think about where you change the volume, and where not...
oh...
wait lemme change it
well that didn't work
the sliders work fine but when I disable and enable playmode, the sliders are still set to what they were set before disabing playmode, but the audio just sets itself to max again, I am so confused and annoyed AHHHHHHHH
could you share your code properly
ok ok I took some footage for it for you to see what I mean
Keep ignoring suggestions to share code, so people will ignore your further input ...
I cant, each time I try to paste the code it becomes a text file lol
You did not read a single line of the bot message, right?
I did
So where did you paste your code?
yeh, not read a single line of the message
so what does the third line of the embed say
to surrong the code with ```
i specifically mentioned the large code blocks section #💻┃code-beginner message
that's not the third line, but ok
oh shit I though it was websites that tell you how to lol
I am gonna paste the code in and see
huh, that's unfortunate. try others
second one
right you don't have to keep posting them, we all have access to the internet
ok the third one worked, now what the hell do I do?
share that link
there we go
can you help me figure out the problem now?
Why are you naming things differently in playerprefs?
master = PlayerPrefs.GetFloat("Master vol", 1f);
music = PlayerPrefs.GetFloat("Music vol", 1f);
sound = PlayerPrefs.GetFloat("SFX vol", 1f);
vs
mixer.SetFloat("Master", LinearToDb(master));
mixer.SetFloat("Music", LinearToDb(music));
mixer.SetFloat("sfx", LinearToDb(sound));
as a sanity check, have you tried debugging to make sure ApplyAudio is being called? beyond that, debug the values you're getting from playerprefs and the values before & after LinearToDb to make sure they're what you expect
ok, imma try that
Id stick with the same naming. But thats just an improvement/nice to have
I debugged it and yes, applu audio is being called
do the other things too
yup, they work as expected for mister audio mixer : from -40 to 0, at least I think that is normal, right?
Debug your load and save settings method. Run them once, restart playmode, and run them again. Are the values expected as they are?
ok imma do it very quick
perhaps check if anything else is changing the mixer volumes
nope, there is one script and one script only
also I checked, save and load settings work properly
I would rewrite the LinearToDb, so first calculate the log10 without clamping and then clamp the result to 0.0001f and 1f Did not think obviously 😄
that is what I used to do but it virtually changed nothing
HOLD ON I CHECKED I THINK I FOUND THE PROBLEM
playerprefs have been deleted in a previous test I did, wait lemme make new ones
Could be, that you run into imprecision float values which result in something lower than 0.0001 which results in miscalc and reset to 1
Playerprefs should create newones with SetFloat/GetFloat(defaultValue)
Did you try to rewrite the Log10 method?
It’s time to quit. You’ll never figure it out.
do I remove the * 20?
I don't know what you are trying to do sir but nah, stopping ain't me chief
I am the most delusional person out here and I won't stop until I figure it out
ok I am gonna remove the * 20 and see if it works
your original seemed correct
i'm using a similar method in my own impl
audioGroup.audioMixer.SetFloat($"{audioGroup.name}Volume", Mathf.Log10(Mathf.Max(value, 0.0001f)) * 20);
that's not how that works
can you show me your full implimentation so that I can learn?
the rest probably isn't going to be relevant to your case, i don't have saving
i mean, not like there's much there to begin with
@hoary nova have you verified that the LinearToDb(master) is the value you expect right before you pass it to mixer.SetFloat?
shouldn't that be -80 to 0
log10(0.0001) should be -4
anyways, are you getting any warnings or errors?
nope
are SetMasterVolume etc perhaps getting called
it is, yes
they are called through sliders
I am gonna try and see if calling them at the start works
i mean at the start, the code you have assumes it doesn't
so i have a monobehaviour class A that depends on Rigidbody:
```c#
[RequireComponent(typeof(Rigidbody))]
public class A : Monobehavior {
// ....
}
inside another script, i run:
```c#
gameObject.AddComponent<A>();
```
in runtime. the thing is will the `Rigidbody` component automatically added when class `A` is added?
Note: RequireComponent only checks for missing dependencies when GameObject.AddComponent is called.
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/RequireComponent.html
or, yknow

GUYS I GOT IT TO WORK YEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH
ALL I HAD TO DO WAS PUT ApplyAudio(); ON THE START FUNCTION
GUYS I don't know how to code😭💔
I've only ever coded scratch
and I still barely know💔
so you do know how to code 
anyways to learn c# or unity, see the tutorials pinned in this channel or unity learn
!learnm
There's no command called
learnm.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I have an array called target[] and I want to use target as a parameter in the same class. Using this. got rid of the error, but just to make sure, does this. pick the class array or the parameter in the function?
```c#
public bool IsTargetValid(int host, int target)
{
if (enumsData[target].State == State.Dead)
{
enumsData[host].State = State.Idle;
this.target[host] = host;
return false;
}
return true;
}
Surely if it picked the parameter you'd still get the same error for trying to use an int like an array
x.y gets the y that belongs to x, or in the context of x
Good point
If I remove [host] it gives an error
But my question was whether x is the class or the function
functions aren't first class members in c#, so it can't be the function
That's all I needed to know
i guess that's kinda a blurry line, since you can use functions as their equivalent delegate
i remember having this discussion in the ts server and it did not yield any concrete answers lmao
Well, if it referred to the parameter, then target[host] would be an error because you can't index into an int
But this always refers to the Object running that line of code
this just points to the current instance, as a rule - not just in c#
not much use to have it point to the current function call
i guess that's another angle - the function call doesn't exist in this way, and target is within the context of the function call, not part of the function, so this.target can't possibly be the param
Hey guys im instantiating an object at a random point on a sphere.
I already have that handled
but now im trying to set its rotation so that "up" is the same direction as
[Quaternion upFrom Planet = centerOfPlanet - positionOfSpawnedObject]
so that it faces "up" no matter where it spawned on the planet.
INSTANTIATE(positionOfSpawnedObject, upFromPlanet)
but its not actually working?
it works near the equator but not the poles
so theres something im not understanding
what code are you actually using
please don't retype code, you lose a lot of information doing that
Quaternion x = a - b with Vector3s isn't valid
"up" ... on planet
var instance = Instantiate(...);
var direction = instance.transform.position - planet.transform.position;
instance.transform.up = direction;```
Sorry i ask about it because im thinking about it at work, i dont have code in front of me
ill ask again with pictures later
How can I make the Cinemachine's movement smooth when following an object?
it should be smooth by default
if it is not smooth, you have misconfigured something
The most common issue is the use of Rigidbody without interpolation or with some code that breaks interpolation
Is there something wrong here that might be causing the problem?
here? no. It would be in your code.
also consider if your object might be the one jittering, rather than the camera
you have interpolation enabled here but your code may be breaking it
Any code that directly modifies the position or rotation of the Transform will break interpolation
Good day to everyone. Just a quick question about the Pong game. Which script would make sense call the ball reset whenever the ball triggers the zone and the score goes up? Should the ball call on trigger enter on itself or the score zone calls when the ball enters its trigger? I would guess the ball only knows where to reset its position, direction and velocity, and the score zone triggers the "event" that a ball has triggered its zone and then the ball reset will be called from the score zone script
I don't think there's a clear answer in this case
It can be done, validly, in many different ways. Kinda depends on how you want to structure things
I guess I'd lean towards the score-zone being responsible for telling the ball to reset
One might imagine more than just the ball needs to reset. In which case you could either:
- reload the whole scene
- Have some centralized manager that imperatively resets every object that needs resetting
- Have some event that fires that any "resettable" object listens to and resets itself when the event is fired.
in that case, either source (the ball or the zone) would just tell a game controller that it's time to reset
and the controller would handle the rest
you'd tell the controller "this ball just entered this zone!"
maybe you're doing multi-ball, so the game doens't reset until every ball hits a zone
Yeah so I'll do something like if the zone is triggered by the ball then send the appropriate code function to the game manager which then the game manager invokes a ball reset event and the ball itself would be the subscriber of said event and would call its functions inside of it.
and unity provides the UnityEvent, which comes handy for you
I'm only familiar with the regular C# event action still ^^
yeah you can do it as you want, just saying
It's basically the same, but you can set the callback in the inspector
Not sure where to ask but I'm really trying to add text to a dark scene which will later get illuminated by lights. SRP/Unlit or Tmp/DistanceField(Surface) don't work. Ive been scouring niche Unity Forums for the past hour.
you mean ui text right
not in a code channel 😄
if you can't find an appropriate channel topic, then #💻┃unity-talk is the place
I mean... I made it through UI- TMP, It is on scene. Im trying to make a diegetic interface.
Sorry, thank you
anyone here started and finished the program of programer jr in unity learn? it's worth it do it? i'm new in C# btw
everything is worth it if you learn somethign new.
pretty sure the course will teach you some
okay, thank you!
i finished 90% of it without submitting my projects. I would recommend if you know some C# already and completely new to Unity. You will learn something new if you apply the knowledge on your own small project.
First watch and then do
i mean, yeah, but for example i've apps in my cellphone of "learning" C# and i don't understand nothing or it's to simple, so that is why i'm asking
if I have a lerp function where a = Mathf.Lerp(a, b, Time.deltaTime), will that desync gradually on different framerates?
alright, thanks
Applying lerp so that it produces smooth, imperfect movement towards a target value.
an intuitive explanation:
at 1 FPS, you're doing Mathf.Lerp(a, b, 1)
so you obviously just get b
At 2 FPS, you're doing Mathf.Lerp(a, b, 0.5) twice
you get 75% of the way to b
That article includes a function that gives you very similar behavior, but does it in a framerate-independent way
ok thanks!
that makes what I want to do about 10x more convoluted
It's very useful! I use it for smooth-damping motion in VRChat (using constraints + an animator to calculate the weights)
You can just swap the ExponentialDecay function in
You may also want Mathf.SmoothDamp or Mathf.MoveTowards
for springy and linear motion, respectively
you can create a class like this:
public static class MathTools {
public static float ExponentialDecay(...)
}
and then add this to the top of your script:
using static MathTools;
now you can write ExponentialDecay(...)
(or just do MathTools.ExponentialDecay(...))
im trying to make a system where an entity slowly pans the player camera towards it with a strength correlating to the distance the entity is from the player
yo is there a wiki for unity?
somthing like the roblox documentation for roblox studios
there are unity docs tho
There used to be a unity wiki but that went years ago
Unitys official docs are soo good that they cover everything you need
yeah, they're quite good
one really important thing: package documentation doesn't live in the manual!
e.g. Unity UI was broken out into a package ages ago
but many google results still point you to the very old manual pages
thank you
hi all. i'm still new to unity, and teaching myself c#, but i'm trying to make a metroidvania (hollow knight style) and i was just wondering if anyone could check out my character controller to give me any tips? or just let me know if i'm coding like an idiot, lol
!code
📃 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.
rb.linearVelocity += Vector2.up * Physics2D.gravity.y * (hangMultiplier - 1) * Time.fixedDeltaTime;```
Using Time.fixedDeltaTime here doesn't really make any sense. It's just kind of arbitrarily dividing this number by 50 (or 1 / whatever your fixed timestep is)
or wait actually - this is for gravity in Update? This belongs in FixedUpdate
and it makes sense with fixedDeltaTime in there
For rb.linearVelocity.y; - Rigidbody2D lets you just do rb.linearVelocityY;
the reason i put it in update is because of how "WasPressedThisFrame" works on input, and would miss inputs while in fixed update. it's the only way i knew how to fix that thought :(
You need to separate the input handling from the physics
input handling goes in Update.
Physics in FixedUpdate
The way to do this with a jump is by storing the user's intent to jump in a variable, and consuming it in FixedUpdate
oohhh!
e.g.
bool userWantsToJump;
void Update() {
if (IsGrounded() && JumpButtonPressedThisFrame()) {
userWantsToJump = true;
}
}
void FixedUpdate() {
if (userWantsToJump && IsGrounded()) {
Jump();
}
userWantsToJump = false;
}```
gotcha gotcha! that makes a lot of sense actually. i knew moving to update for physics was bad, but i for some reason didnt think of doing it separately
thank you for the help! i'm very much still learning it, so any tips are appreciated!
!code
📃 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.
Howdy, I'm back! I've got my gerstner waves shader running and a functional recreation of the shader on my CPU that allows my character to walk on the gerstner waves. However, I'm having trouble syncing my shader (wave visual) with my code (wave physics); would anybody be able to help me?
actually (unless im mistaken) this is more of a coding problem, I need to make my code so the physics syncs with my renders
should probably share code and anything relevant then
oh yeah lol one sec
Showing your code is onlyhalf the issue though. It could be fine, but it could just not be identical to how your shader is handling it.
here's my code for the physics: https://paste.ofcode.org/7rD6CL8idYCnbk9gPNmXEQ
and here's my gerstner subgraph:
Hey guys so i have objects randomly spawning on the surface of my planet.
Now I'm trying to spawn these object that their "up" rotation is "up" away from the planet
I already have the direction from the center of the planet to the position that the object is spawning... I just dont know how to rotate the object in a way where that direction is "up"
the second parameter to LookRotation is the "up" vector. So you're doing that part right. But you need a valid forward direction
Vector3.up is arbitrary
there are infinite possible valid look directions so you'll need to pick one somehow
you could just pick a random rotation around that up axis if you want
for example:
Vector3 localUp = positionOfSpawnedObject - targetPlanet.position;
float randomAngle = UnityEngine.Random.Range(0f, 360f);
Vector3 randomDirection = Quaternion.AngleAxis(randomAngle, localUp) * Vector3.forward;
Quaternion rotation = Quaternion.LookRotation(randomDirection, localUp);```
Something like this should work I think?
basically imagine a person standing on a planet. They can rotate freely in any direction while their head still points up.
You need a way to decide which way they are looking
If I’m understanding right Generally this kind of thing would be done by raycasting at the planet (which you might be doing already) and using the RaycastHit’s .normal value which basically will be a direct away from the surface you hit
Yes that makes perfect sense to me
Praetor’s advice might be more valid
If you had some specific orientation you wanted the objects to face in, say "away from the camera" - then you would basically just project the direction from the camera to the object on the surface normal (which is the same as that up vector)
Right yup
misread and didn’t realise they already had the info just not how to use it 👍
Food poison brain
so i just started coding like a hour ago and im trying to make flappy bird with a yt video ofc. but i restarted my pc and suddenly for some reason when i go and make a custom script it goes into visual studios. its just blank there's no code what so ever?
well depending how you created it, yeah mostly files start out empty
If you did "new monobehaviour script" from in Unity there should be a basic template
Using Angle axis makes sense
I inplemented it as you instructed and now im having strange artifacts.
My objects im spawning "upright" are only spawning "upright" in the X Axis, then they dont want to face the Z axis at all.
any idea what might be causeing this?
show the code you used?
im pretty sure i did that
im also unable to type in it so i dont think its that
your description of the situation is too vague to really know wha'ts going on
unable to type sounds like your project hasn't opened up properly in VS
Most likely you haven't configured it for Unity properly
how can i fix that?
!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
i tried stuff that it said but its still blank
The only thing left to show would be how im spawning in the objects i guess
Are you sure targetPlanet is the correct object?
also if the planet is a sphere, the raycast seems redundant
To get a position on the sphere you could just do:
Vector3 spawnPos = planetPosition + Random.onUnitSphere.normalized * (planetRadius + elevationAboveSurface);```
can anyone help me with the pixel perfect camera, i want to increase what the player can be see while keeping pixel perfect. My problem is my player view is either too small or too large
The planet isnt a perfect sphere so i wasnt sure that would work and i wanted to make room for modeling it more later
Probably sounds silly but im finding the "Random.OnUnitSphere" intentionally above the surface, then shooting a raycast back down from that point to find the elevation of any given point to make that the spawn location.
zoom the camera (by setting its orthographic size)
Yes i just checked its the right object
and is that object always at 0,0,0? Your code seems to assume so
Ill def try this soon
i can only have it at specific sizes if i want it to remain pixel perfect
It is yes
so change it to one of those specific sizes that is larger or smaller as needed to zoom in/out
my issue is they are either too small or too big is there a workaround to this?
I’d personally suggest sticking with raycasts in the event you want to start to sample what your hitting to determine what can and can’t be placed on that part of the planet too
Can you try this instead?
Quaternion alignment = Quaternion.FromToRotation(Vector3.up, localUp);
Quaternion randomSpin = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f);
Quaternion rotation = alignment * randomSpin;```
That def worked perfectly
what is the difference im not sure i understand
danm this sucks is there like a 90% working way to fix this? i have tried alot.
Fix what?
I’m using unity and I’m trying to code and it worked fine but I restarted my pc and now when I double click a script it sends me here to just blank
Try resetting the windows layout in vs. It just seems like you don't have anything open.
it worked tysm
Is there a way to constantly add force without it being in Update or FixedUpdate?
Why?
I am trying to make a dash and it checks every frame if the player is dashing which id rather have it do the dash when the player activates it and it runs a function that does it without having to check every frame if the player is dashing
I think you can use a coroutine with a while + WaitForFixedUpdate()
after a WaitForFixedUpdate() the coroutine will be in the fixed timestep, yeah
or if it doesn't need to be on the fixed time step, a typical coroutine would also work
phone pseudo but i think
while (true)
yield return new WaitForFixedUpdate()
//applyforce
and then kill the routine when needed, or handle it in the while condition directly
Thanks ill try it out
Idk if this is a dumb question, but how bad is just 1 bool if statement inside of Update or FixedUpdate for performance?
work is work. an if is 3 instructions, so that's gonna be an extra, say, 0.9 ns per frame
Oh so it basically doesn't matter, okay thanks
Is there one object doing it each frame or 5000 objects doing it each frame?
5000 is a bit small
one
You know the answer then
what would be a common mistake when trying to put text onto the ui?
cause i cant see it when i play the game
You'll solve the problem much faster if you ask about it directly instead of some generic common cases
Post a screenshot of the editor to #📲┃ui-ux with the scene open and the text selected
why doesnt this work? its not letting me put the TMP text into the scoretext
things are only type, not two
Commas are also never used like that
You’d want just
public TMP_Text scoreText;
there
But actually TextMeshProUGUI is the type your probably looking for
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
TMP_Text works
it's a superclass for both the gui and worldspace versions
Is unity good for making games?
i already did that

that's its main purpose, yes
Does unity offer free courses
I want to learn the programming part of unity its what im more interested in
Where can i find this tutorial
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
there are several online as well, and pinned in this channel
Ok thx
i did it i had to put using TMPro;
you should configure your ide so it can do that for you
so can i have your help on something. i was given this task in class. i have this box "player". which is supposed to move forword when the game starts and move left and right with arrow key. i have done until this point. later i was told to add a sound for the game i did that too. but in this next part the player was supposed to collide the enemy box and the game over. but the player box collides but the code for the crash ant working. i assigned the enemy tag to the another box but it didn't work out and when the game overs the game over ui is supposed to come but the i dont where to put the code for the canvas. and the crash sound.
You have to set the audio source you want to play
i tried to drag the sound but it didnt work
It's an audio source, not a sound
Which audio source do you want it to play?
but what i concerned about is the collision.the player box is passing thorough the enemy box how do i fix that first?
You don't need to fix that, when playing the audio doesn't throw an error anymore it'll load the next scene
Although your next issue will be that the sound won't have time to play because it goes to the next scene immediately
does your player have a rigidbody? if so, you should be moving via the rigidbody, not the transform
!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
i put the screenshot above of player and enemy rigid body
you should be moving via the rigidbody, not the transform
i want to fix the collision problem
wtf
I want help with slider
The slider is only moved with the arrows and not the mouse.
how
there's quite a few ways, try googling around
is there perhaps something covering it
i can click on slider but i can move it only by arrows
Is it a default canvas slider or something special?
default
can you click anywhere on the slider and will it move the indicator there? or how do you know, you can "click" it with your mouse?
color change
the handle is white but if i click on handle the color is change to gray
i can use arrows but i cant use mouse
arrows or WSAD
Just for sanity check, can you add a new slider from the context menu and see, if it behaves the same?
i try add new slider and it works
So find the difference between your current one and the default one. Could be something on settings or you disabled some raycast on an image while trying to customize it and what not. not a code issue
okay i try it thank you
Does anyone know how many times per second the ‘onaudiofilterread’ function is called
It says on the docs around every 20ms but it seems way faster than update so that cant be right
1 frame lasts 16 ms at 60fps
or do you mean, in your testing, onaudiofilterread is being called much more often?
On audio filter read runs on a different loop to update and is called dependant on the sample rate and buffer size
However not sure how to calculate it
This is what its based on
Yeah i think its buffer size / sample rate
Vice versa
So 48khz would be 48000 a second, devided by the buffer you want to use, essentially slicing the sample rate into parts. there you get your callback rate
little read about it: https://embaudio.grame.fr/lectures/architecture/
you get a value in Hz there, if you want a value in s or ms then it would be buffer/sample rate, no?
Hz is basically cycles per second, so second divided by the cyclecount would give you the ms, from what I understand there
yes, i mean that their original answer was correct if they wanted a value in seconds or ms
Ahhh, true. Of course this already returns the inverse then in ms
Hello, I use a CapsuleCollider2D with a RigidBody for my sidescroller game. How do I prevent the player from gliding off when standing near platform edges?
could consider a boxcollider instead, depends on the level geometry you need to handle
Are there ways of pulling it off with a capsule collider?
Like sticking to ground or something
Why do you wanna use a capsule collider?
Are you planning on adding slopes?
Because my teammates tell me "its the first thing they teach you in game programming class"
we don't have slopes so I don't really see a point in using capsule colliders personally
The point is that it won't get stuck between seams in your colliders.
Box colliders can, resulting in the occassional "hop" when moving along a surface if there is a seam.
ah, well in that case what is the way to solve it?
I found a work around for small textures!
Apparently theres a setting called Non Power of 2 that can mess with the color indexing
this is a code channel
I'm making an outfit change script
Unfortunately, the proper way to solve it is to not rely on a collider to do all the ground collision logic for you. Polished/advanced character controllers use raycasts in addition to the collider to handle the movement. For the case of sliding off the edge, you could detect that the outter edge of the collider was hanging off the side and if far enough, either prevent additional movement (if you don't want them to fall off), or force the fall.
hi guys. is this the right place to ask questions? :3
i've got a weird issue
i'm having a problem with registering overlaps/triggers.
on the left is a character controller (with grey capsule mesh). on the right is a green boxcollider.
in the left image, i do NOT get an overlap event, even though the box and the capsule are clearly overlapping.
in the right image, i DO get an overlap. the only difference is that I moved the boxcollider closer to the capsule.
why do I not get an overlap in the first case?
what on earth is Visual Studio on? or am I dumb?
You aren't overriding anything
sup
what do you mean?
try the show potential fixes and see if there's something to generate method stubs
then see how the method stubs are written
its with lowercase e, but why???
You aren't implementing the interface. You just have another function with the same name. It's not an override or abstract
that can't be it because its fine with OnEquip
So your interface has an OnUnequip, not OnUnEquip.
Have you saved the file?
I have
let me restart VS ig
very confused
maybe I've got too much stuff in one file rn and it's being weird
delete the two methods you created, and get VS to auto create them for you
wtf
not afaik but I'll double check
OH
yeah I do 🤣
Hi I have a question with regards to creating an inventory system in Unity. I've been working on an inventory system for a demo game. I have it partially working. My inventory system architecture plan is as follows:
- I create the inventory and store it in memory but not the game objects. I use a wrapper for this.
- Inventory Slots are stored in the inventory class as a 2D array so one can set the rows/columns dynamically.
- The inventory slots themselves contain an inventory item class which is a wrapper for a particular item that may go in that slot. It contains a field to store the actual item
- When the player needs the inventory for instance by hitting a certain key, I then spawn in all the game objects in the world.
- When the player is done with the inventory all the game objects get destroyed.
My question is, is this the correct way to do things? I'd imagine having game objects for every inventory in the scene wouldn't be too performance friendly, hence why i generate them on demand. I have seen a lot of Youtube video tutorials where they either manually create the inventory with each slot in Unity or they generate them but leave them in the scene but neither seems ideal
- there's not going to be 1 specific "correct" way to do such a thing, if it works it works
- keep in mind that there's also a cost to instantiate all those gameobjects. you have to consider the tradeoff between time and space (aka speed vs memory)
that is a good point
I'd imagine having game objects for every inventory in the scene wouldn't be too performance friendly
what aspect are you concerned about exactly? deactivated gameobjects don't get updated, for example, and the memory footprint is there, but it would probably be much less than you think. do you expect to have, say, a million inventory slots total loaded at once?
well say im making an rpg game, and u go to town and theres a bunch of npcs selling stuff
there might be 20 npcs with 1 or more inventories each
and how many slots would they have
i guess my question how much memory would a gameobject take up vs keeping the same kind of information in memory as part of an array minus the gameobject and all its components like image etc
well could be 30 or so slots
or more
One question for you, are you using addresables or are they assigned somewhere in the inspector within the scene?
im not using addressables
Than its in memory anyways, unless you load it through resources with a string
Everything you assign in inspector is basically "preloaded", as long as its not addressable/assetreference. Anyone correct me if I am wrong.
let's take a pessimistic estimate then - 40 npc with 50 slots each would be 2000 inventory slots
just the gameobject on its own, plus maybe a component referencing an so, would be, from a vague estimate, 90 bytes, so let's go with 300 bytes
so the dormat inventory slots would be 600000 bytes, aka 600 kb / 0.6 mb
that's like, 2 small pngs worth of memory
even with these extremely pessimistic estimates, the memory footprint is still practically nothing in the scope of a game
each inventory item has an image for an icon too which make that a bit bigger
it'd just be a reference, the inventory slot doesn't hold the entire image
also related to this it worth using an 'inventory manager' like a singleton kind of setup on a game object that knows about all the inventories in the scene
and it wouldn't be loaded and drawn when it's not open
ok
if that makes sense, sure. i don't think it does, but i don't know your game. try designing out your systems first, before thinking of implementing them
im kinda going mad here.
is there a threshold at which two colliders overlap? because the green box triggers an "OnTriggerEnter" event but the white one doesnt.
the boxes are exactly the same object in every other regard. it's just the green one is a little closer. but BOTH are overlapping visually, and both should trigger OnTriggerEnter?!
i ask cause so many youtube tutorials seem to use one
to me it doesnt make sense either, the inventory should be part of the object its related to
both have trigger set?
the physics messages should be symmetrical. make sure you don't have any conditionals that might be filtering out the message where you check
both will get a trigger message if either one is a trigger
could you show the code you're using to check for the trigger message, just as a sanity check
(i don't think it'd be there, but it'd be nice to rule that out)
its just this. its called in the object with the boxcollider
box is an object with BoxCollider component set to IsTrigger: true and a script
the capsule is a CharacterController
you might want to add a context argument to that log to see more clearly which box got triggered
the hitbox thats closer to the capsule gets triggered.
so weird man
this is the code to spawn em
(i know im reassigning the variable but i dont do anything with it anyway for now, so i think that doesnt matter)
wait are you just expecting the boxes to hit the capsule
i thought the issue was the boxes hitting each other but only sending a message to one...
since both of them are visually overlapping, im expecting both of them to send an OnTriggerEnter message
Is atleast one of your involved objects a rigidbody?
no, but I also tried with that and that didnt work either. I will try again just in case.
and if that was an issue, wouldnt both stop firing? its weird. lemme check tho
https://unity.huh.how/physics-messages/trigger-matrix-3d make sure you are in line with the matrix at the top
Oh yeah then both would stop firing, sorry I gotta read through your whole conversation here
it's just the green one is a little closer
does the white one also trigger if you put it closer?
Which object did you attach the OnTriggerEnter script to?
maybe I shouldnt use a CharacterController component and try a standard rigidbody and rewrite my little movement code :[
OnTriggerEnter is on the objects with the BoxCollider
My guess: they trigger each other, player does not trigger at all
does the white one also trigger if you put it closer?
yes
maybe I shouldnt use a CharacterController component and try a standard rigidbody
You can attach a kinematic rigidbody to something controlled by a charactercontroller
this triggers just like before, theyre definitely hitting the object with the playerchar script :(
do an explicit PlayerCharacter == null check
the boolean conversion is the same thing as the null check
huh i thought boolean conversion and object?.property are problematic when working with unity objects
type conversion can be overridden, it's is null/?./?? that are problematic because they can't be
Ah good, ive been avoiding boolean conversion in the past, good to know I can use it