#💻┃code-beginner
1 messages · Page 748 of 1
you wrote IPlayerLocomotionActions
thanks
i didn't see that
now i am getting this Assets\Adam O'Keefe\FinalCharacterControler\Scripts\PlayerLocomotionInput.cs(16,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
this is all yopu copying the code incorrectly
oh ok
Note that this: PlayerLocomotionInput.cs(16,13) is telling you the filename, line number, and column number of where there is an issue
that's a good place to compare your code to what is in the video
(I know )
lol
Hello how are you I don't know English but I need help
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
Sorry
It's that the problem doesn't come out on yotube is that I get that unity doesn't have permission
@nova saffron Don't cross-post on the server and this is unrelated channel as well.
Hi, I'm trying to make an object appear at mouse position (At the point a raycast hits another object),
(In a 3d, first person controlled project)
I know I need the point hit by the raycast, and to transform the object to the position (accounting for its dimensions), and to get the side the raycast hits (wich also probably implies rotating the object to match the face I'm looking at)
(Like this, https://www.youtube.com/watch?v=1ecYZXNneu0, but in first person)
I don't really have much experience on Unity and I'm trying to learn, without using AI (As it's wrong most of the time), where could I learn how to do so?
Jessie becomes a new power From the foundation.
what do you want to know, its pretty much done how you say it Instantiate it the raycasthit.point
I'm having some trouble creating a script that just seamlessly loops the background for an endless sidescroller. Does anyone have any advice?
using UnityEngine;
public class BackgroundScroller : MonoBehaviour
{
public Rigidbody2D rb;
public float scrollSpeed = -2f;
private float width;
void Start()
{
// Get collider and rigidbody
BoxCollider2D collider = GetComponent<BoxCollider2D>();
rb = GetComponent<Rigidbody2D>();
// Get width of the background tile
width = collider.size.x;
// Disable collider if it’s only used for measuring
collider.enabled = false;
}
void FixedUpdate()
{
// Move the background left each physics frame
Vector2 newPos = rb.position + Vector2.right * scrollSpeed * Time.fixedDeltaTime;
rb.MovePosition(newPos);
// Check if background has scrolled off-screen
if (transform.position.x < -width)
{
// Move it to the end of the loop (seamless reposition)
Vector2 resetPosition = new Vector2(width * 2f, 0);
transform.position = (Vector2)transform.position + resetPosition;
}
}
}
I can get it moving, but the process of getting the first background to move to the second isn't working.
Why is the background a rigidbody?
Because that's what the tutorial I was following told me to do. The script uses it too.
If you're only moving the GameObject and it doesn't interact with anything else, I see no reason to put a Rigidbody on it. That's all . . .
Should I start with the process of scrolling in some other way?
When I did this, I placed a trigger collider off-screen. When the background hits the trigger, I reposition it on the other end . . .
its similar code just don't need the rigidbody / physics parts
all you're doing is check a position has reached a certain treshold and put it back
When the first background moves to the resetPosition does it line up with the second background?
I can't tell if it moves at all. Since when it moves all the way to the end of the two images, it just fails to produce anything and shows the blue screen.
I'll probably just reset everything and try a different scrolling background tutorial.
Blue screen? Isn't the second background that follows the first background currently in view on the screen?
tbh . look at multiple ones , dont need to commit to a specific one, this way you get the overall picture/workflow you need
more important learning the concept / process of it instead of blindly copying a specific tutorial
Yeah, it scrolls through the first background, and the second one, since there's two separate objects in the scene. But I'm just going to try one of the simpler methods first and come back.
Tiny thing but is there a way to use ContextMenu if the function has a parameter?
No, create a variable you can edit from the inspector to use as the parameter . . .
Thanks
hi im trying to change my first person camera to where i can look down and around to where i can see my shoulders with out my body turning with my camera but then if i look past that then my body turns. if you dont know what i mean, rust has this type of camera in their game. if someone can help me out or show me a tutorial that has this it would be very helpful.
its just a regular first person camera setup..
and the arms/body/shoulders is seperate gameobject of the cam
can do em procedurally, w/ animation, or w/e
you'd just want to adjust ur clipping planes
and make sure u clamp it so u can't look too far downwards / into the model
any camera setup/script would work.. i dont have a character mesh here.. but same concept.
if u wanted to make the arms follow the camera you'd use something like unity's animation rigging package i believe
to take control of the hands/ make them follow the camera's up and down rotation
or if its only arms/hands could just parent them to the cam
i used the unity animation rigging package so that my head and top body would follow what im looking at but realized its pointless if i the body is always following the camera
what did you child the camera to? i have it as a child to the whole player for mine
yea same..
- Root (the actual CC/Collider/Movement)
- Camera
- Graphics
Controller moves Left and Right (making the cam follow that axis automatically)
The camera moves Up and Down (relative to the roots rotation)
common way to do first person cams
make the body follow the roots rotation
make the arms follow the cameras rotation
edit: ahh, i see, ya to have the body moving in one direction and the arms moving in another direction you'd end up needing to change the way the movement works
to make the camera and body seperate you'd have to change it so the player moves like a top-down controller like when left is always west and so on
-# clamp so u can't twist ur character like a pretzel
u could also have the body just twist to the direction ur moving.. (so instead of strafing ur running sideways w/ ur torso facing the cam)
but in my opinions those type of animations always look ackward to me
u'd just use ur input to change the animation rigging ik target or w/e
okay this is what my project looks like, its my first one and i know its messy. but i dont understand all the terms your using, what should i do?
that does sound like it looks akward but thats not what im going for
ahh i see what u mean.. the camera movement doesn't allow for u to just parent the camera to the headbone gameobject for example
not sure how you'd make the camera follow along w/ the head and still have ur camera code work..
because the camera code is in control of the rotation. so the animation rigging stuff wouldn't matter to it unless it was parented beneath the head-bone
and u changed the movement code to work differently.. (maybe controlling that ik target instead?) not sure to be honest
in the scheme of things u would probably only want the camera to track the position (doing the head bobs and stuff) and ignore the rotation of the head..
it would conflict with ur mouse look code... unless u were to make the mouse code rotate relative to the head-bone's rotation which i figure would look and feel strange
and/or don't have the IK system affect the head at all.. only the shoulders and torso
ur camera code would rotate the camera and the head.. (maybe a seperate ik)
and anythings possible.. rotations can be relative or combined w/ other rotations to achieve more complex camera scripts
do you have any tutorials or terms i can search on youtube to help, im still figuring out unity and it would be very hard for me to even try what your talking about lol, either way i appreciate the help thank you.
Having a first-person controller with a disembodied character is not very immersive, even with all the bells and whistles of procedural camera animation and tricks that we've been adding so far. Let's see how to add a proper character to our first-person controller, and do it with the available characters and animations from Mixamo without requi...
you'd might have to change ur movemnet/camera code
So. I have a scrolling background working fine, and my main controller working fine, but now I'm trying to create some random obstacles generated in the way. I'm trying to get my random objects to be generated, but so far they're not quite happening.
private Renderer bgRenderer;
void Start()
{
ResetObstacle();
}
// Update is called once per frame
void Update()
{
bgRenderer.material.mainTextureOffset += new Vector2(speed * Time.deltaTime, 0);
}
void ResetObstacle()
{
transform.GetChild(0).localPosition = new Vector3(0, Random.Range(-3, 3), 0);
}```
It's just supposed to create a new random object, with the asteroid childed to the background in the inspector.
i don't see any code that would create a new object here
also why are you offsetting the texture every frame instead of just moving the object?
I had the texture cycling through to give the illusion of the background moving, but I think I may have figured out what I need to do.
for obstacles u need to use real objects.. (move its transform <-) over time to match the speed of ur scrolling background.. (spawn them off to the side) can reuse them.. once they go off the other side of the screen you just reuse it and move it to the other side (can randomize where they spawn using a min-max range)
if ur scrolling a texture nothings actually moving
How come I can't drag and drop the "pointsource" gameobject on the left hand side to the script's field on the right?
honestly thank you so much, you helped out a lot
Incredibly dumb question I'm sorry. I was looking at the script itself and not as a component
You need to place the script on a GameObject in the scene. Then you can drag an in-scene GameObject (or a prefab) into the slot . . .
What you're looking at is the actual script file (asset) in the project folder. This will only set default values. If you have a prefab, you can place it as the default PointSource, but then you'd need to set it correctly when gameplay starts . . .
Yes I noticed, thanks
Parameter 'Hash 46624491' does not exist.
UnityEngine.Animator:SetFloat (int,single)
AdamOKeefe.FinalCharacterController.PlayerAnimation:UpdateAnimationState () (at Assets/AdamOKeefe/FinalCharacterController/Scripts/PlayerAnimation.cs:41)
AdamOKeefe.FinalCharacterController.PlayerAnimation:Update () (at Assets/AdamOKeefe/FinalCharacterController/Scripts/PlayerAnimation.cs:29)
A tool for sharing your source code with the world!
your animator doesn't have a parameter named inputMagnitude
but your code is looking for one
so you get an error
oh ok
i am following this tutorial https://www.youtube.com/watch?v=PIFQbxMgT0c
In part 2 of this series, we go through animations for running, sprinting and idling states. Additionally, we make a basic enum state machine to keep track of our player's movement state.
In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topi...
thanks
21 minutes 20 seconds is when he adds it
i know
Please don't copy and paste; write it manually. Trust me, it's different . . .
i know i just keep messing up and then coming here cuz i misspeld if or some shit and then feel more dumb
Plz help
see #🌱┃start-here message for what to include when asking for help
https://apps.apple.com/vn/app/this-is-blast/id6738323233
hi guys I am trying to clone this casual game but I don’t know where to start. Could anyone give me some clue so I could Google it later. Tysm :unity: :unity:
Dive into This is Blast!, the ultimate color-matching block shooter! Line up your shots, tap to aim, and blast away blocks of matching colors. With simple controls and challenging levels, it’s a game that’s easy to pick up and hard to put down.
From the very first level, This is Blast is easy to pi…
:/
!learn the pathways on the unity learn site are a good place to start learning how to use the engine so you can understand what you'll need to do 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
oh and don't crosspost
I crosspost by mistake I thought I was on different sever
If you are gonna post in a code channel, pls provide the code
You may added damping to the camera?
id recommend just hiding the player (deactivate it). if you provide 3rd person views too and when the player decided to switch the camera views, u can simply unhide it (activate it).
Guys, I made a state machine for my character, but the issue is that I can’t jump and walk at the same time. It’s a really big problem. I searched on YouTube — I think it’s called an advanced state machine — but unfortunately, I didn’t understand it. Can someone explain it to me easily?
i think this should be in the #🏃┃animation channel
it has nothing to do with animation but code
its a State pattern
is it animator?
so you control the animation based on code?
to code cleaner and more readable
no there is no animation
its a coding pattern
are jumping and walking separate states for some reason
yeah because jumping is a state too and for this problem normally people make hierarchical state machine but i cant understand it 😭
well there's your issue lol
if they're separate states, they can't happen at the same time
could just make them the same state
a state of no active action, so free movement
yeah so i asked myself how people solve this problem and they usually use hierarchical state machine for this problem
you asked yourself...?
yeah
how do you know that's the actual answer then lol
I told you that i found this on youtube and it works but i couldnt understand it
sorry bro i misunderstood u, i thought ur talkin about the animator state machine
all good ^^
you found what on youtube exactly
the state machine, or the hierarchical state machine?
can i send links here?
i found about 3 videos and they hierarchical state machine for this issue
1 of them is: https://www.youtube.com/watch?v=kV06GiJgFhc&t=980s
Learn how to program a Hierarchical State Machine in Unity with this new video break down and tutorial!
Want to learn how to program state machines in Unity? This video will help get you there! Today we'll go over important concepts of the State Pattern and refactor our overly-complex code into a clean hierarchical state machine! With a detaile...
if there is another way to solve this problem then im all ears
i gave you one already
if you're a beginner, i'd say this is just overkill for getting into unity and making something to start
then it would see messy because at this point i would have to the same thing for swimming too and for swimming i would have to write walk and like eating state at the same time
Yeah, just use Animator and set trigger for jump
im coding like since 3 months
and i have experiences on roblox coding
Do u have experience with state machine in prior?
no its my first time using it with jump state
imma be real, time spent coding doesn't really say much
i coded state machine before without jump state for 2d
If u want to get into more advanced coding, u can start with what u are doing. But it's not recommended for simple movement logic.
did you say that for me or like generall my eng is not that good so i didnt understand exactly what u wanted to say
the thing is i cant never be better at coding by coding with easy and messy style
like imagine im using the easy method for that every time and i woulnt be able to better methods
Easy =/= messy. Optimization is the key
clean code is so important for me so im trying to learn with better and cleaner patterns
methods
U can write clean code without using complex methods, as long as it meets the requirement of the project
It's just readable code
sorry if im bein an idiot but for me i create functions with labels on them and each function's name generally describes its purpose. a clean code for me is less code but more on reusing the existing functions. i think thats enough, u dont need pattern machine or anythin
in general, yes. "3 months" could be expert or absolute beginner, i have no way to know
with complex methods its even better to read and these pattern are not that hard to do for something different like apple its so easy to code state machine but for character its just hard and im trying to solve this problem
i would say im beginner but not absolute beginner
pfft.. more like 3 years u still a beginner imo 😄
for me that what you are doing is right but there is some easy patterns for more readable codes
xd
well the one you're trying to get is clearly not easy for your skill level
considering you said you're a beginner, i'd recommend just making it work before making it good
make it work.. figure out why it works (in and out) then make it good
extra step i added there @naive pawn
Subjects are much much easier if its said correctly the way how they explain is hard to understand for me
use multiple sources always
i can make it work normally already its easy for me so thats why im trying to code it better
yeah
i know how to make character controller like the basic stuffs
coding better and learning good code structures/syntax/and patterns just comes from experience
like trial and error
there is not a lot of videos of this topic unfortunatly
thats a disadvantage for u
how u apply it is almost always relative to you and ur project
and learning how to apply it is what comes from experience
but i cant learn a pattern by doing what i know i have to try learn new things
why
if I dont try i will never be able to collect experiences then
considering u want to code it ur way but few people teaches it
what patterns or concepts u trying to learn?
state machine. I can do it its easy for me but the issue is i cant jump and walk at the same time i cant swimm and walk at the same time i cant eat and swimm and walk at the same time you know what i mean? but normal state machine is easy to code
Movement really doesnt need to be a state machine unless this actually solves something in your system. Separating things into states when you really dont have separate states just makes things more difficult
start with enum learn it in and out
then u can go into the more advanced state machines.. then u got ur boss level: stateless state machines
Especially if u are using animator, then u just create more overhead
It sounds like to me that you dont need a difference between walk and jump. You only need a difference between on land and on water (swimming)
A state machine by itself is a simple concept. Youre just seemingly overcomplicating it by having 2 states that really arent separate in the first place
if i dont use states when i code swimming eating walking jumping etc the code will be so messy
messy code is part of the process 😄
- else-if chains
- switch statements
- state-machine
thats how i progressed ^ atleast
Yet its clear you need to walk when jumping as per your whole issue. Eating could be separate sure if you dont allow any other action like jumping. That all depends on your design
Compare the two, either a system that doesnt work (your current setup) or a system thats messy. Which one will be playable?
eating doesn't seem to me like it'd need to be a state..
just check the state
i experienced that already on roblox coding lol
canEat? areswimming? Drown
"Running, walking, jumping" are all part of Moving state just to be clear
this is me day to day ^
Then there’s no point in using this pattern. the point using this pattern is break the codes into peaces so that it wont be messy
i just find something that i dont think is nice.. and refactor it..
and then move on.. rinse and repeat
it kinda cleans up organically
Ive already stated its possible to use this for the difference of walking and swimming. Yes its pointless if your differentiation is walking and jumping
That was one of the first things I said
#💻┃code-beginner message
The point is to optimize the calculations. Instead of checking every state condition every frame, u break them into smaller chunks to reduce the calculation.
you can break the code into pieces many different ways.. (without even needing a statemachine) thats not really the purpose of a statemachine
the one who has bad codes but at the end of the day i wont be better at coding and i will make games slower
a statemachines purpose is lock the thing into a single state... and run code accordingly
gotta walk before you run mate
Really? Because right now youre stuck on an issue thats solved by not making "cleaner" code. In which case many dont consider cleaner even
The one who makes it simple seemingly makes it faster already
ya, and also dont even think about performance until u need to
gonna shoot urself in the foot and not realize it
If u really want to pratice the concept, it's better to use for other cases like game states
Anyways I dont even think youre understanding the fact that I'm saying youre just using a state machine for the wrong purpose. Walking and jumping arent two different states if you want both working at the exact same time. Something like walking and swimming are perfectly valid as different states
yeah i get it now so but woulndt it be messy to have swimming eating moving idle etc in the same script
can you give me an example please?
Maybe reread what I'm saying. I cant make it anymore clear that swimming and walking CAN be different states
Idle wouldn't matter. Thats just moving with input of 0
For example, a game in general has Start, Playing, Paused, Win, Lose, etc.
The logic is way more decoupled
you are now saying that i should use states i guess so i shouldnt use states when i do something at the same time right? like character controller
hmm i get it ty
a statemachine for a cc
would be like
walking / swimming / flying
when eating you'd allow that in the walking and flying state but not the swimming state for example
but eating wouldn't be a state
Yes it doesnt make sense for walking and jumping to be separate if you need them both to happen.
While walking and swimming are going to be completely unrelated code, it makes sense to split that up using states
Eating itself yea its hard to say what to do there. There are definitely designs where you could make it a state like if it slows you down, doesnt allow jumping etc
also true..
statemachines will take a while to get good at ..
you'll get enough experience to know later on when and how to use them more properly
while (eating) defecate = false;
shouldnt i be able to walk when i swimm? but playing another animation and slower
pfft.. watch me
that just complicates it..
Send clip
ewww.. lol

o-of what?
Well you'd be moving with different gravity and likely slower. The only similarity would be the method you choose to move the object
offtopic.. dnt worry bout it just trolling
- You can’t be both Walking and Swimming at the same time — you’re in one environmental state.
- But you can be Walking and Eating — those are actions, not global states.
then i should change the state name walking something different because now it contains jump and maybe other things
void HandleMovement()
{
switch (currentMovement)
{
case MovementState.Walking:
HandleWalking();
break;
case MovementState.Swimming:
HandleSwimming();
break;
}
}
void HandleActions()
{
if (isEating && currentMovement != MovementState.Swimming)
HandleEating();
}```
heres an example.. (the states of movement are *exclusive* its either one or another.. thats when u could use a state machine)
for something like eating.. (even if it based on which state ur in it doesn't necessarily need to be part of the state handling..
u could just consider which state ur in when attempting to eat..
Dry state, Wet state 😉
lol
What do you think?
What should i name it instead of walking because it contains jump
Hi,
I would like a sprite to jump only in case it touch with ground though, it cannot jump.
Could you guys give me advices ?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
//Unityの基本クラス(MonoBehaviour, Rigidbody2D など)を使うための宣言です。
using UnityEngine;
//新しい「Input System」APIを使うための宣言です(従来の Input.GetAxis() ではなく)。
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
//Class 名はファイル名と同じにする必要があります。
{
[SerializeField] private float speed = 5.0f; // 横移動速度
[SerializeField] private float jumpForce = 10.0f; // ジャンプ力
[SerializeField] private float groundCheckDistance = 0.1f; // 設置面判定の距離
[SerializeField] private LayerMask groundLayer; // 地面レイヤー(Tilemap用)
private Rigidbody2D rb;
private PlayerInput playerInput;
private bool isGrounded;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody2D>();
playerInput = GetComponent<PlayerInput>();
}
// Update is called once per frame
void Update()
{
//移動処理
Vector2 move = playerInput.actions["Move"].ReadValue<Vector2>();
rb.linearVelocity = new Vector2(move.x * speed, rb.linearVelocity.y);
// ジャンプ処理
if (playerInput.actions["Jump"].triggered && isGrounded)
{
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpForce);
}
// 接地判定
CheckGrounded();
}
private void CheckGrounded()
{
// 下方向にRayを飛ばして、地面に当たったら接地中
//RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, groundLayer);
//isGrounded = hit.collider != null;
Vector2 checkPos = new Vector2(transform.position.x, transform.position.y - 0.3f);
isGrounded = Physics2D.OverlapCircle(checkPos, 0.2f, groundLayer);
}
// SceneビューでRayを可視化(デバッグ用)
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position, transform.position + Vector3.down * groundCheckDistance);
}
}
I suppose the gap between BoxCollider2D and Rect tool might be one of causes.
how do I make my knockback eventually stop?
This is my knockback code, how it works is basically it just applying force onto a direction from the source (aka you the player who hit the enemy)
in the tutorial, they increased the mass of the object, and the object in the video was a cube instead of a cillinder, so maybe that could have something to do with it
using UnityEngine;
public class EntityKnockback : MonoBehaviour, IHitable
{
private Rigidbody rb;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
public void Execute(Transform executionSource)
{
KnockbackEntity(executionSource);
}
public void KnockbackEntity(Transform executionSource)
{
Vector3 dir = (transform.position - executionSource.transform.position).normalized;
rb.AddForce (dir, ForceMode.Impulse);
}
}
Is the code AI generated? The box collider isn't involved in the ground check. Also the gizmo debug does something completely different than what the actual ground check does, and the editor doesn't even have gizmos enabled
Yes. It is AI generated. You can ignore the gizmo debug if it has nothing to the behavior.
You should consider following a course or a tutorial instead so that you'd know what your own code does
The first thing to do would be to apply gravity to the enemy
I have gravity ticked off on the rigidbody because the enemy just kept falling off the map 🙏
Is having it fly off the map any better? Fix the fall-off-the-map problem properly and the knockback issue solves itself
damn you right
It's basic physics
bruh the fucking gravity works now??
it doesnt fall of the map i just ticked it on
well its working now, if it aint brokey, dont fix it
😭
now another issue
since its a bean, it just falls instead of being like pushed
Make sure the Overlap position aligns with the ground. If u are not sure just use OnCollisionEnter(), OnCollisionExit() to check ground
now this is happening lol
Freeze the rotation
is there some event when Time.timeScale gets changed?
wont that matter in the future when the enemies start chasing me?
cuz their animation will be all sorts of weird if they can't rotate around
you'll still be able to rotate it w/ code and anims..
it just stops the physics from affecting it
ah gotcha, thanks
just lock axis's that are needd
You can keep the Y rotation unfrozen, X and Z are what make it tip over
axi..
it works like I wanted it to, thanks
hey i made a marching cube algorithm implementation and i tried interpolating it but i get this error: "Mesh '': abnormal mesh bounds - most likely it has some invalid vertices (+/-inifinity or NANs) due to errors exporting.
Mesh bounds min=(-nan(ind), -nan(ind), -inf), max=(-nan(ind), -nan(ind), -nan(ind)). Please make sure the mesh is exported without any errors.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)"
i think it has something to do with the result of value2 - value1 as it could be 0 and i would be dividing by it. i can provide the full code if needed, heres the most important snippet:
Vector3 edgeStart = position + MarchingTable.Edges[triTableValue, 0];
Vector3 edgeEnd = position + MarchingTable.Edges[triTableValue, 1];
float value1 = GetDensity(edgeStart.x, edgeStart.y);
float value2 = GetDensity(edgeEnd.x, edgeEnd.y);
Vector3 vertex = edgeStart + (heightThreshold - value1) / (value2 - value1) * (edgeEnd - edgeStart);
vertices.Add(vertex);
GetDensity is just providing me with my height value igenerated with my noise
should i keep my movement script in Update or FixedUpdate most tutorials i see is Update but since update called per frame would movement be diffirent on diffirent devices (faster or higher jump at better fps)

