#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 101 of 1

rich adder
#

CC doesn't have forces

edgy hearth
#

is there another way for me to get the same effect?

timber tide
#

time to implement your own physics

rich adder
#

pretty much this ^

edgy hearth
#

uh ok lol

#

ill try and figure it out

timber tide
#

start with gravity, it's the easiest

edgy hearth
#

ill probably be back tho

rich adder
#

or just use the RIgidbody like the tutorial maybe
(dont mix it with cc tho)

edgy hearth
#

ive already been using a CC for everything else, so i dont want to start over

rich adder
#

this can be easily done with CC (crouch/sprint)

edgy hearth
#

i dont want my player capsule to float

rich adder
edgy hearth
#

oh ok

rich adder
#

and for crouch you shrink collder and move the center up

edgy hearth
#

So will i be fine if i skip that bit?

rich adder
#

should be

edgy hearth
#

also, why do a lot of the people i see use rigid body instead of a CC?

#

is it cuz of the premade physics?

rich adder
#

pretty much

timber tide
#

physics stuffs not that hard to implement

#

it's just more convenient to use rigidbodies

#

oh, rigidbodies do have the benefit of high speed collision detection which is actually somewhat of a pain to implement

edgy hearth
#

hey so i skipped it and it didnt float, but now when i stop pressing the crouch button, i stay in the ground

#

ope sorry i thought the vid would preview, not make you download

rich adder
polar acorn
# edgy hearth also, why do a lot of the people i see use rigid body instead of a CC?

Both the CC and Rigidbody do some things very easily, at the expense of making other things more complicated. Depending on which part is more important to your game, you might pick a different one.

Character controllers make general four directional movement dead simple, but struggle to have fine grained collisions and respond to forces. Rigidbodies do this really easily, but struggle with things like slopes and are quite a bit more fiddly with the code for movement and braking

edgy hearth
#

thank you kind sir

eternal needle
rich adder
#

Unity standard assets used to come with RB third person controller , I wonder why the new ones they decided to just use CC

timber tide
#

I try to keep a lot of my level flat, and slopes clear of any bumps and it seems to work out well enough, I only use the CC cause I wanted to make a freaking cool blackhole effect and I wanted some of my own fake physics in the calculations

#

oh that and people tell me that rbs are performance heavy considering I have like 500 enemies

#

haven't actually profiled that though

eternal needle
rich adder
#

i dont mind the CC except for moving platforms

#

"works right away" and takes less messing about with different drag modes with RB

#

dealing with RB sliding against walls smoothly (without using cheap physic material no friction) is a pain..somehow...

eternal needle
timber tide
#

yeah hoepfully cause atm my cpu is kinda maxed and I've been trying to load more work on the gpu as possible

eternal needle
timber tide
#

really should have done ECS but too late now

frosty hound
#

If you're doing a kinematic CC, just get KCC off the asset store and save yourself the headache of handling any of the background stuff so you can focus on pure movement logic.

rich adder
#

good thing its free now ๐Ÿ™‚

#

its very complex to extend though initially

rich adder
#

I tried moving platform is kinematic, i tried using Physics.SyncTransforms

#

twitch city

queen adder
#

oooook so im trying to code a camera shake effect myself and this code is NOT optimal it goes wayyy too fast. any ideas on how to make it slower? i dont know how i coudl make it slower consdiereing update() runs on every frame

edgy hearth
#

ok so i decided to completely redo the movement and camera system in order to use a rigid body, and now when i press play my camera is being teleported away from the player, how could i fix this?

queen adder
#

coroutine huuuhhh

#

sorry big word

#

actually i think i know what that is i just dont know how i would establish it in C#

ivory bobcat
queen adder
#

is this goood???

rich adder
#

not code question

queen adder
#

you said scalar so i assumed you meant you wanted me to scale deltatime up since it is a decimal i think

ivory bobcat
#

I said replace one not incr

queen adder
#

oh

#

sorry

#

OHHHH

#

OK

#

I HAVE TO make the cos INCREMENT smaller

ionic zephyr
#

quick question

#

why do we usually put cameramovement in the lateUpdate

rich adder
#

just kidding

#

afaik I think because movement happens in Update/Fixedupdate

#

if they try to move on the same frame its choppy

#

but seriously don't make your own camera follow and use Cinemachine..

gaunt ice
#

You are not understand why we need time.deltatime, not a hard coded number, imagine you have 1000fps now and what will happen to your code

rocky canyon
#
    private void Update()
    {
        mousePos = Input.mousePosition;
        mousePos.z = depthOffset;

        if(MasterPowerSwitch.isOn)
            UpdateMousePositionUI();
        else
        {
            xTxt.text = "00.00";
            xTxt.text = "00.00";
        }
  
        rectTransform.position = cam.ScreenToWorldPoint(mousePos);

        //mouse cursor offset
        rectTransform.anchoredPosition += offset;
    }

    void UpdateMousePositionUI()
    {
        xTxt.text = mousePos.x.ToString();
        yTxt.text = mousePos.y.ToString();
    }```
wonder why there's a trailing `.5` on the Y coord
weak talon
#
    void MoveCamera()
    {
        rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
        rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
        playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
        transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
    }
    public override void OnStartClient()
    {
        base.OnStartClient();
        if (base.IsOwner)
        {
            playerCamera = Camera.main;
            playerCamera.transform.position = new Vector3(transform.position.x, transform.position.y + 0.6f, transform.position.z);
            playerCamera.transform.SetParent(transform);
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
        else
        {
            gameObject.GetComponent<PlayerScript>().enabled = false;
        }
    }

when i play and start a server in unity, when moving around its smooth but when i move my camera it is really glitchy the movement and it is not smooth at all
how do i fix.

rocky canyon
north kiln
rocky canyon
#

scaling issue, yup, it was half a pixel off ๐Ÿ˜„

#

yea, i never stopped and thought about what mouse position is actually using

#

some sort of interpolation could work to smooth out the camera.
there's a few differnt ways. you can search camera smoothing on google to find some examples..
then you can multiply the logic with a modifier you can adjust as needed for the amount of smoothing you want.

ivory bobcat
queen adder
#

oh ok

#

sighhh

rocky gale
#

_______ = _______? ______ : _______; What does this format mean and how do you use it

summer stump
#

It is an if statement essentially

#

X = Y ? A : B

If Y is true, assign A to X
If Y is false, assign B to X

#

It only works with assignments

rocky gale
#

i see

#

thx

gentle moat
#

anyone know how to make it so that one animation needs to end befoire playing another in a blend tree?

north scroll
#

Hai, I need some help reading one var from a script to another. In this case, I have a UI display script with the UI game object added and a score text field in the CANVAS gameobject parent. There is a child text on it. The UI display script has a public score text variable where I can add a text item on to it, and I can't add the child to that section of the inspector for some reason. I'm trying to make it so that the UI script modifies the score text based off the score int from the playerMovement script. Im sure there's more efficient ways to do it, but prob more complicated to me atm. THis is my current UI script:

public class userInterfaceScript : MonoBehaviour
{
    public playerMovement moveScript; // Reference to Script A
    public Text scoreText; // Reference to the UI Text component

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void UpdateScore()
    {
        Debug.Log("Counted!!!");
        scoreText.text = "Score: " + moveScript.score;
        Debug.Log(moveScript.score);

    }
}

#

oh and this is where I update the score in the playerMovement script when it collides with the coin:

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Collectible"))
    {
        //Collectables should play a sound effect when collected. 
        PlaySound(coinCollectSound);

        //The collectables count as the score for the player and disappear when touched by the player. 
        score += 1;
        Debug.Log("MOVE: " + score);
        Destroy(other.gameObject);

        // Call the UpdateScore function in userInterfaceScript to update the UI
        if (uiScript != null)
        {
            uiScript.UpdateScore();
        }
    }
}
#

if anyone could help, please ping me :D

gaunt ice
#

i would remove the checking of uiScript!=null (unless the ui script will be destroyed?)
then after you increment score in script A and script B read it back.....why dont just pass the score or let the player control over it?

north scroll
#

I will remove that null check.

I thought I was attempting to pass the score through the
public playerMovement moveScript; // Reference to Script A
public userInterfaceScript uiScript; // Reference to Script A
lines. I thought they would allow me to just easily pass a variable around for accessability but I guess I'm not? Can you tell me how to properly pass the score then ? @gaunt ice

gaunt ice
#

if you want accessibility, you can make anything static.....

uiScript.SetScoreText(score);
```pass the score as some ways above
weak talon
#
    void MoveCamera()
    {
        float mouseY = Input.GetAxis("Mouse Y") * Time.deltaTime;
        float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime;

        rotationX += -mouseY * lookSpeed;
        rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
        playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
        transform.rotation *= Quaternion.Euler(0, mouseX * lookSpeed, 0);
    }
    public override void OnStartClient()
    {
        base.OnStartClient();
        if (base.IsOwner)
        {
            playerCamera = Camera.main;
            playerCamera.transform.position = new Vector3(transform.position.x, transform.position.y + 0.6f, transform.position.z);
            playerCamera.transform.SetParent(transform);
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
        else
        {
            gameObject.GetComponent<PlayerScript>().enabled = false;
        }
    }

when i play and start a server in unity, when moving around its smooth but when i move my camera it is really glitchy the movement and it is not smooth at all
how do i fix.

eternal needle
north scroll
wintry quarry
#

That will cause jitter

weak talon
gaunt ice
#

let uiScript directly access some variable is not a good idea (you can change player score in ui script), instead lets player tell ui script when its score is changed

wintry quarry
weak talon
wintry quarry
weak talon
wintry quarry
#

instead of transform.rotation *= Quaternion.Euler(0, mouseX * lookSpeed, 0);
it should be rb.rotation *= Quaternion.Euler(0, mouseX * lookSpeed, 0);

weak talon
#

iull try that now

north scroll
# gaunt ice let uiScript directly access some variable is not a good idea (you can change pl...

ok so usually its best practice for a script to not have direct access to another variable from an outside script? My UI Script isn't really that big atm, its literally just that updateScore() function. Should I just allow the player to have access to UI functionality and change the score text from the playerMovement Script itself rather than having its own seperate script for UI ?

#

I was also thinking of adding a timer tho

weak talon
gaunt ice
#

usually an individual ui script is needed to handle some common ui elements like main screen or pause screen or settings, but the score text is tightly related to player to i think it is better to give control to player.

wintry quarry
weak talon
wintry quarry
#

AddForce you said?
Can you show how the code is currently?

weak talon
#
if (grounded)
        {
            rb.AddForce(moveDirection.normalized * moveSpeed * 10, ForceMode.Force);
        }

sorry did you mean the camera code or the movement. above is the movement on ground
its very small so it doesnt matter too much. but it is noticable, all my friends noticed it
you know what its fine, now that i think about it. it isnt worth all this struggle just to fix it. later if it really is bad then i can try to fix it again
soorry if i wasted your time

north scroll
#

ok so I deleted everything and currently in my player script I have

using UnityEngine.UI;
public Text scoreText;
scoreText.text = "Score: " + score;

I am adding the Canvas' child (Score), into the player's public Text scoreText in the inspector, but Unity won't let me.

The game itself runs but then I get this error :

#

NullReferenceException: Object reference not set to an instance of an object
playerMovement.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/playerMovement.cs:102)

