#💻┃code-beginner

1 messages · Page 802 of 1

rich adder
#

yeah exactly because if needed you can use direction somewhere else with ease, and its easier to read at a glance

wintry quarry
#

You don't need any of those.normalizeds pretty sure

rich adder
#

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

queen adder
#

for the Vector3 probably no

keen dew
#

Also note these are extremely minute details, not really worth getting stuck on

queen adder
#

I think I always normalized since I only need the directions with a magnitude of 1

warm crater
#

@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?

rich adder
#

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

quartz orbit
#

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).

rich adder
#

its probably nothing to worry about, restart the editor and see if it comes back

swift crag
queen adder
#

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?

naive pawn
#

not seeing any issues that stand out

#

is there something specific you have in mind with regards to correctness?

wintry quarry
naive pawn
#

i will note that that ResetBall method isn't named very accurately

queen adder
naive pawn
#

and it doesn't really need to exist to begin with

wintry quarry
#

is it not working?

queen adder
#

how is it done correctly

naive pawn
#

there's no single correct answer

wintry quarry
#

Assuming you've assigned the reference in the inspector, this is fine

naive pawn
#

there are several valid answers and several invalid/problematic answers

queen adder
#

Something like

naive pawn
#

it's kinda like you're asking if you painted something correctly
did you destroy the brush? no? it's fine

wintry quarry
tender mirage
#

Personally i just reference it directly and that’s been working well, i would love to hear or experiment other methods tho.

quartz orbit
#

@rich adder@swift crag i used editor verision 6000.1.8f1, gonna download newer now

naive pawn
queen adder
#
Ball ball = other.GetComponent<Ball>();
#

this is from a collision

naive pawn
#

yeah that's fine

rich adder
naive pawn
#

there's also TryGetComponent that could simplify the presense check

rich adder
#
if(other.TryGetComponent(out Ball ball)){
// we do have ball component 
ball.dosomething```
wintry quarry
queen adder
#

okay thanks for your input guys. im yet to do null checks myself, I do realize its absolutely needed in development

wintry quarry
#

null checks are not absolutely needed. They are needed in scenarios when they are needed.

queen adder
#

i do get the reference errors if i forget to assign objects

wintry quarry
#

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

queen adder
#

So is it just to prevent crashes?

wintry quarry
#

It has nothing to do with crashes

queen adder
#

but the game stops

wintry quarry
#

it certainly does not

rich adder
#

the opposite

wintry quarry
#

the current script execution context stops

queen adder
#

if I get the exception error

wintry quarry
#

other scripts will continue just fine

wintry quarry
# queen adder but the game stops

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

rich adder
#

Unity Editor has "Pause on Error" which would stop it but in a build it wont

wintry quarry
#

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

queen adder
#

I tried it and it seems the play mode just pauses

wintry quarry
#

yeah due to the error pause setting in the console window

#

if you turn that off it won't pause

queen adder
#

well now I learned something only today ^^

#

so these null reference errors arent a bad thing?

wintry quarry
#

the fire is the bad thing

#

the alarm is good

#

it's telling you about the fire

queen adder
#

yeah true

#

nice way to put it, im writing this down ^^

wintry quarry
#

You should definitely fix all such errors

#

but it's good we get them

rich adder
#

a good time is to do additional logic if something is null (null check)

queen adder
rich adder
#

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```
queen adder
#

so its the same if I do this?

#
if (!hands.Ball)
#

is it the same?

rich adder
#

yea

naive pawn
queen adder
#
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();
    }
}
rich adder
#

having seperate methods is always preferable IMO
its cleaner looking but also you can use them other places if needed, like reset ball

queen adder
rich adder
#

its good practice, you're on the right track donkeyKongThumbsUp

queen adder
#

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

naive pawn
rich adder
#

also makes debugging easier, so you can just comment out a specific function instead of a whole block of code

naive pawn
#

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

rich adder
#

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

queen adder
#

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

naive pawn
#

and the paddles are collliders as well? they should be moved via rigidbodies then

#

not necessarily with physics, but at least via a rigidbody

queen adder
naive pawn
#

