#💻┃code-beginner
1 messages · Page 572 of 1
There is never a need to convert to string, unless you want to display something in an interface
I was actually talking about nonbinary, but I guess there's not too much reason to do that
yall know how you can edit a null value in unity rather than assign a value in the script itself right
how do you do that with integers
nvm i found it tis serialize field
small note, ints cant be null
you can also make the value public instead of private. although usually you'd use serialize field (depends on whether or not you want the value to be accessed by other scripts)
Ints default to 0, but if you want the null option, try int? with the question mark
i got a question guys
why does this not work?
if (Input.GetKeyDown(KeyCode.Q))
{
rb.velocity = transform.forward *dashForce;
}
my character just freezes in the air for a moment when i press it
and when i increase the dash force i just teleport forward
the same happens when i use
rb.AddForce(transform.forward * dashForce, ForceMode.Impulse);
!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/, https://scriptbin.xyz/
📃 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.
check what dashForce is equal to. it's probably zero
Try printing the value of rb.velocity using debug log
is the position locked? it could also be set to kinematic
Where and how are you assigning a value to dashForce
freeze position should be false on all axis and is kinematic should be false
is it higher than 0?
yes its 1000 rn
i did this and it still didnt resolve the problemn
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Try printing both the value of rb.velocity and transform.forward*dashfore after setting it. If the former is 0 while the latter is non zero that means there is something that prevent you from setting the value
i cant it says that i need nitro
i mean the position that i teleport to changes based on the value of dashforce
!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/, https://scriptbin.xyz/
📃 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.
Just print both of it, check if the value is different
use one of the paste sites
heres the code https://paste.ofcode.org/ubj3Ds43McCnkaCKpRNSyu
so i print rb.velocity and transform.forward?
transform.forward*dashforce changes but velocity is still 0
im pretty sure i used the same method on a previous project and it worked fine
rb.velocity = new Vector3(movement.x * speed, rb.velocity.y, movement.z * speed);
call this inside fixedUpdate(), also multiply with time.FixedDeltaTime
aight lemme try
rb.AddForce(transform.forward * dashForce, ForceMode.Impulse);
Also this
anything related to physics goes inside FixedUpdate()
Also for physics based calculations, use Time.fixedDeltaTime instead of Time.deltaTime but make sure to call in fixedUpdate()
what exactly do i multiply with deltatime
the force, or the velocity
aight ty imma try that
hello i have a problem i try to add a Coyote Time and a Jump Buffering but now my character can double jump if i spam space https://medal.tv/fr/games/requested/clips/jt4A5fUeWNTfh3BvI?invite=cr-MSx6Q1EsMjUxMjMyMDQ3LA
this is my character controller code: https://pastecode.io/s/iop2q9ak
Regarde Requested et des millions d'autres vidéos Requested sur Medal, la plus grande plateforme de clips vidéo.
so im calling it in the fixedupdate and it doesent seem to do danyhitng now
not even teleport
go in rigidbody settings, set to interpolate and continous collision detection
private void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.Q))
{
rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, rb.velocity.z * dashForce*Time.deltaTime);
}
}
like thuis
nope
Its wrong
oh
rb.velocity * Time.fixedDeltaTime
I meant this
Multiply the final product of whatever physics u calculated, with the delta time
And why are you using deltaTime in FixedUpdate()??
Its okay, everyone is dumb.. We just gotta do it better
lmfao
Try this
But what I suspect is, this might not even be the main issue, But atleast do this then lets see if it works
just this in fixedupdate?
deltaTime in FixedUpdate is the same a fixedDeltaTime.
The question is why are you reading Input in FixedUpdate. That should be in Update
yeah
yeah this, try taking the input in Update(), but apply the physics in FixedUpdate()
i dont understand how do iget the input and then apply it in the fixed update
with a void?
no, with a bool
makes sense
instead of bool, try working with Events
how are you going to sync FixedUpdate with an event?
use events whenever input is retrieved, store them somewhere, maybe the direction or anything.
so isnt there any better way other than a bool?
so i set isdashing true in update and i used the thing with velocity in a if statement in fixedupdate
no
why wud it do nothing? did u debug
i tried ye
what does it show in debug
by debug i mean go into play mode and press q
bool isPressed=false;
void Update() { if (Input.GetKeyDown(KeyCode.Q)) isPressed=true; }
void FixedUpdate() {
if (isPressed) {
isPressed=false;
// Do other stuff
}
}
@sharp sigil
ye i did that
it gets my input but nothing happens
i printed something into the log in the if statement
so you need to add some debugging
im thinking about making teleportation into a feature man
add more debugging, till the point it sounds silly just do debugging
break the problem into each step
try solving 1 at a time
take a paper and a pen, note down whats the problem?
You cannot solve it ofc, so debug, ask questions to the program.. maybe ask a duck about your problem..
it will help a lot
private float Speed = 8f;
[SerializeField]private Vector2 TargetPosition;
// Update is called once per frame
void FixedUpdate()
{
if (TargetPosition == null || new Vector2(transform.position.x, transform.position.y) == TargetPosition) {
TargetPosition = LogicManager.Instance.GetRandomCanvasPosition();
Debug.Log("Searching");
} else {
transform.position = Vector3.MoveTowards(transform.position, new Vector3(TargetPosition.x, TargetPosition.y, transform.position.z), Speed);
Debug.Log("Moving");
}
}
I have a Objects that just should moving around the canvas, it works for 1-2 cycles, after that it stop moving. It still prints out "Moving", But the valus doesnt match. The Screenshot was taken after it stoped moving. Is something wrong with my moveTowards Code?
public RectTransform MyCanvas;
public Vector2 GetRandomCanvasPosition() {
float RandomWidth = Random.Range(-MyCanvas.rect.width/2, MyCanvas.rect.width/2);
float RandomHeight = Random.Range(-MyCanvas.rect.height/2, MyCanvas.rect.height/2);
Debug.Log(new Vector2(RandomWidth,RandomHeight));
return new Vector2(RandomWidth,RandomHeight);
}
you think my project is the problem?
once in my project the light flickered all the time
and i switched projects and it didnt happen anymore
hey?
would help if you sent the !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/, https://scriptbin.xyz/
📃 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.
i send it...
forget it im giving up
stop using FixedUpdate if you are just moving the object without the physics involved, use Update(), also use time.deltaTime in Update()
Mhh okay, you mean instead of using speed, i should use deltaTime? and not moveTowards
i meant, multiply the speed * time.DeltaTime
@queen adder also try this Vector2.Distance(new Vector2(transform.position.x, transform.position.y), TargetPosition) < 0.01f)
make sure to set the correct language (top right option)
https://pastecode.io/s/khriurcb
instead of comparing vector 2 positions directly, calculate if they are close or no
reading the code now, i assume the coroutine is whats causing it
whats the issue, can u point it?
i make a clip of it
here
yes
what if u just press space one time? does it double jump too
That fixed, now its moving constanly. Thanks !
np
what i understand is, if u keep holding space, it makes ur character stay more in the air, right? but in your case it is making it double jump
yes if i spam it that double jump
but u want it to have more time in the air if u hold space?
so holding space doesnt cause double jump? but spamming it causes right?
no i want he jump more if i hold space and shorter if i press it fast
yes
In that case you can pause the input system for a while till the jump completes, make a coroutine, and make the elapsedTime get decreased until it reaches the jumpTotalTime. Then the input system can read values again
I mean, make something, make a function, that stops reading the input values from the keyboard till the jump completes and it is grounded
in that case the coyote time will be useless :(
what is coyote time? and why have u named it such
Learn how to implement coyote time and jump buffering in Unity!
Source code: https://gist.github.com/bendux/f717ebc5155506d83afefd34fabb3b00
SOCIAL
Discord: https://discord.gg/harSKuFR8U
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
A Nigh...
rb.velocity = new Vector2(rb.velocity.x, jump);
Try this when applying force
instead of the add force ?
that dont change anything
i can always do a double jump with spamming
but now the coyote time is more smooth i think
i mean ofc this wouldn't solve your problem
i just noticed an area of improvement
otherwise i never have done buffer jump or coyote, so maybe i wont be able to help much in that sorry
np ty anyway
i found the problem it was because my scene is really small so i need to reduce the time of the coyote time and of the jump buffering
great
hi, i am pretty new to unity and all that stuff and i am trying do make a simple script that helps me open and close a inventory, that i copyed from an other asset. i really tryed a lot but im not finding a solution for it. so i am having a canvas that i want to be able to close and open with a button, but always when I try its just not opening xd does someone know what the problem might be?
You would have to explain how you set it up
you have to post the !code so we can see what is wrong with it. there is no way to tell beyond that . . .
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh sorry, sure here is the code: https://paste.mod.gg/qhgnmrvifsxp/0
but i really don't know if that problem has to do something with the inventory system, if so i might also send you this
A tool for sharing your source code with the world!
did you put that code in that inventory gameobject?
how do I set the lightmodetag of a shader graph in urp?
by default its none in the generated shader and I can't find a way to change it
you can't edit the generated shader code either it just reverts
https://pastebin.com/rvAmsfKv
I have this script for my stickman ragdoll enemies. But it doesnt work.I mean doesnt get the triggers from "weapon1 hold" gameobject.I want weapons to collide so I wanted to keep them as colliders but oncollisionenter2d doesnt work if gameobject doesnt have a rigidbody and when I put a rigidbody that is not kinematic, everything messes up.When I put a kinematic one, I prevnt collisions between weapons and thats not something I want. So I added a trigger collider to "weapon1 hold" and a normal collider on "weapon 1". Then, changed oncollisionenter2d to trigger enter.But it never triggers.
this photo is from when I equip a weapon.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
First step - can you explain what you're trying to do?
hello I have a problem that when i jump i keep sort of floating and go down really slow is there any quick solution i am using rigidbody for my movement?
u probably have some type of
movement code influencing it..
maybe a collider or two interacting w/ each other
ur drag value is too high..
or not enuff gravity * u can always crank up the gravity settings (but this will affect everything).. or add a bit extra negative forces to ur player when not grounded..
oh yea.. check ur grounded state ^ make sure its working as it should as well
thanks!
sending a video, sorry for answering late
[SerializeField] float Sens;
public Transform camtransform;
float xRot = 0f;
public float xMouse;
public float yMouse;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Sens = 180f;
}
void Update()
{
xMouse = Input.GetAxis("Mouse X") * Sens * Time.smoothDeltaTime;
yMouse = Input.GetAxis("Mouse Y") * Sens * Time.smoothDeltaTime;
xRot -= yMouse;
xRot = Mathf.Clamp(xRot, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRot, 0, 0);
camtransform.Rotate(Vector3.up * xMouse);
}
So i have this problem in all my first person FPS games where my camera position and rotation is not calculated properly. When in Playmode my Camera stutters, randomly accelerates the sensitivity, and skipps multiple frames when looking at certain objects. How can i fix this, and what is there to know when making a camera controller?
maybe this will help you to understand
I have two objects I wann rotate the same amount, I input the same degrees but they rotate diffrently.
Code to rotate the Obejcts:
transform.Rotate(new Vector3(0, yRotation, 0), Space.Self);
Camera.Rotate(new Vector3(0, yRotation, 0), Space.Self);
is the y values on inspector when you rotate, same on both?
no, but it should be, since im rotating by the same amount
do they have rigidbodies?
one does but the rotation is locked
Camera.Rotate(new Vector3(0, yRotation, 0), Space.World);
try this
Show a video
Also, log yRotation, see if it matches
Rotate differently as in different rotational speeds?
yeah the camera rotates faster
its the same variable how could it be diffrent
I would not know. You haven't shared anything but two lines of code
Are these two lines after eachother?
yes
this is the function
void TurnCamera()
{
/*
yRotation += Input.GetAxisRaw("Mouse X") * Time.deltaTime * xSens;
xRotation -= Input.GetAxisRaw("Mouse Y") * Time.deltaTime * ySens;
xRotation = Mathf.Clamp(xRotation, -90, 90);
transform.rotation = Quaternion.Euler(currentPlayerRotationOffset.x, yRotation,currentPlayerRotationOffset.z);
Camera.localRotation = Quaternion.Euler(xRotation, yRotation, transform.rotation.z);
*/
//xCamRotation -= Input.GetAxisRaw("Mouse Y") * Time.deltaTime * ySens;
//xCamRotation = Mathf.Clamp(xCamRotation, -90, 90);
yRotation = transform.rotation.y + Input.GetAxisRaw("Mouse X") * Time.deltaTime * xSens - transform.rotation.y;
transform.Rotate(new Vector3(0, yRotation, 0), Space.World);
Camera.Rotate(new Vector3(0, yRotation, 0), Space.World);
Debug.Log("Y Rotation: " + yRotation);
}
whats the purpose actually?
What gameobject is this on? the player?
yes
Is the camera a child component of anything?
And do these components have scaling of any sort?
yes but the rotation of the parent is always 0
the scale of everything is 1
Well idk. If I were you I'd rotate the transform and then set the camera's rotation to match the transform's rotation
Doing it separate can lead to issues in general
I don't see why it's broken here, but I would just synchronize it like that regardless
but then the cam doesnt rotate around its local y axis and I need that
the only way to make a capsule collider stay fixed in one side (only increase or decrease height from one side) is to use an offset, right?
can someone take a look
as far as i know u can't change the shape of a capsule collider like that...
then it wouldn't be a capsule anymore.. but a weird metaball or somethin
What do i need to do, when I want one animation to be played on S or D (Walking animation
Tried this but this dont work (first one)
i really wish there was a !screenshot command 
No
Be mindful, if someone requests your code as text, don't send a screenshot!
you probably set it up wrong in the animator or used the wrong name
there it is
o, good to know
https://screenshot.help
also !code posting guidelines are below 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
guys, hello. how to get an angular velocity. like... i use this code to move character on slopes:
rb.velocity += transform.TransformDirection(new Vector3(Xlimit * axis, 0, 0) * Time.deltaTime);
and how to get this Xlimit if z rotation is not 0 (that code moves body based on it's z rotation)
anyone?
Q? wdym?
you question, I cannot understand what you are asking.
you mention angular veloicty, but dont talk about rotataions.. just linear velocity.. not sure what XLimit is, nor where the z rotation comes in
do you want to rotate something?
okay. I use this script to move my character along the slope with the same speed
and i want to check if this velocity.x is higher or smt like that
and as i use transformDirection, my velocity would not be like (Xlimit * axis, 0, 0)
should i describe it clearly?
just stared using untiy on my home computer instead of the ones at my collage, however visual studio wont recognize
using System.Collections;
using System.Collections.Generic;
or
MonoBehaviour
Can anyone help?
check if you chose unity on installer
!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
done the unity hub and manual install, doesnt work for me sadly
im not too sure on what my issue is
If i have a 3D plane in unity of some scale... I want to know what is the width and height of it, how can I calculate?
if you have the mesh, you can use localBounds, if you have the MeshRenderer you can use bounds. lemme find the links.. once sec
here is the basic code, but its just not compiling properly or recognizing anything
yeah i have mesh Renderer attached
!ide configure your 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
They are aware, read above
Did you verify you have the Unity workload installed?
Also, is VS the external editor used?
no?
yes
Alternatively, you might want to regenerate the project files
already have
This is a step in the manual installation of VS to use Unity. If you didn't do this then that will be the issue most likely
#💻┃code-beginner message
the instructions you claimed to have followed would have made you confirm that if you had actually followed them
Considering there are only three steps, and it worked for everybody so far, I suggest you try again
well ive already done them prior to joining this server
That's fine, but we require users to have their editor set up regardless of the problem
Not just to fix the problem either. You should have a configured editor to improve your development experience, and we want to ensure you have that
ok. I have velocity (a, 0, 0) and rotation (0, 0, 0) on the first image. And i have TRANSFORMDIRECTION velocity (a, 0, 0) and rotation (0, 0, 45). how to find this a in second image outside of TRANSFORMDIRECTION? like not from variable a, but from velocity.
since you appear to be manually assigning velocity anyway, just keep track of what the current velocity would be if you were travelling along flat ground, and just rotate that to use for assigning the rb.velocity. then you don't need to do extra math to dtermine the linear speed
but... what math would i do to find this... velocity?
so you just completely ignored what i just said or what?
no... i.. can't describe it clearly...
here is a code where i want to find this... velocity:
if (transform.TransformDirection(rb.velocity).x > 0)
rb.velocity -= transform.TransformDirection((new Vector3(Xlimit, 0, 0)*Time.deltaTime));
if (transform.TransformDirection(rb.velocity).x < 0)
rb.velocity += transform.TransformDirection((new Vector3(Xlimit, 0, 0) * Time.deltaTime));
if (transform.TransformDirection(rb.velocity).x > 15 && transform.TransformDirection(rb.velocity).x < -15) { }
rb.velocity = transform.TransformDirection(new Vector3(0, rb.velocity.y, rb.velocity.z));
i am telling you to change how you go about this, not to do something specific with your existing code. because frankly that's horrible
okay...
instead of rotating the velocity increase before adding it to the current velocity, you instead just have a flat velocity that you increase then rotate that before applying it to the rigidbody. then your max speed is right there in your flat velocity
setting velocity seems like extra work if you're doing a sanic game
cause you're going to have to manage the deacceleration on collision
no, i use rigidbody, so my Sonic stops automatically on collision
or... it's not as i need to do..?
and setting velocity overrides friction making physics material unusable
I have Plane's width and height, now I want to decide how many cells must be in that plane, suppose 120 cells I want, so How do I calculate the no. of rows and no. of columns required? (Grid System)
usually these games have some accumulation of forces; you don't instantly set the velocity to 0 when hitting a wall
you do generally stop if you crash into a wall
yes but the forces are still being applied
you don't go through it or catapult into the air
you can't just change your direction instantly when ramming into a wall at a speed
that's why i use rigidbody
okay i thought i understood how transform positions work but apparently not. Why is the room being spawned at such an offset if the transform pointer is at the middle of it, and is being instantiated with no offsets?
(image 1 is the room, image 2 is the spawner, image 3 is the code spawning the room, image 4 is the result)
it was working fine until i increased the size of the room, and i thought i made sure the transform position was still correct
the script is inside the spawner btw
template.structures[3] is just the room prefab
make sure that you have your scene view set to "Pivot" and not "Center" -- check the top left of the corner
It's useful in a few cases
notably, when you have many objects selected, it lets you rotate them around the center of their combined bounding box
instead of rotating individual objects in-place
same goes for scaling
that is interesting, thanks!
is there a easy way using tile maps to move the tiles beyond the move tool?
you should be able to select many tiles..
I'm a bit of an novice with the tilemap system though
Anyone knows why animation that require 2 Keys pressed at same time doesnt work?
show code
else if ((Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)) || (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.D)))
{
animator.SetInteger("Animacie", 15);
}
in animator its set up correctly, from primary to this equals 15 from this to primary equals 0
have you actually confirmed the condition is true? also !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/, https://scriptbin.xyz/
📃 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.
note that if whatever if statement precedes this one is true this one won't be evaluated
how? 😭
i see
mhm
literally the first thing you should have learned in unity is how to log something to the console. so maybe consider doing that?
Debug.Log("text");
this, except log something actually useful instead of just a useless message that provides no context
yea lol I just gave example
cuz i m trying to do mk character he jumps and walks but when u play W (jump) and D or A (Walk) all at once he just walks in the air
i thought i can fix it like this but idk
If I have a list of game objects, and I am referencing the positions of those game objects several times in code, would it me more efficient to make a new array/list of vectors containing the positions of the objects, and reference those instead?
probably not
Is this question in response to an actual performance problem you're seeing, or just exploratory premature optimization?
I'm working on a school assignment, and efficiency and optimization is a core part of the course, so I just wanna make it as efficient as possible, even if I might not notice it at the scale of my project
Use the profiler and check it both ways. My guess is the overhead of managing the secondary array etc is going to be much worse than any potential savings. But it really depends heavily on your access patterns.
There is no real way to answer this without profiling and benchmarking.
If you're doing something in the name of performance for your assignment you should be prepared to demonstrate with data that it actually helped.
Accessing a property like .position involves a call into native unity code, so it's certainly possible that it'd be faster to store it and re-use it if it's being accessed many many times
Also, if you do wind up profiling this -- don't use the Deep Profile option. It will give you very skewed results
when you get the position from a Transform its a copy so these will become outdated fyi
so as others say there isnt gonna be a benefit if you want to be looking at the Transforms actual positions
It'd only be valid if you were certain that the transforms weren't moving (along with their parents!)
Yea if if you need to grab many hundreds of positions and you have a shit ton of work to do over them all then it may help. Profile to find out!
Stopwatch is also good to time code: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=net-9.0
You can use the Profiler methods to view timings in the profiler window
oh yea i forgot about those
is there a way to use Vector3.MoveTowards with root motion?
transform.position = Vector3.MoveTowards(transform.position, currentTarget.transform.position, Time.deltaTime * correctionSpeed);
I am trying to make it so the player moves closer to the enemy when it's about to attack but is very slightly out of range, but changing transform.position directly causes issues, due to me also using root motion
What sort of issues are you seeing? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.OnAnimatorMove.html might be worth a shot.
well, the character doesnt move to the desired position at all
turning off root motion does fix the issue, so I can only assume that its that which is causing problems
oh shit
that works!
now I only have some mathematical things to deal with
thank you very much!
ah, one problem
it seems to... turn off root motion now?
Hmm... I was replacing the Input Manager with the Input System, and I decided to try to do a lightweight replacement with this code:
if (_controls.DungeonEscape.Attack.IsPressed() && isGrounded)
{
_playerAnimation.SetAttack();
}
Except, when I do that, the attack fires off twice for some reason. I've replaced my code with catching the event for the button press being performed, but I'm curious as to why it worked this way.
Maybe you wanted WasPressedThisFrame?
IsPressed is like GetButton
WasPressedThisFrame is like GetButtonDown
Ah, that does fix it. Thank you.
if(correcting){
Debug.Log("correcting");
float distance = Vector3.Distance(transform.position, currentTargetPosition);
if(distance > maxDistance)
transform.position = Vector3.MoveTowards(transform.position, currentTargetPosition, Time.deltaTime * correctionSpeed);
else if(distance < minDistance)
transform.position = Vector3.MoveTowards(transform.position, currentTargetPosition, -Time.deltaTime * correctionSpeed);
else correcting = false;
}
}```
it does work, it does the correction
but it just completely turns off root motion?
what else could I use, or how could I do it so I can still apply root motion?
I tried animator.applyRootMotion = true; but it makes no difference
If you have a component with an OnAnimatorMove method, the animator will no longer apply root motion on its own
ah, there you go
thank you tho, thats good to know!
seems to work well!!
this is basically the effect I wanted
cause, you know, otherwise you might miss a hit because you were a few units off
hello any idea why my enemy is not moving he should move left between my posts and i dont understand why he is isnt
sorry i meant this code ```using UnityEngine;
public class PatrolController : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
[Header ("Patrol points")]
public Transform rightEdge;
public Transform leftEdge;
[Header("Enemy")]
public Transform enemy;
[Header("Movement")]
public float speed;
private Vector3 initScale;
void Start()
{
initScale = enemy.localScale;
}
// Update is called once per frame
void Update()
{
MoveInDirection(1);
}
private void MoveInDirection(int direction)
{
enemy.localScale = new Vector3(Mathf.Abs(initScale.x) * direction, initScale.y, initScale.z);
enemy.position = new Vector3(enemy.position.x + Time.deltaTime * direction * speed,enemy.position.y,enemy.position.z);
}
}
Hello, i am currently working on a lil project and i am struggling with displaying the good layers of my sprite
well, notably, your code does not use leftEdge or rightEdge at all
I tried to handle the layers i wanted to display with this script:
public class LayersHandler : MonoBehaviourPunCallbacks
{
private Dictionary<string,GameObject[]> _allLayers = new();
[SerializeField] [CanBeNull] private GameObject childToEquip = null;
[SerializeField] [CanBeNull] private GameObject parentToUnequip = null;
void Start()
{
// loads all layers
GameObject group, layer;
for (int i = 0; i < gameObject.transform.childCount; i++)
{
group = gameObject.transform.GetChild(i).gameObject;
GameObject[] layers = new GameObject[group.transform.childCount];
for (int j = 0; j < group.transform.childCount; j++)
{
debug += " | " + group.transform.GetChild(j).gameObject.name + "\n";
layer = group.transform.GetChild(j).gameObject;
layer.SetActive(false);
layers[j] = layer;
}
_allLayers.Add(group.name, layers);
}
}
void Unequip(string parentName)
{
foreach (GameObject layer in _allLayers[parentName]) layer.SetActive(false);
}
void Equip(GameObject equipement)
{
// Equipements data
string[] inputs = equipement.name.Split('_');
Unequip(inputs[0]);
equipement.SetActive(true);
}
// Update is called once per frame
void Update()
{
if (childToEquip != null)
{
Equip(childToEquip);
childToEquip = null;
}
if (parentToUnequip != null)
{
Unequip(parentToUnequip.name);
parentToUnequip = null;
}
}
}
but he should atleast move but he doesnt i dont know why
I wanted to drag and drop the gameobjects i wanted to equip or unequip here
the problem is that it should have equiped it and set itself to None
like that but it does not
thanks in advance
UI Toolkit and legacy UI can both be used in the same project right
problem was not in script but when i disabled animator in my enemy it started working but i dont understand
why?
Ah, the animator was probably controlling the position of the enemy
but that animation is was idle
As long as it sets the enemy’s position, it will override whatever you try to do to the enemy
nothing there
This happens if any animation sets the position
I usually set up my characters with a root object that I parent the visual to
(And the visual is what has the animator)
how do i know if animation set postion beacuse in animation i only change sprites
You'd need to look at every animation that the Animator is using
(which will be all of the animations in this list)
yes i know but how to check if they change postion beacuse my only animation that was running was idle
if you have write defaults on (for an animation state) and another state set position, the other states will change it back to the "default"
the Write Defaults setting is irrelevant -- the animator will control the property at all times
as long as any motion on any layer with a non-zero weight sets that property, the animator will never stop writing to that property
i dont understand i didnt write anything there
so what to do
You may be right. Doesn't sound great though 😆
Write Defaults just determines what value you get if the current motion doesn't set the property
What object are you trying to set the position of?
Show me in the hierarchy. Also show me which object in the hierarchy has the Animator on it.
and melee enemy has animator
and in enemy patrol is script that makes enemy patrolling
If you can't move MeleeEnemy around at all with the animator turned on, that means that an animation is controlling the position of MeleeEnemy
You'd see it in the animation window like this
You may want to have animations that actually move the enemy's sprite around
I would suggest doing this
So the MeleeEnemy prefab would look more like this
- MeleeEnemy <-- enemy component (if you have one)
- Visual <-- animator
i only have default sprite in idle so it doesnt change and i dont see anywhere where my animation is controls enemy postion
Again: ANY animation setting the position is all it takes
It does not matter if MeleeIdle doesn't set the position
It doesn't matter that you never leave the MeleeIdle state (which plays the MeleeIdle animation)
Hi, I’m making a game on Unity 2D mode, and when I turn the "Control the selected camera in first person" at the "Cameras" a message appears in the consol "SceneView rotation is fixed to identity when in 2D mode. Thie will be an error in the furur versions of Unity". What can I do?
What do you intend to do exactly
As the warning implies, it doesn't make much sense to move a 2D perspective in the first person
How can you store calendars and dates in Unity? I need to keep track of what week of the year it is and having a hard time figuring out the best way to do it.
Basically I want to start with say January 7, 1980 and the be able to know the date for each subsequent week that follows.
System.DateTime
Please is there a way to change those variables while running the game ?
I am new to Unity and noticed that when i print(t) which is the range(1, 100) field it does not change
sure you can assign variables in your code at any time with the = operator
yeah but can i change it directly on unity
[Range(1, 100)] [SerializeField] private int t = 50;
why not
What makes you think it isn't changing?
even if i change the value it keeps printing 50
Hello I’m trying to move my camera. And this message is a repetition. I’m in 2D. I go into the camera option of my scene and try to remanipulate it and this message comes out.
What keeps printing 50?
You'd have to show your code
ok
Scene window's camera controls are intended for 3D
In 2D you'd move the camera gameobject with the move tool or by changing its transform properties through the inspector
tooClose = Physics.SphereCast(transform.position, personalSpaceRadius, Vector3.zero, out spaceBubble, 0f, ~0, QueryTriggerInteraction.Ignore);
using a spherecast in this way causes the cast to be just a bubble of radius "personalSpaceRadius" on the transform.position, right? or am i misunderstanding how spherecasts work
SPherecast with a direction vector of zero makes no sense
public class LayersHandler : MonoBehaviourPunCallbacks
{
private Dictionary<string, GameObject[]> _allLayers = new();
[CanBeNull] public GameObject childToEquip;
[CanBeNull] public GameObject parentToUnequip;
[Range(1, 100)] [SerializeField] private int t = 50;
// Update is called once per frame
void Update()
{
print(t);
}
}
if you want to detect objects inside a sphere you should be using Physics.OverlapSphere.
yes this is fine - make sure you're changing the variable on the actual instance of the script that is in the scene
not a prefab or something
When you make a spherecast does it not check a volume in a sphere shape from the point of origin?
Spherecasts, raycasts and other "casts" don't detect anything that the shape is already overlapping at the start of the cast
they are intended to be cast in a direction and a certain distance
That's what OverlapXXX methods are for
Spherecast is a raycast in every sense but it has a thickness defined by the radius
So it's shaped like a capsule, in practice
Oh so its more like a hyperspherical cast? Where it checks a sphere radius across a distance
I start a 2D game i dont understand why my camera is like it.
Thank you
not sure what you mean by "hyperspherical". Imagine throwing a basketball through the scene and seeing what it hits
(but the ball goes in a perfectly straight line)
oooh okok
Hypersphere is a 4 dimensional sphere. im saying that because when you do the cast its like a sphere in one position that moves across an 'axis' R and checks for hits anywhere that each sphere in the frame touches
thanks @wintry quarry
It's definitely not a 4 dimensional sphere. But the rest of your explanation sounds roughly correct
I don't quite know what this means
Unity 2D tutorials or courses should be able to tell you how you are meant to move the camera in a 2D project
did you figure it out?
isn't there a way to do it on a prefab ?
what do you mean
I bet you it is. I'm not sure how better to explain it. But for a capsule cast instead, which I think might be more appropriate for what i need, are the two vector positions at the start the foci of the capsule?
I'm sorry i'm not english. I just want move my camera and understand why i have this message to talk about future version unity
Prefabs are not in the scene.
They are not loaded into the game.
Code on them doesn't run.
Code only runs on actual objects loaded into the game world.
In my consol
What are you actually trying to achieve gameplay-wise?
The docs explain what the points are - https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.CapsuleCast.html, I guess you could call them the "foci"
not that it's an ellipse
Well like I said the warning is there because there's no practical way to move a 2D camera with first person controls
I understand i try to found houw to change the first person control
CapsuleCast sweeps a capsule forward towards a direction, so the area of contact is more likely to resemble a rounded flat slab? than a capsule
As mentioned previously you'll probably want OverlapSphere or one of the similar Overlap checks
You don't, if you're making a 2D game
causes the cast to be just a bubble of radius "personalSpaceRadius" on the transform.position, right
If this is an accurate description of what you want, then as I mentioned earlier Physics.OverlapSphere is what you want.
When you run into walls or steep slopes, its very annoying because the player rigidbody will 'stick' to the wall instead of just sliding down it like normal. I'm writing into a script that will push the player in the normal to the walls face with the same amount of force that the player is attempting to put into the wall in the hopes that it will prevent that sticking. It seems like the best way since thats very similar to what happens in real life physics
The cast is just going to be around the player to check if its close enough to a wall
the personal space of the player
you should do a cast in the direction the player is trying to move
then you can see if there's a wall there
Yes, I was trying to figure out how the spherecast and capsulecast worked to better understand how to use them
actually the reason we don't stick to walls in real life is simply because we have no way of applying force to ourselves midair
Do you still think I should use an overlap?
no I think you should use a spherecast or capsulecast in the direction the player is trying to move
depending on the player's shape
basically simulate where the player will be next physics frame with the cast
and see if it's hitting a wall
and prevent that motion so you don't push into a wall and create that sticking effect
I would assume the sticky motion still happens even when the player is on the ground, but in real life you can push against a wall on the ground because your feet provide the force necessary. The force still happens even if you push against the wall in midair(ex moving very fast toward the wall) but generally as soon as you hit the wall the wall will push back with equal force enough to stop you instantly and depending on the material of the wall elastically put some force back into you to push you away from the wall
Thats what I think would be best to simulate in unity to prevent the sticking to the walls
The force still happens even if you push against the wall in midair
Unless you have rocket boots or something, you cannot consistently push against the wall
whereas in many games you have e.g. "air influence"
that's not a thing in real life
Thank, you. It’s strange because the message is multiplied in my console
Yes, but I didn't say consistently, the force vector exists until you hit the wall, and then an opposing force vector from the wall pushes you back and since you cant move in midair, you dont continue pushing like in the game
thank you a lot u saved me
you're confusing "forces" with "velocity"
your willhave velocity towards the wall until you hit it and bounce
but you don't have a force pushing you
The wall has to have a force pushing you
otherwise your acceleration wouldnt change and you would keep moving through the wall
yes the wall will exert a force, that's why you stop moving
You mean your velocity wouldn't change
you are one degree off in all this terminology
Usually we want video game characters to be able to control their velocity in the air
Since the force to keep that velocity* comes from "nowhere" that's why it causes wall sticking
You don't go through the wall but velocity against the wall's friction prevents sliding down
acceleration means "change in velocity"
No, your acceleration too. You have an acceleration of 0 while moving fast toward the wall, but when you hit the wall, your acceleration goes negative until your velocity toward the wall is 0 or away from the wall
I tried using a physic material to put the friction to 0, but it didnt seem to change anything. Did I do something wrong?
Or maybe the player object has a friction on it too thats affecting it, let me test
Is it correct to assume you're letting the player move the character by overwriting the rigidbody velocity in some way
If so, 0 friction walls are usually a band aid solution at best
I think so, is there a better way to do it? My current setup is adding force. I'm going to try setting up the script I was mentioning before where it sends a capsulecast in the players rb.velocity.normalized to check if a wall or some object that you cant normally stand on is too close to the player and then adding an opposing force normal to its plane
Not normalized. Use the actual velocity and multiply it by Time.fixedDeltaTime
that will give you a cast that moves exactly as far as your player will actually move in the next physics simulation update
Good idea, that would help in cases where the player is moving really fast as well
Preferably you'd not let the character push against solid walls at all
But ultimately there isn't a simple answer to this, especially if it has to be a rigidbody based character controller
Does anyone know how to integrate a splatmap into a shader graph? The way I have it is I isolate each color using smoothstep and/or subtract, and then multiply that with the texture, and add all textures back together for the final product, but the result is terrible and extremely pixelated for the base color, and utterly broken for the normals. I know it's more straightforward with terrain tools, but I'm using my own procedural terrain implementation.
Is there a better way to make a character controller? I had made characters that used transform.position and deltaTime before but it seemed like their wall interactions were even worse where if a wall was too thin or the player was moving too fast it would end up going inside or through the wall
kinematic controllers that directly move the character will almost always be doing something like the capsulecast technique to handle collisions
It's nice to know I was already looking in the right direction even if im on the wrong street
That type of character should not be allowed to push into solid objects either
I recommend you use unity's own CharacterController component (which starter assets has an example implementation of)
Or find a character controller someone else made that works well and dissect it along with studying more general theory of how character controllers are made in game engines
Is the way that characters are disallowed from pushing into solid objects done by what I'm trying to do? Or was I supposed to do something first that prevents characters from touching solid objects in that way before I set up the movement?
There's more than one way to do that, varying both by whether the controller is kinematic or not, and also varying by the game's needs
I might let the character push against nonkinematic colliders when walking on solid ground, but if in air I'd instead not apply the force at all if there's an obstacle detected in the intended move direction
To prevent it from seeming like the character is getting momentum from the invisible rocket boots
But maybe that's not what you want, and maybe you can get by fine with a kinematic character controller
You can make them push objects just as well
It's a pretty common path to start making a transform based character controller, realise how terrible the collisions seem with a naive implementation
Then try to make it a nonkinematic rigidbody as a bandaid solution to that
I think the type of game I am making would be better with a rigidbody over a kinematic controller, because I want it to be very physics and movement based
If I set up these type of interactions it would make adding new functionality a lot easier when it comes into contact with the player
How can i do that a 2d object moves when a rotating force is applied?
This question is too vague
Im using a physics material and the object bounces when i hit it
But not with rotation movement
I don't know how to explain it
Have you frozen that object's rigidbody rotation?
Like spokes on a tire?
I didn't
It will behave that way by default if you use a Rigidbody2D
Yeah this is default physics behaviour
Does it have any angular drag/angular damping?
How are you moving the object that hits it?
Perhaps so, but note that typical "video gamey" character movement that also interacts with physics both ways is not usually a beginner friendly challenge
Try to rely on forces that don't come from "nowhere" as much as possible, and try to keep the situations the character gets put into simple
That doesn't answer how you are moving the object. Like are you using AddForce, transform.Translate or what
I'm not using anything the object just moves when i hit it
I mean the object that is hitting it. How are you moving it
Things don't move by themselves
Except for rigidbody gravity
With move
"move" is not a way of moving things
You mean when another object hits it and moves it?
unless you mean this? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody.Move.html
TIL that exists
I don't know what type of movement is that
!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/, https://scriptbin.xyz/
📃 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.
That's the full script
You could also just read the code and tell us
no, it isn't
It's from chat gpt so i don't understand a lot
You are making it very hard and annoying to help you right now
You don't understand what "full script" is either, apparently
I don't
Paste the whole script file into a paste site.
Start over with code you understand then
Here?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yeah i should probably learn instead of just asking chat gpt
Thanks for your time random gentleman's
How can I tell the capsulecast to ignore only one layer rather than only apply it to one layer?
public LayerMask mask; set it up however you'd like.
Or you can invert a mask with ~mask
Thank you
What is common practice when dealing with defining ground? You can add a layer to something like a building to set it as a 'wall' mask, but what about the top of the building? You'd have to add another object that sits on top of it to let people have the correct ground interactions if you use layer masks to define grounds.
Nobody know how to clear the message 'SceneView rotation is fixed.....UnityEnfine.GUIUtility:ProcessEvent (int,intptr,bool&)" ?
I look in tuto but found nothing and i cant send pictures...
I just think the easiest way to define whats ground and whats walls would be to just check the angle of the object you are interacting with
I guess that makes sense
I was about to ask why many beginner tutorials wouldn't just use that and instead do either tags or layers to define ground but I guess most games dont need more than tags and layers
beginner tutorials often don't do things in a "good" way, they do them in an "expedient" way because they are competing on platforms like Youtube which are more about engagement and selling ads than making quality tutorials that emphasize best practices.
This includes Unity's junior programmer class
There are also many ways to do everything and there's not always a clear "best" way or it depends on the requirements of the given game
Unity's own tutorials are also not always perfect.
Discord was my last chance. Have nice night everyone
Layers are kind of a dead simple way to do it, and they're a unity feature which is relevant for tutorials that mainly try to teach how to use unity
Understood
I know I'm close but I'm doing something wrong.
{
// Prevent the player from pushing into walls
tooClose = Physics.CapsuleCast(orientation.position + Vector3.down / 2f , orientation.position + Vector3.up / 2f, personalSpaceRadius, rb.velocity.normalized, out closeWall, rb.velocity.magnitude * Time.fixedDeltaTime, ~0, QueryTriggerInteraction.Ignore);
if (tooClose && climbScript.checkIfWall(closeWall))
{
Debug.Log("Attempting to force player away from wall");
rb.AddForce(Vector3.Scale(closeWall.normal, rb.velocity));
}
}```
I know the cast is hitting properly cause of the debug log, but its not pushing me away even if i set the personalSpaceRadius high.
I wouldn't push the player away from the wall if the cast hits.
I would disallow adding force towards the wall in the first place
personalSpaceRadius is a funny variable name :P
note that it's not going to push you away with this code because when you're not moving the cast isn't going to move
and if you are moving, this force would need to be stronger than your normal movement force to overcome it
Would this be achieved with a projectonplane vector? where it takes the current vector direction and just projects it sideways rather than into the wall?
(What behaviour do you want?)
Hopefully in the end itll be exactly just that, an invisible forcefield around the player that stops the player from moving into walls
Basically, I want the player to slide across the wall as if it were frictionless
I would probably stop adding forces on the Y axis when I'm not on the ground
Some projection should be done too, if you want to be able to slide along the wall
Not sure how well Vector3.Scale(closeWall.normal, rb.velocity) works here.
I'm going to try rb.AddForce(GetSlopeMoveDirection(rb.velocity, closeWall.normal), ForceMode.Force); public Vector3 GetSlopeMoveDirection(Vector3 direction, Vector3 plane) { return Vector3.ProjectOnPlane(direction, plane).normalized; }
This is the code i used to get movement for slopes, I'm sure it will still work on walls
im pretty much in bed and half asleep. but, if the issue is the player sticking to the wall then im pretty sure you can fix that with a physics material
I thought about this too, but I was told it was a band aid solution
yup, but it works
all this extra code above is a good fix too (or so i assume, i've only read half of it)
That looks decent to me
I can feel the force being applied, but I don't think its the correct amount. I'll try and figure out how to make it more precise
After projecting the movement to the plane, you could restore its original magnitude
If I understand what you mean
I do, that's what I'm trying to figure out how to do now
Idk about using rb.velocity as the parameter here though
What do you think I should use?
Don't you have something like a "target movement vector"?
What are you using to add forces/set velocity in the first place?
I have a target max move speed, and a move direction
{
// calculate movement direction
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
// on slope
if (OnSlope() && !exitingSlope)
{
rb.AddForce(GetSlopeMoveDirection(moveDirection, slopeHit.normal) * moveSpeed * 20f, ForceMode.Force);
if (rb.velocity.y > 0)
{
rb.AddForce(-slopeHit.normal * 80f, ForceMode.Force);
}
}
// on ground
else if (grounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
}
// in air
else if (!grounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
}
// turn gravity off while on slope
rb.useGravity = !OnSlope();
}
private void SpeedControl()
{
// limiting speed on slope
if (OnSlope() && !exitingSlope)
{
if (rb.velocity.magnitude > moveSpeed)
{
rb.velocity = rb.velocity.normalized * moveSpeed;
}
}
// limiting speed on ground or in air
else
{
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
// limit velocity if needed
if (flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
}
}```
Well you're overwriting velocity entirely with this code
so adding forces won't do anything really
I would basically expect code like this:
if (there is NOT a wall in the way) {
// move normally
}
else {
// there's a wall in the way
// remove the portion of the desired movement vector that coincides with the direction towards the wall with Vector projection and subtraction
}```
because as soon as the player moves again itll just get reset back
I'm going to change this void to a bool
private void MovePlayer()
{
// calculate move vector if theres a wall in the way
if (PersonalSpace())
{
Debug.Log("Attempting to stop player from moving toward wall");
moveDirection = new Vector3(GetSlopeMoveDirection(rb.velocity, closeWall.normal).x * verticalInput, rb.velocity.y, GetSlopeMoveDirection(rb.velocity, closeWall.normal).z * horizontalInput);
}
else
{
// calculate movement direction
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
}
// on slope
if (OnSlope() && !exitingSlope)
{
rb.AddForce(GetSlopeMoveDirection(moveDirection, slopeHit.normal) * moveSpeed * 20f, ForceMode.Force);
if (rb.velocity.y > 0)
{
rb.AddForce(-slopeHit.normal * 80f, ForceMode.Force);
}
}
// on ground
else if (grounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
}
// in air
else if (!grounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
}
// turn gravity off while on slope
rb.useGravity = !OnSlope();
}```
I know im close to figuring it out, but im stuck here because I know the values I put in for the new moveDirection vector are incorrect but im not sure what to change them to
Use paste sites or at least add formatting to your snippets
Will do
Its kinda funny the wall acts like a magnet
https://pastecode.io/s/5go6bb9i
Heres a much better paste that includes all relevant information
Maybe changing rb.velocity in the plane projection to just the vertical and horizontal inputs would get the correct direction?
for something like ``` moveDirection = new Vector3(GetSlopeMoveDirection(orientation.forward * verticalInput, closeWall.normal).x, rb.velocity.y, GetSlopeMoveDirection(orientation.right * horizontalInput, closeWall.normal).z * horizontalInput);
After some testing, I think it would be better to just do an overlap. I can't get it working
Does anyone know how to make lerp or smoothdamp or similar functions framerate independent?
My code:
transform.localPosition = Vector3.SmoothDamp(transform.localPosition, targetPosition, ref currentVelocity, swaySpeed);
Every tutorial I've seen on weapon sway uses a function similar to this (usually multiplying swaySpeed * Time.deltaTime), and obviously it's not framerate dependent.
It already uses delta time by default, so multiplying with deltatime would certainly not be accurate.
Without context, the code you showed looks correct. Except that you use a "speed" variable in palce of the smoothTime argument
"Speed" would suggest that a higher value if faster. However a higher smoothTime value makes it slower
When I manually set the framerate low, the sway goes absolutely crazy 😔
so maybe it isn't a framerate dependency issue but I actually have no idea
Show the GetLookVector method
i also used the old input system but it doesnt seem to work
start debugging the values and see if the vectors are changing drastically
I assume delta time is implied. I don't really use smooth damp much
ok its difficult to tell but I think the input vector spikes on lower frame rates
yea I set the framerate to 6 fps and the Mouse X input goes up to like 80 while max on 165 fps is 11
It is expected that you get higher mouse delta values with higher framerates
Sounds like you have some framerate dependent code/logic
I always assumed mouse input was framerate independent buttt
like is this not framerate independent?
It's more about how you use it.
Mouse delta = how much your mouse moved during the last frame.
So it is inherently "framerate dependent", you just have to use it correctly
Yea my mouse logic are both inside Update()
That's not it.
You seem to be clamping the value with const values. That's making your logic framerate dependent as it would behave differently on different framerates.
Oh my mistake I was using different code earlier, Im using this code now. Got rid of the clamp
It might be easier to pinpoint the issue if you show a video of both low and high FPS
Ok Ill get on it
This is more or less fine, though I'm not entirely sure if smoothdamp is okay. Never used it myself.
Also if your swayTime is .15 and your frame takes more than .15 seconds, no idea how smoothdamp behaves then (or should behave)
I'm not even quite sure if smoothdamp is reliable on low framerates
One fix I can think of is to do multiple steps of smoothdamp with a smaller deltatime, when the frame's deltatime is high
I sort of used smoothdamp out of desperation since I dont know how to use lerp
Like if you have 0.1 second frame, you would do 4 smoothdamps with 0.025 deltatime, for example
This page goes over how to use it correctly. Read it and see the "improvements" section for the framerate-independent way of doing it
https://unity.huh.how/lerp/wrong-lerp
That's for Mathf.Lerp but it should apply to Vector3.Lerp as well
ok thanks
Could unity serialise other float values like +/-Infinity and NaN?
That is something that you can easily try and see
back to the problem i had yesterday in which when i dashed it just teleported me forward. I did the same with a basic cube and it worked fine. I get the input in update and set a bool is dashing to true, in fixedupdate i check if its true , set it to false and then add force to my player using addForce with the forcemode impulse but it just teleports me forward instead of a smooth dash.
make sure your rigidbody is interpolated, perhaps
i set it to interpolate and it still does the same
i mean i spawned a cube and did the same with it and it worked fine
nvm it was the animator ig
but still i think i dash but its just too fast is there a way how i can slow it down?
Wouldn't you just add a smaller force?
You can also add it over time, in a coroutine for example
then i just dash a little distance
Please enlighten me what you did brother 🙏
makes sense imma try that
Been struggling with this for so long
but i gotta learn what they are and how to use them :)
If you use a coroutine, make sure to use WaitForFixedUpdate to wait so it runs in sync with physics
aight im learning how they work rn
This can ofc be done without a coroutine but they are good to learn
i know what they do but i just dont know how to use them yk
You can find examples in the docs etc
I have a Transform that I want to keep in its original spot, but I want to make another Transform variable based off the transform but shifted 1.0f in the y axis. How can I go about this?
A Transform is a location and rotation, correct?
And scale*^
I think I figured it out,
cameraPos.position = orientation.position + Vector3.up / 2f;```
(Decided to make it 0.5 and not 1)
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
why does the unity documentation create 2 object pools for a single type?
its just so difficult to understand what is going on
all I want is object pooling for projectiles
That doesn't create two pools. It's an if-else
the first 2 lines
theres 2 IObjectPool<ParticleSystem>s being defined
one of them is private other one is public
The second one, Pool is just a property that has a getter for the private field m_Pool
The idea here is that it doesn't create m_Pool until it is actually needed
what if you just make m_Pool public?
I want to create it during loading, not during gameplay
using UnityEngine;
using UnityEngine.Pool;
public class ObjectPoolingProjectiles : MonoBehaviour
{
[SerializeField] GameObject bullet;
public IObjectPool<GameObject> m_Pool;
public static ObjectPoolingProjectiles Instance;
private void Awake() {
m_Pool = new ObjectPool<GameObject>(CreatePooledItem,
OnTakeFromPool, OnReturnedToPool,
OnDestroyPoolObject, true, 20, 30);
Instance = this;
}
GameObject CreatePooledItem()
{
GameObject go = Instantiate(bullet);
go.GetComponent<BasicBullet>().pool = m_Pool;
return go;
}
void OnReturnedToPool(GameObject projectile)
{
projectile.gameObject.SetActive(false);
}
void OnTakeFromPool(GameObject projectile)
{
projectile.gameObject.SetActive(true);
}
void OnDestroyPoolObject(GameObject projectile)
{
Destroy(projectile.gameObject);
}
}```
this is what I have currently
You can do that, it's just not "clean code" or whatever
its not a big snippet so I won't put it on hatebin
right now, the problem is that all this does is instantiate projectiles whenever I fire
it doesnt instantiate them all at once and then activate/deactivate them
Does it not instantiate 20 objects when you initialize it? That's what you are passing into the defaultCapacity argument in the constructor
nope
I call GameObject proj = ObjectPoolingProjectiles.Instance.m_Pool.Get(); to fire
Ok apparently it just sets the capacity of the list
am I meant to create a loop?
I guess you can just call Get and Release in a loop, yeah
so if I call Release and then try to use Get again, it works properly
but the first projectiles that you fire get instantiated when you fire
GameObject[] gos;
private void Awake() {
m_Pool = new ObjectPool<GameObject>(CreatePooledItem,
OnTakeFromPool, OnReturnedToPool,
OnDestroyPoolObject, true, 20, 30);
Instance = this;
for(int i = 0; i < 20; i++){
gos[i] = m_Pool.Get();
}
}
private void Start(){
foreach(GameObject go in gos){
m_Pool.Release(go);
}
}```
I tried doing something like this but it didnt work
i dont even get why I have to do this manually
i dont think this worked like this before
it feels like it completely ignores the whole capacity thing
👆
As in, List<T>.Capacity or similiar
that's not going to work, your gos array is null
yeah I figured
not sure how to fix it tho
doing new() doesnt do anything
new GameObject[20];
basic C# knowledge
it does it, alright
but I still get this error
void OnReturnedToPool(GameObject projectile)
{
projectile.gameObject.SetActive(false);
}```
says that projectile is null
yes you have created a pool but there is nothing instantiated in it. So it is full of nulls
The max amount of objects in the pool. Excess objects will be destroyed on return:
What fills it with null? Shouldn't calling Get call CreatePooledItem and therefore instantiate?
of course not
How does it work then? 🤔
the createpooleditem callback needs to do the instantiation
no, there is
private void Awake() {
gos = new GameObject[100];
m_Pool = new ObjectPool<GameObject>(CreatePooledItem,
OnTakeFromPool, OnReturnedToPool,
OnDestroyPoolObject, true, 20, 50);
Instance = this;
for(int i = 0; i < 20; i++)
gos[i] = m_Pool.Get();
}
private void Start() {
foreach(GameObject go in gos){
m_Pool.Release(go);
}
}```
show your CreatePoolItem code
wdym
GameObject CreatePooledItem()
{
GameObject newPooledObject = Instantiate(bullet);
newPooledObject.GetComponent<BasicBullet>().pool = m_Pool;
return newPooledObject;
}```
and have you debugged any of this?
And when does createdpooleditem get called?
I'm not sure what to debug.
the nullreference happens once when the game boots, thats it
so work it back, you are trying to release a null object, therefore your array has null objects, therefore your create is probably failing
when a new object is required, point is you need to instantiate in Create. Create does not automatically do it for you as you implied
Alfy already showed that CreatePooledItem instantiates it
but appareantly CreatePooledItem only gets called when there's no items in the pool and you call Pool.Get()
Ah, I hadn't scrolled that far back
Where does it say that it should
and instantiate more if I'm trying to Get from the pool when theres no free objects
I remember it working that way
I used this before
(I mean, to me, intuitively it would make sense if it automatically instantiated the min amount)
but now it just doesnt
yeah, exactly what I'm saying
maybe I remember wrong, but thats how I remember it working
ill just try
if(go != null)
m_Pool.Release(go);```
although I have an idea
I feel like it happens because I click on the play button
and clicking is how you fire
so maybe you try to fire before the items are loaded in?
no that cant be it...?
You can use Ctrl + P to enter playmode too
You can also check if m_Pool is null and debug.log it
nope, still causes error
this fixed it
kinda cheaty but yeah
that did not 'fix' anything, it just hides the error in your logic
well, it no longer tries to release nothing
Are you still initializing it in Awake, and calling Release in Start?
i mean, it tries, but it cant
yes
So this is in Start
which should not be happening in the first place. you are addressing symptoms instead of the actual problem
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
for(int i = 0; i < 20; i++)
gos[i] = m_Pool.Get();```
vs
gos = new GameObject[100];```
Do you see the mistake?
honestly, no
you are creating an array of 100 objects but only filling the first 20 of that with something, the other 80 will be null
yeah, setting it to 20 works
yes, but then why do I only get a single nullref? shouldnt I be getting 80?
other times I get like 60 nullref errors per second
probably called in Update
I know these, I just havent coded in long
my bad
I mean, I coded, but in c++, which is completely different
yeah, C++ will not help much with basic C#
Hey everyone!
Just got a quick question related to script-writing.
So there is a task that asks to to code an object to move in a specific direction.
But in Unity course there were 2 different types of writing Movement script:
Which one is better to use?
Why are they up to using 2nd option over 1st, if these scripts almost the same and do the same job?
What's exactly is wrong?
The first Translate in your code includes a float multiplication, the second one does a vector multiplication so there's a micro difference
they both move the car in world space forward, you probably want to move the car in the forward of the car itself
- works with numbers
- works with Vector's object?
Are you doing this course? https://learn.unity.com/project/unit-1-driving-simulation
Yeah
They are just different overloads (versions) of the same method. They do the same thing. It's just split into two overloads for convenience
I gotta say though, that particular Unity learn lesson is bad, it teaches you to move a rigidbody with transform, which is incorrect
It will lead to oddities in the physics, like missed collisions and glitching
Well, I knew that
So, I assume it's a good course to get into unity, but you need to re-learn some of the aspects that they taught?
Hello! I would like a little help. I am trying to make a simple mini-game where you place little blocks on an isometric map to prevent floods. I am following the "Junior Programming Pathway" course and am doing the "lab project as recommended. I am having a little struggle trying to make a grid system
(Concept art that I make quickly in pixel art, but I want to build it in 3D)
Another thing is its generally better practise to do any sort of calculation outside of the method itself.
Vector3 foo;
transform.Translate(foo);```
Reason why that matters is say you want to change how you calculate `foo`, you can just alter the line for that Vector3 and you never have to worry about touching the Translate method again
I want to be able to make a 3D-storage where the positions, data and other information of blocks are stored, can be edited in the Unity Editor mode and in game as well. And then Exported later if possible as a spreadsheet
In course I heard that it's called a "hard-coded number"? And making variables makes it easier to change values
You can use an array for the grid
A C# array
Is there a good tutorial I ccan follow to do so?
I scraped together a bunch of information from other (non tutorial, and actually "minecraft clone" tyoe) YT vid and made some progress but I think I need to scrap it.
I made this using Unity's in built system, but the collision system isn't what I want, unfortunately. I don't understand it and I dont know how to read for neighbouring blocks
It could be a 3 dimensional array of your custom type. Each item in the array would store info about the cell that it refers to
And also a small question:
You can define variables only in functions such as Start() and Update ()?
You can't define them before Start()?
How much experience do you have in coding/unity though?
This is not the simplest beginner project tbh
I have basic experience with coding, and I started Unity on Wednesday
Those are field initializers and they can't reference each other
Unless the other field is static/const i guess
In a bigger context question, I am learning Unity for a Uni project where I need the 3D-positional data to be exported (Hopefully in real time)
But one step at a time
Alr, ty
Mini-projects to learn, y'know?
Is is comparatively difficult?
Also, I know I should probably start from scratch
Should I try making a different mini-game first?
Probably
Damn
If you can't begin to think how to implement the 3D array, it's likely too early for that
I don't know really how to start
btw, if I do this, do I need to do new()?
public List<IObjectPool<GameObject>> m_Pool;
The water simulation part would be pretty complex too
For a beginner
Maybe I should start with a car that moves from one place to another
yes, Unity will not be able to serialize that
Oh the water sim will be simple as like "Check i neighbour block is "air", if so, flow into it"
so something like public List<IObjectPool<GameObject>> m_Pool = new List<IObjectPool<GameObject>>();?
exactly like
I basically want to make it so I can have different object pools for different projectiles
Okay so the water in a cell never decreases? Only expands to neighboring cells?
But I think I will put this complex project on hold and try a "move a car from one town to another over pre-built iso metric plane"
so if I want to add a new projectile type, I just add a new prefab to pool
Yup, minecraft physics
As shown in the concept art, the water just flows into neighbour blocks
Btw you can just do ... = new();
Unless you are on some ancient version
But for now I think, on your recommendation, I will put this project on hold and make a simpler one.
Just drive from point A to B over Terrain, using the 3D collision blocks given in Unity
Just to continue down the Junior Programming course
ah okay so here it works
for arrays it didnt cuz i needed to set the size
Some theory that might give you some ideas.
If you created an array like this, int[,] someArray; , what you have is a 2D array.
Say that blue is where your player is, and red is the wall. Its easy enough to find the tile to the players left, by doing [X-1, Y]
what if I want to do
for(int i = 0; i < bullets.Count; i++){
m_Pool[i] = new ObjectPool<GameObject>(CreatePooledItem,
OnTakeFromPool, OnReturnedToPool,
OnDestroyPoolObject, true, 20, 50);
}```?
Yeah, conceptually, I understand that. I just dont know how to code it/ implement it
Thank you though
Create a separate pool for each and have them use a different prefab
thats what I'm trying, but I dont want to create new scripts for every single new projectile
like how can I tell them which prefab to use?
You'd obviously use the same script
Add a new component of this script's type for each bullet type
Or you can put it all into one script, up to you
I have no way of telling the function which projectile to use
that sounds kinda cheaty
thats my issue
Then put the pool into its own class, non monobehaviour
I basically want a list of pools, and to be able to access any of the pools by just using a number
And have the one monobehaviour hold a list of those classes
Anyway, thank you for the recommendations and advice. I feel like if I wasn't told that it is above my skill-level I would have kept banging my head against this wall.
so you need to figure out a way to get i into the method as a parameter. Anonymous functions are your friend here
That would work too
What are the errors?
if its non-mono, then I can't use stuff like Instantiate for the CreatePooledItems
i dont know what those are
Instantiate is static
You can call it from anywhere
UnityEngine.Object.Instantiate or GameObject.Instantiate etc.
I keep telling you to learn, at some point you are actually going to do it
and then I just create a list of classes?
In a monobehaviour you can just do Instantiate because this is already a UnityEngine.Object so it has Instantiate as a member
int width = 5;
int height = 3;
int[,] someArray = new int[width, height];
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
someArray[x, y] = 0;
}
}```really simple way would be like this, though how to get it working alongside the unity tilemaps I couldnt say
well what are they?
go read the docs
this makes like no sense
System.Linq.Expressions.Expression<Func<int, int>> e = x => x * x;
People sometimes give you keywords to search instead of explaining something that has been alreaedy explained online thoroughly
Have the implementation of instantiation be handled by what's referenced?
this is appareantly an anonymous function but ive no clue how to comprehend it

Thank you, I will note that. But I want to just get a smaller/simpler game from what I learnt in the course first before I continue to entrench myself in the same concept continually
so you spent all of 30 seconds to try and learn a new concept? What do you expect? Instant comprehension?
no, but it's difficult for me to understand a new concept without being able to apply it
or being able to see how it works
but it literally shows one extremely rudimentary example, and then an extremely complicated one
the rudimentary one isnt enough to understand anything, and the complicated one is too much to be able to take anything out of
have you ever used Coroutines in Unity?
I have
have you used a yield Wait statement ?
even those ones were explained quite weirdly until I implemented it myself and it just worked
yes
ok, so you have used an anonymous function
my understanding is its basically a very shorthand way of writing
int someMethod(int val) {
return val * val;
}```
yield return new WaitUntil(() => isDone);
correct
I'd also add using System.Linq.Expressions; to the top of the file, it will shorten how long the line needs to be
do not need Linq for this
true
i was about to say, it works without
any idea how i can fix this? idk understand what it means, my item is a scriptableObject
though it is in the original line so its interesting how it got there
what is line 21 of Container
Honestly im not sure why the Expressions part is in the original line either
public T[] InitializeMap<T>(Func<int, int, T> factory) any time I've used Func before and it only ever needs using System;
so I have this
actually these
so inside the Instantiate, I want to be able to set what projectile to use
oh ur right ty
would I need to call create inside of CreatePooledItem?
wrong place, you need the lambda here
new ObjectPool<GameObject>(CreatePooledItem,
OnTakeFromPool, OnReturnedToPool,
OnDestroyPoolObject, true, 20, 50);
in place of the CreatePooledItem
You need a Func<GameObject>, not action
Func allows a return type, Action only takes inputs
oh, I see
he does not need a Func at all
something like this?
all he needs is a lambda to capture i and pass it to a method
oh
wait I'm confused now
no
Yeah nevermind the Func part
but which method would I need to pass it to?
I cant pass it to the CreatePooledItem method
You can if you use a lambda and add an int parameter to CreatePooledItem
I can't add any parameters to CreatePooledItem
Why do you say that?
look, your CreatePooledItem will not take a parameter as you currently have it
So, you modify CreatePooledItem to take an int parameter
But, this makes the signature required by Objectpool invalid
So you use a lambda to correct the signature
You are missing the lambda part
CreatePooledItem works as a Func<GameObject> here, because it returns a GameObject
wouldnt I need a Func then, not an Action?
I just said that createpooleditem is your Func
You need to use a lambda expression to call it with the i as an argument
hold on
right now I have this
would I need CreatePooledItem to call the Lambda?
im sorry im being really slow right now
You don't need the action
then....?
look, this is so simple
m_Pool[i] = new ObjectPool<GameObject>(() =>
{
int x = i;
return CreatePooledItem(x);
},
OnTakeFromPool, OnReturnedToPool,
OnDestroyPoolObject, true, 20, 50);
...
GameObject CreatePooledItem(int i)
{
GameObject newPooledObject = Instantiate(bullets[i]);
return newPooledObject;
}
what is the ...?
I am making a grid system, the catch is, i dont have a pre-defined width and height with me. I have a plane, and i want all the tiles to be fit upon it (consider chessboard). I have total amount of tiles I want to fit upon a plane of some size. I tried using renderer.bounds.size but it gives huge amount of value which i cannot use as height/width. Please help me out here!
commment to illustrate other code
(Deleted my reply since it had the variable capture problem)
3d plane...?
yes, its a match based game made in 3D
@naive pawn
seems pretty 2d to me
🤔
you have a total width/height, and a tile count?
It's a 3D concept too
oh
just divide them
Nope, I just have the tile count
yeah I think I get it
it's a 3d concept, not a 3d object
How do I calculate the width and height
I want 120 blocks to be spawned upon that plane, equally aligned
Unity even has a default Plane 3D object so not sure what you mean
well you have 3 variables (tile count, tile height, total height) (in each direction/dimension)
you can't determine the others with just 1, you have to define 2