This error ****

gaunt ice
#

what is line 102.....

north scroll
#

scoreText.text = "Score: " + score;

#

and the error comes up when I collide with the coins

gaunt ice
#

sorceText is null, you need to assign it in inspector
but idk why the error is not unassigned reference

north scroll
#

I know, what I am saying is Unity doesn't allow me to drag the Score text child object from the Canvas parent into the player's inspector where it hold that

gaunt ice
#

is it textmeshpro not text?

north scroll
#

oh I think ur right

#

so TextMeshPro ?

#

and do I change the using unity.ui to text mesh pro or is that the same thing ?

gaunt ice
#

yes

#

textmeshprougui, btw your ide will remind you

grizzled kite
#

MC_Wave I'm having an issue with a script, would someone be willing to help me troubleshoot?

north scroll
#

@gaunt ice tysm!

grizzled kite
#

oop, So I'm using the documented gameobject recoreder script to record animation in runtime, but I'm using to record a rigs animation that is being controlled by an IK system. it is only recordering the main object none of the armature

#

I had it as humanoid and ik that was some issue, so I was able to get the IK working fine with it in generic, but still to no avail

summer stump
loud mauve
#

Okay, so learning Unity
And for educational purposes I'm making my own first person player controller.
Working on the movement and I'm having issues with the diagonal movement.
I see a common problem is diagonal movement being faster due to not normalizing, but my issue is that 2 of the 4 diagonal movements don't move at all, the player just stops.

private void Move()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 inputVector = new Vector3(x, 0f, z).normalized;
    player.transform.Translate(inputVector * currentSpeed * Time.deltaTime);
    Debug.Log(inputVector * currentSpeed * Time.deltaTime);
}```

Assuming it's due to the -x and positive z (or vice versa) fighting each other, but am unsure how to get around it.
It's probably something simple that I'm overlooking / over thinking.
W/D works, S/A works, but W/A and S/D just stop dead
grizzled kite
# summer stump Probably best for <#502171313201479681> as this is not really a code question. ...

It is easily made humanoid, the script is just not recording the armature, It gave me an error when it was humanoid so I made it generic. but now it still doesnt record the armeture even though there is no more error.
so I'm assuming its not recording it bc of the IK actively moving the armaeture but, that kinda defeats the whole point of a gameobject recorder so im unsure of how to work around that

grizzled kite
#

oki, I'll give that a try ty

static cedar
queen adder
#

other way around

#

i had no idea what deltatime was

static cedar
queen adder
#

i read up and its interval of how long a frame took to get to the next frame

north kiln
static cedar
#

Last frame to current frame actually.
You can't predict when the next frame happens.

queen adder
#

yeah thats what i said

loud mauve
north kiln
loud mauve
north kiln
#

and presumably inputVector is the same

loud mauve
#

Yep, although sometimes it doesn't quite hit 1 or -1, it'll stop at a like 0.998 or something

north kiln
#

Well, then it sounds like you would be translating by that amount (scaled), so there's no reason why you wouldn't travel in that direction

#

unless you're setting currentSpeed in a weird way that contradicts with the diagonal movement

loud mauve
#

currentSpeed is always at least 2.5f
currentSpeed = baseSpeed *2 while sprinting
currentSpeed = basespeed /2 while crouched
assigned back to baseSpeed (which is 5f) whenever I exit one of those conditions.
Tracking those variables, I don't see any unintended values

#

Wondering if I should switch to using velocity off a rigidbody

slender sinew
loud mauve
rich adder
#

!code

eternal falconBOT
loud mauve
rich adder
#

are you mixing rigidbody with translation?

loud mauve
rich adder
#

I would drop the translation and keep the rigidbody

#

if you want accurate collisions its easier to use colliders than making your own casts

loud mauve
#

Then I'm back to using velocity for the movement, correct?

rich adder
#

if you don't want velocity you can always make it kinematic

#

with that you might still need to check walls so you don't go through them

loud mauve
#

Honestly I'm impartial, I'm mostly just confused as to why it's happening to begin with.
I'm not opposed to using a different approach

rich adder
#

btw this is reduant doing if statements for these bools

#
if(Physics.Raycast(checkGround, out hit, rayLength))
        {
            isGrounded = true;
        } else
        {
            isGrounded = false;
        }```
can just be `isGrounded = Physics.Raycast(checkGround, out hit, rayLength)`
loud mauve
#

Fairly certain
Only happens when the translate is being fed -x, z or x, -z regardless of position within the world, rotation or terrain/objects around it

and agreed, was just writing it as simply as possible for my brain, was going to go back and clean up once it was working

loud mauve
rich adder
rich adder
loud mauve
rich adder
#

idk how I did not see this before lol

#

doh

#

Get rid of this
if (Input.GetAxis("Horizontal") + Input.GetAxis("Vertical") != 0)

#

pretty sure that will fix it

loud mauve
#

An audible faceplam was had, that was the issue

#

-1 x and 1 z sums to 0...

rich adder
#

I would clean this up btw