we dont know anything about your movement script
so we can't say
its with invoke unity events new input system
rb.linearvelocity = new Vector2(moveX * moveSpeed , rb.linearvelocity.y)
this kind of script
Have you used a debugger to try to catch any invalid vertex positions?
no not really i dont really know how i would go on there
Add some code to help check if something is nan and put a breakpoint so you can see what caused it.
https://learn.microsoft.com/en-us/dotnet/api/system.single.isnan?view=net-9.0
https://docs.unity3d.com/6000.2/Documentation/Manual/managed-code-debugging.html
its better to just add an if statement for such things as conditional breakpoints can slow down execution a lot
what am i seeing bro 😭
Read what i said, add some code to help find what caused nan or infinity to be produced
@hallow acorn add something like this and then attach your IDEs debugger to unity
if(Single.IsNaN(vertex.x) || Single.IsNaN(vertex.y) || Single.IsNaN(vertex.z))
{
Debug.Log("Found NaN!");
Debugger.Break(); //make the debugger break here without a breakpoint
}
okay ill try that
If this is confusing then you need take the time to learn about debuggers before trying to implement a complex algorithm
something like that could be in Update, though it'll really only apply once FixedUpdate happens
i think if you're setting velocity directly then it can't be different depending on the fps
They usually keep Input value in Update() and anything physics-based in FixedUpdate()
Thanks
i wanna make my player jump shorter on light tap but i still jump in same jumpForce
anyone knows solution?
#🖱️┃input-system probably
is using animator.GetStateInfo to keep track of state bad practice?
it depends
Possibly. What do you even need to "keep track of state" for
i need to know whether or not the attack animation is currently playing, bc if it is i disable the player turning around
The animator should be mostly an independent system. You should pass data to it, rather than reading from it
so like hardcode the amount of time it takes for that animation to play and set a timer?
to keep track
Or make a code based state machine and have that state machine drive the animator
or use event keys inside your animation
i did, but i still need to know when the attack finishes
unfortunately the script is on a different gameobject
still you can do that
You could use an Animation Event to signal a change in state at the end of the attack animation.
https://docs.unity3d.com/6000.2/Documentation/Manual/script-AnimationWindowEvent.html
"Use an Animation Event to call a function at a specific point in time. This function can be in any script attached to the GameObject"
its a different game object
i could use another script to bridge the gap but that feels inefficient
i´d say do what works best for you
oh wait i can just move the script 🤦
thank you
you are cross posting
which one should i remove
you were redirected to the #🖱️┃input-system
U should probably use a jumping bool to check if u are jumping and in the air
{
if(isGrounded())
jumping = true;
}```
then check for that bool in `FixedUpdate()` for jumping
ill try
Can anyone help me make a game
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**
State machines my beloved
I’m so glad I started learning about them, they’re so fucking cool
What do you think would be the most appropriate way to create a health/damage system for enemies in a game and why?
dejavu..imo a component per char
Something like health would just be a property of the enemy, unless theres a specific thing you need to do with it, nothing else should have access to the health. Its just a private property
If something directly hurts an enemy, you only need to tell that enemy how much damage you are doing. And then the enemy itself can determine whether it should be killed or not
unless you use an Interface , that doesn't scale very well
The specific reason as to why I'd want to create a health manager is as listed on the left.
I'm still confused about which one you're talking about :V
what's the point of this global volume entity that ends up here whenever I create a new project? is it safe to delete it?
the part keeping health variable in enemy script. If you dont have an interface, if you need to damage multiple types of things. You have to check if the thing you damaged is (a, b, c, d etc..)
an interface at least creates a "common" functions/properties they all share...say a IDamageable etc..
like, similar to a dedicated component i mentioned before..
So you're more in favor of the left one and Hapi is in favor of the right one?
I'm saying right, not sure what they meant in terms of that graph..I meant like separate components imo.. I think I suggested this yesterday, at the end of the day it's whatever is easier to you & your project needs
So you meant to say left one wasn't scalable? How weird I thought it would be the opposite
Is the right not separate scripts aka components on the same object? That's what I meant
Left could be okay too but it really depends also on the game and design
Some games use a centralized system and some let components handle their own thing
I just thought that left one would be easier to scale up if I got the system running, like creating a new enemy would be as easy as putting some stats here and there and let the system take care of the rest instead of turning knobs for each enemy.
I don't know much of what I talked about because I'm experimenting with ideas, but it is similar to the idea of creating a centralized system that handles a general function of the game.
Just wanted to be sure it wasn't some terrible idea that a new game dev might have.
Might also be useful if I wanted to dive deeper in that function in the future?
Are enemies the only thing with health / take damage ?
No, player objects some specific projectiles and enemies all have health and take damage.
I'm not sure how I'll modify them in the future, but the current plan is that.
should have these things laid out more if you want to build a system around it
If I want to Damage a Player or Bullet or Enemy, how will you tell which I can damage
hence why I suggested , using a separate component to handle that or an Interface
if you used a POCO and if they all had the same HealthStats stored you need a way to know you can access and Damage/Heal that..
Ok in the shortest explanation possible, this basic demo will have a player character that can shoot objects of different weights, speeds and health. Damage towards enemies will be calculated by the terminal velocity in which it hits an enemy * by a preset number.
As far as health interactions go, that's it
I'm not talking about the projectile damage or its calculation, I'm talking about in practical terms.. What is going to be damage, its important early on you can make this modular in case you add other items that can damage / with health..
for example, adding a Breakable box or something
I feel like our interpretation of an interface is different. I don't know the meaning of interface in coding terminology but I heard about it before.
I'll send you some info on it, basically an interface a good way to "force" certain classes to carry certain methods/ properties.. so you're always guaranteed
image you had IDamage
it has a method Damage(int amount)
in your public class Enemy : MonoBehaviour, IDamage
Like that..
Now you dont care to damage Enemy, but you care you can damage anything with the Idamageble because it has a Damage method
Sure I'll check it out, sounds complex though so I might need some more learning before understanding how to implement that kind of stuff.
public interface IEnemy {
float Health { get; set; }
float MaxHealth { get; }
void Heal(float amount);
void Damage(float amount);
}```This ensures that your Enemy would always have all of this stuff
Any clue why an overflow occurs?
what do mean "overflow"
its not complex at all don't worry, they are pretty basic but very powerful to keeping your objects modular
I'll check it out soon as I learn more
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
I'll try to find guides on the topic first, I don't understand much of how that works. Weird that no tutorial or guides online ever talked about that.
oh there's plenty , especially on Unity
they are useful for many things besides health ofc
If you did something like this, it ensures the Enemies always have a max of 100 health, and the only thing youd need to do is Enemy.Heal(5f) or Enemy.Damage(20f) there isnt so much you have to worry about, because the Enemy itself handles something like checking if it ran out of health
public class Enemy : IEnemy {
float _hp;
public float MaxHealth => 100f;
public float Health {
get { return _hp; }
set {
_hp = value;
if( _hp <= 0f ) { Die(); }
if( _hp >= MaxHealth ) { _hp = MaxHealth; }
}
}
public void Damage(float amount) {
_hp -= amount;
}
public void Heal(float amount) {
_hp += amount;
}
}
I guess I just don't know how to search for them since I ask online unspecifc questions beginners would ask.
written in notepad so it might not compile
“overflow” means that a numeric value has exceeded the maximum (or minimum) limit that the variable type can hold, causing unexpected behavior or a crash.
Again thanks for the code, but I need to first understand what's happening to apply that type of code.
which variable are we talking about here ?
Got it I'll search more about it
gamedevbeginner.com usually has pretty decent blogs on these unity things, but theres plenty of video formats too anyway and Unitys own site I sent, though their example code is a bit gringe lol
So, what's overflowing?

