#💻┃code-beginner
1 messages · Page 802 of 1
You don't need any of those.normalizeds pretty sure
ya maybe if you use a projectile, then normalizing would be good to do
Otherwise you end up shooting faster bullet when they are further from you
for the Vector3 probably no
Also note these are extremely minute details, not really worth getting stuck on
I think I always normalized since I only need the directions with a magnitude of 1
@rich adder So I managed to seperate the Camera code from the PlayerController. Now I have 2 scripts (one for movement and one for the camera). Is this what you meant with the method?
sure this way also works fine, though I meant mainly the Scripts the processes inputs
its good practice to change values through methods though so you're on the right track
now playercontroller doesn't care where it gets speed changed from, which is good
imagine you have a speedbooster or something else, its as easy as calling that method
any idea why i get his error on a fresh unity project? : built-in render texture type 3 not found while executing (SetRenderTarget depth buffer).
could be a busted template / editor version ?
try different version
its probably nothing to worry about, restart the editor and see if it comes back
what template did you use, and what unity version are you on?
Can I ask if im accessing the HandleBallReset method from the Ball script inside the player Controller script correctly?
public class PlayerController : MonoBehaviour
{
public InputActionReference resetBall;
public Ball ball;
private void Update()
{
ResetBall();
}
private void ResetBall()
{
if (resetBall.action.WasPressedThisFrame())
{
ball.HandleBallReset();
}
}
}
public class Ball : MonoBehaviour
{
private void ResetBallPosition()
{
transform.position = new Vector3(xAxisStartPosition, Random.Range(-yAxisSpawnRange, yAxisSpawnRange));
}
public void HandleBallReset()
{
ResetBallPosition();
InitialLaunch();
}
}
Just create the reference with Ball ball and doing the drag and drop in the inspector?
not seeing any issues that stand out
is there something specific you have in mind with regards to correctness?
sure - but are you sure the code is even running? With InputActionReference most of the time you'll need to do resetBall.action.Enable(); before you can use the action
i will note that that ResetBall method isn't named very accurately
it does work without those Enable Disable thingies
and it doesn't really need to exist to begin with
so what's the question then?
is it not working?
my question was about accessing a method from another script
how is it done correctly
there's no single correct answer
yes you have done so correctly.
- Get a reference to an instance of the other script
- Call the method on the reference
Assuming you've assigned the reference in the inspector, this is fine
there are several valid answers and several invalid/problematic answers
I did. I saw tutorials using the GetComponent method too
Something like
it's kinda like you're asking if you painted something correctly
did you destroy the brush? no? it's fine
GetComponent is another way to do step 1 - getting the reference
Personally i just reference it directly and that’s been working well, i would love to hear or experiment other methods tho.
@rich adder@swift crag i used editor verision 6000.1.8f1, gonna download newer now
that works too, but if there's some specific component on the object that's desired then it's easier and safer (in terms of workflow) to just use that type directly for the serialized field
yeah that's fine
nothing wrong with that, always guard it with a null check Or even easier
a TryGetComponent
there's also TryGetComponent that could simplify the presense check
if(other.TryGetComponent(out Ball ball)){
// we do have ball component
ball.dosomething```
yep, you're just getting a reference to a Ball here
okay thanks for your input guys. im yet to do null checks myself, I do realize its absolutely needed in development
null checks are not absolutely needed. They are needed in scenarios when they are needed.
i do get the reference errors if i forget to assign objects
that's a good thing
If you added a null check that squelched the error, then you would just never know you forgot to assign it
And you would be scratching your head about why the game isn't working right
So is it just to prevent crashes?
It has nothing to do with crashes
but the game stops
it certainly does not
the opposite
the current script execution context stops
if I get the exception error
other scripts will continue just fine
The right time to put a null check in your code is when a reference being null is a normal and expected part of the operation of the game
Unity Editor has "Pause on Error" which would stop it but in a build it wont
If you have something that should never be null, silencing the error is counterproductive
Ah yes, I forgot about error pause
that's just a debugging tool in the editor
Note I'm not arguing that you should just let NullReferenceExceptions happen and ignore them
When you get one of those you either need to go fix whatever reference is broken, or you need to evaluate whether the code should expect something to be null sometimes and handle it appropriately
I tried it and it seems the play mode just pauses
yeah due to the error pause setting in the console window
if you turn that off it won't pause
well now I learned something only today ^^
so these null reference errors arent a bad thing?
No more than a fire alarm is a bad thing
the fire is the bad thing
the alarm is good
it's telling you about the fire
a good time is to do additional logic if something is null (null check)
Sorry Chris I missed your message. Why it doesnt need to exist? Im calling it in the Update method to check if the button was pressed
imagine you are holding a Ball ?
can we pick up a ball ?
We do null check to see if we already hold a ball in our hands
if(hands.Ball == null){
//we are not holding a ball already,we can pickup another
PickupBall();
else
DropPreviousBall(); //or whatever```
yea
you can do the same thing directly in Update
I was aware, but I thought it would be more clean to only have method names inside the Update instead of having lots of separate behaviors happening, which was harder to read for me?
private void Update()
{
Move();
RestrictMovement();
ResetBall();
}
this looks easier for me
than this
private void Update()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2();
Vector3 finalInput = verticalInput * (movementSpeed * Time.deltaTime);
transform.Translate(finalInput);
if (transform.position.y > yAxisBoundary)
{
transform.position = new Vector3(transform.position.x, yAxisBoundary);
}
else if (transform.position.y < -yAxisBoundary)
{
transform.position = new Vector3(transform.position.x, -yAxisBoundary);
}
if (resetBall.action.WasPressedThisFrame())
{
ball.HandleBallReset();
}
}
having seperate methods is always preferable IMO
its cleaner looking but also you can use them other places if needed, like reset ball
that is true for me at least for now
its good practice, you're on the right track 
I was tought to do everything into methods and call them wherever I need them
not taught but more like advised how to go about organizing code
and dont get me started about variable, method names haha
if you have multiple things sure, but if the only thing a method does is delegate to 1 other method then no reason to separate it out
also makes debugging easier, so you can just comment out a specific function instead of a whole block of code
but personally i would have the input handling still in update and only call Reset (via the method or the ball's method) in that conditional
if using polling HandleInputs() is not uncommon to have in Update()
btw are you using physics because transform.Translate(finalInput); you might wanna switch this to a kinematic Rb / constrained axis dynamic rb.
You will get a much more accurate simulation / hits
im moving my paddles with Translate and the ball is moved with a rigidbody
should I move the paddles with physics too? they do seem to collide alright at the moment when the ball is set to continuous detection
and the paddles are collliders as well? they should be moved via rigidbodies then
not necessarily with physics, but at least via a rigidbody
yes the ball bounces from them
otherwise that's a desync+resync every physics tick if i'm not mistaken
it does but at varying FPS you might get issue
it recreates the colliders that have moved without a rigidbody every fixed update which can get expensive
the Physics has to catchup to where Translate put it, instead of the other way around
so basically if someone is moved and collided with its better to keep everything in sync, if one is a rigidbody the other should be a rigidbody aswell?
if something moves and interacts with physics it has to most likely have a physics body
kinematic if doesn't need to be affected by other physics and act as a moving obs
it's not that - if it has a collider and is moved, it should be moved with a rigidbody (except CC, which is its own thing)
so can the paddles be kinematic? wont they be "see through" ?
wdym "see through"
no, you're thinking of a trigger
when I make something kinematic its not affected by physics, so its not colliding?
or am i mixing something
it can interact with physics, but it doesn't simulate physics on itself
no velocities, no forces
but it can collide/apply forces to other things
oh so thats perfectly fine or pong paddles since they move up and down
so I can move them with linearVelocity property as well?
Kinematic rigidbodies do not respond to forces, but can exert forces
Unity2D engine is weird than 3D, they do have velocity but you should move them via MovePosition method, its similar to translate but you need to add the current rb.position of it
Hi all, it's been a while.
I'm trying to figure out a system to generate my gameworld (top down game, the 'ground' is tile based, with everything else spawning in a non-tile based way). At the moment the only way I can think of doing things in a sequential manner as per the code in the link (no actual logic inside the various methods as yet, just an example.
https://hastebin.com/share/unaturutut.csharp
Would anyone be able to point me in the right direction of some methods to look at please?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Will the oncollision function work with a kinematic paddle?
i think I read that 3D rigidbody velocities shouldnt be changed but 2D is fine
im moving the ball with linearVelocity too
Kinematic in 3D wont let you move via velocity it just sets to 0. In 2D is a differnt engine so works a bit different
for 3d, no
for 2d, yes
oh yeah im only talking about 2D now, 3D has to be used with a method
that's not related to 2d/3d. that's just a warning that setting velocity directly can make it unrealistic physically. there's no technical limitation
yeah you can use velocity for 2d kinematic, though I personally still prefer MovePosition
I remember this to be true, everything seemed fine until I read the documentation
it's easy to get confused by the differences
2D is Box2D and 3D is PhysX
so they have fundamentally different behaviors
I mostly do 3D physics, so I get tripped up by 2D behaviors a lot
Note: MovePosition is intended for use with kinematic rigidbodies.
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody2D.MovePosition.html
but yeah up to you in 2D .
the documentation does state this reasoning
some cases you don't care about unrealistic behaviour, or you're modulating the velocity yourself, or you want more control
In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour
Do not set the linear velocity of an object every physics step, this will lead to unrealistic physics simulation.
I guess MovePosition works too but have to also multiply with fixedDeltaTime which isnt needed for linearVelocity. I will try both ways now, thank you ^^
objects teleporting isn't realistic either - but sometimes you do need that for game reasons
regardless, they should be in Physics tick aka FixedUpdate
but thanks for clarifying that the paddles preferably have to be rigidbodies too
oh now I have an idea, since the paddles will be kinematic rigidbodies I can add a physics material so that when the ball touches a paddle it can also slow down using friction on the paddles? all this without code
this can work right?
slow down in what sense?
just out of curiosity
in pong the balls generally bounce right off the paddles, so not sure what you're going for
that mainly affects the collider itself usually, so if you put friction on the collider yes the ball will try to "stick" on it
ball hits paddle, ball velocity slows down due to added friction on the paddle
i know this doesnt make sense in the pong game, just my mind spinning now ^^
well, if the ball like, rubs against the paddle without rolling, it'd slow down as it simulates friction
private void Move()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2();
Vector2 finalInput = verticalInput * (movementSpeed * Time.fixedDeltaTime);
myRigidbody.MovePosition(finalInput);
}
So this method would be used inside FixedUpdate method now correct?
or not necessarily?
in general input is frame-bound, but since this is a ReadValue it's fine to be here
(though, you are missing a closing > on that)
Yeah I delete it once copying here
you need to add myRigidbody.position in the calculation to make it local
can you expand, not sure what you mean
MovePosition takes a position, not a delta position
as shown here rb2D.MovePosition(rb2D.position + velocity * Time.fixedDeltaTime);https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody2D.MovePosition.html
i thought this was in 3d?
huh, mustve been remembering someone else's chain of discussion
I'll have to read up on that why that is
otherwise you're moving in WorldSpace rather than Local to your object
private void Move()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector2 finalInput = verticalInput * (movementSpeed * Time.fixedDeltaTime);
myRigidbody.MovePosition(myRigidbody.position + finalInput);
}
So this method should be in FixedUpdate or Update?
Ohh okay I have a vague understanding what you mean here
i feel like that's not quite accurate
you'd be moving from the origin every tick
did mention it briefly here ^
yeah but its default expects a World-Space target pos
unlike Translate that defaults to Space.Self
fair enough
i don't think that's comparable, that's about global/local axes
RB.MovePosition is always global
the difference is that MovePosition takes a target position, but Translate takes a.. well, a translation from the current position, a delta position
we basically saying the same thing kinda lol
hmm the movement is off once I made the paddles rigidbodies
sometimes its out of sync, or seems to move by themselves with lots of latency
well.. yes, we're dealing with the same facts. i just think how you've explained it is kinda unclear
true true. It happens at times lol
I guess the difference is MovePosition wants absolute position, translate expects amount to move
yeah that's what i'm trying to convey lol
yea I see mb
might need to show full code to see how everything links together in your current iteration
!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.
hmm seems to have fixed itself when I unticked Freeze Position on the X axis
I dont have inputs on X axis anyway but I saw the transform position is changing very tinnily
So I think freezing the X axis somehow induced this strange behavior
well, your moveAction was a Vector2
(is that other axis even hooked up to anything? why isn't that just an axis (float)?)
tru this is misleading
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
should just be
float verticalInput = moveActionReference.action.ReadValue<Vector2>().y;
public class PlayerController : MonoBehaviour
{
public InputActionReference moveActionReference;
public InputActionReference resetBall;
public Rigidbody2D myRigidbody;
public Ball ball;
public float movementSpeed;
public float yAxisBoundary = 3.05f;
private void Update()
{
RestrictMovement();
ResetBall();
}
private void FixedUpdate()
{
Move();
}
private void Move()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector2 finalInput = verticalInput * (movementSpeed * Time.fixedDeltaTime);
myRigidbody.MovePosition(myRigidbody.position + finalInput);
}
private void RestrictMovement()
{
if (transform.position.y > yAxisBoundary)
{
transform.position = new Vector3(transform.position.x, yAxisBoundary);
}
else if (transform.position.y < -yAxisBoundary)
{
transform.position = new Vector3(transform.position.x, -yAxisBoundary);
}
}
private void ResetBall()
{
if (resetBall.action.WasPressedThisFrame())
{
ball.HandleBallReset();
}
}
}
your RestrictMovement is still modifying the transform from Update
so the code inside is fine but it should be in fixed update since its tied to the rigidbody?
no, you shouldn't modify the transform at all, it should all be via the rigidbody
myRigidbody instead of transform
you should not use transform.position at all, is what they are saying . . .
hmm okay, ill try that
yknow you could probably just have this as a dynamic rigidbody colliding with the walls and then set linearVelocity every tick
not saying that's better, just an alternative
that could work too yup
yeah i usually do it that way for pong like game / breakout.. much easier to deal with if you have any dynamic playing field
going to take a brake and see how can I restrict the movement so the paddles stay inbounds
just lock your Constraints so it doesnt get pushed / rotated by colliding bodies
oh rigidbodies have a position property as well, didnt notice that
is there a way to stop the paddle to jitter once it reaches its boundary?
when I keep the input pressed it wants to go in and out with this jittery behavior, this didnt happen with transform.position
you could probably check for bounds before doing the MovePosition
you get a target position from the current position+input, so you could clamp that before applying it to the rigidbody
Hey, I’m new to Unity and game development in general.
Today I finished the Essentials tutorial, and in that tutorial, the character movement was controlled using Vector2 input for horizontal movement, and jumping was done using upward force on a Rigidbody.
Now I’m trying to do stuff on my own, and ChatGPT gave me a code where movement is handled using Vector3 calculations on a CharacterController, and the jump ignores physics forces.
Which approach is better? I want to make a Super Mario 64–style game.
should I be adding/removing listeners for buttons the same way as for any other events (OnEnable/OnDisable), or is that handled already anyway?
you can try
rb2d.Cast before moving
the better approach is not using ai-generated code tbh
but about the jumping, it's hard to comment without seeing what exactly that logic is
CCs don't really have physics to begin with iirc?
and guessing magic spells as a beginner coder is better? 😄 I want to start creating games and not learn C# for 2 years to get moving. Also AI is still a tool that can help out a lot, so its not a bad thing. In fact without it, my character model would still be stationary, now its at least moving
no, use actual reliable sources
no big locig behind it, get the character moving with wasd and jumping with space like every other game
"don't use AI" ≠ "don't use existing resources"
I dont know any
you just mentioned one, the unity learn
you can find several via google or youtube as well - quality may vary, but overall it's still better than the overconfidence of AI tbh
in the tutorial they provide most of the code except a few lines that you have to code yourself, tiny stuff. Also they mention themself to use AI for code generation in some scenarios
yeah, gotta keep the shareholders happy...
i'd still recommend against it
anyways, you could try researching about the other lines, the ones that were provided, through docs or forums as well to get a better understanding
if that's not working out, you can ask here
my character model would still be stationary, now its at least moving
yet if something breaks or you need to extend on it you won't know how it works, its a black box now..you learned absolutely nothing
ofc you do, you can write code like texting a friend. Im still confused at stuff like void
i recommend against AI for anything related to learning, not just things i already know
if you typed " what is void c#" you will get plenty of answers
that's a good starting point, being able to identify the gaps in knowledge - you can research that by just searching google with the right context, really (as mentioned above)
thats true, been there when I coded my website, now knowing html and css I wouldnt do it again but C# is a different beast, you cant just learn it by reading trough code a few times
if you build a base knowledge you can
and we aren't saying to do that! utilize the available resources - docs, guides, tutorials, etc online
there's an official c# guide by microsoft for example
one more thing, do I need to know ALL C# commands and building blocks or is most of the stuff irrelevant for unity?
most stuff is useful to know. you might not use all of it, but it expands your options.
"c# commands" isn't really a thing
one sec
(in general) there's 3 major parts to programming:
- Language - The syntax, structure, and paradigm of each language
- Library - The interfaces and utilities that each environment or toolset provides
- Logic - The algorithms to do work at runtime
Logic is almost completely transferrable between each language and environment, you just have to learn the specific Language and Library that you're using
Language is also shared quite a bit between languagesof course, learning 1 part at a time is easier than learning everything at once, which is why tools like scratch or code.org are popular as coding courses for beginners, especially kids, because it only focuses on the Logic aspect
programming as a whole is the Logic bit
c# is the language bit
unity's specific APIs are the library bit
Unity only has specific concepts like GameObject or Monobehaviour, but they don't create any special code that isn't c#
you'll need to understand the building blocks of course, but stuff like Console.WriteLine aren't useful in unity. but understanding the underlying concepts still helps
Where would you point me first du beginn learning C# for unity? I dont want to master the language, in fact i dont lice coding at all since I want to make games and dont write scripts. But theres no real way around so I kinda have to learn the basics.
there are beginner c# courses pinned in this channel. the microsoft ones are a good place to get started
And for code like making a character move, isnt it like reinventing the wheel? there has to be tons of premade script somewhere?
as a solo dev you have no choice
unity starter assets for third person or first person
tried to use that but when i put it on an different character model it breaks
yeah you probably broke it yourself by not knowing what you're doing
I swap out models on the same character no problem. I've used it in netcode as well
you'll have to code to make a game
code defines what your game is
there is the option of visual scripting but it's more limited, and you still have to learn the Library and Logic aspects i mentioned above
Yea it's hard to get around learning some stuff
Code or visual code logic is needed to make shit work
while we're on the topic - do you mean the microsoft ones pinned in this channel
i remember there being some in the pinned message too but seems like it doesn't link to that
the Intro to C# one in the pins is the microsoft one
One of the links is broken
....man, what.. i remember i checked one time and they were all unity learn
and it introduces some of the very basic concepts (and more if you actually do some extra digging on the site) so it's a good starting point imo
this one is really good tbh
https://learn.microsoft.com/en-us/shows/csharp-fundamentals-for-absolute-beginners/
ima tell admins to add it
have you hello worlded? lol weird question but has a point I promise
someone must have fixed it at some point because they all work for me 🤷
Oh yea very nice 🙂
huh, last edited 24 dec 2025.. maybe there was a period where it was removed before being restored/replaced
ah, nope, i mentioned there not being any microsoft links on the 28th. guess i'm just losing it then 
alright thanks
here : https://paste.mod.gg/imhqitlmppuq/0
Basically I created a door with a plane in the door frame, that display a camera wich is to another place in the scene. To make it as a portal, the code actually rotate and change position of this camera depending on where I'm standing.
A tool for sharing your source code with the world!
And to make it like it's a portal, I made a second camera that displays on the other door
like this
public Camera portalView;
that's potentially gonna be confusing, might want to consider renaming that - IDEs have tools to rename usage of that variable specifically, it's bound to F2 in vscode, not sure for other ides
The issue is, when I enter play mode, the second camera have the same position as camera 1, wich breaks everything
I don't really understand
example of what it does
are your otherPortal fields set up correctly?
Yo so i got this weird bug that doesn't let me open any project i've reinstalled the unity hub 3 times and i keep getting this pop up
you have a field that's named like a different type, that might cause issues in the future. IDEs provide tools to easily fix this
so something other than visual studio?
like i mentioned before, it'd also help to show an example of the issue with more context about where the cameras end up vs where they should be, with both portals visible
visual studio is also an IDE
it also has renaming capabilities
i'm just not sure what button it's on for VS, could still try f2 though
ctrl+r+r
mm don't like that, but ok
I tried those but I don't even understand what I'm clearly looking for, f2 doesn't really work
right clicking the field would probably also have a rename option
so uh is there any fix for this huge problem or nah?
@naive pawn im back. so I was thinking i need to Clamp the y axis position somehow for my paddles to stay inside the boundaries on both sides on the y axis. But I cant think of a syntaxial solution to that.
syntaxial?
do you have enough C drive space
also you don't need to ping me every time you ask
just bump your previous context and ask
413Gb of free C drive space
oh, did you mean syntactic
unless unity the size of 4 cods combined i should be fine
apologies, I dont have an extensive English vocabulary ^^
it's from latin, messes everyone up the first time lol
this sort of menu?
try another template mybe ?
I mean ,even when I don't it's the same menu
and I don't really understand what to do in it
(to be clear, this isn't super important, just mentioned something that could be a future issue, though knowing refactor actions will still help layer)
Oh alright
let's focus on the actual issue, you still haven't shown a full picture of the issue ^
Oh my bad, hold on !
I've tried 5 different templates....whats weird is nothing working like i've hit delete my account didn't work tried to delete unity didnt work for some reason when i was installing unity one of the program failed to download so i hit skip and now were here!
what was your question exactly?
So I do have my movement as this ```cs Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector2 finalInput = verticalInput * (movementSpeed * Time.fixedDeltaTime);
myRigidbody.MovePosition(myRigidbody.position + finalInput);
Now I want to clamp the y axis position
didn't i briefly explain how to here #💻┃code-beginner message
hello, where can I read about world generation algorithms and methods?
Yes you said to Clamp it. So I came up with something like this but I dont know how to apply it with the movement. cs Vector2 position = myRigidbody.position; position.y = Mathf.Clamp(position.y, -yAxisBoundary, yAxisBoundary);
you would clamp on the input, before you put it in MovePosition, rather than the resulting position afterwards - that just makes it easier to control
I dont know how to do that :/
the same way you did here, just on a different vector
but I would be clamping my input not the position?
basically do the position math first, then clamp that. then pass the new position with the clamped Y to MovePosition
ah, my bad. i mean the input to MovePosition, not the actual user input
i described it in more detail here
Thats what I think im missing the position and input math, i dont know how to do that ^^
you already have it in your code, you just need to move where you are doing it
Here, On the left is the scene and on right the Play mode
Vector2 targetPosition = myRigidbody.position;
targetPosition.y += verticalInput.y * movementSpeed * Time.fixedDeltaTime;
The both camera overlaps, While they should both stays close to their door. When they "move"; it should just be equivalent to my movements and nothing more.
holy moly it works
private void Move()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector2 targetPosition = myRigidbody.position;
targetPosition.y += verticalInput.y * movementSpeed * Time.fixedDeltaTime;
targetPosition.y = Mathf.Clamp(targetPosition.y, -yAxisBoundary, yAxisBoundary);
myRigidbody.MovePosition(targetPosition);
}
So thats exactly what you said, but I didnt know how to glue it all together with input. I just wrote it down now but still dont understand how it works
you can clean it up a bit to look better if you revert back to adding finalInput to myRigidbody.position, just do that outside of the MovePosition arguments, then do your clamping on the result of that. then pass the new result into MovePosition
basically this:
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector2 finalInput = verticalInput * (movementSpeed * Time.fixedDeltaTime);
-myRigidbody.MovePosition(myRigidbody.position + finalInput);
+Vector2 targetPosition = myRigidbody.position + finalInput;
+targetPosition.y = Mathf.Clamp(targetPosition.y, -yAxisBoundary, yAxisBoundary);
+myRigidbody.MovePosition(targetPosition);
it ends up reading a bit better than the current implementation
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector2 finalInput = verticalInput * (movementSpeed * Time.fixedDeltaTime);
Vector2 targetPosition = myRigidbody.position + finalInput;
targetPosition.y = Mathf.Clamp(targetPosition.y, -yAxisBoundary, yAxisBoundary);
myRigidbody.MovePosition(targetPosition);
like so?
oh its the same haha
now since it works I need to study this how it actually works because all this multiplying and adding mixes up everything in my head
Vector2 targetPosition = myRigidbody.position + finalInput;
this is the trippy part for me where I add the input to a position
the rest i understand
Input is an XY value. Position is an XY value
vector addition is memberwise, (a, b) + (c, d) = (a + c, b + d)
geometrically, you're moving finalInput amount from myRigidbody.position
so I get the rigidbody.position which is just a vector2 and the finalInput is a vector2. Lets say my rigidbody.position.y position is 0 for the left paddle in the game and I get the same value with a Debug.Log. Now I do a movement upwards which should Increase the finalInput.Y which then "ADDS" to the rigidbody.position.y "OVER TIME" thats how it changes position
I think I got it?
Whenever that line of code runs, it adds the X value of finalInput to your object's X position, and likewise for the Y value and Y position, and stores the result in targetPosition
well, the "over time" aspect is adding a little bit, drawing a frame, adding a little bit more, draw another frame, repeat
yo! I love this. I came in with a question but forgot about it because I was following along.
tab back to unity/your ide and surely it'll come back...right?
-# you gotta note your questions down first lol
Yes, then the clamping happens for the position ```Vector2 targetPosition = myRigidbody.position + finalInput;
targetPosition.y = Mathf.Clamp(targetPosition.y, -yAxisBoundary, yAxisBoundary);
so basically if the finalInput.y wants to add to rigidbody.position.y and the final targetPosition.y isnt allowing > 3.05 or < -3.05 then the rigidbody stays in those boundaries
lol thanks. It came back to me.
I'm being told that calling .Move() for the character controller twice within the Update() method can lead to problems for character movement. I'm currently calling it three times, twice within the scope of conditionals, and once within the general scope of Update(). I'm not seeing any problems so far, but is this okay.
you should only use one Move call
yeah, should be exactly once per Update
Hello everyone, I've been following an older tutorial and my jumping just broke while his still works, I think it has to do something with this
private bool IsGrounded()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center,boxCollider.bounds.size,0,Vector2.down,0.1f,groundlayer);
return raycastHit.collider != null;
}
(also idk how to share code properly so sorry)
it can mess with collisions including ground checks
!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.
here's how ^
Vector2 targetPosition = myRigidbody.position + verticalInput * (movementSpeed * Time.fixedDeltaTime) ;
``` this works too or do I still need that final Input variable inbetween like before?
is it the jumping or this grounded check? do some debugging to see if the grounded check is returning the expected value
if it is, then the issue is with the jumping
if it isn't then the issue is indeed here
any variable you only use once can be inlined, but having them separate helps with clarity
it's pretty subjective what point it turns from clarity to verbosity though
grounded check, if I change it to "== null" it starts working again but I can jump infinitely
well == null would be checking that you didn't hit anything
okay so if used once like player input its okay to inline, but if I want clarity for myself I can use a separate one. Thanks!
so assuming you have a IsGrounded() condition before jumping, that would mean the jump is fine, but the raycast isn't hitting anything
what's the type of groundLayer?
[SerializeField] private LayerMask groundlayer; this?
yeah, though note that that's a layermask rather than a layer, might want to consider renaming that for clarity
is that set correctly in the inspector, and is the ground set to the right layer?
show them if you aren't 100% sure
oh I see what you meant, thanks I found it
Hey I'm curious, since im new to unity, gamedev and programming. Do you guys get those code out of thin air or you have cheatsheets, snippets where you look stuff up from time to time. For me lerning code is like guessing magic spells and I think no way people just type code like writing an email. For me it seems absolutley impossible to write in code naturally
This is a code channel, can you keep it to code questions.
(delete from here)
Hi, well since Im a bit aware of C# syntax and things that Im familiar with or remember seeing somewhere I can write things manually, but of course I dont remember certain things, so I just look it up in the documentation or my notes. I also have auto complete or code suggestions turned off in my IDE so I remember the syntax better when im writing it myself. You will remember what to write and how to write it when you do it lots of times. Syntax is actually the easy part, the hard part is to know the logic behind it how to write it so the computer can compile it ^^
I know how to multiply two variables or values, but the harder part is to know which ones i need to multiply to get the wanted result
You either understand what you're trying to do and know what functions and opeartions to use to do it based on experience, or you know what you want to do and look up the functions from a reference like the documentation
Once you practice enough you will start to remember those "magic spells"
It's like anything else
So even within the scope of if statements I cannot call it again?
thats actually smart, yesterday i tried to get the auto completion tool working but I just couldnt get it running. maybe its a good thing 😄 for me both the syntax and the logic is non existent. I can write pseudocode so i write down what i want the computer to do in a logical way but its neither C# nor any other programming language
I would suggest keeping it off, I forgot how to write for loops because of those auto suggestions. I turned them off now I know once I written down myself a dozen of times. I would suggest first practicing regular C# if your a complete beginner?
any good documentations that "have it all" so I dont have to seach on 4 different websites?
c#: microsoft docs for c#
unity: unity docs
or just google "c# list" or "unity box collider" and take 0.5 s to click
seems like unity's documentation 'has it all'. It's just a lot at first.
what du you mean by regular C#? doesnt unity just use C#?
Scripting API for Unity docs, just search for whatever you need
you gonna laught at me for that but what are API?
Yes but if you havent programmed in regular .NET C# then Unity will be a bit hard to start with. But you still can of course.
Not really because it depends on if you're wanting to look up something from:
- Unity's core libraries: https://docs.unity3d.com/Manual/index.html
- C#'s core libraries - which are on Microsoft's website
- A particular Unity package - for example here's the input system: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.18/manual/index.html
- Some third party library - could be wherever they put it
Doesnt matter for now, there you'll find everything related with syntax for Unity ^^
I come from Javascript/Typsescript, so some of this is familiar. C# is much more strict, but I think that's a good thing.
Knowing TS is a boon as you already understand half of what a strongly typed language offers
but in c# its not optional, its the law 🔫
@stuck parrot this is an example if you want to see how to use linearVelocity of a rigidbody. Theres some explanation and of course code examples. https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody2D-linearVelocity.html
speaking of which, I haven't seen the use of types or interfaces yet in any of these lil tutorials I've seen. I haven't even seen it used in Creating with Code yet and I'm starting the fourth module.
Unless you join the dynamic resistance 
(don't do that)
Interfaces are more of an intermediate topic but its not unitys job to teach people all about c# and object oriented programming so I dont see an issue
il2cpp would like a word
Not a criticism. Just an observation.
You might find it helpful to check this out to learn C# on its own and bring those lessons into Unity:
https://dotnet.microsoft.com/en-us/learn/csharp
I do think Unity learning paths would maybe benefit from like a quick primer on Types, classes, variables, structs, operators, methods, etc.
although maybe that's too much
I'm trying to refactor the following code so that characterController.Move() only shows up once within Update(). I need to restrict or lower the player's momentum when they jump.
isGrounded = characterController.isGrounded;
if (isGrounded)
{
if (verticalVelocity.y < 0) verticalVelocity.y = -2f;
// Horizontal Movement
Vector2 moveInput = controls.Character.Move.ReadValue<Vector2>();
Vector3 moveDirection = new Vector3(moveInput.x, 0, moveInput.y);
// Move the controller laterally
characterController.Move(moveDirection * moveSpeed * Time.deltaTime);
// Rotate the player to face movement direction
if (moveDirection.sqrMagnitude > 0.01f)
{
Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
targetRotation,
rotationSpeed * Time.deltaTime
);
}
// Jump Logic
if (controls.Character.Jump.triggered && isGrounded)
{
// vertical velocity sqrt of (height * -2 * gravity)
verticalVelocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
// Store air momentum
airMomentum = moveDirection * moveSpeed;
}
}
else
{
// Override horizontal movement with air momentum
characterController.Move(airMomentum * Time.deltaTime);
}
//Apply gravity
verticalVelocity.y += gravity * Time.deltaTime;
characterController.Move(verticalVelocity * Time.deltaTime);
}```
dangit! sorry
📃 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.
fixed it
where is this code from may I ask?
looks familiar, is it from the documentation?
I used some old example code but modified it to restrict character momentum during the jump.
the oldest called characterController.Move in the same scope and seemed to be based off an old version of unity.
how do I add a double jump function to unitys default third person controller code? (I wont paste it here since its over 400 lines)
what do you mean by showing up in Update once? If the whole code is in Update it will be called each frame
you have to do it with code I imagine
once the player is in the air you change something
you dont make the Move function show up once in Update
if im understanding correctly
if you want the character controller to stop moving while in the air you just code it like that ^^
haha not that helpful
A double jump is a jump we allow the player to take while not on the ground. This is tracked and is allowed again once the player touches the ground again
People in the Unity forum said Move should only be called once no matter what so I came here for a second opinion. If C# is anything like Typescript, the Move inside the scope of a conditional does not interfere with the Move outside the scope. Am I correct?
Are you talking about a CharacterController? Yes Move should not be called more than once per frame per CC.
If you have Move in two mutually exclusive code blocks it's fine as long as you can guarantee they don't both run in a single frame
e.g.
if (x) {
cc.Move(...);
}
else {
cc.Move(...);
}```
it's fine
although for code maintainability reasons I would still recommend reducing that to one call
e.g.
Vector3 moveAmount;
if (x) {
moveAmount = a;
}
else {
moveAmount = b;
}
cc.Move(moveAmount);```
I'm going to have to put my thinking cap on for that. Thank you!
Hey, I want to make a script that involves multiple factors, like deleting a ton of things and resetting the players score to 0 in an endless runner when they collide with things. But all my scripts are monobehaviour and I don't know how to change all these factors at once. Should I combine all of them into a monobehaviour script or do i need to make a new blank script (I did try this once, but I wasn't sure if I needed to do it and quickly became confused with what I was doing)?
Isn'tt here something like StateMachine for things like that?
Uh... your question is pretty vague. Not really too sure what you're asking.
Are you saying there are a bunch of things in different scripts that all need to reset when the game resets or something?
Or just like:
- something happens, a lot of things in a lot of different scripts need to change
Your two basic options are:
- Have the script that detects the collision reference all those other scripts (either directly, or using singletons, or any way you want) and manually call all of those functions
- Have the script that detects the collision publish an event (either C# event or UnityEvent), and have all the other scripts subscribe to that event with whatever function they need to run when that event happens. e.g.
OnPlayerCollidedWithObstacle
Any way to normalize a vector but instead of normalizing the magnitude I want a projection on a square?
Basically if I have
2,2 -> 1,1
2,0 -> 1,0
-6,-3 -> -1,-0.5
as in is there a utility function for this or do I just calculate by dividing through the bigger of the two?
There's no built in utility afaik
yeah I think just dividing by the larger dimension would do it
There is nothing wrong with calling Move repeatedly, but you need to understand the consequences of doing so:
- The controller has a minimum movement distance. If you do several small moves, it's possible that thay'll get ignored.
- The "grounded" state of a controller only reflects the most recent movement.
use multiple Move calls if the player is actually moving in several discrete steps
(the player generally isn't doing this!)
Thanks, Fen. I'm currently refactoring to try to eliminate that second Move call.
I'm getting close I think. I'm using a finalMove variable that will change if the character is not grounded. I've also flattened the conditionals a bit.
I keep getting this is studio code ive downloaded and installed the SDK and still
restart your pc
that did it thx
Hi! Im new and learning
hi
I get this error when recreating a script I previously made that worked fine I haven't even input the code yet just named it and im already tossing this error im unsure why
nvm I got it its becuase I didnt remove the old script from the gameobject
I want to create a new action for looking in my action map for a 3d game. The action type is value, and the control type would be Vector3, right?
you don't typically look in 3 axes
for looking in 3d it's typically just pitch and yaw, 2 axes
usually roll is locked
thank you sooo much. i made a static function to adjust the alpha and returns it for modularness and also so i can use the triple comment thing for documentation. now no matter what the alpha will be 255 every time the color gets changed. all these years it was a transparency setting stopping me from doing what i want with colors in unity
weird though, Color.white has full alpha and so would any new Color(r,g,b) you make 
oh
well i also just discovered that the way i select colors with the inspector setting is dead wrong
i feel like this doesn't solve the root cause, but eh that's up to you if you want to go there
how so?
i always drag up and left for white and drag down left for black. this sets the alpha to 0.
in the List<> cuz im a modular guy, in both color selections the alpha was 0 so on start no wonder the alpha is 0 on start
i probably would have caught this if i wasnt doing it at 2 in the morning last night
o rmaybe if i got back on when yall mentioned alpha
that's not the case, not sure what you mean by that
alpha is a separate slider entirely
(i'd also like to mention that there could be cases where you'd want transparency, so imo just setting the colors correctly rather than correcting them all to full alpha afterwards sounds like a more future-proof workflow)
but yeah if you have a serialized struct field it'll be initialized to all-zeroes, for a Color that includes alpha=0
ok thats what is it then
i'd guess it's that and you just never noticed beforehand
since in like, SpriteRenderers it's defaulted to 1,1,1,1, so you wouldntve had to touch alpha
because i have 22 elements in the list, i just added the alpha = 255 to the initialization statement in the class
you'd want alpha = 1 for Color, it's floats from 0 to 1
ints from 0 to 255 would be Color32
claude told me all about it
yeah maybe don't use that
its the only ai that doesnt lie to me and teaches me better than the pearson books
LLMs aren't designed for correctness, they're designed for believability
if there's a lie, it was stated confidently and you mightve just not noticed 🤷♂️
that's the main issue with "learning" with AI
among ai users, claude specifically is known for being good at anything coding wise but bad at everything else
they hallucinate as necessary to be convincing
if the unity ai was remotely helpful i would have ditched claude already
im not recommending unity AI either, i'm recommending ditching AI entirely when you're learning
but hey, your perogative to go with a resource that confidently lies as deemed necessary 🤷♂️
thats why this server is my fallback when theres problems claude doesnt correctly fix
and how many problems did it "fix" and leave behind latent bugs i wonder
i tweaked it as i typed it myself so there didnt end up being any bugs cuz i fixed the minor logic errors. i always give claude the context it needs for it to be mostly correct.
the only reason it couldnt fix my color problem is cuz it assumed the alpha value was staying at 255 so it didnt entertain the possibility that the alpha was the problem.
anyways, there's a reason that this opinion is held in basically every technical community, i'm not interested in debating this further tbh
alpha value 255 is invalid for a Color
me neither lol
another question that id rather a real person answered: is it possible for unity to do a LAN only connection through the wifi between a phone and a tv but make the room code based connection look like kahoot?
eh it mostly works time to play uno
Not you specifically but this kinda thinking overall is really annoying for a lot of the people that help here because instead of just needing to teach the relevant info they need to unteach the bullshit previously fed from ai
Hello, OnEndDrag doesnt seem to trigger if you pick up and drop too fast.
Added a Debug.Log and indeed it doesnt call it when this happens.
Any ideas on how to fix this?
pickup and drop doesn't sound like dragging. did you move enough for it to be considered a drag?
use OnDrag to check if that triggers . . .
playerTf.position = dockPoint.position;
playerTf.rotation = dockPoint.rotation;
this should set player position to dockpoint yes? it sets it at a random point
and not the dockpoint I have set
it sets it to the same world space position as the dockPoint object. if you are seeing something you don't expect then either you have assigned the wrong object to dockPoint or it is not actually located at the position you expect it to be. make sure your tool handle is set to Pivot rather than Center so you can see the object's actual position
yea basically it behaves how I want when I undock in my structure. however when I dock it places me at a random spot away from the structure in the world and I cant figure that out
undock places me correctly
just not the dock
if you are seeing something you don't expect then either you have assigned the wrong object to dockPoint or it is not actually located at the position you expect it to be. make sure your tool handle is set to Pivot rather than Center so you can see the object's actual position
oh another possibility, though more unlikely, is that the dockPoint object is being moved after you get its position
I dunno I have it set to pivot now and I see the issue but not how to fix becuase it shows my DockPoint as -5 which is right near the structure. least I can tell when I dock its putting me at -560
reminder that the inspector shows its local position, which is relative to its parent, not the world position
ohhhhhh the far corner of my structre is 0.0.0 not the whole damn thing
nvm I was thinking on the wrong assumption thats why the undock dockpoint was off I figured it out
that and looking at the right position helps
oh and I changed the parent scale to 1,1,1 from 200 so I think that messed with it also
Can someone tell me what is wrong here? the model looks fine in the scene view, when i go into play mode it looks weird and scuffed.
I dont think it has to do with my animations or anything.
Also this only happens on my device, on other devices this works fine.
When i build this i get the weird textures (or what it is) too.
How is that a code question?
Is it (or any of its parents) really small or large or is it far from world origin?
Or it could be animation compression/skinning settings specific to your devince
well i have no idea where the issue lies...
Yeah this is a code channel use #💻┃unity-talk or #🔀┃art-asset-workflow or something
its not small or large, and not far away from origin. Like i said it works fine on other devices
Is there any method to create a lock on target like souls game, I need some suggestion cus can't think of a great solution
this is a code channel, delete and ask in #💻┃unity-talk
I have a couple logic error that needs to be fixed asap. However I feel it would be too long and hard to explain in chat. Would it be possible for someone to help me in a vc
are there any best practices for making a character select screen and passing that data from the selection scene to the game scene?
there are so many ways it could be done
is it a simple pick character A or character B or actual customization?
nobody does vc, it's best to ask the entire channel than a single person who may or may not be able to help.. ending up in both peoples time being wasted
fair
rn its simple character pick but some palette swap options would be conceivable
ok well if it's a simple character pick
its like a fighting game character selection
I mean a static variable could just work I don't see why not
Just have the selection set the (for example) Player 1 character variable
you don't want a static var for that, not very extendable
true
then what should I do?
ScriptableObject, assign the values to it at character select
Oh yeah mb
a scriptable object that holds the selection data? and how do I best pass it to the next scene?
SO's aren't necessarily tied to a scene. Assign the data at character select, load the SO and use it on the next scene
Or utilise multi (additive) scene loading, have a scene loaded that has all the data you need to pass around in.. load/ unload the other scenes
load the SO?
well, a component having a reference to the SO will load it for you
Damn I pressed enter accidentally mb
📃 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.
Oh alright
I don't understand how to do that
Ok so my problem.
Basically general idea is VR game where you build a plan on a grid and then as you are building it the actual house is built infront of you
So currently HouseAssembly is attached to a gameobject "House Assembly Manager" and the SnapToGrid is in every single material block.
The blocks correctly detect if they are corners, or in a line etc. However the big house assembling is really odd as it creates a corner but the last block that set off the block that should be the corner becoming a corner block also became a corner block. That is the main issue.
A tool for sharing your source code with the world!
And image just for a general idea
do I make a static scriptable object
hm all the online tutorials say to just use a static variable
Make yourself some GameManager singleton if you need to carry around game state
I don't need to, I just want to pass the character selection from selection scene to game scene so it loads the right character
That is why you make the game manager DDOL and let it live between scenes
DDOL?
oh destroy on load
I don't need to keep that info after loading the character though
So why does it need to be static?
I'm not sure, thats just what all the websites say
Pass the SO to the Character and be done with it
Can you link one of these websites?
most of what I'm finding is some variation of this
https://stackoverflow.com/questions/32306704/how-to-pass-data-and-references-between-scenes-in-unity
This is passing info between scene. You said you don't need to "keep" info after loading the character, so these are not related.
I mean still need to pass it dont I?
the answers to this give you multiple options, not just "use static"..
If assuming your Character is a unique instance per scene (as in , you've added it manually to each scene), then DDOL is the way you do it.
I'm not sure if I understand that correctly but I think that's not the case. There are multiple characters players can choose from, and different players can choose the same character so there can be multiple instances
Français ?
English only server
Anglais seulement
Ok sorry
What is the SO even storing, for starters?
Do you Guess a unity French server ?
not that I know of
Ok
which character has been chosen, and their chosen skin
I just wanted to let players pick their characters and then have the game load those characters in the level. I don't have scriptableobject or anything yet
since I'm still trying to figure out how to best do this
How you do it doesn't matter to answer the quesiton.
You need to know what data to keep track of regardless of the solution.
well technically every possible choice can be encoded as an int or enum so in theory thats all I need
using UnityEngine;
public enum Character
{
None,
Warrior,
Rogue,
Wizard,
}
public class GameManager : MonoBehaviour
{
public static GameManager Instance { get; private set; }
public Character Player1 { get; set; }
public Character Player2 { get; set; }
public Character Player3 { get; set; }
public Character Player4 { get; set; }
private void Awake()
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
}```
I can do it in any number of ways
there most basic setup
(better yet use an array)
I wonder if doing a string lookup or somesuch might be better actually
or I could generate the selection table from the enum
no, strings are not a good idea for lookups or comparissons
my issue now is if I add a character to the game, I have to also manually add an entry to the selection screen, and another manual addition to the enum
enums are preferable because they have a strong typing compared to strings
so adding an entry to the enum is preferable instead of doing a string lookup
yeah but if I have to manually add data in three different places its bound to cause bugs eventually
for the selection screen, each entry needs the character name and an image for each character, which I can't store in the enum. If I generate the enum dynamically I can't guarantee state. I think ideally, the selection would be generated from the files in the character folder
but then I still need to pass the name as string or character id as an int I suppose
You use SO's then. So you don't write any new code with new characters, you create a new SO file and fill in the data
I would make SO data for the characters at minimum so you have some unique references to an instance of data
then you can use this blueprint to insert it into your character mono instance
If you need a way to access these SO references, you can make unique variables likes I've done above (Player1, Player2, ect -> or as an array), or use a dictionary that points some key (Enum, String, ID) to this data
Which is the more preferred idiomatic code style?
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.GetComponent<ScoreZone>())
{
Debug.Log("something happened...");
}
}```or```cs
private void OnTriggerEnter2D(Collider2D collision)
{
ScoreZone scoreZone = collision.GetComponent<ScoreZone>();
if (scoreZone != null)
{
Debug.Log("something happened...");
}
}```
I personally prefer the top option, but following this tutorial the second option is what they typed and it just reads little weird weird to me.
disregard the generic method name for now
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.TryGetComponent(out ScoreZone scoreZone))
{
Debug.Log("something happened...");
}
}```
How does that determine it is of the type ScoreZone though?
out ScoreZone scoreZone instead of var?
You can't use var there without specifying the type in generics
You'd need to either do TryGetComponent<ScoreZone>(out var scoreZone) or TryGetComponent(out ScoreZone scoreZone)
That's what I thought as well
In the example of Pong, why do you put the OnTrigger on the ball script rather than the area where the score zone is? It seems more intuitive to trigger when something enters vs triggering when the ball contacts something else
good evening, I just touched events for the first time, I think they are regular C# events not Unity. My question is if I can call the ResetRound method in multiple other methods to invoke the OnReset event? Which tells all the "subscribers" to call their respective functions when its invoked.
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public int leftPlayerScore, rightPlayerScore;
public ScoreUI leftPlayerUI, rightPlayerUI;
public event Action OnReset;
private void Awake()
{
Instance = this;
}
public void UpdateLeftScore()
{
leftPlayerScore++;
leftPlayerUI.SetScore(leftPlayerScore);
ResetRound();
}
public void UpdateRightScore()
{
rightPlayerScore++;
rightPlayerUI.SetScore(rightPlayerScore);
ResetRound();
}
private void ResetRound()
{
OnReset?.Invoke();
}
}
Hey there, haven't seen you in a while 🙂
Whenever anything calls ResetRound, all subscribers of OnReset will be called
Just gonna write a message so this doesn’t get lost
Oh hey! Fancy seeing you here! You switched from the dark side of Mono to Unity? ^^
Okay, just wondered if I can call that reset round method from other multiple places
never got far into MG journey... trying to settle into Unity now.
Cool! I had a break myself after learning C# now im diving deep into unity too for a couple of months now. We cant chat here unfortunately or we get slapped on the wrist ^^
It would be interesting to hear if Unity events with listeners are better to use than C# Action events?
but the last block that set off the block that should be the corner becoming a corner block also became a corner block
This doesn't make sense to me.
You'd do well to record a video of the issue happening.
Yeah give me a little bit making food now
It would be better to make Score as a separate class
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Score rightScore;
public Score leftScore;
public event Action OnReset;
private void Awake()
{
Instance = this;
}
public void UpdateLeftScore()
{
UpdateScore(leftScore);
}
public void UpdateRightScore()
{
UpdateScore(rightScore);
}
private void UpdateScore(Score score)
{
score.UpdateScore();
OnReset?.Invoke();
}
}
[Serializable]
public class Score
{
public ScoreUI ui;
public int value;
public void UpdateScore()
{
value++;
ui.SetScore(value);
}
}
It's better to use Action, but in UnityEvent you can subs in the inspector without code
Thank you. i do have a SetScore function in the Score UI class
I don't like to use enums for things that can easily change
public class ScoreUI : MonoBehaviour
{
public TextMeshProUGUI scoreUIText;
public void SetScore(int i)
{
scoreUIText.text = i.ToString();
}
}
Instead of TextMeshProUGUI better use TMP_Text
But I do understand what you mean, to separate "work" to different objects. The Game Manager would just delegate work to different classes
Why and what are the differences? Thats a different component right?
TMP_Text is the base component that TMPUGUI extends from.. it allows you to easily change between the two types of TMP and is shorter to type
public TMP_Text scoreUIText;
Okay so I didnt have to change anything in the inspector too
Yeah, that should be fine
Sometimes, changing the type of a field can leave you with a bad reference, even though the inspector looks okay. Notably, switching from GameObject to Transform will do that
because there are two separate things being referred to
yes exactly
in this case, you're still referring to exactly the same thing: the TextMeshProUGUI component
For characters in a game, I'll create a ScriptableObject type that represents one character
it includes the name, a portrait, a reference to a prefab, etc.
that object goes into a list in another "catalog" asset
since I'm using Mirror Networking, it seems it actually has to be a network message instead of a SO
this asset identifies the character; you would send some kind of identifier in a network message to pick the character
one handy trick is to copy the asset GUID into the asset
this gives you a unique identifier
so, to pick a character, you'd send a network message containing the GUID of the character
I pass the SO index to RPCs and then just get SO from the list.
public abstract class Identifiable : ScriptableObject
{
[SerializeField] private Guid _guid;
public Guid Guid => _guid;
#if UNITY_EDITOR
public void ConfigureGuid()
{
string path = AssetDatabase.GetAssetPath(this);
_guid = new Guid(AssetDatabase.AssetPathToGUID(path));
}
#endif
}
e.g.
this is using a custom Guid type, because System.Guid is not serializable
I was just gonna give each character an int id
That also works, as long as you make sure the identifiers are unique 😉
You could also use the index of the character in the list, yeah
I think that will cause problems if the list changes
Sending a GUID may be wiser if it's possible that there will be different numbers of characters in the list (maybe you support mods?)
or you could've rearranged the lists in a network-compatible patch release
My indexes are assigned by a separate class and it makes sure that when the list is changed, the indexes do not change for already created SO
I might just be too stupid for unity or something
there hasnt been an easier time to make games, think about 20+ years ago, we have it easy compared to then
ig I'm too stupid to make games then?
are you expecting pity from this self deprecating language or what?
not stupid, lazy
idk I'm asking newbie questions but I don't understand the answers
who are you asking
everyone
Ignorance is a state of being everyone starts from and can grow beyond.
Stupid is a choice.
then how do I make sense of things
By putting in the effort to learn simpler things until you can combine them into more complex things
but what simple thing do I have to learn here, and how? the things I see online only lead to solutions that are janky af
if I have to write my own networking library instead of mirror, this game will never be finished
Hw do I set the UVs of my custom mesh?
In blender
I want to make meshes at runtime tho
Can use the Mesh API but yeah save yourself the hassle and use blender
Well mesh.uv
Yeah but what do I put there I can't find antything ont the Internet
mesh.SetUVs
You shouldn't be doing multiplayer at all if you have any qualms about your own ability to understand the basics
but the multiplayer is the only issue, it's not a problem in single player
multiplayer eh
Check these tutorials for procedural mesh manipulation. https://catlikecoding.com/unity/tutorials/ It's also pinned in this channel.
Thanks
yeah as it turns out scriptable objects cant be used with mirror so I'm back where I started
I can't find a solution thats better than string lookups
Seems odd, but I've not used mirror but considering almost every other networking library has been fine witht hem
Perhaps you mean to say you cant send serialized SO data packets perhaps
Which is why you use IDs and that's another large concept that networking brings
You don't pass ScriptableObjects over the network, you pass data to identify the one you need. And if you need to pass entire list of properties, you pass just that and create SO from them when they are received.
You can write custom serializers
the whole point of the SO was to use it to pass the data, and that means I'm back to my original question, how to best pass the data between scenes
I would develop this as single player first and figure out those concepts
You serialize the data, send it, deserialize and recreate SO based on it, this is how it works in any Network solution.
Keeping data "between scenes" is not the same as "how to send data over the network"
If you have player data in some plain class you just keep/pass a ref to it when you load a new scene to keep it around
e.g. load new scene, spawn player, give player data
or store in a static field so its around forever
ok so I just use a static int to tell the server which character to load in the next scene?
No
That depends on the networking solution in use
the example that comes with mirror seems to do it like that, but in a very convoluted way
You can use an rpc to do this work and send data easily
But if you use the same "player prefab" in all scenes then there is nothing else to send
Got to think in terms of the server and who actually is storing it. Like if you just rpc the selection to the server, when you load the next scene you can just request it back.
public struct ReadyCommand : IRpcCommand
{
// player name
public FixedString128Bytes name;
// player prefab index
public int character;
}
If there is some concept of different characters a player can pick then this "choice" should be stored both ends (client and server)
You would use rpcs to update this when it changes but otherwise the data should be avaliable to read to use when loading into a new scene
e.g. player joins server, load previous character choice, store, send to client, done.
SO idea still works but you'll need to ID them and put em into a lookup table. Use fen's idea on the GUID and generate the table at runtime.
you wouldn't send the SO over the network but just the ID key (int) which the server can then lookup
Yea we should presume core game data is the same on both ends so you want to use unique ids to refer to entries when communicating
mirror is really hard to understand, but I think it doesn't actually work like that
it does
I have a question about LayerMasks, code wise is there no way to easily compare two, like tags? Im trying to compare when an object collides with another and to check the collission mask on that object to the one I set up in the inspector.
its up to you to organise configuration data correctly so you can network things well
There is two issues lmao. Obv instantiate is being run every fram but also 2 walls become corner not just one
I did if (hit.gameObject.layer == LayerMask.NameToLayer("Ground"))
gameobjects can only be in one layer. layer masks are different and can indicate many, all or no layers
That forces you to write it out as a string. I can't do something like
[SerializeField] private LayerMask _noiseMakingSurfaces;
private void OnCollisionEnter(Collision other){
if (other.gameObject.layer == _noiseMakingSurfaces)
}
```?
if (_noiseMakingSurfaces & other.gameObject.layer > 0)
Thats works... But wouldn't that work for any layer? As long as it had one it would return true
It would work for any layer you have included in the _noiseMakingSurfaces mask
There's no Type Layer is there? If i understood correctly LayerMask and Layer are not the same thing here
Oh, actually, I got it slightly wrong:
if ((_noiseMakingSurfaces & (1 << other.gameObject.layer)) > 0)
yea i said they are different?
layer is an index, not a flag
yay for bitshifting and bitwise comparison
I use a package that generates a Layers.cs file containing a bunch of useful constants
thus avoiding that incantation
Okay so bitwise comparison is the only option
right sorry I was just reiterating
Oh didn't see the other code help channel mb lads
https://github.com/Thundernerd/Unity3D-LayersTagsGenerator
this lets you avoid magic strings
maybe the most straightforward solution is to just make a button on the selection screen for each character that sends the network message with the id of the prefab to spawn to the server
Yes that would be the best solution
you can create other const variables that are a combination of these
sending the least amount of information needed to do the same both ends is the way to go
e.g.
public const int NOISE_MAKING_LAYERS = Layers.FOO_LAYER | Layers.BAR_LAYER;
alright thanks
(where those variables are created by the editor script I linked)
This would also be a decent place to use a "singleton asset"
basically, a ScriptableObject that lives in a Resources folder that can load itself
public abstract class SingletonSO<T> : ScriptableObject where T : SingletonSO<T>
{
private static T _instance;
// only really needed for the editor when Domain Reload
// is disabled.
public static bool InstanceExists => _instance != null;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Resources.Load<T>("SingletonSO" + "/" + typeof(T).Name);
_instance.OnLoad();
}
return _instance;
}
}
public static void ClearInstance()
{
_instance = null;
}
protected virtual void OnLoad()
{
}
}
mine looks like this
This is great for providing serialized data (i.e. anything you can set in the inspector) in places where it'd be really obnoxious to manually assign a reference every single time
(this is what dependency injection does; don't tell anyone 🤫)
Not bad but do remember you can serialize a list of scriptable objects if needed so its not a requirement
But having 1 top level config object is the best
I'm talking about Twisted's situation, btw
not the player selection thing
(but I would also probably have a nice singleton catalogue of all of the characters, in hb's case 😉)
I thought I should avoid singletons
there is zero practical difference between this and a manually-assigned reference to the game's character assets
singletons are bad if it turns out they're not really single
It can cause issues with things such as tests but beginners probably dont need to worry about that
I would also separate this from singletons that you modify
this is just a read-only blob of data
singletons that you can modify the contents of (or use to modify the game world) make it harder to reason about how your game works
i call these kinds of things "catalogues"
in my case, each character is a set of general controller scripts with a set of character specific data and character specific scripts
Do they have a common script/type?
ideally it would be super easy to get characters such as:
Character characterPrefab = config.characters["pacman"];
Character newCharacter = Instantiate(characterPrefab);
newCharacter.DoShit();
how do you mean?
oh like Character? I think I would just keep a list of the prefabs and instantiate as GameObject
they do share controller scripts but there is nothing actually forcing them to
That works too but we can use a component type to refer to prefabs instead (which can be useful if there is a major component you will want to get/use)
So the example works just fine with GameObject too
in my game, every "thing" is an Entity
so I refer to character prefabs as an Entity
If there is genuinely no commonality between any of your characters, then GameObject is the only sensible choice
(but this is unlikely)
I could in theory add some kind of empty component named character or something
almost all functionality comes from "modules" that I attach to my entities
but everything is, at least, going to have the Entity component
I asked because usually if you want to be able to spawn and use many of one "thing" then they all share some type
e.g. Item, Weapon, Car
I tend to not presume much OO knowledge with beginners
even if you aren't doing a hierarchy of things (literally everything is an Entity for me, with no inheritance), you still probably want to have something to identify a "thing" in your game
that was an incredibly vague statement
you have...things
🤷♂️
sometimes you can abstract too hard 
Why you named things as Entity instead Things
"Entity" is a pretty common term for objects in games (especially ones that have complex behaviors, as opposed to stuff like the level geometry)
That was joke
the characters arent actually encapsulated by anything but the prefab, so the classes are NetworkBehaviors
are there common "entry points" on the characters that you currently use GetComponent to find?
e.g. a component that handles player input
yeah, they usually do have those shared controllers for handling stuff like controls, movement, health etc, but they dont actually have to
can I require that in a prefab somehow?
but for example, I also have a target dummy that works just like a character except it doesnt have controls for example
Any "zero or one" component (e.g. you either have no controls or you have one control component) would be a good field on a new Character class)
why deal with 5 components everywhere when 1 do trick?
my Entities have fields for things like:
- a default locomotion mode
- a default brain
since those are mandatory
ahh okay okay
speaking of Entities (the other kind) :p
Entities is analog of GameObjects
using entity is pretending its a different engine
MonoBehaviour would do for any components we make too
is there any downside to just spawning them as GameObject?
no but it then requires the extra step of getting a component
having a serialized field of a component also means you can only assign a prefab with this component on it
They are always spawned as GameObjects . . .
the object picker will just show up empty when looking in the Assets tab
Using the Type as the return value is a convenience to avoid calling GetComponent . . .
If your characters have nothing in common, then an empty Character class would only prevent you from assigning invalid prefabs to the list of characters.
If there is some commonality, then the class could also expose those features, rather than requiring you to use GetComponent
alright thanks I'll have to think about that
Hey im very new to unity and game dev and made a platform and some trees with a player but cant get the player to move for the life of me. anything that i can do to learn basic player movement
Hey everyone ! Im the biggest begginer on unity, I need some help to put a script in on of my project, can someone help me with this pls ?
can you be more specific about what exactly it is you need help with?
yeah sorry
if you're looking for a tutorial, then google will be your best bet.
there are also beginner c# course pinned in this channel, and the pathways on the unity learn site are a good place to learn the basics of the engine (including how to move objects)
Thank you. Will do
I'm trying to create a script that allows the circles in my project to move (rotate). I was in the Project window under Assets, right-clicked, and selected "Create → C# Script". After that, Microsoft Visual Studio opened, but I can't see where to write my code or I don't have the option to do so
Did you open the file
double click the script in your asset folder if the file didn't open automatically
This is the result
that is the result of you double clicking the file?
yes
did you leave visual studio open or did you close it before you double clicked it?
it was closed
okay so leave it open then double click the file
still nothing 😅
!ide 👇 go through the configuration guide here. if the issue persists after following the steps then try a full restart
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
okay ty !
Hey I did a bunch of commits and after regenerating my navmesh it now looks like that (image) but i'm not sure which change it's related to, would anyone please know what could be the reasons? The floor is just a Unity plane
It’s most likely just overlapping with the floor. Try to move the planes slightly downwards - if u don’t see weird NavMesh deformations then it’s fine.
hm yup it's that but why is it happening? It wans't the case before
I don’t really know, maybe it has to do smth with the z buffer or gizmos. I had this issue once but I just ignored it.
Hmmm okay, thanks
i've observed this before
i'd expect the scene-view gizmos to be pushed out of the floor slightly
try selecting an object and hitting F to focus on it
this will update your near and far clip distances
if this is happening because the depth buffer is just slightly too imprecise, then this could fix it
just checked in my editor, and the navmesh visualizer is pushed a fair bit away from the floor
I use physics colliders, rather than renderers, for my navigation
I wonder if the latter winds up putting the surface exactly flush with the floor
To be honest, such an artifact means that the NavMesh is pressed as close to the floor as possible, so this is not a bug, but a feature
Well, it is pushed slightly up so it wouldn’t be an issue. Maybe it’s a voxelization issue which makes it detect the ground at slightly different height, but it shouldn’t be the problem if the NavMesh itself looks flat ¯_(ツ)_/¯
Hello,
I am trying to generate a cube mesh via script but my cube mesh is looking weird. Can you help me?
Here's my generation code: https://pastebin.com/3YmbXExq
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.
(I am running the method via button by an editor script)
I’m an ex-marketing analyst diving into game development. I’ll handle project management, marketing, and bringing in talent, while partnering with a developer to build the first game. From there, we’ll grow the team and expand the studio, turning our ideas into games players actually love.
Looking for a Game Dev
If you’re stuck in tutorial hell, starting projects and never finishing, this is for you.
I’m building a small, focused prototype demo in Unity — something we will actually finish and ship.
You’ll be the dev, coding and building the game. I handle the rest.
Do this right — deliver, show you can handle it — and you’ll be put on a salary immediately. Real money, real spot on the project. This isn’t a maybe.
Perfect if you want:
A finished project for your portfolio
Real experience making a game
Structure instead of chaos
A path from learning to paid work
DM me:
Any projects you’ve done (finished or not)
Let’s actually ship this.
The blobby look is probably from screen-space ambient occlusion (SSAO); however, that's not the root cause
You only have eight vertices for this cube, so it's not possible to get sharp edges.
Adjacent triangles are sharing vertices
Each face shoul get its own four verts
I suspected that but some resources said 8 vertices would be enough
Thanks I'll try that
Eight verts would be enough with what Blender calls "split normals"
that lets you assign a normal vector per face-corner
Unity does not have such a concept; each vertex has a normal, and that's it
When you import a flat-shaded model, Unity splits the vertices so that each face gets its own verts
try importing a smooth-shaded cube and a flat-shaded cube and comparing their vertex counts
if you only want to generate flat-shaded meshes, then you can create a new mesh where you never reuse vertices
why is my rotation messed up?
this is directly setting the camera's rotation based on the latest bit of mouse input
you generally want to add up inputs over many frames
so, perhaps mouseX += ... and mouseY += ..
I see you're clamping it later
you also do nothing with forward or right or the return value from Mathf.Clamp
Operator '+=' cannot be applied to operands of type 'Quaternion' and 'Quaternion'
He said mouseX +=
I honestly don't know how to fix this, I did something wrong
Can someone suggest a solution?
Each arrow is a transition. Transitions are the only way to move between states (unless you're calling Animator.Play to directly switch to a state)
thanks
Posting this again: IEndDragHandler is not calling if i drop the item as soon as possible.
- Debug.Log is not getting called.
- This is regardless of distance dragged.
Any ideas on how to solve this? Its a big issue for my inventory system since the item is left unselectable because OnEndDrag is where i reactivate blocksRaycasts.
Try use input.mouseDown in update
Perhaps it didn't register as a drag at all..? How are starting it?
Are you using IBeginDragHandler?
Yes im using IBeginDragHandler, which deactivates blocksRaycasts so IDropHandler can work on inventory slots, the issue is caused by calling Begin but not End.
!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.
There's no command called
rule.
Main class: https://paste.mod.gg/otmdighmxrvf/0
Base class: https://paste.mod.gg/bmasmjwzpfbd/0
https://pastebin.com/t0Eci7jZ could someone help me figure out why my player isnt moving towards the target proparly im kinda confused as i think i implemented seek correctly but maybe i did something wrong in unity any help would be appreciated
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 begin is Called, end must be called as well. Though the drag needs to end in the same ui element where it started I think.
Hey i tried coding moving animation but when i press the down the down animation for walking doesnt play but when i press the down and the left or right and the same time the animation plays am i doing something wrong in the code
im trying to make a pickup system and i don't know how use rb.addforce to get it to its target location
It would be less math to just set the velocity
Yea but i don't KNOW HOW
Yea towards the point
Well, think about it
do you know how to calculate the offset vector from where the object is now to where it needs to go?
You can get an offset from any point A to any point B simply as B - A
from there, what do you think we'd do with that?
grabbedRb.AddForce(target); ???
again we're not talking about adding forces here
just setting a velocity
you ignored everything I wrote so far
grabbedRb.velocity(target - grabbedRb.position, target);
i know it has a syntax error but
what now
i don't know how to set the velocity
grabbedRb.linearVelocity = whateverVelocityYouWant;
'Rigidbody' does not contain a definition for 'linearVelocity' and no accessible extension method 'linearVelocity' accepting a first argument of type 'Rigidbody' could be found (are you missing a using directive or an assembly reference?)
then you're using an older version of Unity
and it's just grabbedRb.velocity
Do you have ide or just code editor?
Well you can see hint
just im ass at codding
Also what your unity version
2022.3.62f3
Btw in Unity 6 you can hide unity splash screen for free
Im trying to put a game object inside a script inside the inpector but it doesnt let me and if I click the plus and click on the gameobject it says type mismatch can someone help me out?
Sounds like you're probably trying to reference an object that's in a scene from an object that is an asset (such as a prefab)
prefabs cannot reference objects inside scenes
Well from this screenshot I have no idea what you're trying to drag and where, but this screenshot is showing you editing a prefab
which object are you trying to drag and where are you trying to drag it to?
im trying to drag the player at the top left into the box at the bottom right that syas type mismatch
what type is the field
how do I check that?
How did you declare it
what type did you declare it as
public ???? movement;
it will also show in the field when you don't have the type mismatch error
it will say None (SomeType)
not what I asked
I'm asking about the field
the one you're trying to assign
What type is it
Show the full script if you're confused.
Ok so it's a Movement
yes
it doesnt let me
Try opening the prefab in the dedicated prefab view
isntead of thjis prefab preview thing
like - find yhour prefab in the assets folder (in the project window) and double click it
then try
im pretty sure thats what ive been doing
if that still doesn't work then can you share the full PlayerSetup and Movement scripts?
ill send the scripts
no what we are looking at is you clicked the right arrow next to the GameObject that is an instance of the prefab in your scene
Ok you have a problem here
your class is actually called movement and that's the one that's attached to your player
you probably have a duplicate script somewhere else that is defining Movement
since they don't match, you're getting type mismatch