private Vector2 move;
    void Update()
    {
        move.x = Input.GetAxis("Horizontal");
        move.y = Input.GetAxis("Vertical");```
#

then if you want you can do move.normalized

loud mauve
#

Agreed, still plan to go back and tidy everything up
Thanks for the help though, I chased that for far longer than I care to admit

rich adder
#

oh wait you want z movement

#

but yeah def put it in a vector2

loud mauve
#

yeah, I got what you meant pepe_thumbs

rich adder
#

so you can do if (move != Vector2.zero))

loud mauve
#

That's much cleaner but for the time being I just slapped an OR in there

#

if (Input.GetAxis("Horizontal") !=0 || Input.GetAxis("Vertical") != 0)

rich adder
#

so verbose

prime horizon
#

Guys, I need some help.
I'm learning to do the dialogue system with Ink integration based on this video https://youtu.be/vY0Sk93YUhA?si=9k7oH6wimO36MwDT

Then I realized I couldn't use the mouse to click on any button on the screen.
I even tried to make a new project and used his GitHub repo (I took the branch number 2) to test if my script was wrong and I still can't click the choice button provided on the choice button. I also used Unity new input system

In this video, I show how to make a dialogue system with choices for a 2D game in Unity.

The dialogue system features Ink, which is an open source narrative scripting language for creating video game dialogue that integrates nicely with Unity.

Thank you for watching and I hope the video was helpful! ๐Ÿ™‚

NOTE ABOUT INPUT HANDLING - If you're try...

โ–ถ Play video
wheat fog
#

Anyone know why my game is lagging? I know it's because of the player rotation feature I've added. But I cant seem to figure out why. Here is my script:

#
        float angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(-1 * angle - 90, Vector3.forward);
        m_transform.rotation = rotation;```
#

I know the transform.rotation is the reason why, but I can't figure out an alternative or work around

teal viper
rich adder
prime horizon
rich adder
prime horizon
rich adder
wheat fog
teal viper
wheat fog
teal viper
#

If your sprite is on the same object or parented to it, it will rotate as any other object.

prime horizon
meager gust
meager gust
#

this problem is commonly caused by running stuff in fixedupdate without proper frame interpolation

wheat fog
#

its running in Update()

#

not sure if there is a difference tho

meager gust
#

there is, but it's still an odd problem

wheat fog
#

the weapon child rotates as well to face the mouse, before I decided to change it to the player

#

and it doesn't have a rigidbody attached to it

#

whereas the player does

teal viper
wheat fog
#

im surpised no one else has run into this problem before

#

or if they have i cant find any solutions

teal viper
#

Many people do. It's quite common.

#

Some just think that it's supposed to be like that and never think it's an issue.

meager gust
#

I don't do 2D, but you could try

#

I just don't see how setting the rotation would break the position's interpolation

#

since that's where the actual lag is coming from

rich adder
wheat fog
#

would it be like this: rb.MoveRotation(rotation);

meager gust
#

you use your angle variable

#

not the quaternion variable

wheat fog
#

I did, and i dont think it did anything

#

should it be in radians?

meager gust
#

degrees

prime horizon
wheat fog
# meager gust degrees

that's what it's in, but when I call it. WIthout the transform.rotation, it doesn't rotate at all.

#

It may help a little, but the lag is definetly still noticeable

meager gust
wheat fog
#

No, when I remove the transform.rotation it's fixed

#

I can't debug log it because its a void method

rich adder
prime horizon
wheat fog
#

Oh, MoveRotation should be used for Kinematic, not dynamic. Might be why its not working

meager gust
#

This is how you generally rotate something "inline" with the physics engine

#

but it's a pretty ugly approach if you want a snappy rotation

#

again, I know nothing about 2d, so it's hard for me to understand why setting the rotation is breaking position interpolation

wheat fog
#

Do you have tons of dynamic (non-kinematic) rigidbodies in your scene that are getting moved when these objects rotate? The profiler results are telling you that whatever you're doing is very expensive from a physics standpoint. But it might indicate it's because you're not taking your rigidbodies into account. Generally, moving rigidbodies means timing the movement with the physics timestep, and using the rigidbody-specific movement methods. So, instead of transform.Rotate, you'd usually want Rigidbody.MoveRotation.

#

I found this forums post on it

meager gust
#

I mean yeah, you could check the frame rate

#

if it's 60+ then it's not really the issue

#

your game doesn't really look that demanding

wheat fog
#

It shouldn't be

#

Thats why Im so confused too

meager gust
#

post all of your movement code

#

worst case, you could probably just have an invisible rigidbody underneath, and your graphics sprite on top

#

actually that probably still wouldn't work

wheat fog
#

if (canControl) {

        float controlx = Input.GetAxisRaw("Horizontal");
        float controly = Input.GetAxisRaw("Vertical");

        direction = new Vector2(controlx, controly);
        keypressed = controlx != 0 || controly != 0;
        direction = direction.normalized;

        if (keypressed) {
            saved_direction = direction;
        }
#

rb.velocity *= Mathf.Pow(1f - damper, Time.deltaTime * 10f);
rb.velocity += direction * speed * Time.deltaTime;

    base.Update();
#

I think thats everything, I didnt write so Im not entirely sure.

teal viper
meager gust
#

afaik that doesn't happen in 3D

#

so long as you're not modifying the position

teal viper
#

It does from my experience.

meager gust
#

you're probably right. I use a custom interpolator

teal viper
#

And many people had it as the cause of jittering so far. Changing the rotation method fixed it for them. They can't all be lying can they?๐Ÿ˜ฌ

meager gust
#

nah you're right

#

been a while since I touched that project

wheat fog
teal viper
meager gust
#

If you don't like that answer ^ I can help you build a custom interpolator

#

which will solve the problem for good

#

both solutions are janky

wheat fog
wheat fog
#

Infact, I'm getting beta out tmmrw or monday D:

meager gust
#

easier said than done

#

I would probably calculate the error = current_angle - desired_angle

#

and factor that into the rotation speed / direction

#

realistically it's probably gonna oscillate back and forth a minimal amount when it's reached the desired rotation

teal viper
#

There's not gonna be any error if you set the angular velocity manually.

#

Might need to clamp it when approaching the target angle to not overshoot, but it's not very complicated.

meager gust
#

yeah, that's probably the best solution

wheat fog
#

public void AddTorqueImpulse(float angularChangeInDegrees)
{
var body = GetComponent<Rigidbody2D>();
var impulse = (angularChangeInDegrees * Mathf.Deg2Rad) * body.inertia;

    body.AddTorque(impulse, ForceMode2D.Impulse);
}

}

#

is the angular Change in Degrees the same as my angle?

meager gust
#

you'll get finer tuned control over the rotation

meager gust
#

Angular velocity in degrees per second.

#

This line is important in figuring out the equation

#

the physics engine ticks in fractional seconds

#

fixedupdate also ticks inline with the physics engine btw

#

For instance, if my physics engine ticks at 30hz (30 times per second), and my angular velocity is 30 (rotating 30 degrees per second) then it's rotating 1 degree every fixed update (30 / 30 = 1)

verbal cloud
#

hey guys! im making a fishing game and i'd like the fish size (in arbitrary inches), the fish size (in unity units), and the fish sell price to all be randomized but scale with each other. so ideally i'd have a three ranges of twos and then randomize one of them and then scale the other two off of that. does anyone know how i could achieve this? thanks all :D

wheat fog
meager gust
wheat fog
#

Then, i change the speed of the angular velocity until i reach my desired point and set it to 0?

meager gust
#

but yes

gaunt ice
#

why one fish can have two size?
shouldnt there is a inch to Unity unit conversion

wheat fog
verbal cloud
#

trying to block things out

meager gust
#

my brain doesn't work so good at 11pm, but that should be somewhere in your formula

#

the angularVelocity is just how much the physics engine is rotating your object every physics tick

gaunt ice
#

i get what you mean now, since if the actual size of fish is small player cant see the fish in world?
actual size and price should be related, but you can clamp the magnitude when convert actual size to world size (at least make it looks consistence)

meager gust
#

like dlich said, you probably want to clamp the values so it doesn't teleport instantly to the new angle

wheat fog
#

How do you start this rotation, like it's not a constant rotation so how do you turn it on?

meager gust
#

just go ahead and comment out your old rotation code, while we start off with this

wheat fog
#

I pretty much have already haha

meager gust
#

just so you can get a general idea, set the angularVelocity to a constant value, like 0.1 every fixedupdate

meager gust
#

and run the game, and just see what it does

#

your guy should be spinning

#

if your physics update rate is 30hz, then realistically he's rotating 0.00333333333 degrees every physics update

wheat fog
#

rb.angularVelocity = 1;

#

like this right?

meager gust
#

sure, that works

#

do you see the result?

wheat fog
#

no, he doesn't seem to be moving

meager gust
#

do it in fixedupdate

wheat fog
#

private Rigidbody2D rb;

#

it is in

#

fixed update

meager gust
#

in the rigidbody2d in your editor, crank the angularDrag down to 0

#

if that doesn't work, debug.log your rb variable and make sure it's set

wheat fog
#

the debug log returns object

meager gust
#

post all of the code

wheat fog
meager gust
#
        rb.angularVelocity = 1000;
        debug.log(rb.angularVelocity);
    }```
#

tell me what that outputs

#

you can remove the other debug

wheat fog
#

it returns 0

meager gust
#

thats pretty strange

wheat fog
#

or checked

meager gust
#

alright

#

you see your guy spinning?

wheat fog
#

okay now it rotates

meager gust
#

great

#

you'll have to do some trial and error, but just start off by getting
float angleDifference = currentAngle - desiredAngle;

#

and set that as your angularVelocity

#

every fixedupdate

wheat fog
#

so would it eventually hit 0 then and stop moxing

meager gust
#

that's the goal

wheat fog
#

when the current angle and desired angle are the same/

meager gust
#

you might have to do angleDifference * time.fixedDeltaTime

#

or something

#

since we want it happening in 1 step

wheat fog
#

I just need it to get to stop when it reaches that position

meager gust
#

that should automatically be happening with the code I supplied

#

is it not?

teal viper
#

No, a body set in motion will remain in motion unless other forces are applied to it.

#

I think Newton figured it out?

meager gust
#

we're updating the angularVelocity every physics tick though

teal viper
#

Updating to 1000 according to the last code snippet

meager gust
#

I gave him updated code

#

float angleDifference = currentAngle - desiredAngle;
angularVelocity = angleDifference * time.fixedDeltaTime;

teal viper
#

Oh, with the desired angle?

meager gust
#

yes

teal viper
#

I think they should share their current code properly

#

!vode

#

!code

eternal falconBOT
wheat fog
#

my keyboard doesnt let me type that symbol

meager gust
#

its below the escape key

#

top left

wheat fog
#

im on a 60%

meager gust
#

you did it earlier

wheat fog
#

i copy and pasted it then

meager gust
#

ah

wheat fog
#

okay i got it

#
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector2 finaldir = direction - rb.position;
        float angle = Mathf.Atan2(finaldir.x, finaldir.y) * Mathf.Rad2Deg;
        Debug.Log(Time.fixedDeltaTime);
        rb.angularVelocity = angle * Time.fixedDeltaTime;```