otherwise that's a desync+resync every physics tick if i'm not mistaken

rich adder
#

it does but at varying FPS you might get issue

slender nymph
#

it recreates the colliders that have moved without a rigidbody every fixed update which can get expensive

rich adder
#

the Physics has to catchup to where Translate put it, instead of the other way around

queen adder
#

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?

rich adder
#

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

naive pawn
#

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)

queen adder
#

so can the paddles be kinematic? wont they be "see through" ?

rich adder
#

wdym "see through"

naive pawn
#

no, you're thinking of a trigger

queen adder
#

when I make something kinematic its not affected by physics, so its not colliding?

#

or am i mixing something

naive pawn
#

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

queen adder
#

oh so thats perfectly fine or pong paddles since they move up and down

rich adder
#

yea

#

the ball will see it as "Oh this is a moving wall/collider"

queen adder
#

so I can move them with linearVelocity property as well?

polar acorn
#

Kinematic rigidbodies do not respond to forces, but can exert forces

rich adder
ruby python
#

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?

queen adder
#

Will the oncollision function work with a kinematic paddle?

rich adder
#

yea

#

dynamic and Kinematic respond to each other

queen adder
#

im moving the ball with linearVelocity too

rich adder
naive pawn
queen adder
naive pawn
rich adder
#

yeah you can use velocity for 2d kinematic, though I personally still prefer MovePosition

queen adder
swift crag
#

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

rich adder
naive pawn
queen adder
naive pawn
#

objects teleporting isn't realistic either - but sometimes you do need that for game reasons

rich adder
queen adder
#

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?

naive pawn
#

slow down in what sense?

queen adder
#

just out of curiosity

naive pawn
#

in pong the balls generally bounce right off the paddles, so not sure what you're going for

rich adder
#

that mainly affects the collider itself usually, so if you put friction on the collider yes the ball will try to "stick" on it

queen adder
#

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 ^^

naive pawn
#

well, if the ball like, rubs against the paddle without rolling, it'd slow down as it simulates friction

queen adder
#
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?

naive pawn
#

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)

queen adder
#

Yeah I delete it once copying here

rich adder
#

you need to add myRigidbody.position in the calculation to make it local

queen adder
naive pawn
#

MovePosition takes a position, not a delta position

rich adder
naive pawn
#

i thought this was in 3d?

queen adder
#

2D

#
myRigidbody.MovePosition(myRigidbody.position + finalInput);
naive pawn
#

huh, mustve been remembering someone else's chain of discussion

queen adder
rich adder
queen adder
#
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?

queen adder
naive pawn
#

you'd be moving from the origin every tick

naive pawn
rich adder
#

yeah but its default expects a World-Space target pos

#

unlike Translate that defaults to Space.Self

naive pawn
#

fair enough

naive pawn
#

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

rich adder
#

we basically saying the same thing kinda lol

queen adder
#

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

naive pawn
rich adder
#

true true. It happens at times lol

#

I guess the difference is MovePosition wants absolute position, translate expects amount to move

naive pawn
#

yeah that's what i'm trying to convey lol

rich adder
#

yea I see mb

naive pawn
#

!code

radiant voidBOT
queen adder
#

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

naive pawn
#

well, your moveAction was a Vector2

#

(is that other axis even hooked up to anything? why isn't that just an axis (float)?)

rich adder
#

tru this is misleading
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
should just be
float verticalInput = moveActionReference.action.ReadValue<Vector2>().y;

queen adder
#
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();
        }
    }
}
naive pawn
#

your RestrictMovement is still modifying the transform from Update

queen adder
#

so the code inside is fine but it should be in fixed update since its tied to the rigidbody?

naive pawn
#

no, you shouldn't modify the transform at all, it should all be via the rigidbody

rich adder
#

myRigidbody instead of transform

cosmic dagger
#

you should not use transform.position at all, is what they are saying . . .

queen adder
#

hmm okay, ill try that

naive pawn
#

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

rich adder
#

yeah i usually do it that way for pong like game / breakout.. much easier to deal with if you have any dynamic playing field

queen adder
#