I like text because it's easier to reference and look back into
a convenient thing you get for interfaces is that you can have different classes for your enemies like this
public interface IEnemy {
float Health { get; set; }
void Squashed();
}
// each Enemy gains a "Health" property and a "Squashed" method
class Goomba : IEnemy {
public Health { get; set; }
public void Squashed() {}
}
class Bowser : IEnemy { ... }
class Koopa : IEnemy { ... }```
The benefit of this is if Mario jumped on an enemy, it doesnt exactly matter what the enemy is, like whether its a Goomba. Theyre all Enemies, so Mario is able to squash any of them
the major benefit is you're not relying on inheritance which can be very limiting
That'll come useful when I understand what it means :V
you could have List<IEnemy> and thats just a collection of various enemies.
otherwise you might need List<Goomba> List<Koopa> if you needed to know all the enemies in the level
@twilit ocean you will lean more with all the resources out there, but just a quick example why some times "inheritance" doesnt work and interfaces are preferred ```cs
public class Character{
public virtual void TakeDamage(int amount){
Debug.Log($"Character took {amount} damage.");
}
}
public class Player : Character{
public override void TakeDamage(int amount){
Debug.Log($"Player took {amount} damage.");
}
}```
now what if we want a non-character to Take Damage?
we certainly wouldn't want a Box to inehrit Character
so we do interfaces instead
public interface IDamage {
void TakeDamage(int amount);
}
public class Player, IDamage{
publicvoid TakeDamage(int amount){
Debug.Log($"Player took {amount} damage.");
}
}
public class BoxObstacle , IDamage{
public void TakeDamage(int amount){
Debug.Log($"Box took {amount} damage.");
}
}```
guys i have a question about lobbies, im creating this lobby system and whenever i try to join a lobby i get a null reference because my lobby code is null, is this because the lobby code is hidden outside of the lobby?
i mean you can just change the name from character to idamageable right, they are the same,
the main different that with class inheritance you can only have one
right which is the main constrain and limitations.. now you're stuck in that inheretence tree and cant inherit other things
interfaces you can have as many as you need
As I'm reading about it in the guide it's starting to connect. I just need to learn how to actually implement it (which will come later).
Now one important question, the language in the guide I'm reading seems to hint that a project can have many interfaces with specific functions instead of few. How true is that?
exactly you can have on a class as many interfaces as you need, which again is its major benefit over something like Inherence
public class Player : MonoBehavior, IHurt, ISprint, ISaveStats
etc.
Don't interfaces aim to minimize the amount of script files created and aggregate? Why would I create a new interface for so many different interactions?
minimize the amount of script files created
no, that is not an aim of interfaces
the aim is to reduce duplicated code for dealing with similar objects
no that is never an aim for anything...
you can have many because they are kinda like a "Tag"
so different types can have the same "tag" and also the same functions
.. But wouldn't it make sense to create a single interface file and then list all interactions there instead of creating many of them?
no that would be bad to cram everything in 1 interface, especially if you have other classes that only need 1 thing from that
the requirement for interface is, whatever methods/properties are inside the class that Implements this Interface has to have defined all those methods
@twilit ocean if you had
interface IHealth{
void Damage(int amount);
void Move();
void Jump();
}```
```cs
public class Box : Monobehaviour , IHealth {
private int health = 100;
public void Jump() { } // why
public void Move() { } // why -- we are forced to implement them because they are in IHealth
public void Damage(int amount) {
health -= amount ;
}
why would you want this ?
you wont be able to just "ignore" the other things in the interface, you are forced to implement them, normally called a "forced contract"
Ahh I see, I was expecting something similar to inheritance but cleaner, you actually need to list every single method withing a interface in order to have it work
Thought maybe we oculd somehow fetch only the specific needed method from a list that would be the interface and apply it to the desired class that needs it.
not sure what you mean there tbh
the interface itself cannot and doesn't store anything
all the implementations are inside whatever class has this interface
the interface says " you should have Hurt method as a requirement, how you run and what you do inside of it is up to you in the class"
Annd I'm confused again 
Lemme read all the guide all the way before I start yapping more
sure, if you have more Qs just make a thread
Howdy, I need help properly incorporating jumping into a 3D platformer, I have jump working, but Im struggling to attach the proper flags to trigger the jump->airborne->land sequence
where is code
My code is a mess, forgive me in advance, Ive been stitching it back and forth for a while:
use links to post 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/
📃 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!
what is the exact question ? are you trying to do animation / jump through code ?
whats happening vs what you expect to happen
Ok heres my deal: I want to add proper jumping, my character can currently jump, but no animation plays. I have the logic of the animator mostly settled, my goal is to have the character jump, be able to smoothly jump on landing, and also enter a fall state if walking off a ledge thats big enough/falling, I have Landed/isJumping/isFalling bools for it, but I feel like im going in circles because I cant seem to nail it down,
my character currently freezes in the 'spiderman' midair pose until I start walking backwards/rotate when still, and break the pose back to the idle selection
first I'd use blend tree to cleanup that idle / walk cycle thing.
did you check transition to self is not enabled on AnyState just incase, I typically would not use a falling from anystate but most times from movement it suffice
i also would think blendtree's would help here
also not sure if slapping all that stuff on a any state transition will work out exactly how u wish
might want to consider re-doing the flow of that animator
the only time I've used anystate tbh is like a Hurt event or something
Yeah I checked that thoroughly, and Im unfamiliar with blend trees, maybe this is too much I bit off for a basic intro game dev assignment
ya, something quick.. that doesn't involve conditions and transitions quick and easy
I decided to use a asset store dummy with advanced animations to try and make it look good but now this is proving to be a challenge, given this is the first time Im using unity
blend tree is simple, you put say.. forward,backward, run / walk and idle all in 1 spot and its just controlled by 1 float instead of going through a bunch of spider webs
i know that with particle systems you can change the mode to sprites so you can select a random image out of a set list of sprites, but is there a way to select a set image based on an animator’s parameter from a list of sprites?
yea?
how then lol
the animations arent part of any grade req, so in your vetted opinion, should I focus on making the three levels we were asked, that have moving platforms/rudimentary puzzles, and just leave the jump as a jump with no animation?
same way u'd set an animator parameter..
only u read it..
then use that to change out the image
if you mean picking a specific image in a slicesheet, I know this is easier done in visual effect graph
o shoot this is the scripting channel wrong spot lol
we basically have to make a 3 level platformer, with enemies/platforms, and a basic UI, and movement, and a start screen, basically a baby intro to unity
ya, lol!, i would have just used cubes and just rotations as animations 😄
unless "visuals" is an aspect of the grading
no clue.. but doesn't sound like something that would be built into the particle system..
Does anyone have any suggestions for how to do a status effect system?
Rn im thinking about using scriptable objects in a list but is it possible to hold an equation or function in a scriptable object to trigger when needed?
good luck tho, might see u back here to script it 😄
cant use scripts for this - vrchat stuff
ohh oka
asking the vrc server instead lol
u could also ask in #✨┃vfx-and-particles if its possible to do it without scripting
you can use just about anything with this..
SOs included
this is worth like 30% of our final grade and I wasn't sure how best to demonstrate my interest, so I stapled a complicated-ish animator for a dummy off the asset store
i would branch off of running, walking, and idle for jumping and landing and transition to anystate to return
the class assets we were given dont even have turning, jumping, or backwards walking animations, so the bar is quite low but Im not sure if thats for a base passing grade or a full 100%
basic movement, basic UI and HP, enemies that hurt you, obstacles and moving platforms, basic basic puzzle jumps, and 3 total levels
what is assignment for ? isn't this overkill lol
Its a basic intro to game dev
Its possible to call methods from scriptable objects?
I got carried away with my character animations and I wanted to make it look real good but now its becoming an issue
I've never tried using them for anything more than basic data
Strings, int, sprites, etc.
they are just classes.. unity just handles their creation as assets instead of pocos
also this is why you should keep it in 1 channel..
😠
yeah this is overkill already for a basic intro class lol
does it need to do jumping all that? make it a walking sim where you can interct with a button or something
Assuming I add clean sounds, and make the levels visually cool and traversable, and tweak my physics to be comfortable to play, think its worth 100%?
Yeah it needs to have jumping
but screw it, I removed it and simplified it, no jumping animation is a small sacrifice
for an intro class you'd probably get 100 even if it was pong lol
aesthetic is good, but a good understanding of the basics systems is probably more than enough
it needs to be 3D, basic platformer, 3rd person
Im debating attaching cinemachine once Im done the meat to give clean camera transitions
looks simple enough
yes It was more of an example i don't mean it literal
just like a pan from facing forward, to the 3rd person, and yeah lolol nw I gotcha, Im just pressed because of how open ended it is for an assignment
at least I would simplify the animator a bit
well its usually based on what you learned in class, if you included all those concepts in it , you're pretty much scoring 100
if you're doing interactions, would probably score some decent points
we learned how to move with delta time, basic camera attachment and basic cinemachine stuff, and basic interactions
I plan to have a button over which you walk, and it causes platforms to drop down
for a level
ya that would probably be simpler
he demonstrated some more fancier stuff but it was moreso exploratory and less assignment related because the example which he showed us in class of a finished sample game which scored full points, was pretty simple
yes cause teachers got like 5-10 min a student to glance over usually
but Im still sketched so I plan to put as much possible polish before submission in 5 days
Im 100% finishing by then, the hard part of character controls and animation is done, levels will be much easier and UI and start screen should be super easy too given Im not doing anything crazy
with leftover time Il toy around with extra additions
hey, can any admin look into the course Junior Programmer from Unity Learn? the videos are downloading very slow, and remain stuck if I leave them to download ahead. I don't have any networking issue, my down speed is 200
!help
No Category:
help Shows this message
Type !help command for more info on a command.
You can also type !help category for more info on a category.
No Category:
help Shows this message
Type !help command for more info on a command.
You can also type !help category for more info on a category.
Use
!help <command>to get more information
!collab
!code
!logs
!bug
!screenshots
!cs
!vc
!dots
!vrchat
!vscode
!blender
!vs
!forums
!learn
!install
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public Slider musicSlider;
public Slider sfxSlider;
public Dropdown qualityDropdown;
public static int qualityLevel = 5;
public static float sfxVolume = 0f;
public static float musicVolume = 0f;
public static bool postProcessing = true;
public void setQualityLevel()
{
QualitySettings.SetQualityLevel(qualityDropdown.value);
qualityLevel = qualityDropdown.value;
PlayerPrefs.SetInt("qualityLevel", qualityLevel);
}
public void setMusicVolume()
{
musicMixer.SetFloat("MyExposedParam", musicSlider.value);
musicVolume = musicSlider.value;
PlayerPrefs.SetFloat("musicVolume", musicVolume);
}
public void setSfxVolume()
{
sfxMixer.SetFloat("MyExposedParam", sfxSlider.value);
sfxVolume = sfxSlider.value;
PlayerPrefs.SetFloat("sfxVolume", sfxVolume);
}
public void setPostProcessing()
{
postProcessing = !postProcessing;
UniversalAdditionalCameraData cameraData = cam.GetComponent<UniversalAdditionalCameraData>();
if (cameraData != null)
{
cameraData.renderPostProcessing = postProcessing;
}
}
void Start()
{
if(PlayerPrefs.HasKey("qualityLevel") == false)
{
PlayerPrefs.SetInt("qualityLevel", qualityLevel);
}
if(PlayerPrefs.HasKey("musicVolume") == false)
{
PlayerPrefs.SetFloat("musicVolume", musicVolume);
}
if(PlayerPrefs.HasKey("sfxVolume") == false)
{
PlayerPrefs.SetFloat("sfxVolume", sfxVolume);
}
qualityLevel = PlayerPrefs.GetInt("qualityLevel");
musicVolume = PlayerPrefs.GetFloat("musicVolume");
sfxVolume = PlayerPrefs.GetFloat("sfxVolume");
qualityDropdown.value = qualityLevel;
musicSlider.value = musicVolume;
sfxSlider.value = sfxVolume;
}
}
this is my options menu, it doesnt save btwn scns
it saves from the main menu to the level, but when i set it in the level and go back to the main menu it doesnt change at teh main menu
which object is this script on? Which scene does this object live in? How do you handle the menu in your game scene?
this script is on the optionsMenu gameobject, this object exists once in every scene, i handle the menu by clicking a button to open it, then the user is shown a dropdown, and some sliders to change the settings
any errors in console at any point?
have you done any debugging to make sure the code is actually running?
Also - is there a good reason for these variables to be static?
im not sure i understand, i know it runs since it works from the main menu scene to the game scene. not vise versa though
siince im new at this i wanted to first make sure the values transfer between scenes then i added the playerprefs on top of it
yeah but "it works" is pretty vague
does this help at all
everything saves except at the end where i go back to the main menu scene, where it doesnt save the changed i made in level0 scene
honestly this video quality is pretty low so it's hard to see what you're doing.
But what I would do in your shoes is start debugging the code
add Debug.Log statements in all the places. I know for a fact there will be at least some unintentional things happening in this code
yes you are right
For example, assuming setQualityLevel() is hooked up as the value changed listener on the dorpdown (is that correct)? Then calling qualityDropdown.value = qualityLevel; in Start is actually going to cause setQualityLevel() to run too
let me share what i found weird mayube you can figure it out
wait thats exactly what i found weird
why does it call setqualitylevel
i dont understand
because the value changes
Use this instead of setting .value:
https://docs.unity3d.com/Packages/com.unity.ugui@2.0/api/UnityEngine.UI.Dropdown.html#UnityEngine_UI_Dropdown_SetValueWithoutNotify_System_Int32_****
Another issue with your code is you basically have 3 sources of truth
you have:
- The dropdown.value value
- Your static variable
- The PlayerPrefs variable
and at different tiems in your code you treat each of them as the source of truth
does this just mean instead of calling a function to just put it in the update?
For example here:
QualitySettings.SetQualityLevel(qualityDropdown.value); You use the dropdown value as the source of truth
Here:
qualityLevel = PlayerPrefs.GetInt("qualityLevel"); PlayerPrefs is the source of truth
and here:
PlayerPrefs.SetInt("qualityLevel", qualityLevel); the static var is the source of truth
no you put the SetValueWithoutNotify call wherever you want to change the dropdown value
you only put things in Update that you want to happen every frame
Doesnt TMP_Dropdown replace Dropdown now?
this is what im looking for right
the same principles apply to either
That is the documentation for the function yes
it means instead oif qualityDropdown.value = qualityLevel; you do qualityDropdown.SetValueWithoutNotify(qualityLevel);
it might not be the issue, and might not be the only issue
that's just what jumped out at me
I still recommend debugging
yes ok thats one thing fixed
one other thing i noticed
i put a debuglog in the start function
but instead of being called at the start of the scene
it gets called only after i open the options menu
should i move the script to a different object thats always enabled?
its weird beacuse i read that the start function works regardless of wether the object is enabled or not
You're confusing with awake
so its the other way around
i see
but when i set start to awake
the problem still persisted
it doesnt matter this doesnt cause any issues thanks
i figured it out thanks dlich and huge thanks to you praetorblue
the fact that you saw this with your own eyes is genius bro, turns out the main issue was in the inspector lol
Ngl i could just have it be one big script that handles all the actual effects and then have all things just contact that method. I mean I'd probably use scriptabld objects for name, description, and icon but this might be simpler than having every status effect be it's own separate thing and then try to contact all of them individually
I can't test it right now but its been haunting me the entire shift because my game kinda heavily uses status effects as a mechanic. Not a core mechanic but it influences the game pretty majorly.
Trying to look up tutorials but everyone has their own thing that perhaps im too uneducated for my brain to properly process.
If youre using scriptable objects, then it'd make sense for each scriptable object to already handle its own status effect logic through derived classes. Instead of 1 big class doing it
You need to define what a status effect is. What can it do in your game, when does it act?
Thats how you start building a system around it
Hello (I'm a beginner in programming) My question is in what contexts is time.deltatime used? I've seen that they say it works with certain things and that it improves performance, but it's still not clear to me what I should use it for.
Hi
hi yo know about that?
It's commonly used when animating an object inside of Update that doesn't use the physics engine . . .
Has nothing to do with performance. Delta time is just the time passed since the last frame. That's it. Any logic that needs this time, would use it.
Also, there's a whole thread about this:
https://discord.com/channels/489222168727519232/1427000084922634402
Hey guys i am trying to make a 2d endless side runner game and i had a question regarding my enemy spawn script
The above 2 scrensshots show how the enemies are being spawned and in theory i think the enemies should get spawned quickly so that it is challenging
but that's not the case and the eemy spawn is taking too long
the main issue starts at 15 seconds where the enemies are just so slow. Any suggestions why that is
I’m a bit confused the enemies seem to be the same speed at 15 seconds
Oh wait spawning slower?
so i have 3-4 enemies in the beginning that have a spawn speed of 2f so that i can give the player a tutorial
after that the spawn speed should go down to 0.2 which i dont know if it is happening
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
plus i want that the enemy spawn to be challenging - the next enemy should already be on the screen while the player is jumping over the current one bu that is not the case - there is only 1 enemy on the screen at a time
sure
done
A tool for sharing your source code with the world!
Is spawned being printed after the first few enemies
The first step to solving issues like this is something you noted yourself,
which i dont know if it is happening
Almost all problems come down to "This thing isn't happening and it should be" or "This thing is happening and it shouldn't be". You need to figure out what specifically is happening in order to determine what isn't meeting expectations
yes
yes it is being printed
i ran a couple of other tests and i think my corountine is working. The actual enemy spawn is defintely quicker than the initial enemy spawn
Ah I see the problem
At the top of EnemySpawnTimer you’re waiting for 3 seconds
Not sure why
(and waiting 2f every time you do spawn something)
but i still dont understand why is there just 1 enemy on the screen at a time when i theory, considering the enmy spawn rate is so quick - there should be atleast couple of enemies lined up already
Well each enemy you’re spawning takes 3.2 seconds to spawn
Because you have that wait for seconds for 3 secs at the top
5 seconds
That’s intentional the first few enemies they said are supposed to spawn slow
The issue is after the first few enemies spawn
that has been 0ed out in the editor - it was from another logic that i was testing. That variable is not being used anywhere else in the code so it should nit be added
they are not talking about a variable
that has only been implemented in the initial spawn tho?
yield return new WaitForSeconds(3f);
oh shit i see
It’s not a variable it explicitly says yield return new WaitForSeconds(3f) at the top of the coroutine
In the future if you want to solve this problem independently I would
- Add additional debug logs in all related steps that this code involves, potentially with more detailed information inside of them
- Think about the problem more methodically. The issue is enemies are taking too long to spawn. What code here could cause that? What code here makes things wait? Narrow down the amount of suspects you need to look at
okay perfect - thankyou so much guys !!
Glad to hear it, are you open to a quick piece of feedback? No worries if your not 😄
sure
trying to do something I feel like should be very simple, want to change the game speed when animation state of player is a certain state but it's just not working, the if statement doesn't trigger. I think it's because I'm getting the name wrong, but I've tried every possible permutation I've found and nothing seems to work
It would just be “Idle”. Also careful about checking anim state names (as I’ve learned earlier today), I would instead use an animation event instead if possible
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/
📃 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.
okay noted
Actually I might be wrong docs say otherwise
So in your EnemySpawnTimer() function you have a lot of repetitive code going on here, I point this out because it's a good example of where you can think about what here is shared between all these outcomes and what isn't
When we look at what that loop is actually doing logically, we can actually reduce that loop down to
if (initialSpawn == false)
{
Enemies[] initialEnemies = new Enemies[] //This could even be a array or list you configure in editor!
{
Enemies[0], Enemies[0], Enemies[1], Enemies[2];
}
foreach (Enemies enemy in initialEnemies)
{
Instantiate(enemy, transform.position, transform.rotation);
yield return new WaitForSeconds(2f);
}
initialSpawn = true;
}
Furthermore, you might even want to make a little function that handles the creation of all enemies, so that way you know it's all happening the same way, like. This is just an example though 😄
private IEnumerator SpawnEnemy(int enemyIndex, float waitTime)
{
yield return new WaitForSeconds(waitTime)
Instantiate(Enemies[enemyIndex], transform.position, transform.rotation);
}
Your best bet is prolly using an anim event, I’m sure we could figure out how to do the name thing but anim event is generally safer
great, i will apply both these things, thankyou!
hey i'm using that same background lol
haha itch for the win
free assets ❤️
yess lezzgo
one day I may have money for assets, but today is not that day 😛
Hey - currently having a problem. Its less code, more of a general idea, but I don't know how to apply it.
Currently, I have code of npcs/ai that see the player and attack them; however, i want the enemy to be able to attack other npcs. Right now, Im having issues of thinking of how the ai enemy will see multiple groups of enemies and only attack the closest one. Im guessing it will do something with a collider, but Im not familiar enough to think about how to properly implement it.
Here is the state machine code that this will go into, particularly the function "Chasing": https://paste.ofcode.org/Cb9vQ3piFmzi52JNpVrPDx
Is there any way more experienced coders would go about this? Would they find the transform of all the npcs, then find the closest one relative to the current enemies transform? You dont have to write the code, just say general terms like "oh find the transform" or smth. Sorry, I know this is difficult to answer, so I apologize if this is confusing. If you respond, please @ me. Thanks!
Your solution is prolly the best bet yeah just tracking the transforms and comparing the distances
Raycasts would also be needed if for example walls block line of sight
your logic is a bit overcomplicated. Why does it need to treat players and enemies differently?
Mainly because of the hierarchy of enemies - I want the enemies to focus on npcs first before the player - and if both are in the same room itll disregard the player and focus on the npcs.
Also good to see you here, you helped a ton on a previous project of mine!
I would give all of them a "threat" level and just find the highest threat level from the list of nearby things
Gotcha, Ill try it out. Thank you!
No worries! One last thing is a tiny nitpick but is easy to get in the habit of and will really help the readability of your code,
It's worth making slight adjustments to what you name things in order for it to be more clear what it does do and also help you decide what it should do.
some examples of this
Enemies might be better as enemyTypes, enemyPrefabs or typesOfEnemies etc. Just Enemies could also refer to enemies that have been spawned or etc.
initialSpawn would be better as hasInitiallySpawned, hasInitiallySpawnedEnemies or initialSpawningComplete. Specifying the tense in the naming helps ensure you or anyone else understands what this bool specifically represents.
EnemySpawnTimer() as it's currently named to be implies the sole job of this function is to wait but currently this function is largely responsible for the actual spawning of the enemies. If your happy with this function doing the job of waiting and spawning you may want to rename it to something like SpawnEnemiesWithDelay(). It can also be worth considering that maybe you want to split this function up into smaller separate functions with specific names and tasks like EnemySpawnCooldown(), SpawnInitialEnemies() and SpawnEnemy().
You by no means have to act on any of this advice and it's certainly not critical but it's worth thinking about when your in the mood for it 😄
no, this is great advice - i will definitely look into it + make a note of it next time i am coding. I appreciate you taking out the time
using timescale to slow things down is a bad practice, you're changing whole engine's timing this way, meaning unrelated stuff will be affected by it.
instead introduce your own global speed multiplier.
Hey - sorry to bother you again with this. Currently Im having a little trouble with the finding the highest threat level from the list of nearest npcs. Here is how I was thinking of going about it (most likely unoptimized, but slowly getting through it:
foreach (GameObject enemy in enemiesList)
{
if(sphereCollider.bounds.Contains(enemy.transform.eulerAngles))
{
currentEnemy = //enemy with highest level threatlevel of enemies in sphere collider
}
}
Where would I go from there though? If i set currentEnemy = enemy in list with highest threat level, it'll go to the one with the highest threat level even if they are not inside the sphere collider. Is there another method to find a variable from a list in certain bounds?
(Please @ me if you respond. Thanks!)
does anyone know why there seems to be some sort of delay with the testing for clicking e?
like it doesnt seem to be registering all the times i press it.
invisible cooldown...?
You can't check input in a collision event. It needs to be checked in update.
ahh i see, thank you
i should prob put a bool on like trigger enter and then tell it to check in update
You can check whether the key is pressed at any time. You just can’t reliably query the input up/down frames in physics callbacks or fixed update
Why are my rows not even, and why is there an extra 10th colum or even worse as i increase the rows it becomes extra wide
private int LevelRows = 4;
private int LevelColums = 9;
//-------------------------------------
//Start Pos
Vector3 SpawnPos = StartPos;
for (int i = 0; i < LevelColums * LevelRows; i += 1)
{
//Spawn Target
GameObject ClonedTarget = GameObject.Instantiate(TargetObject, gameObject.transform);
//Apply offset
ClonedTarget.transform.position = SpawnPos;
if (SpawnPos.x < LevelRows)
{
SpawnPos.x += 1;
}
else
{
SpawnPos.x = StartPos.x;
SpawnPos.y -= 0.25f;
}
}
Im going to guess that StartPos is not 0,0? what is it?
is there a transform equivalent of Rigidbody.GetPointVelocity? as seemingly the velocity is the forces applied to it rather then the current speed.
It's -5, 3.75f;
this is because my tile ratio is 16 by 4
tiles go down by -0.25f;
it'd give the velocity of a specific point on the rigidbody which includes both linear and angular motion..
(say u had a cube moving forward and spinning around its pivot.. if u used a corner of that cube you'd get both that forward velocity.. but you'd also get the angular velocity of that point, making that number greater than its normal speed you'd call it)
you might could just use rb.linearVelocity.magnitude
or u can just make ur own speed calculations
Vector3 lastPos;
Vector3 velocity;
void Start() => lastPos = transform.position;
void Update()
{
velocity = (transform.position - lastPos) / Time.deltaTime;
lastPos = transform.position;
}```
That code only works by accident because the row count happens to be about half of the column count. The "standard" way to do this would be:
int LevelRows = 4;
int LevelColums = 9;
for (int x = 0; x < LevelColums; x++)
{
for (int y = 0; y < LevelRows; y++)
{
GameObject ClonedTarget = GameObject.Instantiate(TargetObject, gameObject.transform);
ClonedTarget.transform.position = StartPos + new Vector3(x, y * -0.25f, 0);
}
}
I'll try to forget the code you sent me and recreate it out of my head
thank you so much
Yeah, it wasn't initially, but i messed around quite abit with it
since it was being annoying.
The main thing is that don't start counting from the StartPos coordinates because they aren't really related to how many rows/columns there are in total . If the x position is -5 and total columns is 9, if you count from -5 to 9 you'll get 14 or 15
just remember 0 is the first loop
so ur row and col count would be (desired Amount - 1)
explain using the magnitude idea.
well velocity is the speed + direction
magnitude is just the speed
"Give me how fast this thing is moving, regardless of direction."
so if u were moving backwards at 10m/s
ur velocity would be -10 however the magnitude of that velocity would just be 10
ok when i meant speed i still meant a vector3, because i have a floating character controller that follows moving platforms using
rb.linearVelocity += hit.rigidbody.GetPointVelocity(hit.point);
```which works fine for kinematic moving platforms but if a have a rigidbody any time it changes direction its velocity at that point increases more than it should, it seemingly gets the force rather than the actual velocity at that point.
ahh, ya you'll get higher values like that when you get forces or impulses..
it'll spike b/c it hasnt had time to settle yet (using friction, dampening etc)
if u want a smoothed velocity you should probably just track ur own velocity over time instead of using unity's raw physics output
(like that code example i sent up above)
(currentPosition - lastPosition) / Time.fixedDeltaTime;
lastPosition = currentPosition;```
^ if ur calculating it urself and using the Transform it'd work regardless of if its a rigidbody, kinematic, or just a transform
that would give u a Vector3 with each axis showing its speed
i've tried that but i keep getting explosive results
rb.linearVelocity += (hit.point - lastPoint) / Time.fixedDeltaTime;
lastPoint = hit.point;
(2, 0, 1) would be moving 2 units/ second to the right and 1 unit/second forward
this is setting the velocity..
is that the intention there?
rb.linearVelocity += a is the same thing as rb.linearVelocity = rb.linearVelocity + a
❔ let me ask this.. cuz im a bit confused..
"whats the purpose of this mechanic"
like.. whats the game-plan..
i think that will help clear it up
well when i use addforce the player is barely moved. i just want to modify the player velocity so they'll stay on the platform.
ohhh
you could try setting it directly using the platforms velocity
rb.linearVelocity = platformVelocity
// you could optionally try to add some smoothing in the mix to avoid those big spikes
pointVelocity = Vector3.Lerp(rb.linearVelocity, pointVelocity, 1f - smoothing);
// Apply platform velocity to player (overwrites velocity, prevents explosion)
rb.linearVelocity = pointVelocity;```
i would rather add or apply a force to the player rather than setting it as that tends to break momentum and any physicality.
you could *grab it's velocity (without the platform) and + the platform velocity on top
that would keep w/e momentum and movement u already have going on
platforms are tricky..
(pretty simple to get them to work w/ a player that doesn't move)
but once u start walking and jumping on them.. it gets complicated
yeah i've tried that... and if that did work that wouldn't really help as you have to take into account rotation, which rigidbody.GetPointVelocity(hit.point) does.
// players existing velocity
Vector3 currentVel = rb.linearVelocity;
// platform contribution at teh contact point
Vector3 offset = hit.point - platformRigidbody.worldCenterOfMass;
Vector3 platformVel = platformRigidbody.linearVelocity + Vector3.Cross(platformRigidbody.angularVelocity, offset);
// Combine them
rb.linearVelocity = currentVel + platformVel;```
u can also make the rotation affect that platform vel u would add to the player ^
i'd have to test myself for anything more than this tho..
im just assuming it'd work but u know how assumptions go..
let me fire up my editor and see if that ^ works out on a platform..
(been putting off platforms myself for a while now)
sorry mate... but it still has the same issue with rigidbody.GetPointVelocity(hit.point) where it has strong forces when changing directions.
ahh fudge.. sorry thats about all i got
it is super early still tho.. so my brains a bit foggy still
could u share ur code?
that's ok, thx for your help.
the platform + player movement.. the relevant bits?
yea im not really sure how to deal with that tbh..
you could smooth out the values like the lerp i sent up above.. but that would smooth everything.. not just the direction changes
maybe u could smooth just the direction changes somehow..
altho im not 💯 sure how
well the movement part won't effect the platform stuff as it's just adding a force to the player but for the platform code i've already shown all of it.
At this point I almost gave up on this approach to make a rigidbody fps controller work, but before trying next one I would appreciate if anyone can figure out what's wrong with what I got so far, specifically:
Why is my camera stuttering only while I am strafing and turning camera around? Just strafing is smooth (rigidbody interpolation is on), just looking around while standing is smooth (also there is no friction on anything)
camera (nothing crazy, worked flawlessly with character controller basic movement, assume smoothing is 1)
void LateUpdate()
{
if (!isCameraLocked)
{
mouseinput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
mouseinput = Vector2.Scale(mouseinput, new Vector2(sensitivity, sensitivity));
smoothdelta.x = Mathf.Lerp(smoothdelta.x, mouseinput.x, 1f / smoothing);
smoothdelta.y = Mathf.Lerp(smoothdelta.y, mouseinput.y, 1f / smoothing);
mouselook.x += smoothdelta.x;
if ((mouselook.y + smoothdelta.y) > 90f)
{
smoothdelta.y = 90 - mouselook.y;
mouselook.y = 90;
}
else if ((mouselook.y + smoothdelta.y) < -90f)
{
smoothdelta.y = - (90 + mouselook.y);
mouselook.y = -90;
}
else
{
mouselook.y = mouselook.y + smoothdelta.y;
}
playerPosition.localRotation = Quaternion.AngleAxis(mouselook.x, playerPosition.up);
cameraPosition.localRotation = Quaternion.AngleAxis(-mouselook.y, Vector3.right);
}
}
and rigidbody (shortnd)
xInput = Input.GetAxisRaw("Horizontal");
yInput = Input.GetAxisRaw("Vertical");
desiredMovementVectorNormalized = transform.TransformDirection(xInput, 0, yInput);
desiredMovementVectorNormalized = desiredMovementVectorNormalized.normalized;
Vector3 targetVelocity = desiredMovementVectorNormalized * MaxSpeed;//Set a target velocity
Vector3 velocityChange = targetVelocity - movementVector;//Find the change of velocity needed to reach target
Vector3 acceleration = velocityChange / Time.fixedDeltaTime;//Convert to acceleration, which is change of velocity over time
acceleration = Vector3.ClampMagnitude(acceleration, MaxAcceleration);//Clamp it to maximum acceleration magnitude
body.AddForce(acceleration, ForceMode.Acceleration);
I wanted to use physics but keep perfectly controlled speed
b/c ur player is moving with physics Fixedupdate() and your camera (that i assume is a child of the rigidbody) is being modified in Update()
these two functions don't run at teh same rate...
so u basically get sync issues
player get movement forces at fixed update but turns with the camera at update through transform, would that still cause desync?
if ur using a rigidbody doesn't matter where u call the code.. it gets applied in the FixedUpdate()
but the Camera is gonna update in Update() which happens much more often
oh well...
soo thats why u have that happen
unity learn has a tutorial that shows how they solve the camera jitter but i can't find it off-hand
does charactercontroller move at update btw?
yes
now it making so much sense
that answers my "why" and I will find "how", thanks alot
not a problem.. good luck 🍀 if i can find that unity learn example i'll send it ur way
https://www.youtube.com/watch?v=cTIAhwlvW9M this might could help u out
the most common fix for it tho is
- Use LateUpdate(); for the camera logic
- Use Interpolation/smoothing for Rigidbody
also you can use Cinemachine (it has settings for changing how the camera logic works... you can set it to Update(), LateUpdate() or SmartUpdate <-- where it does magic and figures out things on its own..
Cinemachine is really useful for later on in ur game too, like to change cameras, transitions to cutscenes, camera shake, all that good stuff built in
found a thread that validates what i just mentioned
https://www.reddit.com/r/Unity3D/comments/z24l1v/how_to_fix_this_jittering_when_looking_around/
i couldn't do it myself, thanks for the script that handles it correctly.
i'll try to repeatedly write it until i remember it
It'd be more useful to understand what it does instead of just memorizing it
LateUpdate is still update, that would only help if I am not using phsyics, and as I said I turned on interpolation at the start and it would help with moving but not turning while moving
https://docs.unity3d.com/2023.1/Documentation/Manual/ExecutionOrder.html
this was my point saying that..
you do turn ur character in Update() ircc
edit: or maybe u don't im thinkin of someone elses code.. but either way thats why i mentioned LateUpdate().. if it doesn't help
I still linked that Discussion's link that has multiple solutions
🤔
you want late update because without it its possible the camera runs its update, then something the camera is tracking updates after throwing it off by a frame and making it always play catch up
I mean I know I want lateupdate, I missed the part saying I meant to detach camera for it to work
anyway that should work ima stitch something working
yep...
yep that just works and I think won't cause issues I can get from using SmoothDamp
I will have to spend some time thinking on details on WHY does it work
Do you mean that in FixedUpdate() you have some Rigidbody code like AddForce, but then in Update() you are just doing .transform.rotation = ?
@untold shore
Any reason to not use OnTriggerEnter and OnTriggerExit for that SphereCollider?
With that you can just keep a running list of "NearbyEnemies"
& yes no matter the method, it's unavoidable to loop through that NearbyEnemies list and check the threat level member variable
does unity have an object pooling system or will I have to make that myself?
They do have an objectpool object you can use but you need to define some functions yourself:
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Pool.ObjectPool_1.html
oh nice! thank you
seems easy enough, I thought I'd have to start from scratch but this looks good
cus my game spawns a lot of hitsparks so this will alleviate it a bit
I got a character composed of different layered sprites and I want to set the whole composition transparent but going through each sprite and setting the alpha means that parts that would be hidden now become visible
any tips on how to fix this? I was thinking I should merge all the sprites together into one, but that doesn't seem so straightfoward to do
do the merge in photoshop/gimp
not possible with all parts combinations
what's the end goal here?
but going through each sprite and setting the alpha means that parts that would be hidden now become visible
wdym?
I think thye're basically having a blending issue. They want the fully composite image to be alpha faded but instead when you set the alpha of individual renderers you get the thing where you see all the sprites under the other sprites
having a character display with different visual parts (e.g. clothing pieces, face, hair, body, etc.) then being able to manipulate that composition with alpha masks, flipping, etc.
ahhh this is like a modular character
sprite masks should help with that i would think
one option is rendering to a RenderTexture
Another option is to use a custom shader
sprite masks might work, I think..? like, each layer applies a mask to all layers behind it? might get heavy if I got a lot of layers? 🤔
rendertexture sounds promising but I've only ever used it with Camera.targetTexture. Is there a way to directly "write" a sprite to it?
never used shaders before so no idea where I'd start on that one
When would one want to use physics.overlap box over a collider with isTrigger enabled?
A collider with isTrigger enabled is mainly used for checking a zone/area. You wait for something to enter or leave . . .
when you want a direct immediate query workflow vs a reactive workflow
Do I need to consider processing power
If you want to check what is inside of a box at that moment in time (immediate), then you'd use an OverlapBox check . . .
Usually not a concern
I’d imagine being forced to use a rigidbody is pretty expensive even if it’s kinematic/statoc
Oh ok sweet
performance is almost never a concern for these decisions unless you are dealing with very large numbers of objects
Do u guys usually use a single CoroutineHandler to manage all the coroutines?
No. To what end?
I would only do something like that if I have some special requirements
Not every trigger collider needs a rigidbody, just one of the two in an intersection needs it
I see some projects use that as a to provide helper functions that help start coroutines, ideally from other singletons
I'm not sure if that is a thing in common. Most I have seen only about few dozen lines of code
usually they do this to ensure they have an "always active" object to run the coroutine on so they don't run into the issue where they deactivate the object running the coroutine which kills the coroutine
it could be useful to you if you are running into that issue
otherwise it doesn't add much value
hi, im trying to add ads to my game and it seems to work, but when i try to build the game to test it i get this
This is the beginner programming channel. Try moving your question to #💻┃unity-talk
ok sorry i sent here cuz im also a begginer
Is this the right place to ask about Unity Learning problems for beginners?
For beginner coding problems? Yes. For regular Unity problems? check out #💻┃unity-talk
Also, check out the other channels if your problem fits a specific topic . . .
So I am learning how to build the "Tanks" game. And when I go to my prefab>levels> and selct the levels and load it, both the preview, and the loaded level, are all pink, and do not show me the assets, just their wireframe location
Should I snip a picture for reference?
that doesn't sound like a code issue
but see this for how to go to the correct view mode: https://docs.unity3d.com/6000.2/Documentation/Manual/ViewModes.html
and this for shader issues (pink materials): https://unity.huh.how/shaders/errors
That usually happens when there is an issue with the materials or shaders; namely, a shader is missing or incompatible. Make sure you are using the correct render pipeline and follow the links boxfriend sent above . . .
I usually fix that in the Render Pipeline Converter since I have not done anything fancy with shader yet
But I don't know what else it changes in the project
So I went to Window>Rendering>Render PipelineConvertor
And that worked. I can see my beautiful level now...
My beautiful prefab learning tutorial level that is
hey i made this marching cubes algorithm and i also tried interpolating it but i always get these weird artifacts idk how well you can see the in the image. i dont know how to fix it or whats wrong but its very annoying
these are the most important pieces of my code:
https://paste.mod.gg/lueynfznykew/0
A tool for sharing your source code with the world!
Hey! Quick question
I’m setting up my Unity project with Git for a university assignment, and I’m a bit confused about the .gitignore.
My Git repo has a subfolder for the Unity project (for example: repo/Project1/).
Should the .gitignore go in the main repo folder or inside the Unity project folder?
I saw this one from GitHub:
👉 https://github.com/github/gitignore/blob/main/Unity.gitignore
Can I just use it as is, or do I need to change anything for this setup?
into the project folder like projectRepo/ActualProject/.gitignore
Thank you I will try it and I had some issues the first time
yes I was doing that
second time I am screwing up trying to move rb through transform at Update and wondering why is it not working as expected, hopefully the last
I tried it but I still have the issue that I have 10K changes and I think its because I need to ignore the Library and stuff but It just doent work qwq
Or do I have it wrong and this totally normal?
no thats definitely not right. tbh im not really a pro, im just searching for the unity gitignore on github desktop, put it in my project folder and it works
did you already commit the library folder before adding the gitignore?
nope the repo is empty right now
Oh so u just get he ignore from the internet and downloads the file and put it inside your project? Could it be because I use Visual Studio Code?
Show another screenshot but the git tab open
im not sure tbh, i use github desktop which automates the process a lot
Show the graph at the bottom of the page
I dont have a graph there
In this one click the X in the orange box so that it doesn't cover the top
Git is definitely ignoring the correct files
ideally change the view mode in the git view to organize the changes by folder then it will be more obvious where these changes are coming from and if they are from folders that should be ignored
I got a GitLab repo from my professor (it was empty — no README or anything).
I cloned it, and then I created my Unity project directly inside that repo folder.
After making a few quick changes in Unity, I opened the repo in VS Code to commit.
Then I downloaded the Unity .gitignore from this link 👉 https://github.com/github/gitignore/blob/main/Unity.gitignore
and placed it in the repo.
But even after adding the .gitignore, Git still shows around 10k changes (mostly Library, Temp etc.), which is super confusing 😅
Did I maybe put the .gitignore in the wrong place, or should I have set it up before creating the Unity project?
oh but now it says only 96 changes maybe I just needed to wait 🥲
Can anyone help me? My camera position does not reset when I stop moving, and yes, I set m_OriginalCameraPosition to m_Camera.localPosition on the first frame
public void Bob(float magnitude, float speed)
{
if (magnitude > 0f && (PlayerInput.Instance.Horizontal() != 0f || PlayerInput.Instance.Vertical() != 0f))
{
m_Camera.localPosition = DOHeadBob(magnitude + speed);
}
else
{
m_Camera.localPosition = Vector3.Lerp(m_Camera.localPosition, m_OriginalCameraPosition, 0.2f);
}
m_CurrentCameraPosition = m_Camera.localPosition;
}
If it helps at all, the next time I move it "snaps" to the original position before starting the head bob again. Please ping me if anyone has any ideas
show more context
Okay
Try logging the values that were used in the if statement expression
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.
if you're going to use pastebin, at least have the courtesy to select the correct language so there's syntax highlighting.
anyway, where is Bob being called
Where do you call this function? If it just runs in a frame then that check wont do anything
My camera position does not reset when I stop moving
Assuming you're referring to else not ever occurring
I call it in my own player class, and it is per frame
No, it fires, because whenever I DO move, it snaps to the original position before reinitializing the head bob
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class Player : ODSingleton<Player>
{
[Header("References")]
[SerializeField] private CharacterController m_CharacterController;
[SerializeField] private Transform m_CameraContainer;
[Space]
[Header("Extensions")]
public PlayerMovement m_PlayerMovement = new PlayerMovement();
[Space]
public PlayerLook m_PlayerLook = new PlayerLook();
[Space]
public PlayerHeadBob m_PlayerHeadBob = new PlayerHeadBob();
[Space]
public PlayerFOV m_PlayerFOV = new PlayerFOV();
private void Awake()
{
m_CharacterController = GetComponent<CharacterController>();
m_PlayerMovement.Setup(m_CharacterController);
m_PlayerLook.Setup(transform, m_CameraContainer);
m_PlayerHeadBob.Setup(m_CameraContainer, 8f);
m_PlayerFOV.Setup(m_CameraContainer);
}
private void Update()
{
UpdateInput();
}
private void UpdateInput()
{
if (m_PlayerMovement != null)
{
m_PlayerMovement.UpdateMovementInput();
m_PlayerMovement.UpdateMovement(transform);
}
if (m_PlayerLook != null)
{
m_PlayerLook.GetInput();
m_PlayerLook.Rotation(transform, m_CameraContainer, (m_PlayerMovement != null) ? m_PlayerMovement.HasGravity : false);
m_PlayerLook.UpdateCursorLock();
}
if (m_PlayerHeadBob != null)
{
if (!m_CharacterController.isGrounded || m_PlayerMovement == null)
return;
float magnitude = m_CharacterController.velocity.magnitude;
float speed = m_PlayerMovement.CurrentSpeed;
m_PlayerHeadBob.Bob(magnitude, speed);
}
if (m_PlayerFOV != null)
{
m_PlayerFOV.CheckStatus(m_PlayerMovement != null ? m_PlayerMovement.IsRunning : false);
}
}
}
!code 👇 use a bin site for large blocks of code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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.
Hey guys! I'm Jaylan. I'm having a bit of trouble with my Senior Project. You see, I imported an asset called Demo City by Versatile Studio and I successfully added a day/night cycle to it. When I tried to get my spotlights to dim and brighten with my day/night cycle, I noticed that they weren't dimming at all.
I thought it was an error in my script (I have two scripts, one called TimeManager that rotates a Directional and the other called SpotlightManager), but I'm not sure if it's a coding issue. I think it has to do with the fact that the spotlights are GameObjects inside a larger GameObject called LIGHTING and that I'm struggling to connect them inside of Unity Hub.
Is someone able to assist me? I'll send over my scripts, assets, or whatever I need to as long as I'm able to figure this out.
this applies to you too #💻┃code-beginner message
Why do you care if it's in the bin or not @slender nymph ? Not being rude just curious. IT all fit in discord
because it's easier to read when formatted properly on a bin site and doesn't flood the channel. it's also just common courtesy to follow server guidelines
Whoops, I apologize
Oh okay
Yeah, u can’t really read that code on mobile
Well can anyone tell me what's wrong?
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.
if you're going to use pastebin, at least have the courtesy to select the correct language so there's syntax highlighting.
- Me, 5 minutes ago
Bro, you told me to use pastebin, why say "if you're going to use pastebin"
people are so picky, but I'll do it
Try placing some logs to see the value of the if statement
i never said use pastebin specifically, i just said use a bin site and called up the bot which links several that have automatic language detection
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.
there's a reason pastebin is not listed in the bot embed, and it's because it's terrible.
Okay well I made it use syntax highlighting like you wanted
I am having a problem with my game i have a character model with player movement and animations it is first person and the problem is that when i run or move the camera shows the back of the players head because the animation makes the player lean forward a bit when moving how can i fix this
show relevant code. also https://screenshot.help
If this isn't a code question then likely you meant to post this on a different channel.
Just remove the head
That's how AAA studios do it
ya but i might add thrid person or make it multiplayer so there needs to be a head
Are u sure u are tracking the head?
yes
Okay well Unity has layers. Maybe in first person, disable the head by giving it a layer, then in third person, enable the layer
Then just make it 3rd person
i don't want to i want it to also be first person
Bro what did I do to you? I enabled syntax like you wanted
do you know of any videos showing how to do that
I can look some up
that was not in response to you.
I know
thanks cuz i don't really know what to look up
But like you never messaged again
Are u using cinemachine?
you are not entitled to anyone's time. if i find someone to be annoying i am allowed to stop engaging with them.
no i don't think so i am following this tutorial https://www.youtube.com/watch?v=cGLByetxC00
In this part, we'll cover slope handling, wall handling and steps. Slopes are a difficult part of any player controller, and we make use of our state machine and antibump parameters to ensure near perfect edge detection and amazing ground detection.
This is part of a free complete course for making a player controller, I hope you enjoy it!
·...
How the heck am I annoying. I did what you asked. I enabled syntax
@fervent bramble
using UnityEngine;
using System.Collections;
public class ObjectVisible : MonoBehaviour
{
public LayerMask MyMask;
void Update()
{
foreach(GameObject g in FindObjectsOfType(typeof(GameObject)))
if (g.layer == MyMask)
g.renderer.enabled = false;
RaycastHit[] hits = Physics.RaycastAll(transform.position, transform.forward, Mathf.Infinity ,MyMask);
foreach(RaycastHit hit in hits)
Renderer renderer = hit.collider.renderer;
if (renderer)
renderer.enabled = true;
}
}
Its a slight change, but you can tidy part of the code up
bool AllowUpdateInput {
get {
if( m_PlayerMovement == null ) { return false; }
if( m_PlayerLook == null ) { return false; }
if( m_PlayerHeadBob == null ) { return false; }
if( m_PlayerFOV == null ) { return false; }
return true;
}
}
void Update() {
UpdateInput();
}
void UpdateInput() {
if(!AllowUpdateInput) {
// make sure all the components exist so you are allowed to continue
return;
}
// now you dont need all the if statements inside this method
m_PlayerMovement.UpdateMovementInput();
m_PlayerMovement.UpdateMovement(transform);
...
}```
how do i make the mask or layers
Top right of unity, in the inspector, layer dropdown, add layer, type in layer, enter, go back to object, then dropdown layer again and pick it
thanks
https://paste.ofcode.org/pPL2edWV55G298bpcwCsHB
https://paste.ofcode.org/HgauYzJYVFdG4x3cw8DDja
Again, I apologize for earlier. As I said, if there's anything else that I need to send over in order to get the proper help that I need, then please lmk (This goes for anybody).
You're welcome. I actually try to help and not just dance around like @slender nymph
lol
Oh it's because you need to put closing parenthesis on the foreach
ok thanks
could you send me the updated code cuz i can't tell where to put those parentheses
No I'm not gonna be your code monkey
ok sorry i just don't know how to code but its fine i guess
Learn like the rest of us
That's what I'm TRYING to do but boxfriend wants to be a dick
i am trying to that is why i ask for help becasue that is how i learn
ya i see that
Double-click the error message to see which script it is. The specifies at line 16 and column 13
ya no i fixed it with visual studio copilot and it just added the paretheses he said it needed but th escript doesn't work as intended
Yeah we do not recommend it. It can fix other stuff especially if u don’t pay attention to your code
can someone help me fix it because i cant seem to figure out what to do
you're missing opening and closing brackets for your second foreach statement
oh ok so like this foreach (RaycastHit hit in hits)
{
Renderer renderer = hit.collider.renderer;
if (renderer)
renderer.enabled = true;
}
No need to ping me dude
shit
As best practice especially for a beginner i would recommend using opening and closing brackets for all of your for and if statements, even if they're only one line.
i was refrecing the code
Could've just copied it
yes but with better line indentation
dude chill
i am so lost i can't get it to work
oh wait
nvm i think i got it
Sorry I'm just... I hate boxfriend because he told me what I needed to do, I did it, then he went "Uhm, not my problem" like wtf
i get that that i skinda what is happening with me but don't stress it
Wait no wi get this error
"MissingComponentException: There is no 'Renderer' attached to the "[Debug Updater]" game object, but a script is trying to access it.
You probably need to add a Renderer to the game object "[Debug Updater]". Or your script needs to check if the component is attached before using it.
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <41b87322553648a1a76174c5109c71f9>:0)
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <41b87322553648a1a76174c5109c71f9>:0)
UnityEngine.Renderer.set_enabled (System.Boolean value) (at <41b87322553648a1a76174c5109c71f9>:0)
ObjectVisible.Update () (at Assets/AdamOKeefe/FinalCharacterController/Scripts/HidePlayerHead.cs:11)"
Add a Renderer
to the object
a mesh renderer
how?
If by "enabled syntax" you mean "configured your IDE" they told you to do that because it's a requirement to get help here from anyone. That wasn't them volunteering to solve your problem just telling you that most people who can help would just literally ignore an unconfigured IDE
go into the inspector, there's a button that says add a component
then type in mesh renderer
yup got it
I thought he meant enable it in pastebin
No that is what he meant
because my IDE has highlighting
wait but should it be on the whole palyer or each of the peices i want to hide
each
oh ok let me try
Still generally a good idea. If you want people to help you then you should make sure to make your code and question as easy to read as possible
Indeed, the easier it is to read someones code its then easier to provide aid
Yeah that's what I did, and then I said "Bro, I enabled syntax, why are you ignoring me" and then he went "You're annoying". Like... why ask you to enable something if you're just gonna ignore it
I apologize for being rude but I literally have a learning disability, like... at least tell me how I'm being rude
or annoying
i am still getting the error i don't know what to do now. Both the head and neck have mesh renderers and have the layer set to layer
Because you replied to them answering someone else and demanded they focus on you instead. Quite annoying.
You know what? Sorry for earlier. Let me try it on my own and I'll get back to you
its okay and thank you
or if its easier i can add you and then share my screen
Nah, I don't do well that way. Better if I just debug it on my own
ok thanks if it is helpful the player model i am using is https://assetstore.unity.com/packages/3d/characters/humanoids/fantasy/free-low-poly-human-rpg-character-219979
Hey- current thing I’m working on from some advice yesterday.
Currently, I’m trying to find the highest value (the threat value) of an enemy who is inside a collider. Currently, I’m having trouble figuring this out as I’ve seen how to do it for ints, but not for translating this into game objects.
Here is the current script for this specifically (it’s small, but I’m on mobile currently as my desktop discord is broken)
https://paste.ofcode.org/sidxbtp8fqxR2FRCR9gciz
My main question is this: can enemycollider[].max(value) become translated into a game object, or should I attempt to do this process another way? (Please @ me when you respond, though it may take me a second to respond back due to being occupied with work, thanks!)
Better would likely be for you to manage "things" separately from colliders and threat. ie:
public class EnemyMonsterDude : MonoBehaviour
{
public Collider HitBoxCollider;
public int Threat;
public string Name;
}
var enemy = _enemies.OrderByDescending(x => x.Threat).FindFirstOrDefault(y => .. is this enemy inside a collider we care about);
if (enemy != null) .. hit that enemy ..
Dunno if that makes sense, sorta pseudo-codey but might get you on the right track.
(note that I sort by threat first since that's cheap - colliders are more expensive, if you're gonna be doing it every frame or whatever)
That makes so much more sense, I didn’t realize order by descending was a thing! I’ll fix up my code by that. Thank you so much!
@fervent bramble
private void Awake()
{
for (int i = 0; i < gameObject.transform.childCount; i++)
{
GameObject _gameObject = gameObject.transform.GetChild(i).gameObject;
if (_gameObject.layer == LayerMask.NameToLayer("Cube"))
{
Renderer renderer = _gameObject.GetComponent<Renderer>();
if (renderer == null)
return;
renderer.enabled = false;
}
}
}
Just replace "Cube" with "Head"
Idk if the head is separate
Small nit - change return to continue or it'll stop trying to find a renderer if the first item it finds without one doesn't have one
Thanks
gameObject.transform?
transform is already a property for "our" transform in a monobehaviour
yes
Also id recommend only 1 use of NameToLayer() outside the loop
do they still need to have the layer set as layer and have mesh renderer
Wdym
does teh head need to have the layer set to the custom layer named "layer" like the old script an ddoes the head also need a mesh renderer
It has a mesh renderer, it just needs the "Head" layer
maybe simpler:
int layer = LayerMask.NameToLayer("Cube");
foreach (var renderer in transform.GetComponentInChildren<Renderer>(includeInactive: true).Where(x => x.layer == layer))
{
renderer.enabled = false;
}
Hangon, is this all to find the head in some model?
for a beginner id say no this is going to confuse them
no it i sto make teh camera not show the head bacuse durring some animations the camera shows the back of the head but it is first person
perhaps but.. fewer lines of code maybe simpler so fewer off by 1 or unrelated bugs
Why not have a serialized reference already setup so you can show/hide the head without weird code to locate it layer?
so make the layer a newlayer named "Head" and give it a mesh renderer component
becasue i don't know how to code
[SerializeField]
MeshRenderer head;
yay we can drag in the head in the editor and reference it that way
what do you mean
The head already has a renderer
You know that a MonoBehaviour can have "serialized references" where we can drag and drop things in via the inspector ui?
wait the script hsould be attached to the whole player right or just the head
ya
The whole player - but you can add multiple references to whatever pieces that script needs to reference
Cool then we can use this to define a variable using this and drag in what we want to reference, such as the head mesh renderer
public class PlayerGuyThing : MonoBehaviour
{
[SerializeField] private MeshRenderer Head;
[SerializeField] private MeshRenderer Butt;
}
thanks
Is there a way to find all sprite renderers showing a certain sprite in unity?
in the editor? At runtime?
At runtime
Probably track them manually, iterating through every game object in a scene will be slow and expensive
yes but it will be slow and inefficient and there are better ways to do what you aretrying to ultimately do
what's the actual gameplay idea here?
so wait what should my code be because i don't see any {SrializeField} anywhere in the code
your code should look exactly like this
It's a multiplayer game, where I have a spell casting item. All players that have certain spells equipped in different gear slots, should have something happen to that sprite.
just that nothing else
with brackets[SerializeField] not braces and misspelled{SrializeField}
I should probably just do it through the equipment system instead, but would be SO easy to call the sprite renderers 😛
Ok but the sprite renderer is the presentation layer. You should deal with your actual game data to do this, not the presentation layer
putting [SerializeField] before a variable in a script makes the editor show it
Does Cinemachine still have the virtualCamera? I can't seem to find it