#

the time*fixed delta time makes it rotate veryslowly

meager gust
#

you aren't factoring in the current angle

#

we need that for the difference

wheat fog
#

I thought i was doing that in finaldir?

meager gust
#

nope, that just gets the direction for desiredAngle

#

your
float angle = Mathf.Atan2(finaldir.x, finaldir.y) * Mathf.Rad2Deg;
should be
float desiredAngle = Mathf.Atan2(finaldir.x, finaldir.y) * Mathf.Rad2Deg;

#

then currentAngle is the angle that the body itself is currently pointing (in degrees)

wheat fog
#

I understand

meager gust
#

post updated code if you need help

wheat fog
#

am i dumb? doesnt rb.velocity return the direction of the rb

meager gust
#

Rigidbody2D.rotation

wheat fog
#

rb.angularVelocity = desiredangle - rb.rotation;

#

wouldnt it look something like this?

#

it doesnt quite work tho

meager gust
#

rb.angularVelocity = (desiredangle - rb.rotation) * time.deltaTime;

#

try that

wheat fog
#

i just added that lol

#

gimme asec its compling

#

that make its run really slowly

#

makes sense tho cuz my fixeddelta time is .2

meager gust
#

does it work though?

wheat fog
#

no

#

well

#

it would take me 5 minutes to see if it would

meager gust
#

hang on, gears are turning in my brain

#

post your full fixedupdate