going to take a brake and see how can I restrict the movement so the paddles stay inbounds

rich adder
#

just lock your Constraints so it doesnt get pushed / rotated by colliding bodies

queen adder
#

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

naive pawn
#

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

stuck parrot
#

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.

rancid tinsel
#

should I be adding/removing listeners for buttons the same way as for any other events (OnEnable/OnDisable), or is that handled already anyway?

rich adder
naive pawn
#

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?

stuck parrot
# naive pawn the better approach is not using ai-generated code tbh

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

naive pawn
#

no, use actual reliable sources

stuck parrot
naive pawn
#

"don't use AI" ≠ "don't use existing resources"

stuck parrot
naive pawn
#

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

stuck parrot
naive pawn
#

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

rich adder
stuck parrot
naive pawn
#

i recommend against AI for anything related to learning, not just things i already know

rich adder
naive pawn
stuck parrot
rich adder
naive pawn
#

there's an official c# guide by microsoft for example

stuck parrot
naive pawn
#

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 languages

of 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

rich adder
#

Unity only has specific concepts like GameObject or Monobehaviour, but they don't create any special code that isn't c#

naive pawn
#

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

stuck parrot
#

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.

slender nymph
#

there are beginner c# courses pinned in this channel. the microsoft ones are a good place to get started

stuck parrot
#

And for code like making a character move, isnt it like reinventing the wheel? there has to be tons of premade script somewhere?

rich adder
#

as a solo dev you have no choice

rich adder
stuck parrot
rich adder
#

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

naive pawn
#

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

grand snow
#

Yea it's hard to get around learning some stuff

#

Code or visual code logic is needed to make shit work

naive pawn
#

i remember there being some in the pinned message too but seems like it doesn't link to that

slender nymph
#

the Intro to C# one in the pins is the microsoft one

grand snow
#

One of the links is broken

naive pawn
#

....man, what.. i remember i checked one time and they were all unity learn

slender nymph
#

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

rich adder
#

ima tell admins to add it

spare tundra
#

have you hello worlded? lol weird question but has a point I promise

slender nymph
grand snow
#

Oh yea very nice 🙂

naive pawn
#

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 dissolve

void bluff
#

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.

#

And to make it like it's a portal, I made a second camera that displays on the other door

#

like this

naive pawn
#

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

void bluff
#

The issue is, when I enter play mode, the second camera have the same position as camera 1, wich breaks everything

void bluff
#

example of what it does

naive pawn
#

are your otherPortal fields set up correctly?

void bluff
#

It is!

#

I checked it many times

rose trellis
#

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

naive pawn
void bluff
#

so something other than visual studio?

naive pawn
# void bluff example of what it does

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

naive pawn
#

it also has renaming capabilities

#

i'm just not sure what button it's on for VS, could still try f2 though

hexed terrace
#

ctrl+r+r

naive pawn
#

mm don't like that, but ok

void bluff
#

I tried those but I don't even understand what I'm clearly looking for, f2 doesn't really work

naive pawn
#

right clicking the field would probably also have a rename option

rose trellis
queen adder
#

@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.

naive pawn
#

syntaxial?

rich adder
naive pawn
#

also you don't need to ping me every time you ask

#

just bump your previous context and ask

rose trellis
naive pawn
rose trellis
#

unless unity the size of 4 cods combined i should be fine

queen adder
naive pawn
#

it's from latin, messes everyone up the first time lol

naive pawn
#

it looks like you've highlighted the entire line

#

but yes, that sort of menu

rich adder
void bluff
#

I mean ,even when I don't it's the same menu

#

and I don't really understand what to do in it

naive pawn
#

(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)

naive pawn
rose trellis
# rich adder try another template mybe ?

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!

naive pawn
queen adder
#

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

naive pawn
limber gazelle
#

hello, where can I read about world generation algorithms and methods?

queen adder
naive pawn
#

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

queen adder
#

I dont know how to do that :/

naive pawn
#

the same way you did here, just on a different vector

queen adder
#

but I would be clamping my input not the position?

slender nymph
#

basically do the position math first, then clamp that. then pass the new position with the clamped Y to MovePosition

