#π»βcode-beginner
1 messages Β· Page 636 of 1
i have no clue what causes this. I have no code which loads the level scene
man
why is it link
MKVs do not embed
oh
Convert it to MP4 as Spawn said
oops sorry
why does it load the level sceneeeeee
wait maybe i dont know how the build settin gworks
Didn't you say this was a build
I already said, in Editor, you can load whatever scene you want
And the scene is inside MainMenu, so loading MainMenu is going to also load Level
the level scene is in the main menu scene?
Yes, you've loaded it additively
You dragged the whole scene into another scene
So they're both loaded
how can I cut them
Right click -> Remove
Yeeeesirrr
It is normal that when creating a shader it comes by default with 20 or 19 errors ?
depends on what your level of "normal" is i suppose lol
shaders are different depending on the renderpipeline ur using..
best way to get up and going with shaders is in ShaderGraph, imho..
hey
im new to unity i recently switched from godot to unity
and one question
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
Hips.GetComponent<ConfigurableJoint>().targetRotation = Quaternion.Euler(0, -mouseX, 0);
and could someone tell me why is the characters target rotation going back to 0
Mouse movement is expressed as a delta, which is the amount the mouse moved since the last time Update was executed
If you do not move the mouse, the variables will go back to 0
oh
could u tell me how to repair it
wait would it work if i would make another float
nvm
Use a variable in which you add the value of mouseX, then use that variable into your rotation
okay thx
How can i Make singleton before Start
Soemetime i get null excepion
I use Awake() to create Singleton Instance
And for my "weapon" in Start i try to get the Singleton
but sometimes i get null ):
you can use enumeration and yield return , chek until it is not null
every scripts Awake runs before every scripts Start
private void Start()
{
enemyInRange = EnamyInRange.Instance;
}
void Awake()
{
Instance = this;
}
still sometimes i get null
use a task maybe
still does not work it moves shlightly and then it goes back to the 0 rotation
Show your updated code
What is that ? XD
if it is null then either the object had been destroyed or you are trying to access it before it's even been created
you do not need a Task for this, that suggestion is wildly incorrect
i know but i create it at Awake So WTF
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
float X = 0;
float Y = 0;
X += mouseX;
Y += mouseY;
Hips.GetComponent<ConfigurableJoint>().targetRotation = Quaternion.Euler(0, -X, 0);
BTW ITS IN THE FIXED UPDATE FUNCTION
the only thing that would cause that is if u somehow went and manually changed scripts execution orders in the project settings
are you sure that the object is actually in the scene
unless theres an error ur missing
I have 2 scripts
1 Weapon
and
2 EnamyInRange
and somethimes Weapon can't find EnamyInRange instance at START()
Pull both X and Y outside of FixedUpdate so their values are retained when FixedUpdate is executed again
ohhh i forgot
Right now you reset them to 0 each time FixedUpdate is executed
show the actual scene setup and both of the full classes
Ensure you have an instance of the Singleton in that scene and it is active when the scene starts
it is
prove it
private void Start()
{
StartCoroutine(InitializeAfterEnemyInRange());
}
private IEnumerator InitializeAfterEnemyInRange()
{
while (EnamyInRange.Instance == null)
{
yield return null; // Wait one frame
}
enemyInRange = EnamyInRange.Instance;
// Proceed with other initialization logic here
}```
I mean Coroutine. smth like this
Then you wouldn't be getting this error
What? No.
MiniGun have WeaponScript
GameManager have EnamyInRange
thats an xy solution.. the problem is its not initialized when he asks for it
a coroutine is unnecessary for this too and wouldn't fix the issue if they are trying to access the singleton in Update or something
Lol why @polar acorn
show it
its a convoluted solution to a problem with a simpler fix
Because that's not the issue, this code wouldn't solve it, and it's ludicrously slower than just fixing the actual problem
can you stop taking these mail slot screenshots and actually show the full context here
Show the inspectors for MiniGun and GameManager
ATTAK! π½
i did send that insperor
and you've still not shown the code as i requested several minutes ago
is anyone free to give me some help with code, scenes and json files
Hpw cam o share big part of code ?
!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 still don't actually know which script is which, should probably wait until we get the code before attempting to answer further
@polar acorn i think i crushed it.. my first property π΄
Yep, there you go
A tool for sharing your source code with the world!
thx but it seems that it cant fully rotate like its rotating 90 degress and then its going back
now you just need to invoke an event in that if statement and it will be top tier
much love guys! i feel rejuvenated
now point to the line that the actual NullReferenceException is happening on
Looks like the bot ate your second link, try sending it again now
aren't awake() and start() asynchronous in Unity? if the awake takes longer it can cause the problem
No
All unity code is single threaded
im having a issue where when I look around and move at the same time everything looks jittery. this is the code for looking around.
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
transform.Rotate(Vector3.up * mouseX * lookSpeedX);
rotationX -= mouseY * lookSpeedY;
rotationX = Mathf.Clamp(rotationX, -upperLimit, lowerLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
line nr 39
this is the movement code
isGrounded = Physics.Raycast(transform.position, Vector3.down, groundCheckDistance);
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 movement = transform.right * horizontal + transform.forward * vertical;
rb.velocity = new Vector3(movement.x * speed, rb.velocity.y, movement.z * speed);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
- if you are using a rigidbody then you are breaking interpolation by rotating it via the transform
- update the camera in LateUpdate so it updates correctly after the player object has moved(also obligatory: Use Cinemachine instead)
of which file
ill try that
WEapon ofc
screenshot the entire error
There is Problem with EnamyInRange Instance
some good context
Can you show a screenshot of your entire unity window, while the game is running, with the error in the console visible and GameManager object selected and visible in the inspector?
GameManager object selected
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
X += mouseX;
Y += mouseY;
Hips.GetComponent<ConfigurableJoint>().targetRotation = Quaternion.Euler(0, -X, 0);
Can someone help me the player is not fully rotating
Okay, cool. We have now confirmed that the object does exist, and it's Awake is running. Since your issue is in findTarget, that means that findTarget is getting called before start on that object
So, what calls findTarget
Update ()
Anywhere else?
i must be stoned or something..
What does the stacktrace of the error say?
Nope
NullReferenceException: Object reference not set to an instance of an object
WeaponScript.findTarget () (at Assets/Scripts/WeaponScript.cs:39)
WeaponScript.Update () (at Assets/Scripts/WeaponScript.cs:23)
put these two lines before line 39 in WeaponScript:
Debug.Log($"{name} ({GetInstanceID()} has EnamyInRange assigned: {enemyInRange != null}");
Debug.Log($"But is the list assigned? {enemyInRange.getCloseEnamy().Count > 0}");
then obviously show what they print
Oh. Right. The instance is completely fine
it's the list that's null
Ok i know what is wrong
Singleton is OK
but the list don't exists XD
at first update
no kidden.. we' just debugged the entire thing with u.. we also know whats wrong π
lol
future reference.. u run into a similar issue like this #π»βcode-beginner message π throw debugs like crazy... you'll find what parts missing
So what is happening instead?
hes rotating 90 degrees or smth
Limited to 90 degrees? Or always at 90 degrees?
limited
This is too vague. You need to also show your joint settings
i think its a setup issue ^
im trying to send a video
of it
here it is
idk it doesnt want to uplode on discord
upload not uplode
also the play has animations but i dont think its changing anything
!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.
show the joint..#π»βcode-beginner message
and you mean the object also has animation? if yes double check that its not changing the transform in any way
https://paste.mod.gg/zaqbrsvcqbxc/0
can someone please tell me how tf is player able to stick to walls I might have made somewhere mistake also please help me fix it
A tool for sharing your source code with the world!
the animation is not changing the trasform atleast from that what i see and all of the joints have the same settings
use frictionless physics2d material
and i showed the hips
so yea
idk
? is that on me?
I'm making a fps game and my player has a rigidbody the camera isn't a child of the player when I move/look around there is a very small stutter. I have interpolate on am I doing something wrong? https://paste.ofcode.org/utJ9dDstDK8G6YECkxA8hE
yup
you confused me even more how am I able to make 2d in 3d game
how to make it frictionless? never did that
also should I put that onto player?
You make a new physics material
throw it on the player
then set dyanmic and static friction to 0
the harder way is to detect if ur velocity has stopped..
Its that that bad but the stutter is there
and then use extra gravity to force it down..
but then ud need to check if u were against the wall.. and not grounded.. and etc etc.
physics material is tried and true
I'm pretty new to Unity, but I am really enjoying how user friendly it is
I'm working on a Unity player selection system where players can create a new profile with a name and age, and their level is assigned based on the age. The data is stored in a JSON file and loaded when the game starts. At the end of each level, if the player has accumulated enough points their level should be updated, the level updates in the JSON folder but when the user goes back to the main menu 2 things happen.
a) All of the players from the players list are gone
b) Once restarting the game the players do appear but whilst in the JSON file their level has updated, inside the game their level has increased to 4 for some reason.
See video and code below.
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.
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.
mmmm... wheres ur cam code?
should be in lateupdate
so it runs after the physics
i think
yea
we're all pretty chill around here..
if u put in a little effort so do we π§‘
oh hell nah I am not doing that
its the ones that come for hand-outs that get angry and think we're all toxic
I saw this in a tutorial vid and I wanna know the hotkey for it, he instantly placed the camera where he was looking from in the scene
that seems so useful
ya, its annoying lol
Align With View
align to selected
forgot the shortuct
I am still sticking to the walll
or view ^
I have no idea what that is π
did u put it on the rigidbody?
normally you google it
the shortcut shows , it under the GameObject menu
freebie for you
oh for some reason it cant be applied
nu uh..
this seems like user error
and somehow it broke my wallbuy
is it cuz ur using too much force?
script
ohh.. weird.. remove it then.. u may be into some extra work π
script to buy weapons off wall and somehow adding the new physics material it broke :/
ya i gotcha
how π«
you can basicly steal my code
here it is
SpawnCamp by any chance do you have script that would make me not sticky?
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivityX * Time.deltaTime;
@noble cedar never multiply mouse input by Time.deltaTime
ohhh my bad
i started out with CCs b/c of how much easier it was to use camera's with them
0FPS = spinning the shit out of the player π
and i kinda only ever use rigidbodies to play around with... they never get perfect
thats not how that works.
Mouse Input is already the delta between frames
idk I took that script from out teacher
what sort of collider are u using?
your "teacher" has no idea what they are doing
the mouseSensititvity is probably cranked up more than it needs to be
1000
actually with 1800DPI its really good
sooo... this is annoying
sphere collider?
uhh ook lol keep your mouse as is, watch what happens later
hmm... so the collider with the smallest surface area.. contacting the wall
you mean those random jumps of camera were because of that?
quite possible, there are many things it messes with because again MouseInput is already returning the moved amount between frames, so its already framerate independent
so I should only remove the time delta and I would be ok?
not impressive annoying
u can multiply it w/ a sensitivity variable.. but i'd start at 1
yea u dont need time
from all the mouse inputs yes, this will be more noticeable later
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivityX;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivityY;
i do this
yea raw is good too esp if you don't want smoothing
wut is that
its just sensitivity and smoothing.. w/o the broken time.deltaTime stuff
The first line puts the input values into a Vector2
The second line multiplies the Vector2 created earlier by the sensitivity and smoothing
there ya go ^
yea I know but how ventor2 works in 3d?
shouldnt it be vector3?
no..
Does your mouse move in three dimensions
Later we'll use the created Vector2 to rotate the camera by the y axis and right axis
DEF
It's not in the screenshot though
they've tried those mice..
they suck apparently
like a big terminator arm contraption
3d mice... There's a point where you just work entirely with AR glasses and hand tracking
The bottom does the same as cs inputValues *= lookSensitivity * smoothing;
so i dont need the scale?
Using Vector2.Scale is a bit extra because you use the same value for x and y there anyway
ahh okay.. thanks for the heads up
i was just googling why i had used it in the first place
Vector3.Scale(float, Vector3) multiplies the Vector3 by the float
guys what does vector4 do?
used for shaders and stuff i think
It's just 4 nunbers
4 DIMENSIONS
like Quaternions
A Vector2 is 2 numbers, Vector3 is 3 numbers and Vector4 is 4 numbers
We love quaternions
π«
I removed the time delta from the camera
even with sensitivity 1 its unplayable
:/
you'll need to readjust ur values
obviously..
u tuned it to be good with broken code
now tune it to be good with correct code
Yep that's fine, you don't need Delta time when using Input.GetAxis("Mouse X") because the value is already based on the mouse movement that frame
π«‘ Brackeys
I mean if it works it works dont touch it
does it work
what about someone trying to play on a computer that isnt urs
my worked
will it work then?
yea
it's just 4 numbers. it might be 4 dimensions if you choose to interpret the 4 numbers as such
How about this, anywhere in your code add Application.targetFrameRate = 15
its simple to see how bad it is to use time.deltatime in ur mouse inputs
just build to standalone and then build to webGL and compare
one of em will be uncontrollable
WEBGL will be uncontrollable
:/
I HAVE SENSITIVITY ON 0.001 and I spin 20times
you can make your code so it has a different speed when on webgl
#define
ohh okay
seems a little overkill though
same as editoronly stuff
can someone help me tune the mouse input please?
I am dumb
your code should be able to scale for any platform
Are you dividing by the sensitivity or something?
Show your code
maybe your DPI is probably too high
A tool for sharing your source code with the world!
idk he told me to remove time.delta it worked perfectly with it xD
No it didn't
b/c its wrong..
yes you don't use Time.delta on mouse input
You just happened to have a stable frame rate so it's not noticeable
my framerate is around 1000 :/
then could you please show me the correct way of doing it?
π
Are you talking about Y rotation (left-right) or X rotation (up-down)
because I have no idea how to make it without time.delta since that is the only thing that teacher teached us
@noble cedar consider these 2 scenarios; assuming same monitor, same window size, etc
mouse moves horizontally, uniformly, 50 screen units over 1 second
scenario 1: 20 fps, so deltaTime is 0.05; 50 screen units per second -> 2.5 units per frame; mouse input * deltaTime = 0.125 per frame, for 20 frames, so 2.5 angular units total
scenario 2: 100 fps, so deltaTime is 0.01; 50 screen units per second -> 0.5 units per frame; mouse input * deltaTime = 0.05 per frame, for 100 frames, so 5 angular units total
when deltaTime is involved with something that already considers time, you get inconsistent results
sure, i'll show u my entire look script.. im using values like 1.5 https://scriptbin.xyz/efoyeravac.cs
Use Scriptbin to share your code with others quickly and easily.
where? In the inspector? Or in the code?
Because I see 100
lol..
in the code in unity
havent updated the web one yet
web? wdym web?
You need to change the sensitivity in the inspector
since it's a serialized value
You don't write code in unity. Did you change the value in unity's inspector?
uhmmmmm no I forgot you have to change also there :/
you don't have to change it in multiple places
if u expose it there u do
you can just... write it properly
if u right click on the menu bar and go to Reset it'll use the values u had changed in teh script
You do have to adjust it in the inspector if the default value was already serialized once
but it'll lose values u've added in manually
ok sensitivity 1 feels like I am playing valorant again :/
and if you treat the default value as just the default, you can change only the inspector value
thats an improvement tho..
NOW u wont have to worry about other people having different sensitivities
Sure, but probably don't wanna keep 100 as the default right now lol
what u have.. other ppl will have
I want to make somehow that players can make their own sensitivity somewhere in settigns to ill read more unity docs to know how to make menu :/
yup, thats a whole different can of worms
uhmmmm I smell another 2 months alone just making menu xD
for that i use a settings gameobject with all the values i need.. when the game starts it'll change things like my mouselook script
Can anybody help me with this?
we can surely try. momentum controllers are fun
since my project took me around 3months I feel like menu will be just 1 month alone
making the menu would take u no time.. wiring it up takes the time
also can I share another code here
I just wonder why when I switch guns the gun that was reloading never stops reloading
A tool for sharing your source code with the world!
please dont kill me for my code I am dumb
is this a unity bug? tree branch tips are randomly pointy
public void DrawTree()
{
DestroyPreviousTree();
GameObject lineObj = Instantiate(lineRendererPrefab, transform);
LineRenderer lineRenderer = lineObj.GetComponent<LineRenderer>();
lineRenderer.positionCount = linePoints.Count;
for (int i = 0; i < linePoints.Count; i++)
{
lineRenderer.SetPosition(i, linePoints[i]);
}
}
the mesh looks screwed too, maybe something to do with linerenderer setup but couldn't figure it
Yeah it's because there are shallow angles so it adjusts the vertices. You can edit the "end cap" options of the renderer
I see I think at the end branch (leaf) it tries to render a line backwards which causes the problem
Please help I am stuck
can you try to debug it by putting a breakpoint where the isReloading is set and trace back from the callstack
Hi stuck! Im spawn.. its probably b/c Reload coroutine is still running even after switching weapons.. and possibly also seperating it from the thing that needs to stop it..
ez solution would be to stop the reload before switching weapons
maybe track how much time elapsed b4 it got stopped also.. so if u swap back itll not have to do the entire thing again
but thats #archived-game-design up to u
What type do i use for prefabs? gameobjects?
what else would you use lol
prefabs are templates to gameobjects
If i wanna reference to a prefab to switch it after an action
what kind of prefab ? switch it from what to what
if you have components on it you generally refer to that component directly
Lets say blue window, then I interact and switch it to green window
yeah so just swap the gameobjects, not sure where prefab comes in
are you instantiating it?
they either both exist at the same time and u disable-enable them
or u spawn them in and destroy them.. u can do this with some other script referencing either the gameobject or the prefab.. (also as a gameobject i guess)
Oh thanks
I know but since there's going to be a fair amount of them I'll just do prefabs cause its easy to manage right now
might want to learn about pooling if theres too many of them
so not windows? haha
Nah it was just an example xd
So when I chop the tree down I want the stub or whatever its called to be left
hi i am trying to make a lawnmower in my game and add a push mechanic to it but when i press e and start pushing my lawn mower freaks out. i am using physics joints because i want the lawnmower to feel heavy and wiggly. does anyone know how i can make the push mechanic i want? the lawn mower is the thing in the top right of the picture it just orbits around me.
π 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.
Hips.GetComponent<ConfigurableJoint>().targetRotation = Quaternion.Euler(MoveDir); can someone help me with this?
You have to actually say what the problem is
Stump just incase u want accurate naming π
Yeah I realized
anyone else have this problem when u tab in and out of vs studio?
same.. but its happening like non-stop now
pretty sure that's a windows issue as i've had that happen with numerous programs, not exclusive to Visual Studio studio
Alt+Tab is broken
its not rotating
you should check #854851968446365696 to see what you should include when asking for help
To be in more detail, any way thats lets me ditch the capsule and use purely the characters real mesh for collision
There is a reason almost every game uses a capsule for character hitboxes
thats not clearing up why you would do such a thing.
And the ones that don't use a capsule, it's usually because they can get away with a cube
less math = better performance
ik
Precise collision for each body part for example
thats what capsules are for
Im aware its performance harsh and less uncommon
they are an approximation
I want like perfect accuracy
all games do that
Yes I know
I can understand if it was like a human body part selector for a like a medical app where you ray onto mesh colliders, but a character controller?
in Unity you can only use Convex MesheCollider for Rigidbody / Physics movement.
I may have got the terminology wrong
Right, so if i want to make a character with complex collision, i need to make its movement based on either rigidbodys or purely phyiscs?
Is that correct?
only if you don't want to calculate your own collisions
That sounds like a lot of math π
exactly
thats the purpose usually using an engine for, someone else did the heavy math for you
It is, that's why everyone uses capsules
Ok, now back to the original question kinda, do you have any resources on either a rigidbody or physics based character?
there's plenty
Google gots u covered on stuff about basic physics
do you want to create your own controller or use a premade good one
what are you trying to accomplish
iteration speed , etc.
If using a premade one lets me use the precise collision i wanted yeah
Creating an own controller would be like manually setting up movement etc?
are you trying to just have something that just works or do you want to code everything of a character like friction, airspeed etc.
Lets go for just works for now
I dont want to code everything from scratch
also unity has starter assets too for CC
I did look at that, but i felt like an idiot cuz i could not get the example working!
It just wouldnt move for me
even KCC just uses a capsule collider
I even checked its yt video
strange, its a bit of a learning curve but it has so many features
That was the other thing i noticed
I wasnt sure how i would change that
in most cases you wouldn't
I have the basic third prson one but its capsule based too
Have you determined that anything isnt actually precise yet? Because most games dont even have "precise" collisions like this in the first place. Only games with active ragdolls, and in which case the movement is usually very goofy and not realistic at all
your players are not going to notice
why would you even need anything other than a capsule for the movement?
Yeah every game has clipping
Even ultrarealistic ones like bodycam
I know you can use a paintbrush to paint on prefabs using a terrain but is there any way to do this using a plane instead? Im wanting to just place various trees changing the orientation and size around on a plane but not really seeing any easy way of doing this unless I use a terrain instead
its simply not worht the math to be so precise
Ok thank you for the help guys, i reckon i will just go down the active ragdoll route
Is there a way to make a border around objects? Like without making a new object?
i think polybrush can do it but not sure
also not a code question
sorry if i looked dumb π
I want the left side (game view) to look more like the right side
My suggestion of that isnt even telling you to use an active ragdoll. You really shouldnt unless that's the literal design of your game
This really just sounds like "I think my characters will clip into walls" when it really wont.
And you'll have a hell of a time when you realize how shit active ragdolls are
Im just trying ot learn things, i havent got anything to change
I know most games use capsules but i have speicifc use cases for that precision
these are objects created by a script, so I'm not sure how to implement a shader on it, is it just like mesh.AddComponent<Shader>(); or smthn like that?
what specific use cases would those be
thats how I added the renderer and filter
my enemies have 1 capsule to move but their body parts have a bunch of primitives to approximate humanoid like euphoria type
For precision hits like rays
i don't know what that is, but the actual control (ie movement) does not need to use the same collider(s) as the actual hit detection
so each limb is like its own capsule?
yea or sphere
its closest to mesh I can get and gives good results for hits
It doesn't really sound like you're even sure of the design. Afaik, tabs does use active ragdolls which gives it the goofy look. That isnt a requirement of an object being able to move
You should have separate colliders for hitboxes and an overall capsule for movement if you dont specifically want a ragdoll at all times
hi
can someone help me with this?
i have a problem with my sliding mechanic
also i added some logs to see if the slide is working or no
here is what is happening: when I press the button for slide in the unity's editor console it will say "slide initiated" but the player doesn't do anything and stays where it was(it can still go left or right or even jump and wall jump)
i noticed that my player's movement script is overwriting rb.linearVelocity that I'm trying to change in my player's slide script.
i tried to disable the player's movement script when the player slides but it didn't help me
i also asked chatgpt for a solution but even chatgpt couldn't solve it
can someone help me please?
here is the player's movement code ->https://paste.myst.rs/p4jjz1uo
and here is the player's slide code -> https://paste.myst.rs/buouexbt
please someone help me i don't get it
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
But what if you needed like precise hand or foot collision? you cant do that really with a capsule
did you not just read what i said
Sorry it scrolled out of view
and if you mean climbing holding ledges or walking stairs, most of the time its just visuals aka IK
Ah
So i can use capsule for ground collision and movement
And then mesh collsiion for hits?
like bullets
or i can go the active ragdoll route
Ok
i get it now
I had assumed other collisions just got overriden by the capusules one because my character kept falling for the ground
But alr
ty guys
I wish there were VCs where people could get help with a screen share active, that would make it so much easier for the people helping and the people learning
just make sure the layers ignore each other
layer based collision unity
can someone help me with this?
You were already given an answer the last time you asked: #π»βcode-beginner message
You can't have the slide code in a separate component, all movement has to be handled in the same place
I still need un poco help on this,
essential context: these are gameobjects that I create through a script in an 8x8 pattern to create a chessboard, I was wondering if there was a way to add borders to each piece so they were distinctive eg. the game view on the left looks more like the scene view on the right
!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.
If they're all distinct objects, you could just change the sprite/texture to one with a thin gray border
GameObject tileObject = new GameObject(string.Format("X:{0}, Y:{1}", x, y));
tileObject.transform.parent = transform;
Mesh mesh = new Mesh();
tileObject.AddComponent<MeshFilter>().mesh = mesh;
tileObject.AddComponent<MeshRenderer>().material = tileMaterial;
tileRenderer = tileObject.GetComponent<MeshRenderer>();
Vector3[] vertices = new Vector3[4];
vertices[0] = new Vector3(x*tileSize, 0, y*tileSize);
vertices[1] = new Vector3(x*tileSize, 0, (y+1)*tileSize);
vertices[2] = new Vector3((x+1)*tileSize, 0, y*tileSize);
vertices[3] = new Vector3((x+1)*tileSize, 0, (y+1)*tileSize);
int[] tris = new int[] {0, 1, 2, 1, 3, 2};
mesh.vertices = vertices;
mesh.triangles = tris;
tileObject.layer = LayerMask.NameToLayer("Tile");
tileObject.AddComponent<BoxCollider>();
mesh.RecalculateNormals();
So like in the material menu my tile material where would the option to make it have a border be? All of the surface inputs stuff changes everything about the material
it would be in the texture you assign to the material.
this isn't a code question btw
Sorry
got this little snippet, problem is it doesn't completely stop rotation of the object, how would i fix this?
That sets the object's current rotation to 0. If it's currently rotating it probably has angular velocity
If you want it to stop rotating where it currently is, that's what you'd want to set to 0
i want it to not be able to rotate at all tbf
or if you just want to prevent all physics rotation, constrain the z axis rotation on the rigidbody2d component
constrain the rotation in the inspector
Then freeze the rotation in the inspector
oh that's a tab i have not seen before, thank you
i will start opening more of the menus probably
make a reference from one script to another, access the field and assign value
same as you did with text component
Yeah i got it all done, i doubted myself hahaha
any reasons why netcode isnt showing up when i try to add a component
wdym by "netcode showing up"? What are you expecting to see exactly?
netcode isn't a component?
i mean network manager π
you've installed the netcode for gameobjects package, right?
is the netcode package installed?
yup
and for entities
why entities?
will be adding later
are they supposed to mix? I never used both together
maybe check Console tab for compile error or something
oh i don't know for sure just assumed that entities like npcs come under that catagory but maybe i am wrong, π first time creating a multiplayer game
that's not what entities is
ECS is completely unrelated to npcs
ah right
sorry but if you don't know difference between gameobjects and entities, should you be doing multiplayer? π
Look at the list, is this a decent inventory setup?
i mean first time making a game at all in unity previously done server side anticheats for other games so thought it could give a decent starting point however i am wrong! π
thanks though works now β€οΈ
Nice, what games?
oh okay, is just a lot of nuances to unity api
unturned ark and minecrat π
yea π¦
You work for BE?
no no no haha i mean as in server side mods and plugins as anticheats
not the actual game anticheats, they dont seem to do much these days....
BE works great other than client side cheats and bandwidth abusing
which is the biggest problem though
Yea so i make stuff which analyzes headshot percentages, angle of hit relative to players etc stuff like that that isnt in battleye since they cant make it specific to every game that uses be
oh i see
is there any possible way to default the code editor to vscode instead of visual studio code? when opening scripts?
"vscode instead of visual studio code" ?
anway check !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
visual studio vs vscode*
ty
why doesn't this work for legacy text input field
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class LobbyInputClick : MonoBehaviour, IPointerDownHandler
{
private InputField inputField;
private TouchScreenKeyboard keyboard;
private void Awake()
{
inputField = GetComponent<InputField>();
}
public void OnPointerDown(PointerEventData eventData)
{
inputField.Select();
// Force the keyboard on mobile
if (Application.isMobilePlatform)
{
keyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default);
}
}
private void Update()
{
if (inputField.isFocused && Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
Vector2 touchPosition = Input.GetTouch(0).position;
if (!RectTransformUtility.RectangleContainsScreenPoint(inputField.GetComponent<RectTransform>(), touchPosition))
{
DeselectInput();
}
}
}
private void DeselectInput()
{
inputField.DeactivateInputField();
EventSystem.current.SetSelectedGameObject(null);
// Close the mobile keyboard
if (keyboard != null)
{
keyboard.active = false;
keyboard = null;
}
}
}
You may want to describe what doesn't work
I can't select it in simulator or game mode
Try adding logs.
When you select it, do the functions fire any logs?
oh it works in multiplayer play mode all good ty
https://paste.ofcode.org/c3GPa3hUjt8Ugh3J7anHBE
Can anybody help me implement something. This is my movement script and Im using it to do many things but im currently experiencing 3 problems.
-
When I was first testing I had the issue where when ever i jumped forward over a low wall, my velocity would still build up while against the wall causing the player to launch forward. To fix this, I added a collision flags check and used an if statement to stop movement until the character was above the obstacle.
-
Now I face the problem where I cant slide against a wall when jumping against it at an angle. I tried to fix this but I just cant figure out how to get both to work at the same time.
-
I also wanted to implement a crouch system similar to minecraft so I couldnt walk off edges when crouched. To do this I used 4 directional raycasts for edge detection, but theyre not reliable. Sometimes they work sometimes they dont.
Internal unity bug with graph windows, you can ignore it, it won't affect any builds
https://i.gyazo.com/17be082b84760c40361e30996fe1789e.png
https://i.gyazo.com/ae8eb10de946ac3c8ee4e8996e645c2c.png
Can somebody help me figure out why I'm getting a null reference on line 38 when instantiating the dagger?
Line 38 can't throw an NRE. Are you sure it's this script that's throwing the error? And that it's been saved and recompiled in case the line number changes?
Oh, wait, it can actually
transform.parent could be null
Does every object with a SubWeapons script on it have a parent?
omg, I was so convinced it was something weird w/ the dagger I didn't even consider that being the issue. Solved, ty lmao
I missed it at first too, didn't notice the .parent in there
Null reference errors only happen when you try to access a member(field/property/method) on a null reference. The only place where that happens on line 38 is transform.parent.position.
I have a SpawnManager game object w/ a SpawnManager script and some empty game objects to represent spawn points for both player and enemies. The player and enemies are prefabs that I spawn on Awake() of the SpawnManager script. It seems like my enemy is walking towards position.x of 0. My EnemyMovement script uses the player's position to drive its direction. Everything appears to be connected properly in the Unity editor. Here's a video of what I'm seeing. I can provide code snippets if that helps. Any ideas?
// EnemyMovement script
private void Update()
{
if(!player)
{
Debug.Log("Cannot flip(), Player not found...");
return;
}
if(player.transform.position.x > transform.position.x && facingDirection == -1 ||
player.transform.position.x < transform.position.x && facingDirection == 1)
{
Flip();
}
}
private void FixedUpdate()
{
if(!player)
{
Debug.Log("Cannot move to player, Player not found...");
return;
}
if(!isEnemyDead && !isEnemyHurt)
{
float distanceToPlayer = player.transform.position.x - transform.position.x;
// Only move if beyond threshold
if(Mathf.Abs(distanceToPlayer) >= 0.01f)
{
Debug.Log("moving enemy...");
Vector2 direction = (player.transform.position - transform.position).normalized;
rb.linearVelocity = direction * moveSpeed;
anim.SetBool("isChasing", true);
}
else
{
Debug.Log("enemy too close to player, stopping movement...");
// Stop moving when close enough
rb.linearVelocity = Vector2.zero;
anim.SetBool("isChasing", false);
}
}
}
private void Flip()
{
if(isEnemyDead)
{
return;
}
facingDirection *= -1;
transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z);
}
since your enemy is a prefab it's almost certainly just referencing the player prefab or something
you can see here the editor has the player prefab assigned
yeah
exactly
the player prefab
And if you look at the player prefab guess what its position is?
how should I handle spawning a player and enemies?
it's 0
you need to give the enemy a reference to the actual player instance in the scene. Your spawning script can do this
Thank you, I suspected this was an issue
e.g.
public Enemy enemyPrefab;
public Player playerPrefab;
private Player playerInstance;
void SpawnPlayer() {
playerInstance = Instantiate(playerPrefab);
}
void SpawnEnemy() {
var enemyInstance = Instantiate(enemyPrefab);
enemyInstance.SetTarget(playerInstance);
}```
The structure you want is something like this
the spawner spawns the player and can hold onto a reference to it.
It can then pass that reference to the enemies when it spawns them
I'm using this code, but I'm getting this error in the console for the Enemy and the Player: The type or namespace name 'Enemy' could not be found (are you missing a using directive or an assembly reference?) Why does it not like the datatypes Player and Enemy?
The offending lines in VSCode:
public Enemy enemyPrefab;
public Player playerPrefab;
private Player playerInstance;
I mean... my code was an example
you naturally have to use the classes and script names that actually exist in your project.
Could I use GameObject instead and drag the in scene Player and the prefab Enemy?
you could use GameObject but why would you want to make life harder on yourself like that
Use your actual script
so you don't have to mess around with GetComponent and stuff
in your case Enemy -> EnemyMovement
for the player you could just use Transform I suppose
I'm new to game dev programming. Ahh, ok I'll try that
Using GameObject variables is often the wrong choice and just makes your code more verbose and more complicated than it needs to be.
Directly referring to the components your code is interested in is the better choice
So in my case, line public Enemy enemyPrefab; would become public EnemyMovement enemyPrefab; ?
I think I misunderstood previously. So this would go in my EnemyMovement.cs not SpawnManager.cs? I'm still trying to understand how a spawn manager should properly behave
I very explicitly said this was code for the SpawnManager
Look at what the codce is doing
it's spawning players and enemies
the enemy would not be doing that
how do i refer to a list from another game object
like any other variable
but - I would recommend letting the owner of the list manage the list
depending on what you need from the list exactly - there is probably a better way than directly passing around the list itself
ok
I updated the datatypes to EnemyMovement and PlayerMovement, but it's still complaining EnemyMovement doesn't have a func called SetTarget(). I assumed it was a static method it inherited from somewhere. I see this is a real thing https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Animator.SetTarget.html. Why is this an issue?
EnemyMovement' does not contain a definition for 'SetTarget' and no accessible extension method 'SetTarget' accepting a first argument of type 'EnemyMovement' could be found (are you missing a using directive or an assembly reference?)
again my code snippet was an example
there is no documentation for your EnemyMovement class
because you wrote it
I was implying "you should make something like this"
I get that, I thought you were referencing some static class I hadn't heard of. Thanks for clarifying
It's a method, not a class
how am I supposed to handle multiple audio sources on one gameobject? Setting an audio source in a script takes the whole gameobject as an audio source
What's the use case? Why do you want multiple sources on one object?
Attempting this, but it's not assigning anything to the array, where SoundManager is a gameobject with three AudioSource components
you can drag individual components
Use case is I have a telegraph, it needs to hold keyDown, keyUp, and Tone
this will work fine but it assumes all the sources are on the same GameObject as the script
I figured I'd make one gameobject that was the sound manager and give it three components but it's giving me pain
if I try to assign an audioSource in the inspector, it takes the whole gameObject instead of any single audioSource
you can drag individual components
right click the object with the script and select "Properties"
this will open a separate inspector locked to that object
then you can find and drag the individual audio components from wherever you want into it
That did the trick, thank you!
π 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.
laser turret script https://paste.mod.gg/rxytlrgxovhx/0
A tool for sharing your source code with the world!
like the damage and everything works but the beam isnt appaering
do some debugging and see if any of those conditions are preventing your code from running. theres a lot of logic we cant see, and you should at least start by debugging to see if theres any line in specific thats wrong
another thing could just be checking the line renderer itself and seeing if you can even see it at all in the scene view, if enabled manually
I don't see anything in this code that actually calls FireLaster()
Also the code you shared has no Debug.Log so it's not clear where these are from
the link doesnt update, it shouldve generated a new link for you. id also double check if its even visible in scene view if you're sure the object is getting enabled
i think i should check the line renderer
cuz verything is working
its just the laser isnt appearing
did i assign the line renderer correctly?
you should be able to see that, if its actually visible in the scene
nope not visible in the scene
that width of 0 is probably the cause, been some time since ive used a line renderer
the width is 0.1
oh wait
i forgot to set the material length
oops
found the problem
forgot to set a value for the positions of the line renderer
https://i.imgur.com/e6Ys330.png
I don't use unity events too much besides stuff for buttons and other UI components where everything is present on the scene, but let's say I want to add unity events to this PageSO such that I want to call a manager when it ends. I'm trying to make sense of how this being on an SO can actually call any type of manager because it doesn't live on the scene.
Usually I just do some singleton call, but I was wondering if I can do anything similar without hardcoding too much
Like, you can target prefab instances, but you can't really do much with that right
you could call a function on another SO (or itself) or a prefab yeah
if you architect your game a certain way you could do quite a lot with that.
Wouldnt make too much sense though eh? I'm trying to make it somewhat accessible without having another dev have to implement their own singleton calls
It depends. You could make another SO that already has those singleton calls and then assign that SO's methods here
ultimately calling the singleton
It relies on the assumption the singleton will exist at the time of use
it doesnt have to necessarily be a singleton since this is an SO. the manager could just directly reference the SO and subscribe too.
I dont think there is a way to do what you want without adding logic to your manager game object though
if you use something like the Atoms arechitecture or use SO assets as singletons, then you get a direct line here
Which is an assumption which is bad but in the context of it being a relevant singleton based manager is a reasonable assumption to enforce
Like I can just instead use Serializable pages instead of SOs which would give scene presence, but it removes the ability to add pages dynamically (to my typewriter script/component)
Not that it's an unsolvable problem by any means but this does mean going the route of "saving runtime data on so"s in the form of the event's listeners right?
i dont really know what you mean by that route
nevermind read that wrong, apologies
What kind of practical usecases of this event did you have in mind out of curiousity
Up to the dev I guess. Say like some event to continue the game
in that case I'd probably want to communicate with the GameManager, but I assume an SO can bridge that right
This is just a thought that may or may not influence the way you wanna go about this but you might not want to leave the game continuing or not as such an open ended question a page SO has to answer
Yeah I probably wouldn't either, so maybe a better event would be to call an audio manager to play some SFX
Maybe something like this has the ability to do things in the event this page finishes and maybe it has control over in what way it ends but at least how i see this it feels a little scary to just pray the page makes the game go again
That's how I always feel when playing with any sequencing
eg. maybe you have a more free form "on page finished" event and then some more controlled, select-able setting to determine how the page wants the game to continue (because it's gonna continue regardless)
assuming its supposed to communicate with any manager, no matter what you'll need some logic that has this instance of the manager stored. If you use another SO, its still the same problem. The manager would either have to reference the SO and subscribe, or the SO would need to be passed a reference to the manager
One thing you could do is define an enum mapped to the actual type of manager assuming they're all singletons and access it that way... editor friendly but questionable code wise
I believe in some approaches to a setup like this though the page itself would only have the ability to do stuff when it ends (eg. do reactionary stuff like sfx and whatnot) and then how it got to that page and what happens after it's done to that page is handled by something managing the pages (eg. some visual graph based thing or something). Not saying you should do this but just that it might not be ideal to give the isolated page that much control
I think having another SO which has those singleton calls is probably the call. Ideally I wouldn't want anyone editing the actual tool code and would prefer that they make their own SO with those bindings
Which would mean I'd have to suggest that type of workflow to get the events to work
is there a reason you cant just add logic to the manager class, to subscribe on awake or something?
This would require the dev to write code for the tool to function, but I guess what I'm looking for is that it should be code-agnostic and work as is
If they set up an SO bindings for the managers, that doesn't necessarily imply that it's made just for the tool
Maybe I'll just ditch the idea and keep events local to the component. I thought having some per page would be a neat idea but seems like a pain
If the editor setup is really beneficial it doesnt seem like that bad of an idea honestly. It does kinda force every manager to be a singleton and having to keep this list of singletons up to date though
Im not so big on unity events in SO, it always does seem like a pain
I've always heard of people using them as event buses and seems like a neat idea, but it's not something I think is too common enough to expect people to make
I've seen that stuff in some tutorials and I dont think it's useful. Ofc it was always presented as "decoupling code" as if that was true, and being able to send events throughout scenes
It very clearly would run into issues once you need to setup a lot of them. I couldnt imagine trying to find why a method is getting called, then suddenly I gotta find whats invoking a method on an asset, which is subscribed to an asset, which a GO is notified about
It's kinda a half measure compared to something like unity's recent-ish visual graph tools (in concept anyway)
I won't elaborate on anything specific but the mod API I made for a game allows people to make custom levels and such in editor without the requirement of any custom code whatsoever and the more inventive people have ungodly amounts of components on certain objects feeding events into events into filters into events into etc. and it gets messy fast. it's just a poor mans visual scripting solution
For implementation on that specifically I had code based events for various gameplay related events (entering an interior, a player dying, a player equipping an item, the hour changing etc. etc.) in the API and then had a separate mod/tool that acted as like a serialized wrapping around all of those which had components that middle-man unityevents into those actual ones
This kind of lets you have three different layers of implementation and usage that consist of
-the backend where all the actual code is running, in where you could/should/may implement code exposed events for when gameplay mechanics happen and accessible functions to manipulate the game
-the kinda middleend where you create behaviours/so's/classes etc. that convert code that can listen to gameplay events and invoke gameplay invents into serialised designer friendly puzzle pieces
-the frontend where you can mix and match those pieces in the editor
example of one of those middle pieces
namespace LethalToolbox
{
public class PlayerEnterDungeonEvent : NetworkBehaviour
{
public UnityEvent<PlayerControllerB> onPlayerEnterDungeonEvent;
List<EntranceTeleport> whitelistedEntranceTeleports = new List<EntranceTeleport>();
public void Awake()
{
LevelManager.GlobalLevelEvents.onPlayerEnterDungeon.AddListener(OnPlayerEnterDungeon);
}
public void OnPlayerEnterDungeon((EntranceTeleport, PlayerControllerB) teleporterAndPlayer)
{
if (whitelistedEntranceTeleports.Contains(teleporterAndPlayer.Item1))
onPlayerEnterDungeonEvent.Invoke(teleporterAndPlayer.Item2);
}
}
}
could someone please help me with fixing that player is sticking to walls? I can provide code if needed
!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.
A tool for sharing your source code with the world!
also somehow when you are sticking to wall when you press A or D you wont move, camera rotates there
mouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
transform.Rotate(0f, mouseInput.x * sensitivity, 0f);
I have these lines of codes for my y axis rotation. but for some reason it jitters while i move the mouse. anyone has any idea why? Thanks
I am little bit inexpirienced but if I am correct you should use transform ONLY when you want something to teleport
ohhh. do you have any ideas on how i can rewrite the code? will transform.rotation = Quaternion.Euler(0, mouseInput.x *sensitivity, 0) work? (i suck with quaternions btw)
private void Rotation()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivityX;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivityY;
transform.Rotate(Vector3.up * mouseX);
float xRotation = cameraHolder.localRotation.eulerAngles.x - mouseY;
if (xRotation > 180) xRotation -= 360;
xRotation = Mathf.Clamp(xRotation, -80, 90);
cameraHolder.localRotation = Quaternion.Euler(xRotation, 0, 0);
}
this is my code for camera rotation
tho lets be real most people would kill me for that π
yesterday I has few people help me remake my camera script so I think this one is the correct one now
transform.Rotate(Vector3.up * mouseX);
this is the exact same line i use for my y rotation, but it still jitters
yea I have no idea why since for me it works flawlessly
can you show me your hierarchy setup? i think its because i have the main player as the child of my player object
as of now I am in school so I can not sent it ill try to find it in screenshots I was sending to teacher because I had few problems also but dont get your hopes up
oh alright. thanks though!
What's this rotation for? Camera?
yeah, a first person camera
What do you have it under, Update()?
yes
Try FixedUpdate() instead
FixedUpdate basically forces the camera to operate under 60fps conditions
Update() is too fast for camera controls so you'll get jitters
??? That's not how any of this works
That's what i understood 
Feel free to correct, but you do definitely want it to be fixedupdate
Use cinemachine. It's a premade camera that's better than what most people will write
Let the boy walk before running first
ikr π
If you understand the basic camera stuff then you can do cinemachine
is it easy to learn?
Cinemachine takes a bit of time
Please just stop offering advice when you arent even familiar with the basics either.
Can you at least correct me then please
Like say anything other than "you're not being helpful"
Tell me WHY I'm not correct
It is incredibly easy. There are tons of tutorials, its just a matter of choosing the correct cinemachine camera and then you can play around with the settings.
yooo the fixedupdate thing worked... its still not that smooth but wayy better than before
should i put my input function in the lateupdate as well?
Fixed update is used for physics, update doesnt "run too fast causing jitters". Theres nothing I can say to correct about that, it just simply isnt true.
The only reason youd use fixed update is if the player object moves via rigidbody AND doesnt interpolate which a player rigidbody should.
Cinemachine handles literally all of this you just need to select which update mode to use too
how did putting my rotation function in fixedupdate help though
If you really are gonna read the first 6 words and ignore everything else which is pretty useful information, I see no purpose in explaining anything further to you
What is your problem? Why are you assuming that I haven't read the rest?
You want to do all your input and game object movement in update, then update the camera in late update
I havent seen how you move the object, refer to my message above about why you could use fixed update but ultimately shouldnt. The player being a rigidbody should use interpolate, or it might look choppy for people with high end pcs.
this isnt beginner code stuff this is advanced shit xD
It kindaa is beginner, i have interpolation in my movement too
It's not that advanced, just some couple extra steps
It is about as beginner as it gets when we're literally talking about how objects move.
yea but how cinemashine is beginner stuff
cinemachine isn't some advanced thing, it probably can be if you get really deep into it
Because it's a plug and play solution. No beginner should write their own camera if you are intending to use it in your game. Sure you can learn using it but, it's simply not going to end well
Cinemachine requires no custom code, you literally just choose a camera. How much easier could that get?
okay so lateupdate didnt work. fixedupdate is the only thing that helped. i heard someone say its not good to put the main camera under a rigidbody, is that the issue?
It's completely fine to write your own camera, it helps you learn how everything works behind the curtains
Plus you'll get more used to coding your own components
tbh I am just going thru docs and cinemachine is somewhere I havent gotten to yet
π
You may want to have your movement interpolated, I don't have the code on me right now, but it's basically adding one extra line
ohhh. if you dont mind explaining can you tell me what is does basically? i like to learn my stuff before using them hahaha
Because if you fixedupdate on a non-interpolated player, then high end pcs do get jittery
Can you screenshot the rigidbody?
Truthfully I wouldnt have it underneath anyways but remember rigidbody moves within the physics loop (like fixed update). If you have interpolate on, it will smooth the movement and move every frame. The camera would also do the same as a child object
Interpolation is basically the computer calculating extra frames between an object's position
also while we are here could someone help me with this please?
ooooohhh
If you've seen those "60fps anime fight" videos, that's where you can see interpolation
(they look horrible btw lol)
But for stuff like physics it's really good
Because it reduces the jitteriness of physics simulations
ohhh i see
And it's literally just one line to your movement code
Not even that, just a statement i believe
I think it's like an extra parameter to your rigidbody
yeahh it is turned on
see? i put my interpolate to interpolate
Hmm i need to check mine later, I know i enabled interpolation within code
try setting the friction of the wall to 0
Within the inspector it "could" be different, but i could not explain why it would be if it was
the wall has only collider
you cant set friction there
yeah
I tried that didnt help also somehow it broke my other script
very peculiar, it shouldn't affect other scripts
With networking there could be a ton more reasons than what we see here.
#archived-networking or the unity multiplayer server pinned in there is where youd want to post this. though truthfully if you're a beginner you shouldnt even be touching multiplayer
my multiplayer works correctly as of now
I have been working with unity for 9months now
I just ran into this problem for the first time
or maybe even earlier just hadnt notice it
so do i leave my rotation script in fixedupdate or do i switch to cinemachine?
That doesnt change anything about my response, if it uses netcode at all then it's more appropriate in the other channels. If you're doing multiplayer you should be familiar with how to debug though.
I STRONGLY suggest you reconsider multiplayer. This is the advice many others would give as well
Hi what's the function of touching colliders? like ontriggerEnter2d(){}.
In the end you're better off with cinemachine but i do recommend you figure this out with the manually coded camera, you'll learn a lot
Oncollision?
yeah
#π»βcode-beginner message
Up to you. I dont think you'll learn enough from it at this point because making your own isnt completely trivial
Yea oncollision is the touching of colliders lol
π
but why would I remake my game now when basicly this is the last thing that needs fixing? also should I really switch to Networking even tho its mostly just normal code with few changes?
true, i want to use manually coded camera as well, but i've been stuck with the movement for 3 days and i dont want to spend more time
I'll get home soon and send you what I have, if it helps then great, if not then it's up to you
alright. i want to try and use quaternions instead of transform.rotate, can someone help me with that?
or does it overcomplicte things?
ohh.. i still want to give it a try though
Oh yes you definitely do want to know how they work
They're very useful
From what i saw that you posted earlier, why not give it a try?
The snippet you sent
This isnt even close to the first time I've seen this exact ideology of "I just need to fix this one thing!"
Also yes it's more appropriate because if anyone helping you in here isnt familiar with how network transforms (or even ownership) work then they could entirely miss what the real problem is. I didn't fully look line by line to see what your issue was (because on mobile the website keeps going blank) but you should really add debugs and see why things dont align with what you think.
alright! transform.rotation = Quaternion.Euler(0, mouseInput.x *sensitivity, 0), this you mean right?
Yea give it a try
It's better if you try it, and then ask why it doesn't work - than to ask if it would work beforehand
might be just my idiocy what about checking every time if player is grounded which I already have for when he jumps and if he is in the air for more then idk 0.5s it will forcefully add velocity down?
let me go try that brb
nope it does work. it doesnt even let me move along the y axis this time, it just snaps back. i was able to move it with jitters the last time around
With what you describe, the issue really just sounds like you are using the default physics material. You should assign one that has 0 frictions to the player
Oh i just noticed, you might want to try either *= or +=
Quaternions are a little silly like that
yea but how come when I add new physics material to it my script which checks collider (its shop) suddenly breaks
π€·ββοΈ it's not like your monitor is physically breaking when this happens. "It breaks" is not an actual error
Surely something more specific is happening
i can move it this time, but with more jitters hahahaha
if i were to not put my main cam under the rigidbody, what should i do?
Don't take it off the player
Unless you're using cinemachine there's no reason to really take it off the player
You'd have to make the camera follow the player's position in code, which would just make it more jittery
let me try debug the problem first before I go whinning about it in chat
π
I'm using unity Netcode For Gameobjects and following the tutorial https://docs-multiplayer.unity3d.com/netcode/1.11.0/tutorials/get-started-ngo/. I am up to the HelloWorldManager.cs script part and have pasted the script. However, error message Assets\HelloWorldManager.cs(34,43): error CS0120: An object reference is required for the non-static field, method, or property 'HelloWorldManager.m_NetworkManager' shows up even though I copy-pasted the code from the tutorial. How do I fix this?
Use this guide to learn how to create your first client-server Netcode for GameObjects project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects.
so you mean i should move my slide code into my player's movement code?
oh mb
- that documentation is outdated, the page says it
- #archived-networking is a better place to ask
yea idk I created new physics material but I am still sticky to walls
Change that friction combine to whatever the minimum option is called
I think the default is 0.6 (been forever since I've created one, could be wrong). So an average in that case would be 0.3
you are the best thanks
also my problem was that I have been stupid I forgot to add in inspector in my shop Prefab to show what gun you are getting π
I'm using unity 2022.3.54f1 and I can only download netcode for gameobjects 1.11.0
I would recommend using the unity 6000.1 version they remade whole networking there
How do I upgrade unity to that version?
you download it in unity hub
Then you backup your project if you aren't using source control before you begin.
source control?
Git, unity scm, SVN, perforce.
easy start is using git with github
oh so basicly somewhere to put your code?
Yes, source control systems are used to track all changes made in a project so you can go back in time, have multiple branches and collaborate with others easily
oh yeah you definitely want to use github
starting out at least
even as a solo dev it's super nice
if you messed something up you can just go back to the last commit you made (like rob mentioned)
lets remember that Github is a online host for a GIT repository. Others exist such as gitlab.
though i recommend github desktop for managing the repo for beginners
my dumb ass just made copy of the whole project xD
also @hidden marten I'm home, so can you send the script for the player movement and the camera look?
Hey when i started out I did too but we learn!
narr π hahaha
yea don't do that, you're also wasting a lot of space on your pc (since the unity libraries take up a surprising amount of space)
because I had single player game but for our 1y project to pass the school year it wasnt enough so I had to remake it into multiplayer :/
surpisingly it takes up 10gb the copy :/
when you set up your source control, there's a thing called ".gitignore", make sure you have it set up for unity
on github desktop its really simple, it's literally just a dropdown tab
that will prevent "too large file size" commit errors, just because of those libraries
you mean the Library/ folder.
Some plugins such as firebase have actual lib files that are too big (which require something called git lfs to commit properly)
yep
this will only help up to a certain point though, if you have some crazy large assets (or just a large amount of them in general) then you'll have to set up git lfs or switch to something else like Perforce
for a student project don't worry about it too much though
that's gitlfs, not gitignore.
Use the gitignore to not upload the things you don't need to backup (ie: library folder), and gitlfs to commit large files correctly
don't they "kind of" go hand in hand though? since the library folder is quite large, and you'd need git lfs to commit it (if you didn't have gitignore for it)
no, they don't
makes sense
gitlfs is for single files, and the library folder is ignored
because I remember doing my first project, and encountering the same error
I did the gitignore, and the error was solved
well it's not an "error", more so that it's just git asking if you want to set up LFS
yea you are meant to not include anything in Library/ but a file being too big is another problem
ahh i see
you only need to backup these three folders of a project
delete this and shar !code correctly π
π 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.
@hexed terrace @grand snow thanks guys, understand git a lot better
A tool for sharing your source code with the world!
sorry for the delay i was eating lol
no worries lol
ok so one thing that i see right away is try putting the moveplayer and the movemouse under fixedupdate
since i assume the movemouse was your camera controls
because you're moving your player with physics, so fixedupdate works perfectly for that purpose
true. but moving mouse doesnt really use physics. like i said earlier, it kinda works when i put move mouse in fixed update. should i leave it there and move on?
you could also have the movement in fixed, and mouse in late
also side note, but yep having interpolate set up in inspector or code is the exact same, so you did fine there
nope doesnt work
Show the code
skip a bit to the end lol it takes a long time to run
(also i didnt clamp the x rotation yet)
i had to watch the whole thing because for some reason discord didn't embed it correctly lol
so in your code i'm seeing that you're multiplying your mouse movement multiple times by the sensitivity
so first you do it in myinput, and then you do it again in movemouse
that could be why there's some weird behavior
oh you actually do it for the third time in movemouse when you do the transform.rotation
you only need the sensitivity from the input
i removed everything, it still jitters
send code
A tool for sharing your source code with the world!
hmm ok i'll boot up a project and run it there, maybe i can spot something better that way
so i'm thinking there's two possible issues,
one is that you might want to multiply time.deltatime for the mouse movement
the other is that instead of using linearvelocity, you use addforce
addforce is probably a lot better than linearvelocity
addforce?
yeah...
oh its quite simple actually, let me see
and the only issue i have is with the mouse movement, not with the player movements, the movement is pretty smooth
well the player movement is tied to your mouse movement, which is what might cause issues
even if this was true, why is putting it under fixedupdate working
putting the mouse movement under fixedupdate?
yeah
hmm trying it from my end, it makes the camera a bit more jittery
also i really recommend to separate the keyboard inputs into two:
horizontalInput
verticalInput
(you'll also have to do this for the mouse)
in your myinput, the mouseinput section
like this?

its still jittery π
Why wouldn't it be?
FixedUpdate most of the time only runs once every few normal Update loops.
it worked for you?
yeah it seems to work completely fine for me
can i get your script?
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public Camera cam;
public float speed;
public float jumpForce;
public float sensitivity;
private Vector3 keyboardInput;
private Vector2 mouseInput;
private float xRot;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
rb = GetComponent<Rigidbody>();
}
void Update()
{
MyInput();
}
void FixedUpdate()
{
MovePlayer();
}
void LateUpdate()
{
MoveMouse();
}
void MyInput()
{
keyboardInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
mouseInput = new Vector2(Input.GetAxis("Mouse X") * sensitivity * Time.timeScale, Input.GetAxis("Mouse Y") * sensitivity * Time.timeScale);
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
}
void MovePlayer()
{
Vector3 moveVector = transform.TransformDirection(keyboardInput) * speed;
rb.linearVelocity = new Vector3(moveVector.x, rb.linearVelocity.y, moveVector.z);
}
void MoveMouse()
{
xRot -= mouseInput.y;
transform.rotation *= Quaternion.Euler(0, mouseInput.x, 0);
cam.transform.localRotation = Quaternion.Euler(xRot, 0f, 0f);
}
void Jump()
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
it's basically the same
i tried to not adjust your script too much in order to see if it was just the timescale
im using your script and im seeing the jitter still π
at this point i can't really tell tbh, it could just be an editor thing - try building the game and see if it comes up there
Are you guys sure your values of the component are the same in the editor?
I'll take a look
Other then that, your FPS in the editor might be the same as the FixedUpdate speed for example, and you might not notice the delay.
I changed my values to be the same as his, I don't see any issues
can i just put it in fixedupdate and forge about it lol
i mean if it aint broke you dont gotta fix it
no. Camera rotation/movement HAS to happen in LateUpdate
didn't it stutter in fixedupdate too though?
no it works perfectly
i spent 4 days on just the movement π ion wanna make it 5
also i would actually try having the camera be separate from the player, so not as a child to player
i know i said it wasn't necessary but honestly it would probably work better
no worries you'll solve this within minutes
and then updating the camera position to player in update
the issue if you put it in FixedUpdate is that the updates aren't smooth
that's because Physics (like RigidBody movement) DO interpolate
but the camera movement doesn't -- because there's no built-in functionality for that (it's outside physics)
the stutter you're encountering is likely because of edge-case synchronization issues, so just gotta ALSO update sometimes in FixedUpdate lol
and a potential issue is this:
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
void Jump()
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
here you're just adding force IN UPDATE
which isn't necessarily wrong, but not ideal. there's a recommended pattern for that
void Update()
{
keyboardInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
mouseInput = new Vector2(Input.GetAxis("Mouse X") * sensitivity, Input.GetAxis("Mouse Y") * sensitivity);
wantsToJump = Input.GetKeyDown(KeyCode.Space);
}
void FixedUpdate()
{
Vector3 moveVector = transform.TransformDirection(keyboardInput) * speed;
rb.linearVelocity = new Vector3(moveVector.x, rb.linearVelocity.y, moveVector.z);
if (wantsToJump) { rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); }
wantsToJump = false;
}
but primary issue is that you're moving rotation like this:
transform.rotation *= Quaternion.Euler(0, mouseInput.x, 0);
but in physics, you should be using rb.rotation IN FIXED UPDATE