wheat fog
#

        Vector2 finaldir = direction - rb.position;
        float desiredangle = Mathf.Atan2(finaldir.x, finaldir.y) * Mathf.Rad2Deg;
    
        rb.angularVelocity = (desiredangle - rb.rotation) * Time.fixedDeltaTime;```
#

when i devide by fixed delta time its instant

meager gust
#

yeah, that might be it

#

let me verify one sec

wheat fog
#

it faces the right way for my y values

#

but my xs are flipped

meager gust
#

Atan2 is (y, x)

#

not (x, y)

wheat fog
#

It works!

#

I just multiplied by the x value by -1

#

Ill probably just leave it at that

#

just has to do w my sprite orientation probably

meager gust
#

yeah, division is right for the equation. you're set

meager gust
wheat fog
#

thanks for all the help bro i really appreciat eit

queen adder
#

what is the getmask for anything except again? public static int AllExceptCharacters = LayerMask.GetMask("Character");
is ~ havent used for a while

static cedar
#

It's the ~ alright.

hardy mist
#

How can I launch a dedicated server build from MacOS terminal with arguments?

Can't even launch it, "open executableFileName" doesn't work.
The executable is correct, double clicking it works.

rocky lava
#

anyone know how to fix this?

languid spire
timber tide
#

look closer

rocky lava
#

im really confused

#

OH i see it

#

i'm still getting used to unity sorry

timber tide
#

number #1 rule of learning to code. Make sure if you're following tutorials or guides you're typing the correct syntax

rocky lava
#

ok ty!

languid spire
timber tide
#

yeah that too

rocky lava
#

IDE?

#

whats that?

languid spire
#

the program you are using to write code in

rocky lava
#

no clue tbh

languid spire
#

!ide

eternal falconBOT
rocky lava
#

ooooh that

languid spire
#

follow one of these links

rocky lava
#

yes it does that

languid spire
#

it does not look like it, your IDE should have shown your error

rocky lava
#

oh

#

ohhh now i get it

#

alrighty lemme install it

pine dagger
#

Right so when im in edit mode and click run the camera rotates on the x axis as i want but it doesnt move when im viewing through the game tab

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour
{

    public float mouseSensitivity;
    private float xRotation = 0;
    public Transform playerBody;
    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90, 90f);
        Debug.Log(xRotation);
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }
}
#

anything visibly wrong with that?

#

oh...

#

Theres a camera in my body and i cant access ut

woeful hedge
#
public class ScareCrowReveal : MonoBehaviour
{
    // Start is called before the first frame 
    public float RevealTime;
    public float delay;
    void Awake()
    {
        Debug.Log("Hi");
        Color colora = gameObject.GetComponent<SpriteRenderer>().color;
        colora.a = 0;
        StartCoroutine(Reveal(RevealTime, delay));
    }

    IEnumerator Reveal(float time, float delay)
    {
        Color color = gameObject.GetComponent<SpriteRenderer>().color;
        float deltaTime = 0;
        yield return new WaitForSecondsRealtime(time);
        Debug.Log("alpha");
        while (deltaTime < delay)
        {
            Debug.Log(color.a);
            deltaTime += Time.deltaTime;
            color.a = deltaTime / delay;
            yield return new WaitForFixedUpdate();
        }

        color.a = 0;
    }
}

So I just made Coroutine which changes color alpha but It dosent works well
Debug.log(color.a) printed well but the actual value uis still not changing since Awake().
what should I do to solve this?

languid spire
#

you need to set the changed colour back to the renderer. Color is a struct which is a value type

woeful hedge
#

the GameObject's actual color alpha is always 1 as default although I made them 0 on Awake

woeful hedge
languid spire
#

doubt

#

this

Color color = gameObject.GetComponent<SpriteRenderer>().color;

makes a copy so any changes to color will not affect the original

woeful hedge
#

hmm youre right but one question

#

    IEnumerator FireShakeEvent(GameObject RailGunTrail, GameObject RailGunCircle, List<GameObject> Effects, float count)
    {
        GameObject EF1 = Instantiate(Effects[0]);
        GameObject EF2 = Instantiate(Effects[1]);
                ....



        RailGunTrail.SetActive(true);
        RailGunCircle.SetActive(true);

        Color colorRG = RailGunTrail.GetComponent<SpriteRenderer>().color;
        Color colorCircle = RailGunCircle.GetComponent<SpriteRenderer>().color;

        int x = 1;

        Vector3 railgunScale1 = RailGunTrail.transform.localScale;
        Vector3 railgunScale2 = RailGunCircle.transform.localScale;


        while (x < count + 1)
        {
            //Debug.Log(color);
            // color.a = UnityEngine.Random.Range(0f, 1f);
            // obj.GetComponent<SpriteRenderer>().color = color;
            colorRG.a = x * 0.1f;
            colorCircle.a = x * 0.1f;

            railgunScale1.x += (float)Math.Sqrt(x) * 0.00075f;
            railgunScale2.x += (float)Math.Sqrt(x) * 0.00126f;

            RailGunTrail.transform.localScale = railgunScale1;
            RailGunCircle.transform.localScale = railgunScale2;

            x++;
            yield return new WaitForSecondsRealtime(Time.deltaTime * 0.25f);

        }

        colorRG.a = 1;
        colorCircle.a = 1;

        RailGunTrail.GetComponent<SpriteRenderer>().color = colorRG;
        RailGunCircle.GetComponent<SpriteRenderer>().color = colorCircle;

    }
#

then why this code works well?
I assigned them at end of coroutine but its alpha changes slowly

languid spire
#

it doesn't work 'well'

RailGunTrail.GetComponent<SpriteRenderer>().color = colorRG;
        RailGunCircle.GetComponent<SpriteRenderer>().color = colorCircle;

need to be inside the while as well

#

it may be that you are starting many instances of your coroutine

woeful hedge
#

thanks

autumn tusk
#

why cant i directly drag in this textmeshpro function, im setting up a ui function to display my player health

#

this is the textmesh i want to drag in

verbal dome
languid spire
#

change the declaration to TMP_Text

verbal dome
#

Use TextMeshProUGUI or TMP_Text

autumn tusk
deep bear
#

Hey everyone, so I'm making a game in Unity. I want to add a sprite to my 3D scene, but when I right click > 2D Object in the scene panel, the only option available to me is Pixel Perfect Camera (URP)

How do I get Unity to give the option to add a sprite like in this tutorial screenshot?

wintry quarry
deep bear
#

Are there any other packages that are generally useful to have in Unity?

slender nymph
#

cinemachine

spare sparrow
#

What is the absolute most simple braindead way to get data from one scene to another. i dont care wether its clean or pretty

timber tide
#

lol

slender nymph
#

Store that data on a DDOL object, store it on a ScriptableObject referenced from both scenes, serialize it and write to disk then read it in the other scene, store it in a static variable. there are many ways to accomplish that

spare sparrow
languid spire
#

reference it in a static class

static cedar
#

Basically just a singleton.

patent compass
#

Hello. How can i apply force in opposite direction of a body. like add force but in opposite direction from the collision direction

slender nymph
#

depends on your actual goal, you could just get the normal from the first contact point and apply force in that direction. or you could get the velocity of the rigidbody and add force in the opposite direction of the velocity

amber spruce
#

so i have a npc and when a player gets close i want smth to happen how to i check for when they get close

slender nymph
#

you could have a trigger collider and use OnTriggerEnter to determine when the player gets near, or you could use a physics query like a CheckBox or OverlapSphere or something. the query would give you a bit more control for when you want to check
i would personally use the physics query

tropic shuttle
slender nymph
#

did you read past the first bit of my message?

tropic shuttle
#

I don't know what messages I'm supposed to have, and I don't accurately understand the meaning on the site. The translator is not very accurate

#

I had a bug with two audio listeners, I solved it but still no sound

slender nymph
tropic shuttle
#

okay

amber spruce
slender nymph
#

no, you can read the docs or find a video yourself though

tropic shuttle
#

Can a single object be subject to OnTriggerEnter and OnCollisionEnter?

slender nymph
#

yes provided that object has a non-trigger collider. OnCollisionEnter will not happen for trigger colliders but OnTriggerEnter can be called on a non-trigger because that collider could enter a trigger

#

also don't crosspost

spare sparrow
#

im trying to use UnityEngine.InputSystem in one of my tests. ive installed the package and added it to my assembly definition. but its still not being recognized in my test. What coul be th reason?

tropic shuttle
#

I don't understand what I need to do to get the OnCollisionEnter message sent and OnTriggenEnter working

slender nymph
#

if you would go through the steps in the page i linked you would see that two kinematic rigidbodies colliding do not produce an OnCollisionEnter message

tropic shuttle
#

These are not kinematic bodies, there is a tick on Is Trigger in the screenshot. But it won't work without it. You yourself said that OnCollisionEnter and OnTriggerEnter can be together, but I've tried everything already

slender nymph
tropic shuttle
#

I am a newbie and may not understand the meaning of the word "Kinematic Object" if so, I apologise

frosty hound
#

You also shouldn't be putting rigidbodies on environment objects that aren't moving, such as the floor/wall.

tropic shuttle
slender nymph
#

and you're not bothering to show what your code even looks like so ๐Ÿคทโ€โ™‚๏ธ

tropic shuttle
#

I showed you the code above, here it is

#

Fall - Sound

#

Trigger lamp - Trigger

#

You know what I mean.

slender nymph
#

well for one !code
and two, did you not bother following literally the first instruction on the page i had linked that said to use breakpoints or logs to determine if that code is even being called?

eternal falconBOT
slender nymph
#

and again, OnCollisionEnter cannot be called when those two colliders intersect

tropic shuttle
#

Firstly:I don't know what these dots are, haven't looked into it yet.
And secondly: How do I get this code to execute then? There is even a video where the author succeeded and I did not. ( Most likely he didn't say or show something).\

slender nymph
#

i feel like i'm giving instructions to a brick wall so i'm not going to try helping any further. maybe someone else will have the patience to do so ๐Ÿคทโ€โ™‚๏ธ

tropic shuttle
#

Maybe I should try to do a different floor. An invisible one that will perform the OnCollisionOn function?

#

Ok, thanks for trying to help, sorry for being obtuse, but that's what I am, a newbie

rare basin
#

Looks like you cannot get helped

#

If you dont understand the help

#

You should learn the very basics first in order to understand the provided help

#

I have linked you the OnTriggerEnter docs, did you read it?

#

there are conditions that must be met in order to call this function

tropic shuttle
#

OnTriggerEnter works for me. Yeah, I read it. Hold on, I'm going to try one thing now, in case it works

#

To reproduce OnCollisionEnter both objects must be non-triggered without Rigidbody?

frosty hound
#

To have a collision, one object must have a rigibody. Both must have a collider.

fossil sable
#

Hi everyone, new user of the discord community. I've been struggling for a couple of days on this bug and I can't figure out what's causing it. I implemented a grid-based movement for a pokemon clone. The movement works, I was also able to add collisions and animations. But after some time I realized something was off. I removed animations and tilemap rendering and saw that the player lags from time to time when moving. It's very subtle but I'm providing a clip showing the bug (hopefully you can see it).

I'm adding the link to the code here:
https://gdl.space/qibayihaca.cs

tropic shuttle
tropic shuttle
#

That's how it works, isn't it?

ivory bobcat
#

How to post !code

eternal falconBOT
fossil sable
fossil sable
# eternal falcon

Oh I tried using the inline method and hit the character mark so I thought I could upload it as txt file as recommended by Discord. Shall I delete and reupload as a link using one of the website?

ivory bobcat
#

Some people will not get the embedded text and won't bother to download the text file.

fossil sable
#

Okay I reuploaded it, thanks for showing me how

frosty hound
#

You may want to try using the pixel perfect camera package to ensure your art doesn't sit between pixels.

#

Also, just a note that setting the scale value of your game view isn't making things bigger. Keep it to the left, and scale the size property of your orthographic camera instead.

fossil sable
#

Okay I'll try looking into the pixel perfect camera

fossil sable
#

Even after adding the Pixel Perfect camera component there is no change

#

It's silly since it is a really minor thing, but I can't stand not having crisp movement. I want to nail at least that down before proceeding with more complex stuff

rare basin
#

you won't have smooth code by directly modyfing the transform.position

#

that is a very bad way of handling the movement for several reasons (collisions, weird stutter movement)

fossil sable
#

Really?? What's good practice then? Adding a dynamic rigid body and changing its position? I saw that in another video

floral siren
#

hey

summer stump
fossil sable
#

Okay then I'll try doing that and see if the problem gets fixed, thanks

tawdry nymph
#

is there a way to get the normal of the collider when using ontriggerenter2D?

#

when using oncollisionEnter2D you can just use collision.contacts[0].normal; but that doesn't work with triggers for some reason

wintry quarry
#

Triggers don't generate contacts

tawdry nymph
#

oh, is there another way to get them?

bitter abyss
#

hi I am trying to do something from tutorial but itยดs not working

eager elm
eager elm
# bitter abyss

alright. ScoreText is of type 'Text' and you want to assign a 'String' to it, which doesn't work.
A 'Text' type contains many things, for example the font size, font type, spacing etc. And it also contains a variable called 'text' which is what you are looking for.

cobalt wing
#

guys can i use C++ in unity

bitter abyss
eager elm
# bitter abyss

If you look closely you can also see that the code in the tutorial and the code you posted don't match exactly.

cobalt wing
eager elm
bitter abyss
eager elm
# bitter abyss I am stupid but I canยดt find it

scoreText is of type 'Text' which is a class that contains all things you would need to display a text, the font, the spacing of the letters and more importantly the actual text you want to display. To set the text you need to call:
scoreText**.text** = "this text will be shown";

boreal tangle
#

When you make game object and give it a child
Do you add scripts to the parent or child

swift crag
boreal tangle
#

I am trying to make a player move and I put the body of the player in a game object called player

swift crag
#

If you want to move the parent object around, you probably want to put your movement component on the parent object

#

not because you couldn't put it on the child, but because it just makes more sense that way

boreal tangle
#

Ok ty

swift crag
#

also, you add components to objects, not scripts (:

boreal tangle
#

Ok ty

swift crag
#

Your script files don't get "attached" to anything. They just declare components.

#

So your Player.cs script probably has a Player class in it, which derives from MonoBehaviour

#

that creates a new kind of component called Player

boreal tangle
#

Ok

tender stag
#

how can i limit the velocity without setting it directly like i am doing now?

rich adder
#

look fine

tender stag
#

its setting it directly

#

like my player now falls really slowly

rich adder
#

oh its because velocity overrides gravity

tender stag
#

and its not adding accelerating force anymore

#

its just instant

rich adder
#

maybe run handle speed only if vel is above certain treshold

#

doesn't solve it fully tho, you're fighiting forces with vel override :\

tender stag
swift crag
#

Is player movement always horizontal?

tender stag
#

i was thinking of this maybe

tender stag
eager elm
swift crag
swift crag
#

You could separate out two parts of your velocity:

  • Horizontal movement -- in the X and Z directions
  • Vertical movement -- in the Y direction
#

and then only clamp the first one

#

But this would behave weirdly on slopes. You'd be able to climb them super quickly

tender stag
#

this is the whole script

violet falcon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class finalScript : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            int buildIndex = SceneManager.GetActiveScene().buildIndex;
            if(buildIndex == 2)
            {
                SceneManager.LoadScene(0);
            }
            else
            {
                SceneManger.LoadScene(buildIndex + 1);

            }

        }
    }
}
broken sail
#

No ```?