naive pawn
#

ah, my bad. i mean the input to MovePosition, not the actual user input

naive pawn
queen adder
queen adder
#

let me see

slender nymph
void bluff
queen adder
#
Vector2 targetPosition = myRigidbody.position;
targetPosition.y += verticalInput.y * movementSpeed * Time.fixedDeltaTime;
void bluff
queen adder
#

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);
}
queen adder
slender nymph
#

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

queen adder
#
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

polar acorn
naive pawn
#

vector addition is memberwise, (a, b) + (c, d) = (a + c, b + d)

#

geometrically, you're moving finalInput amount from myRigidbody.position

queen adder
#

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?

polar acorn
#

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

naive pawn
vapid egret
#

yo! I love this. I came in with a question but forgot about it because I was following along.

naive pawn
#

tab back to unity/your ide and surely it'll come back...right?

#

-# you gotta note your questions down first lol

queen adder
#

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

vapid egret
#

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.

rich adder
#

you should only use one Move call

naive pawn
#

yeah, should be exactly once per Update

undone bridge
#

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)

naive pawn
#

it can mess with collisions including ground checks

radiant voidBOT
naive pawn
#

here's how ^

queen adder
#
Vector2 targetPosition = myRigidbody.position + verticalInput * (movementSpeed * Time.fixedDeltaTime) ;
``` this works too or do I still need that final Input variable inbetween like before?
naive pawn
naive pawn
#

it's pretty subjective what point it turns from clarity to verbosity though

undone bridge
#

grounded check, if I change it to "== null" it starts working again but I can jump infinitely

naive pawn
#

well == null would be checking that you didn't hit anything

queen adder
naive pawn
#

so assuming you have a IsGrounded() condition before jumping, that would mean the jump is fine, but the raycast isn't hitting anything

undone bridge
#

[SerializeField] private LayerMask groundlayer; this?

naive pawn
#

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

undone bridge
#

oh I see what you meant, thanks I found it

stuck parrot
hexed terrace
#

This is a code channel, can you keep it to code questions.
(delete from here)

queen adder
# stuck parrot Hey I'm curious, since im new to unity, gamedev and programming. Do you guys get...

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

wintry quarry
#

Once you practice enough you will start to remember those "magic spells"

#

It's like anything else

vapid egret
stuck parrot
queen adder
stuck parrot
grand snow
#

c#: microsoft docs for c#
unity: unity docs

#

or just google "c# list" or "unity box collider" and take 0.5 s to click

vapid egret
stuck parrot
queen adder
grand snow
stuck parrot
queen adder
wintry quarry
# stuck parrot any good documentations that "have it all" so I dont have to seach on 4 differen...

Not really because it depends on if you're wanting to look up something from:

queen adder
vapid egret
#

I come from Javascript/Typsescript, so some of this is familiar. C# is much more strict, but I think that's a good thing.

grand snow
#

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 🔫

queen adder
vapid egret
wintry quarry
#

(don't do that)

grand snow
vapid egret
wintry quarry
#

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

vapid egret
#

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

hexed terrace
#

for long blocks of code like that, use a paste site

#

!code

radiant voidBOT
vapid egret
#

fixed it

queen adder
#

looks familiar, is it from the documentation?

vapid egret
#

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.

stuck parrot
#

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)

queen adder
#

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 ^^

grand snow
#

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

vapid egret
#

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?

wintry quarry
#

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);```
vapid egret
wild cove
#

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)?

vapid egret
#

Isn'tt here something like StateMachine for things like that?

wintry quarry
#

Or just like:

  • something happens, a lot of things in a lot of different scripts need to change
#

Your two basic options are:

  1. 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
  2. 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
silk night
#

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?

wintry quarry
#

yeah I think just dividing by the larger dimension would do it

swift crag
#

use multiple Move calls if the player is actually moving in several discrete steps

#