violet falcon
#

so what i do

cosmic quail
violet falcon
cosmic quail
summer stump
#

Misspelled

wintry quarry
#

right now you wrote SceneManger

#

which maybe has something to do with Christmas

violet falcon
#

let me see

wintry quarry
#

๐ŸŽ„

summer stump
#

Probably need to configure your IDE? Did it underline the word?

wintry quarry
violet falcon
#

thanks

summer stump
violet falcon
#

i mean

#

i'm spanish

#

yk sometimes hard to write

cosmic quail
# violet falcon thanks

why did you manually type out the error message and hide the most important part where it says "SceneManger" instead of "SceneManager"

ruby python
#

Evening all. I was just wondering if anyone had a 'technique' for hiding objects that the player character passes behind (fixed Camera angle always following/focused on the player), especially with things like 'multi-storey' buildings that the player can walk inside?

summer stump
timber tide
#

can do it with raycast from the camera too if you wanna just hide the walls

#

like, fully

#

shaders allow you to do some cutouts though

summer stump
#

Yeah, I was imagining only a piece being transparent. Raycast is a good idea too, and would be easier

ruby python
#

Okay yeah I'd thought about raycasting and shaders/disabling objects, but not entirely sure how I'd go about only disabling floors 'above' the current floor that the player is on if that makes sense?

timber tide
#

comparisons

ruby python
#

as in.....(pseudo)

if raycast hit floor3
enable floor1, floor2
disable floor4, floor5

etc.etc

timber tide
#

floor + 1

ruby python
#

Aah, I get you.

cunning rapids
#

How to maintain lighting of the environment for viewmodels that uses camera stacking

#

Gun is bland and doesn't follow the lighting of the scene

grim wyvern
#

dudes, when it comes to handling attack animations, would you rather use triggers or boolean variables in your animators? I want to assess pros and cons.

timber tide
#

if it's not a loop then I trigger

lofty lotus
#

@grim wyvern a bool is good for looping animation, or animations that you don't want to be stopped if interrupted, like if walking is true, keep walking, while a trigger is good for something like an attack you want to do once or like a death animation, generally I use triggers most often

royal ledge
#

rb.velocity = new Vector2(movementInput.x * movementSpeed, rb.velocity.y);

Am i correct in assuming setting the rb velocity like this in an update, negates any force applied to said object?

#

As adding force just sets velocity on the rigidbody?

languid spire
#

yes, but this should be done in FixedUpdate

royal ledge
#

Yes ofc

#

Then i have to recode my movement haha;D

lofty lotus
#

if you want forces to impact your movement you may want to use addforce

#

instead of velocity

royal ledge
#

I didn't want to use addForce for movement cause then there would be acceleration, but i geuss it is inevitable

#

I'm sure i can work around it

summer stump
languid spire
royal ledge
#

Ye, i think i saw a good video on how to approach it awhile back

queen adder
#

how can i change this on code guys anyone know?

royal ledge
#

2d platformer, just wanted the movement to be precise

#

https://youtu.be/KbtcEVCM7bw?t=116
Found the video if anyone is interested

๐ŸŽฌDesigning a Platformer Jump: https://youtu.be/2S3g8CgBG1g

Want to make your character feel fluid and responsive to control? Use these tips and tricks to improve your platformer in any Engine or Language.
In this video, I'll show YOU how you can make more advanced platformer movement, which is more flexible to your needs as well as feeling fan...

โ–ถ Play video
royal ledge
#

While i'm at it, when i want to use AddForce once on an object can i just call it in a random method or do i want to flag it so it's used in the fixed update?

amber spruce
#

hey so for my game i have npcs with dialogue how would i make it so the player cant move while they are listening to the dialogue

summer stump
languid spire
summer stump
amber spruce
# summer stump How do you move? Just make a bool to prevent it It really depends on what you're...

this is my move function ```csharp
public void Move()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * m_Speed;
Vector2 targetVelocity = new Vector2(horizontalMove * 10f, m_Rigidbody2D.velocity.y);
m_Rigidbody2D.velocity = Vector2.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (horizontalMove > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (horizontalMove < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}

royal ledge
#

You have given me knowledge.

lofty lotus
summer stump
#

At the top of Move write
if (!canMove) return;

When you start dialogue, disable canMove

royal ledge
lofty lotus
queen adder
#

i want to make this objects renderer mode opaque

rich adder
# queen adder

thats now how you do it
btw:

When you change the Rendering Mode, Unity applies a number of changes to the Material. There is no single C# API to change the Rendering Mode of a Material, but you can make the same changes in your code.

queen adder
#

yea i looked it

#

it says BlendMode.Opaque this but doesnt work

#

i dont know how it works i am very beginner if anyone know can help

rich adder
summer stump
#

But I agree, just swap materials

rocky gale
#

if im making a customization system where you can choose your color do i make a scriptable object that has a color for each image (that you select to choose your color) and then just use that or is there a better way

rich adder
slow crystal
#

Someone can help me to do an script that makes the player knockback when attacked? feel free to dm me

rich adder
queen adder
#

youre right

#

i added a wall in front of the glass so when i touch a button or something the wall will be disappear

slow crystal
rocky gale
#

ye that wil prolly work thx

rocky gale
rich adder
slow crystal
#

Yes

rich adder
#

def use it , it will make it easier

slow crystal
#

I tried to use AddForce but it dont worked

slow crystal
rich adder
queen adder
#

how do i reference a component from an entirely diff obj

#

for example

#

in a script inside my camera i want to reference the rigidbody component of the player object

#

i want to access the rigidbody's velocity

rich adder
rocky gale
#

player.GetComponent<Rigidbody>();

queen adder
#

what is a serialized reference

rich adder
#

public Rigidbody rb;
or
[SerializeField] private Rigidbody rb;

#

ideally the private one

queen adder
#

soooo.. this will refrence a rigidbody component from a entirely different object yes?

rich adder
#

this makes it easy to drag n drop the component directly in the fieldvia inspector

queen adder
#

how do i initialize?

#

oh wait

#

๐Ÿคฆโ€โ™‚๏ธ

#

ed just told me how

#

thank you all

rich adder
queen adder
#

ohhhhhhhh thats how it works

#

wow

rich adder
#

GetComponent is ok too but imo no reason to use it if its not a runtime search , and even then stick with TryGetComponent

queen adder
#

niiice

#

so no need to initialize

queen adder
rocky gale
rich adder
#

not sure what you mean initialize in this context

queen adder
#

i mean like

rich adder
queen adder
#

whenever you make a new variable

#

and it has to be defined

rich adder
#

you're just declaring

queen adder
#

hiding the object or deleting it

rich adder
#

I hate that unity made an overcomplicated example code on this one but yeah

#

just SetActive

rich adder
#

accessor T variablename that defines vairable name as Type

queen adder
#

im sorry im confused now

last edge
#

question does anyone know how to use git bash? im trying to update my unity project which i edited

rich adder
#

Rigidbody is a type you define for example myrigidbody

queen adder
#

ah

#

that makes sense

#

ok

last edge
#

like i remember doing add . "name" but forgot how to get ther

queen adder
#

even when i use serialized field,

#

i have to define it? the unity wont just handle it for me?

rich adder
last edge
#

a gui? how so

rich adder
valid pulsar
#

I have two functions (https://paste.ofcode.org/385sHssbFBmyMxzDXGtqxVe) that are very similar and both rebind controls but the one thats supposed to work for composites(the second one) dosent run the On complete part of the PerformInteractiveRebinding but the first function runs perfectly fine.

rich adder
last edge
#

oh gotcha

valid pulsar
rich adder
valid pulsar
hollow carbon
#

why can i move left and right but not up and down in my Game?

valid pulsar
slender nymph
# hollow carbon

you have two local variables that are named very similarly and you are using the wrong one in a couple places due to that

hollow carbon
#

and now?

#

Hello

slender nymph
#

you should print the position to see if the Y value is actually changing

#

and if it is not, then it is most likely your input axis not set up correctly

#

and if your Y axis is changing correctly but you do not see the object actually moving then you've deliberately rotated everything 90 degrees around the X axis for some reason so that you have a top down view in a 3d world instead of using the default 2d view

languid spire
hollow carbon
#

ok thanks

#

where are they?

#

!docs

eternal falconBOT
summer stump
languid spire
#

even better, if you want to google something from Unity put Unity first in the search

royal osprey
#

where i can find support for unity mirror?

slender nymph
#

pretty sure there's a mirror discord

royal osprey
#

oh, they have discord?

rich adder
frail star
#

If I have a string like

Sandpaper - 2136A

How can I remove the - and everything after?
using string.Trim()?

slender nymph
#

if you know it will specifically be that character you could just get the index of that character then use that as the end index for a substring starting at the beginning of the string

fathom ether
#

Can i somehow attach a instace of a c# object (in my case a Item) to a dynamically created gameobject (a button)?

timber tide
#

sure why not

#

not as a component though you need mono for that

slender nymph
#

if it is a plain old c# object you don't "attach" it, just pass the reference to the instantiated object from another monobehaviour

frail star
slender nymph
#

well this already smells

#

you should provide more context for what you are doing

swift crag
fathom ether
swift crag
#

well, start by changing InventoryContentPrefab's type to something other than GameObject

#

that's a very vague prefab

timber tide
#

Inventory and UI stuff follows the basic model view controller pattern if you're familiar with that with the GameObject's being the UI logic and the inventory the business.

swift crag
#
public class InventoryContentEntry : MonoBehaviour {
  public Item item;
  // more code 
}

...

foreach (var item in Inventory.items) {
  var entry = Instantiate(inventoryContentEntryPrefab, InventoryDisplay.transform);
  entry.item = item;
}
#

it might look like this

frail star
swift crag
#

the "Y" in the XY problem

slender nymph
swift crag
#

what are you actually doing?

molten horizon
#

Hi! I'm looking for a way to not trigger OnValueChanged(); when I change the value of a dropdown in a script. Is there any simple way to do this? I haven't found a simple and concrete answer.

swift crag
#

you want SetValueWithoutNotify

slender nymph
#

SetValueWithoutNotify

swift crag
#

you'll find this on all of the UI input classes

frail star
swift crag
molten horizon
#

Oh! It's that simple. Thank you

bitter oar
#

Hey, i want to do that when the player jumps and attacks he does a dive, but he kind of "teleports" instead of moving to the direction, this is my code:


public void Attack()
    {
        if (!readyToAttack || attacking) return;

        readyToAttack = false;
        attacking = true;
        playerRigidbody.AddForce(transform.forward*1000, ForceMode.Acceleration);

        Invoke(nameof(ResetAttack), attackSpeed);
        Invoke(nameof(AttackRaycast), attackDelay);

        //audioSource.pitch = 
        //sound stuff
        if (isGrounded)
        {
            if (attackCount == 0)
            {
                ChangeAnimationState(ATTACK1);
                attackCount++;
            }
            else
            {
                ChangeAnimationState(ATTACK2);
                attackCount = 0;
            }
        }
        else
        {
            if (dived == false)
            {
                //if (animator.GetBool("isDiving") == false && !isGrounded)
                //{
                    //DIVE ATTACK
                    animatorManager.PlayTargetAnimtion("Dive Attack", false);
                    animator.SetBool("isDiving", true);
                //}

                
                moveDirection *= 7;
                dived = true;
            }
            playerRigidbody.AddForce(transform.up * 70, ForceMode.Impulse);
            playerRigidbody.AddForce(transform.forward * 300, ForceMode.Impulse);
        }
    }

I tried using other forcemodes, but they barely make a change.

slender nymph
#

i'm guessing that you typically move the object using velocity instead of force? because you're probably just overwriting any velocity applied by these AddForce calls

swift crag
#

using ForceMode.Acceleration in a method you only call once doesn't make sense, by the way

#

Force and Acceleration are both used to apply force over time

#

they tell you how hard you're pushing

modern seal
#

What happens to my UI code when I build for dedicated server? for example a listener to a button, that wont be needed on my server, is that still running on the server and wasting resources?

cosmic dagger
clever pumice
#

Is there any benefit to using C# instead of C++

#

-for unity. I know C++ is generally more complex, but I'll be forced to learn it either way.

languid spire
modern seal
#

lol

clever pumice
#

What?

cosmic dagger
#

They're not wrong. It's harder to screw up in C# . . .

clever pumice
#

Oh, yeah, I know. But is there any benefit specifically for using it with Unity?

cosmic dagger
#

But since you're in here, Unity is only C# so that's all you have . . .

eternal needle
languid spire
#

Unity only supports c# so there is that

clever pumice
#

I thought you could

#

Oh well

languid spire
#

see what I mean about who 'think'

cosmic dagger
clever pumice
#

Duped?

summer stump
cosmic dagger
clever pumice
#

Oh

#

I could've googled it but it's nicer from others

languid spire
#

but 'others' might not know what they are talking about either, so how much better off are you?

clever pumice
#

So you're saying I can't trust you?

languid spire
#

me you can trust, others I'm not so sure of

bitter oar
#

would it be better to add force using the objects mass or ignoring it?

languid spire
#

depends on your game requirements

cosmic dagger
#

Do you use the correct mass to move every object in your game?

bitter oar
languid spire
#

that should not be your concern, what physics does your game require?

lean geyser
#

in my UI2D script I have a function to restart the main scene

    public void RestartLevel()
    {
        SceneManager.LoadScene("mainGame");
    }

I want it to be triggered upon pressing a button, the problem is that I am unable to select any function in the dropdown

#

Any suggestions as to why I am unable to find the function please?

bitter oar
#

for now im only using rigidbodies with default settings

lean geyser
#

Oh are you implying that I should be attaching UI2D over Player2D?

slender nymph
#

what? you need to drag an object that has the component into the slot. not the script asset

lean geyser
#

That went completely over my head, thank you

slender nymph
#

should have read the info in the link

fathom ether
nova frigate
#

Hi. Does anyone know any tutorials for implamenting melee combat on AI enemies?

slow crystal
#

Someone can help me with this error? Object reference not set to an instace of an object

swift crag
#

this describes what the error means and what causes it.

fluid remnant
#

Huh? We cannot paste from Transform rotation to Quaternion inside a custom struct?
but works for Position ?

#

Am I missing something?

#
[Serializable]
public struct PosRot
{
    public Vector3 Position;
    public Quaternion Rotation;
}```
#