(the player generally isn't doing this!)

vapid egret
#

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.

spare tundra
#

I keep getting this is studio code ive downloaded and installed the SDK and still

slender nymph
#

restart your pc

spare tundra
#

that did it thx

devout pelican
#

Hi! Im new and learning

spare tundra
#

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

vapid egret
#

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?

naive pawn
#

for looking in 3d it's typically just pitch and yaw, 2 axes

#

usually roll is locked

hybrid tapir
#

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

naive pawn
#

weird though, Color.white has full alpha and so would any new Color(r,g,b) you make thonk

hybrid tapir
#

oh

#

well i also just discovered that the way i select colors with the inspector setting is dead wrong

naive pawn
#

i feel like this doesn't solve the root cause, but eh that's up to you if you want to go there

hybrid tapir
#

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

naive pawn
#

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

hybrid tapir
#

ok thats what is it then

naive pawn
#

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

hybrid tapir
#

because i have 22 elements in the list, i just added the alpha = 255 to the initialization statement in the class

naive pawn
#

you'd want alpha = 1 for Color, it's floats from 0 to 1

#

ints from 0 to 255 would be Color32

hybrid tapir
#

claude told me all about it

naive pawn
#

yeah maybe don't use that

hybrid tapir
#

its the only ai that doesnt lie to me and teaches me better than the pearson books

naive pawn
#

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

hybrid tapir
#

among ai users, claude specifically is known for being good at anything coding wise but bad at everything else

naive pawn
#

they hallucinate as necessary to be convincing

hybrid tapir
#

if the unity ai was remotely helpful i would have ditched claude already

naive pawn
#

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 🤷‍♂️

hybrid tapir
#

thats why this server is my fallback when theres problems claude doesnt correctly fix

naive pawn
#

and how many problems did it "fix" and leave behind latent bugs i wonder

hybrid tapir
#

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.

naive pawn
naive pawn
hybrid tapir
#

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?

sour fulcrum
hallow sun
#

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?

cosmic dagger
#

use OnDrag to check if that triggers . . .

spare tundra
#

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

slender nymph
#

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

spare tundra
#

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

slender nymph
#

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

spare tundra
#

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

slender nymph
#

reminder that the inspector shows its local position, which is relative to its parent, not the world position

spare tundra
#

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

limpid thistle
#

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.

midnight plover
verbal dome
limpid thistle
verbal dome
limpid thistle
terse cloud
#

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

hexed terrace
wintry quarry
warped fossil
#

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

silver fern
#

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

warped fossil
#

is it a simple pick character A or character B or actual customization?

hexed terrace
warped fossil
#

fair

silver fern
warped fossil
#

ok well if it's a simple character pick

silver fern
#

its like a fighting game character selection

warped fossil
#

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

hexed terrace
#

you don't want a static var for that, not very extendable

warped fossil
#

true

silver fern
#

then what should I do?

hexed terrace
#

ScriptableObject, assign the values to it at character select

warped fossil
#

Oh yeah mb

silver fern
hexed terrace
#

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

silver fern
#

load the SO?

hexed terrace
#

well, a component having a reference to the SO will load it for you

warped fossil
#

Damn I pressed enter accidentally mb

hexed terrace
#

share !code the correct way

#

!code

radiant voidBOT
warped fossil
#

Oh alright

silver fern
warped fossil
#

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.

The code:
https://paste.mod.gg/basic/viewer/mwmivoeoykln/0

#

And image just for a general idea

silver fern
#

do I make a static scriptable object

#

hm all the online tutorials say to just use a static variable

timber tide
#

Make yourself some GameManager singleton if you need to carry around game state

silver fern
timber tide
#

That is why you make the game manager DDOL and let it live between scenes

silver fern
#

DDOL?

#

oh destroy on load

#

I don't need to keep that info after loading the character though

frosty hound
#

So why does it need to be static?

silver fern
frosty hound
#

Pass the SO to the Character and be done with it

#

Can you link one of these websites?

frosty hound
#

This is passing info between scene. You said you don't need to "keep" info after loading the character, so these are not related.

silver fern
#

I mean still need to pass it dont I?

hexed terrace
frosty hound
#

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.

silver fern
#

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

vague marten
#

Français ?

frosty hound
#

English only server

wintry quarry
#

Anglais seulement

vague marten
#

Ok sorry

frosty hound
#

What is the SO even storing, for starters?

vague marten
#

Do you Guess a unity French server ?

wintry quarry
#

not that I know of

vague marten
#

Ok

hexed terrace
silver fern
#

since I'm still trying to figure out how to best do this

hexed terrace
#

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.

silver fern
#

well technically every possible choice can be encoded as an int or enum so in theory thats all I need

timber tide
#
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);
    }
}```
silver fern
#

I can do it in any number of ways

timber tide
#

there most basic setup

silver fern
#

interesting, thanks

#

I suddenly see an issue with the enum approach

wintry quarry
#

(better yet use an array)

silver fern
#

I wonder if doing a string lookup or somesuch might be better actually

#

or I could generate the selection table from the enum

hexed terrace
#

no, strings are not a good idea for lookups or comparissons

silver fern
#

thats probably smarter

#

wait if I generate from enum I still have to do lookups

silver fern
timber tide
#

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

silver fern
#

yeah but if I have to manually add data in three different places its bound to cause bugs eventually

timber tide
#

Alternatively we do object comparison with SOs

#

Easier to work with on the editor

silver fern
#

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

hexed terrace
timber tide
#

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

silver fern
#

alright thanks

#

I will try

ornate kraken
#

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

vital barn
ornate kraken
#

How does that determine it is of the type ScoreZone though?

#

out ScoreZone scoreZone instead of var?

polar acorn
polar acorn
#

You'd need to either do TryGetComponent<ScoreZone>(out var scoreZone) or TryGetComponent(out ScoreZone scoreZone)

ornate kraken
#

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

queen adder
#

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();
    }
}
ornate kraken
polar acorn
warped fossil
queen adder
queen adder
ornate kraken
queen adder
#

It would be interesting to hear if Unity events with listeners are better to use than C# Action events?

hexed terrace
warped fossil
#

Yeah give me a little bit making food now

vital barn
# queen adder ```cs public class GameManager : MonoBehaviour { public static GameManager I...

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);
    }
}
vital barn
queen adder
swift crag
queen adder
vital barn
#