I can't right click the field at all.

ivory bobcat
slender nymph
#

actually unity displays quaternions as euler angles in the inspector for whatever reason so there's probably not

fluid remnant
#

I just can't copy / paste in this field for some reason

#

only the individual X,Y,Z though

ivory bobcat
#

Haven't tried but is this exclusive to your script only or does this apply for to Transform property as well?

fluid remnant
#

just the struct, works fine between Transforms

ivory bobcat
#

I'm uncertain than

fluid remnant
#

yea Unity must be doing some extra tricks with Transform inspector

bleak vale
#
private void OnTriggerStay(Collider collider)
{
    if (collider.gameObject.GetComponent<Health>())
    {
        Health health = collider.gameObject.GetComponent<Health>();
        Debug.Log(health.healthPoint.Value);
    }
    if (cooldown <= 0)
    {
        if (collider.gameObject.GetComponent<Health>())
        {
            if (!IsServer) { return; }
            Health health = collider.gameObject.GetComponent<Health>();
            if (health.whatIsIt == WhatIsIt.isBoss) return;
            health.healthPoint.Value -= 1000;
        }
        Destroy(gameObject);
    }
}
#

Can someone explain to me why Trigger is not getting the sentry collision?

#

I mean the wall, the boss or even the player are reciving the trigger and they get Debug.Log but not that sentry

#

Colliders are in childs but parent have rigidbody

slender nymph
bleak vale
#

Does rigidbody ignore collision or what?

bleak vale
slender nymph
#

well if you don't want help ๐Ÿคทโ€โ™‚๏ธ

bleak vale
#

Mate

#

I want help

#

I dont want link

#

To something I know

#

Heres the thing

slender nymph
#

show the rigidbody and the collider for both of the objects involved

#

also finish your thought before pressing enter. your vertical messages are annoying

bleak vale
frosty hound
#

Are your colliders actually set to triggers?

bleak vale
#

Yes

#

Inside detonation spell the sphere collider is set to trigger

queen adder
#

Is this channel for beginners?

bleak vale
rocky canyon
slender nymph
rocky canyon
#

lol.. ur gonna have trouble coding ๐Ÿ˜

queen adder
#

Yea but I still want to make sure

bleak vale
queen adder
#

guys i wronly pressed a button now objects move grid grid

#

anyone know the key?

queen adder
bleak vale
#

The name of the channel is a sarcatic joke

queen adder
slender nymph
queen adder
#

How the fuck am I supposed to make a player

#

oh i found

#

This scripting shit is hard ๐Ÿ˜ญ

#

tysm for helping

slender nymph
frosty hound
# bleak vale

Are you spawning this explosion at a point? TriggerEnter won't call for things which are immediately inside the collider when spawned since they never "entered" inside.

bleak vale
#

Its on stay mate

stuck palm
#

why isnt this code working? im using character controller (cc)

bleak vale
#

As I am telling you guys. The script is working on every other gameobject wich has Health script like player, wall or boss

#

But not on a sentry

slender nymph
stuck palm
bleak vale
#

There are so many structure in my game that have health script but this one is not working and its the only one gameobject that has a mesh collider

#

As it's a model from blender

slender nymph
summer stump
queen adder
slender nymph
queen adder
#

But I have to start somewhere yk

bleak vale
stuck palm
slender nymph
# bleak vale

and the default layer can collide with itself? and you've added logs into your OnTriggerStay to confirm whether it is actually being called or not and that this isn't just a logic issue?

eternal falconBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

minor roost
#

placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight);
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight);
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight + 1);
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight + 2);
placeTile(tileAtlas.Leaf.tileSprites, x, y + treeHeight + 3);

    placeTile(tileAtlas.Leaf.tileSprites, x - 1, y + treeHeight);
    placeTile(tileAtlas.Leaf.tileSprites, x - 1, y + treeHeight + 1);
    placeTile(tileAtlas.Leaf.tileSprites, x - 1, y + treeHeight + 2);

    placeTile(tileAtlas.Leaf.tileSprites, x - 2, y + treeHeight);
    placeTile(tileAtlas.Leaf.tileSprites, x - 2, y + treeHeight + 1);

    placeTile(tileAtlas.Leaf.tileSprites, x + 2, y + treeHeight);

** placeTile(tileAtlas.Leaf.tileSprites, x + 2, y + treeHeight + 1);**

    placeTile(tileAtlas.Leaf.tileSprites, x + 1, y + treeHeight);
    placeTile(tileAtlas.Leaf.tileSprites, x + 1, y + treeHeight + 1);
    placeTile(tileAtlas.Leaf.tileSprites, x + 1, y + treeHeight + 2);
}
#

um what?

queen adder
#

๐Ÿ‘

slender nymph
#

so if you have confirmed that OnTriggerStay is not being called then your objects colliders are not actually overlapping

slender nymph
eternal falconBOT
timber tide
#

Seems like you went out of bounds

minor roost
slender nymph
#

newTile.transform.parent = worldChunks[(int)chunkCoord].transform;
this means that chunkCoord is either below 0 or larger than the number of objects you have in the array

minor roost
#

ik that lol

#

where do i put that

slender nymph
#

wdym where do you put that? that's line 221 which is the line your error is happening on

minor roost
#

found it what do i make it

#

what do i change the code to

slender nymph
#

well you need to start by figuring out why that number is outside of the range

minor roost
#

hmm thinking

timber tide
#

start printing values

slender nymph
#

i'd imagine it has something to do with your giant pile of magic numbers being added to your X inside of generateTree

minor roost
#

it prob is

#

does the error affect the game alot or can i just leave it?

slender nymph
#

you need to fix your errors

minor roost
#

ill ask chat gpt

queen adder
#

if you have a time, can you look at the prob in unity talk too.

visual merlin
#

how do make the code wait for a lil bit, like a "time.sleep" but in c#

timber tide
#

coroutines usually

slender nymph
#

use a coroutine or a timer in update

#

and do not fall into the trap of using Thread.Sleep. it's a trick and will freeze your entire game for the duration of the sleep

visual merlin
#

๐Ÿซก aye aye

minor roost
#

ill try and fix ty guys

rocky canyon
# visual merlin how do make the code wait for a lil bit, like a "time.sleep" but in c#
    public void StartCoroutineExample()
    {
        StartCoroutine(WaitAndCallFunction());
    }

    // Coroutine that waits for 3 seconds and then calls another function
    private IEnumerator WaitAndCallFunction()
    {
        // Do something before waiting, if needed

        // Wait for 3 seconds
        yield return new WaitForSeconds(3f);

        // Call another function here
        YourOtherFunction();
    }```
heres an example of a coroutine being called in the `StartCoroutineExample()` function..
#

you'll also need the using System.Collections; using statement at the top in order to access the stuff u need to run one

swift crag
#

You can never stop the main thread. That's the golden rule.

#

So you can't make your Update method "wait", for example

quaint kindle
#

I thought Unity remembers the output folder when you switch from Desktop to Server Build? or is there a setting.. I would think it would remember the different folders you select when Building for the different Platforms in the editor... that just seems like it should naturally remember that. This is on 2022

minor roost
#

quick thing if (y >= height - 1)
{
int t = Random.Range(0, Treechance);

                if (t == 1)
                {   
                     // Tree generation
                    if (worldTiles.Contains(new Vector2(x, y)))
                    {
                        generateTree(x, y + 1);
                    }
                    else 
                    {
                        int i = Random.Range(0, tallGrassChance);
                        //TallGrass Generation
                        if (i == 1)
                        {
                            placeTile(tileAtlas.TallGrass.tileSprites, x, y + 1);
                        }
                    }
                }
            }
#

did i do a mistake or sm

#

Tall grass doesnt spawn

polar acorn
eternal falconBOT
minor roost
#

LINE 169