Instead of TextMeshProUGUI better use TMP_Text

queen adder
#

But I do understand what you mean, to separate "work" to different objects. The Game Manager would just delegate work to different classes

queen adder
hexed terrace
#

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

queen adder
#
public TMP_Text scoreUIText;

Okay so I didnt have to change anything in the inspector too

swift crag
#

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

swift crag
#

in this case, you're still referring to exactly the same thing: the TextMeshProUGUI component

swift crag
#

it includes the name, a portrait, a reference to a prefab, etc.

#

that object goes into a list in another "catalog" asset

silver fern
swift crag
#

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

vital barn
swift crag
#
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

silver fern
#

I was just gonna give each character an int id

swift crag
#

That also works, as long as you make sure the identifiers are unique 😉

swift crag
silver fern
#

I think that will cause problems if the list changes

swift crag
#

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

vital barn
silver fern
#

I might just be too stupid for unity or something

queen adder
silver fern
solar hill
#

are you expecting pity from this self deprecating language or what?

frail hawk
silver fern
#

idk I'm asking newbie questions but I don't understand the answers

frail hawk
#

who are you asking

silver fern
#

everyone

polar acorn
#

Ignorance is a state of being everyone starts from and can grow beyond.

Stupid is a choice.

silver fern
#

then how do I make sense of things

polar acorn
#

By putting in the effort to learn simpler things until you can combine them into more complex things

silver fern
#

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

broken nest
#

Hw do I set the UVs of my custom mesh?

vital barn
broken nest
#

I want to make meshes at runtime tho

timber tide
#

Can use the Mesh API but yeah save yourself the hassle and use blender

vital barn
broken nest
#

Yeah but what do I put there I can't find antything ont the Internet

polar acorn
silver fern
timber tide
#

multiplayer eh

fickle plume
silver fern
#

I can't find a solution thats better than string lookups

timber tide
#

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

fickle plume
vital barn
silver fern
timber tide
#

I would develop this as single player first and figure out those concepts

fickle plume
grand snow
#

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

silver fern
#

ok so I just use a static int to tell the server which character to load in the next scene?

grand snow
#

That depends on the networking solution in use

silver fern
#

the example that comes with mirror seems to do it like that, but in a very convoluted way

grand snow
#

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

timber tide
#

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.

vital barn
#
public struct ReadyCommand : IRpcCommand
{
    // player name
    public FixedString128Bytes name;
    // player prefab index
    public int character;
}
grand snow
#

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.

timber tide
#

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

grand snow
#

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

silver fern
#

mirror is really hard to understand, but I think it doesn't actually work like that

grand snow
#

it does

desert loom
#

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.

grand snow
#

its up to you to organise configuration data correctly so you can network things well

warped fossil
silver fern
grand snow
desert loom
polar acorn
desert loom
polar acorn
desert loom
polar acorn
#

Oh, actually, I got it slightly wrong:
if ((_noiseMakingSurfaces & (1 << other.gameObject.layer)) > 0)

grand snow
#

yea i said they are different?

polar acorn
#

layer is an index, not a flag

grand snow
#

yay for bitshifting and bitwise comparison

swift crag
#

I use a package that generates a Layers.cs file containing a bunch of useful constants

#

thus avoiding that incantation

desert loom
#

Okay so bitwise comparison is the only option

desert loom
warped fossil
#

Oh didn't see the other code help channel mb lads

swift crag
silver fern
#

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

grand snow
#

Yes that would be the best solution

swift crag
grand snow
swift crag
#

e.g.

public const int NOISE_MAKING_LAYERS = Layers.FOO_LAYER | Layers.BAR_LAYER;
silver fern
#

alright thanks

swift crag
#

(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 🤫)

grand snow
#

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

swift crag
#

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 😉)

silver fern
#

I thought I should avoid singletons

swift crag
#

singletons are bad if it turns out they're not really single

grand snow
#

It can cause issues with things such as tests but beginners probably dont need to worry about that

swift crag
#

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"

silver fern
#

in my case, each character is a set of general controller scripts with a set of character specific data and character specific scripts

grand snow
#

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();
silver fern
grand snow
#

A common type/script on each of these character prefabs

#

like in my example above

silver fern
#

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

grand snow
#

So the example works just fine with GameObject too

swift crag
#

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)

silver fern
#

I could in theory add some kind of empty component named character or something

swift crag
#

almost all functionality comes from "modules" that I attach to my entities

#

but everything is, at least, going to have the Entity component

grand snow
#

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

swift crag
#

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

grand snow
#

🤷‍♂️

swift crag
#

sometimes you can abstract too hard DoggoLaugh

vital barn
swift crag
silver fern
#

the characters arent actually encapsulated by anything but the prefab, so the classes are NetworkBehaviors

swift crag
#

are there common "entry points" on the characters that you currently use GetComponent to find?

#

e.g. a component that handles player input

silver fern
#

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

swift crag
#

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)

grand snow
#

why deal with 5 components everywhere when 1 do trick?

swift crag
#

my Entities have fields for things like:

  • a default locomotion mode
  • a default brain
#

since those are mandatory

vital barn
zenith gale
#

ahh okay okay

swift crag
#

speaking of Entities (the other kind) :p

vital barn
#

Entities is analog of GameObjects

grand snow
#

using entity is pretending its a different engine

#

MonoBehaviour would do for any components we make too

silver fern
#

is there any downside to just spawning them as GameObject?

grand snow
#

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

swift crag
#

although, annoyingly

#

you can't pick MonoBehaviour-types from your assets

cosmic dagger
swift crag
cosmic dagger
#

Using the Type as the return value is a convenience to avoid calling GetComponent . . .

swift crag
silver fern
#

alright thanks I'll have to think about that

brisk karma
#

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

dim chasm
#

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 ?

slender nymph
#

can you be more specific about what exactly it is you need help with?

dim chasm
#

yeah sorry

slender nymph
dim chasm
#

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

polar acorn
#

Did you open the file

slender nymph
#

double click the script in your asset folder if the file didn't open automatically

dim chasm
#

This is the result

slender nymph
#

that is the result of you double clicking the file?

dim chasm
#

yes

slender nymph
#

did you leave visual studio open or did you close it before you double clicked it?

dim chasm
#

it was closed

slender nymph
#

okay so leave it open then double click the file

dim chasm
#

still nothing 😅

slender nymph
#

!ide 👇 go through the configuration guide here. if the issue persists after following the steps then try a full restart

radiant voidBOT
dim chasm
#

okay ty !

upper yoke
#

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

chrome tide
upper yoke
#

hm yup it's that but why is it happening? It wans't the case before

chrome tide
#

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.

upper yoke
#

Hmmm okay, thanks

swift crag
#

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

vital barn
#

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

chrome tide
#

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 ¯_(ツ)_/¯

plain forge
#

(I am running the method via button by an editor script)

opaque sandal
#

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.

swift crag
#

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

plain forge
#

I suspected that but some resources said 8 vertices would be enough

#

Thanks I'll try that

swift crag
#

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

golden bobcat
#

why is my rotation messed up?

swift crag
#

you generally want to add up inputs over many frames

#

so, perhaps mouseX += ... and mouseY += ..

#

I see you're clamping it later

slender nymph
#

you also do nothing with forward or right or the return value from Mathf.Clamp

swift crag
#

so maybe you just forgot to do += instead of =

#

(well, trying to clamp it :p )

golden bobcat
upper token
#

Can someone suggest a solution?

vital barn
#

Yes

#

You stuck on duckshot

#

Because there no transitions

swift crag
#

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)

upper token
#

thanks

hallow sun
#

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.
vital barn
teal viper
#

Are you using IBeginDragHandler?

hallow sun
pure drift
#

!code

radiant voidBOT
#
<:error:1413114584763596884> Command not found

There's no command called rule.

hallow sun
pure drift
teal viper
obsidian gazelle
#

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

golden bobcat
#

im trying to make a pickup system and i don't know how use rb.addforce to get it to its target location

wintry quarry
golden bobcat
#

Yea but i don't KNOW HOW

wintry quarry
#

how to do what specifically

#

set the velocity?

golden bobcat
#

Yea towards the point

wintry quarry
#

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?

golden bobcat
#

no

#

only the offset from the camera

wintry quarry
#

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?

golden bobcat
#

grabbedRb.AddForce(target); ???

wintry quarry
#

again we're not talking about adding forces here

#

just setting a velocity

#

you ignored everything I wrote so far

golden bobcat
#

grabbedRb.velocity(target - grabbedRb.position, target);

#

i know it has a syntax error but

golden bobcat
#

i don't know how to set the velocity

wintry quarry
#

grabbedRb.linearVelocity = whateverVelocityYouWant;

golden bobcat
#

'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?)

wintry quarry
#

and it's just grabbedRb.velocity

vital barn
golden bobcat
#

i have ide

vital barn
golden bobcat
#

just im ass at codding

vital barn
golden bobcat
#

2022.3.62f3

vital barn
#

Ok

#

Yes just velocity

vital barn
golden bobcat
#

man i would rather use assembly then ts

#

i give up

small zealot
#

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?

wintry quarry
#

prefabs cannot reference objects inside scenes

small zealot
#

heres a screenshot do you think thats what im doing?

wintry quarry
# small zealot

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?

small zealot
#

im trying to drag the player at the top left into the box at the bottom right that syas type mismatch

small zealot
#

how do I check that?

wintry quarry
#

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)

small zealot
#

The player setup script is

#

public class PlayerSetup : MonoBehaviour

wintry quarry
#

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.

small zealot
#

oh None (Movement)

#

my bad

wintry quarry
#

Ok so it's a Movement

small zealot
#

yes

wintry quarry
#

you can and should just do this

#

click and drag that component directly in

small zealot
#

it doesnt let me

wintry quarry
#

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

small zealot
#

im pretty sure thats what ive been doing

wintry quarry
#

if that still doesn't work then can you share the full PlayerSetup and Movement scripts?

small zealot
#

ill send the scripts

wintry quarry
#

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

small zealot
wintry quarry
#

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

small zealot