#💻┃code-beginner

1 messages · Page 71 of 1

umbral bough
#

what is going on 😭

teal viper
#

So many possibilities. Gotta check them all.

#

Is it being frustum culled maybe..? Gotta check thoroughly.

umbral bough
teal viper
#

When render bounds of renderers go outside the camera frustum(outside the camera view), they are culled.

umbral bough
#

ok, that seems like the most likely scenario

#

why doesn't it get refreshed when my object re-enters the view?

teal viper
#

Sometimes render bounds don't actually aligns with visuals which would result in the object being culled. I'm not sure what renderer you use and how it's bounding box is generated though.

#

We do t even know if that's the case at all.

steel herald
#

can someone help me with animations :s please

umbral bough
#

it would prob explain the object not disappearing when it's visible in the scene view :/

#

also, I am using urp

umbral bough
#

and cinemachine if that makes a diff

teal viper
#

Doesn't really matter, but it might explain indeed.

umbral bough
#

I see, friend suggested that I have another camera that's positioned on the ground level at all times, would this even help if the camera output is not visible and how badly would this impact the mobile performance?

teal viper
teal viper
#

What's the point of another camera if nothing is visible in it?

umbral bough
#

well it would be visible but the camera's output wouldn't be rendered

#

that's why I was wondering if it would work in the first place

#

it does indeed become invisible

teal viper
teal viper
umbral bough
teal viper
#

Wat?

umbral bough
umbral bough
# teal viper Wat?

well it becomes invisible because it's getting culled, we were wondering if it being displaying on the other camera(that's not visible on the player's screen) would resolve the issue

#

a really bad solution but just an idea

teal viper
umbral bough
solid verge
#

how to make a text unvisible

umbral bough
solid verge
#

did i say it was invisible?

teal viper
solid verge
#

i was talking about making it visible in a script

#

so that if a player has no grapes

#

grapes are not shown

umbral bough
silent valley
#

Whenever I collide with the Oxygen pickup. I get an error on line 49 which is oxygenController.UncreaseOxygen(increaseamount);

teal viper
silent valley
#

This is my IncreaseOxygen method in my oxygen controller

umbral bough
#

shown in the vid I sent before, can link it again if you'd like

umbral bough
solid verge
#

no

#

i mean't making it visible

teal viper
solid verge
#

cause i want it to be invisible by deafult

umbral bough
rich adder
solid verge
#

cause the player starts with 0 grapes

umbral bough
#

you need a reference to it and then just call the _yourObject.SetActive(true/false);

solid verge
#

but it's a text

#

so it won't work

umbral bough
solid verge
#

well i tried it

#

it doesn't work sadly

umbral bough
#

select it in your scene, does it have a checkmark in the inspector(top left)?

umbral bough
solid verge
#

yes it does

#

no

umbral bough
umbral bough
# solid verge no

ok, would you mind showing me the piece of code you are using to toggle it and show me how you got a reference to your text?

umbral bough
umbral bough
#

are you sure you set everything up properly in the (possibly)prefab's inspector?

silent valley
#

oh my.... Yep. you are right

umbral bough
#

happens

silent valley
#

Rip to me. Thank you. The oxygen has nothing to do with the player. Will fix that now. THANK YOU

#

fixed

#

no joke. 12ish hours spent pulling my hair out. Need myself a Duck to talk to

umbral bough
silent valley
solid verge
umbral bough
solid verge
#

can you tell me how?

rich adder
umbral bough
solid verge
#

ok

umbral bough
#

oh I see

rich adder
#

when using var you would use the <T>

umbral bough
#

you are using the TryGetComponent() not TryGetComponent<>(), my bad

#

I didn't even notice, my bad

rich adder
#

i just feel like its too verbose so I put it in the out param

silent valley
#

I'm not using var now. I just copied it from my healthscript out of frustration

umbral bough
novel shoal
#

i used fixedupdate to make the speed of a ball constant, but now if i want it to bounce it doesn’t

umbral bough
umbral bough
solid verge
#

i found le answer

rich adder
#

no reason to be in fixedupdate

umbral bough
#

he said he wants his ball speed to be constant

rich adder
#

yes I know that

novel shoal
novel shoal
rich adder
umbral bough
#

I am positive that you can remove the * Time.deltaTime and erase the ForceMode2D.Impulse

#

it should do the same thing

#

talking about start

novel shoal
umbral bough
#

and yeah

rich adder
#

dont use AddForce

novel shoal
umbral bough
rich adder
#

chat GPT is a dumb spam bot

novel shoal
#

and isn't time.deltatime use to make the speed not dependent on the fps?

rich adder
umbral bough
umbral bough
#

you would use Impulse if you wanted to add an instant force such as explosion for example

#

if you want to add a continuous force such as gravity then Force is better

novel shoal
#

so if i remove FixedUpdate it should be correct

rich adder
#

I wouldn't use AddForce in pong like game

#

just use .velocity if you want equal speed until increase

novel shoal
#

am i not using it already?

#

addforce is used only at void start

rich adder
#

you still have it for some reason

umbral bough
# novel shoal so if i remove FixedUpdate it should be correct

I usually don't use the FixedUpdate but it's far from wrong.
Unity doesn't update phyisics more often than the FixedUpdate happens so it's technically more performant.
Does it make a difference in a real world scenario?
Unlikely and just complicates the code imho.

novel shoal
#

and what should i place at its place?

rich adder
#

is this what you're trying to make?

novel shoal
#

yup

rich adder
#

yeah so use .velocity its best imo

umbral bough
#

you should prob store the velocity in a global variable(which is what n.n recommended earlier iirc)

rich adder
#

here is how I do it, yours can be diff

private void Awake()
    {
        startPos = transform.position;
        ResetBall();
    }

    public void ResetBall()
    {
        rb.MovePosition(startPos);
        rb.velocity = Vector3.zero;
        transform.Rotate(0, 0, Random.Range(-180f, 180f));
        moveDir = transform.right * moveSpeed;
        rb.velocity = moveDir;
    }```
umbral bough
#

well not the velocity but direction

novel shoal
rich adder
#

why is this here

 void Update()
    {

        rb.velocity = velocity;
    }```
#

also if you wanna keep adding speed you need a multiplier for moveSped

novel shoal
rich adder
#

look at my example from my project

novel shoal
rich adder
#

use Vector3.Reflect

novel shoal
rich adder
#

sure you can use either one

#

all vector3 functions work fine

novel shoal
#

what does the method "reflect" do?

rich adder
#

unity just 0s out the z

rich adder
novel shoal
rich adder
#

in this case it would make sense the normal (face direction) of the collider

#

eg the paddle or wall

novel shoal
rich adder
novel shoal
#

the starting speed?

rich adder
#

yes and if you want to increase speed on hits

#

you just ++ it

#

or += amount

novel shoal
rich adder
#

make sure to normalize the speed reflected first, so you can assign it another new speed

full imp
novel shoal
#

on CollisionEnter(collider other)
if (other.CompareTag("player")
movespeed++

rich adder
#

yeah but you still need to reflect

novel shoal
rich adder
#

inside that

novel shoal
rich adder
novel shoal
#

oh i thought i needed to add the script to the objects, not to the ball, my bad

rich adder
#

since it keeps track of its own direction

novel shoal
rich adder
#

my goal trigger detects if ball entered trigger

novel shoal
rich adder
#

it calls ResetBall

rich adder
novel shoal
#

okk

#

i found this

#

but what's the red arrow?

rich adder
#

its the normal

novel shoal
rich adder
rich adder
#

to where exactly the ball hit

solemn fractal
#

Hey guys, If I am using other.CompareTag() to see if something hit the enemy in OnTriggerEnter2D on my Bullet script. I want to make that when the player gets a special hability now his bullet will hit one enemy and bounce to the enemy closer to that enemy. But all enemies use the same tag. Is that achievable? Would I just need to get the distance from the enemy hit to the closer one and redirect the bullet there?

steel forge
#

I have two scripts, on that brings the player back to the beginning if he runs into a spike and one that makes him move. My problem is, that while the player is moving, he can't die, because the movement is occupied by the movement script. Can i somehow disable a script temporarily or make like a global boolean that gets set to true when he should be dead?

wintry quarry
wintry quarry
solemn fractal
wintry quarry
#

You can also have the movement script check something like if (isAlive) Move();

wintry quarry
steel forge
novel shoal
#

void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("player"))
velocity += Vector2.one;
Vector2.Reflect(rb.velocity, Collision2D.GetContact());
}
which is the argument of collision2D.GetContact()?

rich adder
#

so how do we get 1 item out of an array?

novel shoal
rich adder
#

yes

#

GetContact returns items from an array, you need index.
well its a custom struct but thats out of the scope

novel shoal
#

why is it an array?

rich adder
#

because you can collide with multiple points

#

on collision

novel shoal
#

oh ok

rich adder
#

but you're reflecting it right away

#

so you only need the first

dry tendon
#

hey, does someone knows why my mobilephone starts to get slow with this simple scene without code or anything else appart from the buildings and the fog?

gaunt ice
#

actually, for nearest neighbor search overlapXX may fail, the only way is to loop through all colliders or considering using space partitioning to speed up

rich adder
#

also not really code question

wintry quarry
dry tendon
# rich adder Profile it

Whats that? I have to say that there are no shadows, so it is no really calculating nothing...

dry tendon
rich adder
#

not maybe though

#

its accurate

dry tendon
#

it's for android too?

rich adder
#

Ideally you would pool those spawned sections and recycle them as you pass

dry tendon
rich adder
#

you should still profile it and see whats using most resources

dry tendon
#

But thanks for the advice

steel forge
#

How do I reference the Script of a parent? The only thing I found is from 2019 and it didn't work and just referencing the component per public Component Moving; didn't work either.

novel shoal
#

void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("player"))
rb.velocity += Vector2.one;

    rb.velocity=Vector2.Reflect(rb.velocity, other.transform.position - transform.position);
}

what's the issue with this now

#

😭

rich adder
# novel shoal void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("play...

dang.. I gotta run for a bit so Ill just spoon feed you my Collision real quick, ill be back in a few to explain it

private void OnCollisionEnter(Collision collision)
    {
        var newDir = Vector3.Reflect(moveDir, collision.GetContact(0).normal).normalized;
        moveDir = newDir;
        if(collision.collider.TryGetComponent(out PaddleMove _))
        {
            moveSpeed++;
        }
        moveDir *= moveSpeed;
        rb.velocity = moveDir;
    }```
gaunt ice
#

other.tf.position-tf.position is not the normal of the surface

rich adder
ornate swift
#

Okay so I have made a walk script but my character suddenly goes on his side when I start walking

ornate swift
wintry quarry
ornate swift
#

and this is after

nimble apex
ornate swift
#

I'll send a video

rich adder
#

thats only if 1 script on the parent ofc

#

or it grabs the first one 😛

gaunt ice
#

why not just assign it manually

rich adder
#

[SerializeField] private MyClass ayo;

ornate swift
nimble apex
#

to prevent not assigning error lol

rich adder
#

thats a good error tho

#

so you know you've assigned it

steel forge
#
 private void OnTriggerEnter(Collider other)
    {
        Debug.Log("Stufe 1");
        if (other.gameObject.CompareTag("Death"))
        {
            Debug.Log("Stufe 2");
            
            gameObject.transform.parent.GetComponent<movement>().enabled = false;
            
            gameObject.transform.parent.position = Startposition;
            
            gameObject.transform.parent.GetComponent<movement>().enabled = true;
            
        }
    }```
Why doesn't this move my character to the defined "Startposition"?
wintry quarry
ornate swift
wintry quarry
#

Again, show what you tried

#

As far as I can tell, you have not constrained your object's rotation in the Rigidbody inspector

ornate swift
#

Thats what I tried

wintry quarry
#

you are messing with quaternion x and y components 😱

#

you should NEVER be doing that

gaunt ice
wintry quarry
#

That's also a problem ^

wintry quarry
eternal falconBOT
wintry quarry
# ornate swift this is the script

what you need to do is:

moveDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up).normalized;
``` _before_ you feed it into the MoveCharacter and RotateCharacter functions
#

you also need to delete the lines:
targetRotation.x = 0; and the z one, they are completely incorrect.

#

then it will work well

#

(although you should also check that moveDirection != Vector3.zero before calling RotateCharacter)

steel forge
nimble apex
#

u dont paste stuff directly

#

that is just a draft

eager elm
#

you need to remove the '<>' from the first ClassName, but not the second

wintry quarry
#

You wouldn't use Component though, you'd use the specific type you want

nimble apex
#

for example, if the script name is RandomScript

private RandomScript randomScript;

void Awake(){
      randomScript = GetComponentInParent<RandomScript>();
}```
nimble apex
#

a script may contain multiple classes

#

ur not referring to the script file

#

but the class inside

steel forge
wintry quarry
#

You're actually referring to a specific instance of the class

#

A "class" in C# is like a blueprint for objects. There can and usually are many objects of a given class in existence at runtime or edit time

ornate swift
ornate swift
dry tendon
#

@rich adder, i ran the profiler and i get this... but i don't know how could this optimyze my code... Could you guide me a bit?

amber nimbus
#

Hello, I have this code for rotating a tank turret towards where the player is looking. This works great as long as the root of the turret is on flat ground. However if the tank tilts the rotation is not linear anymore and it slows down before reaching the target rotation. I cant figure out how to fix this at all :/

swift crag
#

that'll be because it's trying to rotate directly towards the player

#

but you're ignoring the X and Z euler angles

rich adder
swift crag
#

i would suggest not messing with euler angles at all here

#

instead, you should project the player's position into the XZ plane of the turret, so that you aren't trying to look up or down at all

rich adder
swift crag
#
Vector3 targetPos = target.position;
targetPos = Vector3.ProjectOnPlane(targetPos, transform.up);
umbral bough
#

Hi, I have an object that disappears when the player's view goes out of range.
The issue is that it doesn't reappear on time when the player reaches it and the players goes through it instead of colliding with it.
I can't figure out how to disable frustum culling for that object, please help.
This is one thing that I found on it but it doesn't seem to work:
_rend.allowOcclusionWhenDynamic = false;

swift crag
#

If the turret is on level ground, this will throw out the Y component

swift crag
#

That will give you a look rotation that just spins around your Y Axis, without tilting up or down

#

then you can simply rotate towards it

ornate swift
# wintry quarry what you need to do is: ```cs moveDirection = Vector3.ProjectOnPlane(moveDirecti...

I did that but it still doesn't work, do you know what is wrong with this script?

!code using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f; // Adjust this value to control the movement speed
private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void Update()
{
    // Get the input for movement
    float horizontalInput = Input.GetAxis("Horizontal");
    float verticalInput = Input.GetAxis("Vertical");

    
    // Calculate the movement direction based on the camera's forward and right vectors
    Vector3 moveDirection = (Camera.main.transform.forward * verticalInput + Camera.main.transform.right * horizontalInput).normalized;

    // Apply movement to the character
    MoveCharacter(moveDirection);
    // Rotate the character to face the movement direction without tilting
    RotateCharacter(moveDirection);
    moveDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up).normalized;
}

void MoveCharacter(Vector3 moveDirection)
{
    moveDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up).normalized;
    // Apply the movement to the rigidbody
    rb.velocity = new Vector3(moveDirection.x * moveSpeed, rb.velocity.y, moveDirection.z * moveSpeed);
}

void RotateCharacter(Vector3 moveDirection)
{
    moveDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up).normalized;
    // Rotate the character to face the movement direction without tilting
    if (moveDirection != Vector3.zero)
    {
        // Calculate the target rotation only around the Y-axis
        Quaternion targetRotation = Quaternion.LookRotation(moveDirection, Vector3.up);


        // Smoothly rotate the character towards the target rotation
        transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * 1000f);
    }
}

}

eternal falconBOT
steel forge
#
private void OnTriggerEnter(Collider other)
    {
        Debug.Log("HI");
        if (other.gameObject.CompareTag("Player"))
        {
            Player.transform.SetParent(other);
        }
    }```
This should reference the thing I collide with and then set as "Players" Parent, but I get an error that ```Argument 1: cannot convert from 'UnityEngine.Collider' to 'UnityEngine.Transform'```. I just want the Player to tick  a moving Platform...
How can i best achieve that?
novel shoal
forest locust
#

im having an issue with an on click. Im following a tutorial and havent missed a step. void Restart()
I set up the restart but the function WONT ACKNOWLEDGE RESTART. Its supposed to say Restart() under cancelinvoke()

swift crag
# amber nimbus Thanks I will try this
Vector3 lookDir = target.position - transform.position;
lookDir = Vector3.ProjectOnPlane(lookDir, transform.up);
Quaternion goalRot = Quaternion.LookRotation(lookDir, transform.up);
rich adder
swift crag
#

I'm not confident on this yet, though. I'd need to go implement it to make sure I'm doing this right.

#

actually, i'm gonna go do that now :p

rich adder
#

why are your walls / paddle triggers 🤔 @novel shoal

novel shoal
amber nimbus
swift crag
amber nimbus
#

oh ok

swift crag
#

transform.root would be whatever transform is your greatest grandparent

forest locust
rich adder
swift crag
#

oh hey, nice: 2022.3.13f1 has an up-to-date Visual Studio Editor package

eager elm
novel shoal
#

maybe i should watch more tutorials

safe root
#

I'm trying to get my script to read the path points I have layed out but I keep getting this error and I don't know why

rich adder
novel shoal
safe root
polar acorn
ornate swift
novel shoal
#

with collisionenter it says i cannot use comparetag

rich adder
polar acorn
safe root
gaunt ice
#

assign the Grid to a class field instead of find it in run-time

polar acorn
safe root
gaunt ice
#

you can simply solve it by this

polar acorn
novel shoal
#

{
if (gameObject.CompareTag("player"))
rb.velocity += Vector2.one;

rb.velocity = Vector2.Reflect(rb.velocity, collision.GetContact(0).normal);

}
is this right @rich adder

wintry quarry
eternal falconBOT
rich adder
#

also tag check is wrong..

#

Collision2D parameter holds the object you hit..

safe root
ornate swift
novel shoal
#

you are making that not rb.velocity, but the direction

polar acorn
summer stump
polar acorn
#

You said there's an object of type Grid in the scene. Log it

#

See what object it is

rich adder
summer stump
summer stump
#

collision.gameObject.CompareTag
Or
collision.collider.CompareTag

You need to go through the collision struct

safe root
polar acorn
safe root
novel shoal
polar acorn
summer stump
safe root
novel shoal
summer stump
novel shoal
#

yoo @summer stump ;))

polar acorn
rich adder
#

Vector2

amber nimbus
swift crag
#

oh, nice; I was just fighting with getting the gun to elevate properly as well :p

#

getting the turret to rotate worked on the first try

polar acorn
safe root
polar acorn
safe root
nimble apex
#

gameObject.<component>

#

transform is made intrinsic with gameobject because its used very frequently

swift crag
#

yes, any property of a GameObject can be used, by definition

#

i'm not sure what you're saying here

polar acorn
novel shoal
#

{
if (collision.gameObject.CompareTag("Player"))
rb.velocity += Vector2.one;

    var newDir = Vector2.Reflect(rb.velocity, collision.GetContact(0).normal);
    newDir = moveDir;  
}

?

safe root
polar acorn
eternal falconBOT
swift crag
#

Raising the gun is a little more complicated.

novel shoal
swift crag
#

In short, it finds the direction to the target, then rotates it so that it's facing forwards. Then it rotates towards that.

rich adder
#

so you should normalize new dir

candid oyster
#

Is visual studio the superior IDE?
I have gotten a JetBrains License

novel shoal
rich adder
rich adder
novel shoal
#

i guess i'll just watch a big physics tutorial in unity since i am not understanding so much

rich adder
novel shoal
#

it's kind of difficult for me to implement what i know about physics in unity with such a small knowledge

novel shoal
#

or, maybe i did it but it had a different name (i am italian)

rich adder
candid oyster
#

to jetbrains?

rich adder
sharp wyvern
#

a normal vector is a vector with magnitude 1.0- also called a DIRECTION vector. What great about normal vectors is: if you multiply them a by a single float sa X.. you know the length of your final vector will also be X.

rich adder
#

use whichever one, they both do the same

candid oyster
#

I wouldnt call it a life decision

rich adder
#

its preference mainly

#

which is subjective

swift crag
#

Perhaps you're thinking of how you "normalize" a vector

#

The names are confusing, yes.

candid oyster
sharp wyvern
#

no, I'm tyhinking of a normal vector

swift crag
#

A normal vector is a vector that points straight out of a surface.

#

It's the direction the surface faces.

novel shoal
sharp wyvern
swift crag
swift crag
#

A vector with a length of one is a unit vector.

polar acorn
rich adder
#

imagine those squares are bendy walls @novel shoal the blue arrow is which way "they're facing"

#

which is the normal

novel shoal
#

ok

swift crag
#

When you bounce something off a surface, you reflect its velocity using the normal vector.

novel shoal
#

and what does "normalizing" mean?

swift crag
#

That is a separate concept.

rich adder
swift crag
#

To normalize a vector is to make its length exactly 1.

novel shoal
#

okk

swift crag
#

"normalization" more generally means to make something consistent or uniform

swift crag
#
Vector3 dir = rigidbody.transform.position - transform.position;
rigidbody.AddForce(dir, ForceMode.Impulse);

The further away I am from the target, the harder I shove it.

spare umbra
#

Where is game's screen resulation (1920x1080) data stored in a Unity exe build folder?

novel shoal
#

so i should just make newDir.normalize=moveDir

swift crag
#
Vector3 dir = rigidbody.transform.position - transform.position;
dir = dir.normalized;
rigidbody.AddForce(dir, ForceMode.Impulse);

Now, no matter how far the target is, it gets shoved by a consistent amount.

rich adder
#

or you can normalize the result of the whole Reflect which is what I did

swift crag
#

Normalize a vector if all you care about is the direction

#

rather than both the direction and length

#

and if all you care about is the length, get the vector's .magnitude !

swift crag
#
vec = vec.normalized * vec.magnitude;

This code does nothing

#

(plus or minus floating point errors)

chilly vigil
novel shoal
#

my ball is still not bouncing, i am giving up, sorry for bothering you

rich adder
novel shoal
#

i tried my best but most likely this is just out of my range

#

i'll watch more tutorials before trying something made by me

swift crag
#

is there a reason you're reflecting the ball in the collision method?

#

the ball is already gonna bounce

novel shoal
swift crag
#

or is it not bouncing the way you want it to?

rich adder
#

you never applied the new direction

novel shoal
rich adder
#

@novel shoal

swift crag
#

yes, you've calculated a new direction, then thrown it out

verbal dome
rich adder
#

look at my code again cs private void OnCollisionEnter(Collision collision) { var newDir = Vector3.Reflect(moveDir, collision.GetContact(0).normal).normalized; moveDir = newDir; if(collision.collider.TryGetComponent(out PaddleMove _)) { moveSpeed++; } moveDir *= moveSpeed; rb.velocity = moveDir; } @novel shoal

swift crag
#

you've also overwritten newDir with moveDir

novel shoal
swift crag
#

this will reset the velocity to exactly 1

#

because you're normalizing newDir before assigning it to rb.velocity

#

remember: you normalize a vector if you don't care about its length

rich adder
#

yes, you're still missing a velocity you can increase

swift crag
#

you definitely care about this vector's length!

#

also, this is not correct

#
rb.velocity += Vector2.one;
#

This will add 1 to the X and Y velocities

rich adder
#

^^ which is why I suggested a speed variable instead if you want speed increase

novel shoal
rich adder
#

that vector.one thing is useless

swift crag
#

possibly slowing the ball down

#

I think you want it to increase its speed

#

if the ball is moving down and left, you will slow it down by increasing its X and Y velocity by 1 each

novel shoal
#

oh right

#

i didn't think about it

#

sorry

rich adder
#

you see why I used a variable for speed 😏 @novel shoal
moveDir *= moveSpeed;

swift crag
#

we normalize the direction, then multiply it by the move speed

novel shoal
swift crag
#

Since normalizing a vector makes its length exactly 1, multiplying that vector by moveSpeed gives you a vector whose length is moveSpeed

rich adder
swift crag
#

so now the ball will have a speed of exactly moveSpeed

novel shoal
#

i have never used *= in python so i didn't know what was that

rich adder
novel shoal
#

i didn't want to annoy you

rich adder
#

its fine, thats what this channel is for

#

not a unity specific thing per-se but yeah this is a simple math operator for multiply

#

but we short it when we dont want to repeat ourselves

#

so
myValue = myValue + 4;
same as
myValue += 4;

swift crag
novel shoal
rich adder
#

Ahh gotcha well yeah its the same

novel shoal
#

so i have to normalize the vector after using it with the velocity?

rich adder
swift crag
novel shoal
rich adder
#

no

#

normalize first

#

then apply speed

novel shoal
#

ok

#

fixed

swift crag
#

if you normalize afterwards, you're completely throwing out the speed

#

roughly the same as doing

x = 3;
x *= 4;
x = 1;
rich adder
#

also you have to pass moveDir back @novel shoal

#

not newDir

swift crag
#

is there a reason to even store moveDir?

rich adder
#

in my code I use it for other stuff but no they dont have to 😛

#

(in mycode is a backing field for public MoveDir get)

novel shoal
#

i have a question

#

@rich adder

#

what does the keyword "var" means? is it a short of "variable"? but in c# i have to declare the type of a variable before doing anything with it

rich adder
#

if you did
var myValue = 0 the compiler think its a int

#

if you did var myValue = 0f now its a float

wintry quarry
novel shoal
rich adder
rich adder
#

c# is not dynamically typed like js or maybe Py? i dont use py sorry

wintry quarry
#

it's just a shortcut for the type of whatever is on the right side of the = sign

novel shoal
#

so basically i can just type "moveDir" instead of "newDir" when i am storing it?

rich adder
#

you can just assign the newDir to rb.velocity

novel shoal
dense root
#

My goodness chatGPT is useful as a beginner for niche problems

novel shoal
#

is this fine?

rich adder
#

no

#

rb.velocity += Vector2.one; is stil wrong

novel shoal
rich adder
# novel shoal oh i forgot to fix it
 if (collision.gameObject.CompareTag("Player"))
        {
            speed++;
        }

        var newDir = Vector2.Reflect(rb.velocity, collision.GetContact(0).normal);
        newDir.Normalize();
        newDir *= speed;
        rb.velocity = newDir;```
novel shoal
#

noooo

#

im still wrong

#

hold on

rich adder
#

😂

novel shoal
#

now it should be correct (i hope so)

#

now i got it

#

if i increase the value that i use to multiply the direction, the direction will increase

novel shoal
# rich adder wdym

the newdir vector is increased every time it its something by the speed variable, which is always itself, except if it its an object whose tag is specified, because if it hits that object, the speed will increase
if it hits a barrier; 120
if it hits an object;1
21

#

1*20

#

1*21

#

it made the text in italics due to the *

polar acorn
eternal falconBOT
halcyon osprey
#

I'm following a simple top down rpg movement tutorial, and I'm trying to make sure I understand how everything is working so I can actually learn from the code. In the point of making a variable to define the move speed, the programmer gave it a value of 5f, I don't understand what the "f" stands for, if anything, as it doesn't give me any errors without it either.

swift crag
#

It’s important if you want a decimal value

#

1.5 is a double, not a float

#

It’s a more precise type and it won’t automatically convert to float

#

1.5f is a flost

#

5 is an int. That can automatically convert to float

#

Hence why you didn’t need it

#

I sometimes add the f anyway

novel shoal
wintry quarry
# halcyon osprey I'm following a simple top down rpg movement tutorial, and I'm trying to make su...

To learn more about literal values in C#: https://www.tutorialspoint.com/csharp/csharp_constants.htm

halcyon osprey
#

Oh that makes more sense, thanks

novel shoal
summer stump
novel shoal
#

i have just tried

#

and it still doesnt bounce

swift crag
#

Have you checked if your code is even running?

novel shoal
swift crag
#

That’s not what I’m asking

#

Add a Debug.Log statement to the method and see if anything appears in the console

novel shoal
#

ok

#

yea it's running

summer stump
novel shoal
summer stump
novel shoal
#

but it should bounce anyway

summer stump
novel shoal
#

lol i should have started to study 2 hours ago

#

what's the issue with my code then?

#

idk how to solve it

rich adder
#

can you send current code again

novel shoal
#

it shouldn't tho

#

cuz if it touches the paddle, it goes on until it touches the barrier

rich adder
novel shoal
#

idk how to make videos on pc

#

can i make it with my phone?

rich adder
novel shoal
#

i completely forgot about it

#

i haven't been using it since some yt videos

#

literally 2 years ago

rich adder
merry spade
#

If I do StopAllCoroutines();

public IEnumerator TimerStart()
    {
        currTime = 1;
        reviveTimer.fillAmount = currTime;
        while (true)
        {
            currTime -= Time.deltaTime * 0.1f;
            reviveTimer.fillAmount = currTime;
            if (currTime <= 0f)
            {
                cancelButton.onClick.Invoke();
                print("Invoke");
                break;
            }
            yield return null;
        }
    }

my cancelButton gets invoked... why?

wintry quarry
rich adder
wintry quarry
#

possibly you are not calling StopAllCoroutines on the correct object

merry spade
#

this is the whole code:

public class DeadTimerUIScript : MonoBehaviour
{
    [SerializeField] private Image reviveTimer;
    [SerializeField] private Button cancelButton;
    private float currTime;

    public IEnumerator TimerStart()
    {
        currTime = 1;
        reviveTimer.fillAmount = currTime;
        while (true)
        {
            currTime -= Time.deltaTime * 0.1f;
            reviveTimer.fillAmount = currTime;
            if (currTime <= 0f)
            {
                cancelButton.onClick.Invoke();
                print("Invoke");
                break;
            }
            yield return null;
        }
    }
    public void TimerStop() 
    {
        currTime = 0;
        StopAllCoroutines();
    }

}
#

and if I call TimerStop() it doesnt work

wintry quarry
rich adder
#

yeah you start it from somewhere else

swift crag
#

I bet you start the coroutine on another object.

wintry quarry
#

Seems like not in this object

merry spade
#

from another script

rich adder
#

it belongs to that other object

merry spade
#

oh

#

ok

swift crag
#

Each MonoBehaviour has a list of coroutines it's running

wintry quarry
rich adder
#

otherScript. StopAllCoroutines();

wintry quarry
#

pay close attention

swift crag
#

when you call StartCoroutine, you throw the IEnumerator into the list

novel shoal
rich adder
swift crag
#

(this should be in the Video or Output sections of the settings)

#

i forget which

rich adder
#

its better to make a method in this class to StartCoroutine

#

instead of calling StartCoroutine from another class for this very reason tbh

merry spade
#

so I should do

        deadTimerUIScript.StopAllCoroutines();

in the object's script i started it?

novel shoal
swift crag
#

when you call StopAllCoroutines, you're telling the MonoBehaviour to throw out its list of coroutines.

#

it doesn't matter where you call it from

#

I'm guessing you have another class that looks like this

merry spade
#

what do i have to do then to stop the timer and not getting the cancel invoked

novel shoal
#

this is the rigidbody

swift crag
#
public void DoSomething() {
  StartCoroutine(timerUI.TimerStart());
}
rich adder
swift crag
rich adder
#

call TimeStart instead

#

this way it belongs to this script

swift crag
#

So yes -- do what navarone suggested

#

now the coroutine will be running on the DeadTimerUIScript object

#

and calling StopAllCoroutines on that object will stop it

merry spade
#

ah

#

ok

#

thank you

rich adder
merry spade
#

its still getting invoked

swift crag
#

then show your code

merry spade
#

ah

#

nvm

swift crag
#

I can't guess what you wrote

merry spade
#

because i set currTime to 0

#

let me check it

#

yeah it works now, thank you to y'all

swift crag
#

ah, good

quick ruin
#

the current transform moves towards and past the target how do I stop it at the target Point

rich adder
wintry quarry
swift crag
#

If it only moves a little too far, then yeah, your pivot is off

wintry quarry
#

so some other code would be responsible - or yes your object pivot is not correct

novel shoal
merry spade
# swift crag ah, good

No it doesnt work, it doesnt get invoked instantly right now but after the time expires

#
public class DeadTimerUIScript : MonoBehaviour
{
    [SerializeField] private Image reviveTimer;
    [SerializeField] private Button cancelButton;
    private float currTime;

    public IEnumerator Timer()
    {
        currTime = 1;
        reviveTimer.fillAmount = currTime;
        while (true)
        {
            currTime -= Time.deltaTime * 0.1f;
            reviveTimer.fillAmount = currTime;
            if (currTime <= 0f)
            {
                cancelButton.onClick.Invoke();
                print("Invoke");
                break;
            }
            yield return null;
        }
    }

    public void TimerStart()
    {
        StartCoroutine(Timer());
    }

    public void TimerStop() 
    {
        StopCoroutine(Timer());
    }

}
novel shoal
# novel shoal

it kinda bounced on the paddle, but not on the barrier

swift crag
#

That is incorrect.

wintry quarry
swift crag
#

you're telling it to stop the return value of Timer()

#

If you had previous passed that exact value to StartCoroutine, it would indeed stop the coroutine

rich adder
swift crag
#
var enumerator = Timer();
StartCoroutine(enumerator);
StopCoroutine(enumerator);
rich adder
#

also is the Rotation on rigidbody locked by any chance ? @novel shoal

swift crag
#

But this is just starting one coroutine and then stopping another one that hasn't even started yet

#
StartCoroutine(Timer());
StopCoroutine(Timer());
rich adder
swift crag
#

If you want to stop that specific coroutine, save the IEnumerator that Timer() returns into a field, then pass it to StopCoroutine later

#

or you can just keep using StopAllCoroutines()

rich adder
#

You can also store it in a Coroutine

novel shoal
swift crag
novel shoal
#

still not bouncing

merry spade
#

yeah got it now thank you!

timber tide
#

You should get the coroutine ref when you create one so you can store that specific instance

novel shoal
#

@rich adder what?

rich adder
swift crag
#

I am wondering if we're fighting the physics system here

novel shoal
swift crag
#

Notice how OnCollisionEnter2D executes after the physics system is done updating

rich adder
#

but in 3D

#

Im wondering if maybe the in direction might need to be normalized

swift crag
#

hm, even if the collision is really wasteful and loses most of the velocity, the tiny bit that's left should still be enough to make your code work

novel shoal
rich adder
novel shoal
#

gizmos?

rich adder
#

I think something might be wrong with the returned normal

rich adder
# novel shoal gizmos?

haha yeah thats why I try to extract things like direction into variable so i can use it to debug with gizmos (lines/arrows)

swift crag
#

well, to clarify

#

you're probably about to use Debug.DrawLine

#

I guess that is technically a kind of gizmo?

#

I think of all the stuff in the Gizmos class when you say "gizmo", but that's fair

rich adder
#

yeah i barely use Debug class

#

for that

#

I use Gizmos.

swift crag
#

I use Debug.DrawLine a ton

#

super useful

#

it lets you draw a line in the scene view (and the game view, if you turn on gizmos there)

novel shoal
#

what the hell are gizmos?

swift crag
#

I was using it while figuring out that tank turret earlier

#

that's a gizmo!

rich adder
#

particularly invisible to human eye stuff

swift crag
#

actually, is that a gizmo

novel shoal
#

okk

swift crag
rich adder
novel shoal
#

so i need to use gizmo.drawline?

rich adder
swift crag
#

The collider visualizer is definitely a gizmo (:

swift crag
#

oh, I see: there is also Gizmos.DrawLine/Gizmos.DrawRay

merry spade
#

can one object have two tags?

swift crag
#

The downside of that is that you have to do it in a specific gizmo-drawing method

rich adder
#

no

rich adder
swift crag
#

Debug.DrawLine and Debug.DrawRay can be used anywhere.

swift crag
merry spade
swift crag
rich adder
novel shoal
rich adder
swift crag
#

Debug.DrawLine takes two positions and draws a line between them

#

i think navarone is suggesting identifying objects based on the components they have

#

instead of using a tag

#

so you'll look for a Door component instead of checking if the object has a tag named "Door"

rich adder
#

yes Im bad at explain sorry

swift crag
#

So suppose an object can both be damaged and collected

merry spade
novel shoal
#

is there a method to check wheter an object has a said component?

swift crag
rich adder
swift crag
#

you can decide if something can be damaged by testing if it has a Damageable component

#

if it does, you can damage it. if it doesn't, you can't.

merry spade
#

i got the plane and the obstacles as temporary objects, but the obstacles should be deleted with overlapsphere on revive but the plane should stay so i got all the objects from overlap sphere and now i want the temporary obstacles to be deleted but not the plane

wintry quarry
merry spade
swift crag
#

explain what happens in your game

#

no technical details; just tell me what the player sees

merry spade
#

ok the player dies-> all obstacles in the area gets deleted so he can drive by

#

but not the ground

novel shoal
#

using UnityEngine;

public class TryGetComponentExample : MonoBehaviour
{
void Start()
{
if (TryGetComponent<HingeJoint>(out HingeJoint hinge))
{
hinge.useSpring = false;
}
}
}
what's <HingeJoint>(out HingeJoint hinge)?

wintry quarry
#

<HingeJoint> is actually unecessary

wintry quarry
#

but it's the generic type parameter

rich adder
#

but yeah what praetor said

wintry quarry
#

HingeJoint is just the type of the component you want to check for. They are using HingeJoint as an example

swift crag
#

this is using something called an out parameter.

#

It allows the method to assign one of your variables.

novel shoal
#

and (out hinge)?

wintry quarry
#

You can just write if (TryGetComponent(out HingeJoint hinge))

swift crag
#

So you actually hand that variable over and say "here, put something it"

#

If you already have a variable named hinge, you'd just write this

wintry quarry
# novel shoal and (out hinge)?

() is where method parameters go.
There is one parameter and it's out hinge
out just means it's an out parameter. An out parameter comes out of the call, sort of like an extra return value

swift crag
#
TryGetComponent(out hinge);
#

You can also declare the variable at the same time that you call the method.

#

This is for convenience.

swift crag
#
TryGetComponent(out HingeJoint hinge);
#

This is identical to...

wintry quarry
swift crag
#
HingeJoint hinge;
TryGetComponent(out hinge);
swift crag
#

the method needs to give you two things:

  • whether or not it worked
  • the result
nimble apex
#

hingejoint is a component in 2D games

swift crag
#

so it winds up using an out parameter for the latter

swift crag
#

You could also just give every obstacle an Obstacle component.

merry spade
#

yeah i used it and it works, thank you!

swift crag
#

and then only destroy things that have an Obstacle on them

rich adder
rich adder
#

sweet

#

Now I remember why I made an external Var

merry spade
#

you can make own components?

swift crag
rich adder
#

and yes its to do with the physics and .velocity like Fen said i think

swift crag
slender nymph
swift crag
#

note that every thing that derives from MonoBehaviour is defining a component

rich adder
#

change
newDir = Vector2.Reflect(rb.velocity, collision.GetContact(0).normal);
to
newDir = Vector2.Reflect(newDir, collision.GetContact(0).normal);
@novel shoal

swift crag
#

MonoBehaviour is a specific kind of component

novel shoal
#

if (TryGetComponent(out Bar1) || TryGetComponent(out Bar2))
force++;
it says this is an error

swift crag
slender nymph
swift crag
#
public class Foo : MonoBehaviour { }

This defines a class named Foo. Foo derives from MonoBehaviour.

novel shoal
#

what's the difference?

swift crag
novel shoal
merry spade
#

yeah i mean those monobehaviour things and other stuff is my futures problem but i wont learn it today it seems very complex im happy with the skills of monobehaviour xD

rich adder
cosmic dagger
#

I agree; a script (file) is more a Unity term . . .

rich adder
#

so you're essentially reflecting the rb.velocity that collided with the wall

#

@novel shoal

swift crag
#

I use the term "script" to refer to a script asset

grizzled stirrup
#

is there a way i can get the value of the cube when it touches the red part? i already have it destroy itself but i cant figure out how to get the red part to get the value of the cube

slender nymph
rich adder
#

now I remember why I also stored velocity in a seperate value this way it isn't affected by the collision @novel shoal

grizzled stirrup
#

hold up let me get the script

novel shoal
merry spade
rich adder
#

which is stored in newDir

#

before changing it

novel shoal
#

oh ok that kinda makes sense

grizzled stirrup
# swift crag the...value?

this is the script for the cube and i cant figure out how to have the thing under it to get this value of this specific instance of the cube

rich adder
swift crag
#

so yeah

merry spade
#

but its hard to understand everything when youre self teaching because you cant learn new ways of doing things

novel shoal
#

so we are trying to reflect a speed that has just been negated because it collided with the collider?

cosmic dagger
rich adder
swift crag
novel shoal
grizzled stirrup
#

ohhhh

rich adder
swift crag
#

Anyway, you need to:

  • Detect that the red area has hit the cube
  • Get the BasicOreScript object from the object you hit
  • Get the value from the BasicOreScript object
rich adder
#

if we reflect the lost momentum we just flop down as you saw

cosmic dagger
rich adder
#

also please do use brackets. even for one liners

grizzled stirrup
novel shoal
swift crag
swift crag
#

Ah, good

rich adder
swift crag
#

GameObject does not have a field called _worth

#

It will never have such a field

rich adder
#

right now youre trying to pass a blueprint @novel shoal which is a class

grizzled stirrup
#

so i have to get the script from the gameObject?

novel shoal
novel shoal
rich adder
#

and use the variable

swift crag
#

(this should go into a thread too, btw)

rich adder
#

yeah we are flooding chat make a thread @novel shoal

solemn fractal
#

hey guys was able to destroy all enemies inside a list i have.. when i spawn them with instantiate I put them on a list and delete all .. it was working now I have this message here, and cant figure it out what could it be as I didnt change anything in the logic

#
    void DestroyAllEnemies(){

        foreach (Enemy enemy in _enemyList)
        {
            Destroy(enemy.gameObject);
        }
        foreach (BossOne bossOne in _BossOneList)
        {
            Destroy(bossOne.gameObject);
        }
        _BossOneList.Clear();
        _enemyList.Clear();
    }```
polar acorn
#

Something is likely still referencing something in one of those lists

solemn fractal
#

I add to the list the ones that spawn, and I kil them and destroy, and after a whiule I want to delete all in the scene.. but I think it is trying to destroy also the ones I already killed

polar acorn
solemn fractal
#

yeah, but how do I know which one is the one I killed to remove from the list?

rich adder
solemn fractal
rich adder
solemn fractal
#

example, I am adding like that:

#
     private IEnumerator SpawnPoison(float waitTime){
        
        while (true){

            float randomPositionX = Random.Range(-40, 41);
            float randomPositionY = Random.Range(-23, 24);
            float playerX = _player.transform.position.x;
            float playerY = _player.transform.position.y;

            Enemy poisonPos1 = Instantiate(_enemyPrefab, new Vector3((randomPositionX + playerX), (playerY + 41), 0), Quaternion.identity);
            Enemy poisonPos2 = Instantiate(_enemyPrefab, new Vector3((randomPositionX + playerX), (playerY + -41), 0), Quaternion.identity);
            poisonPos1.data = enemyTypeList[3];
            poisonPos2.data = enemyTypeList[3];
            _enemyList.Add(poisonPos1);
            _enemyList.Add(poisonPos2);

            Enemy poisonPos3 = Instantiate(_enemyPrefab, new Vector3((playerX + 56), (playerY + randomPositionY), 0), Quaternion.identity);
            Enemy poisonPos4 = Instantiate(_enemyPrefab, new Vector3((playerX + -56), (playerY + randomPositionY), 0), Quaternion.identity);
            poisonPos3.data = enemyTypeList[3];
            poisonPos4.data = enemyTypeList[3];
            _enemyList.Add(poisonPos3);
            _enemyList.Add(poisonPos4);    
            yield return new WaitForSeconds(waitTime);
        }
    }```
rich adder
#

ease of access

#

or just pass the script that has this list onto the object when you spawn it
like
poisonPos3.spawner = this

#

or something

solemn fractal
#

hmm ok, I will try something. thank you !

rich adder
solemn fractal
#

ok, thank you a lot it will take some time for me to achieve but as always I will get there.. thank you !

quick ruin
#

this is setting the Z position to -10, is there an ez fix?

#

im in 2D

polar acorn
#

That is because that's likely where your camera is, so that is the position of the mouse cursor in world coordinates. If you want the Z value to be different, change it afterwards

ornate swift
#

why don't I have an option to make a volume game object?

rich adder
#

as in Post Processing Volume?

#

if so do you have a render pipeline that supports it ?

ornate swift
#

In the tutorial I am watching they have volume objects

rich adder
#

bastards stole my voice actor from another vid

rich adder
ornate swift
#

I don't know

#

I'm in the normal 3d project

rich adder
#

well then its wrong

#

the video says HDRP

#

so you need HDRP

#

URP and HDRP have built in Post Processing + Volume

#

Built-In "Normal" one doesn't

#

make a new project and select HDRP

ornate swift
#

can I make my existing project hdrp?

rich adder
#

yeah but it takes a bit to configure it

#

also any material you have now has to be converted using the converter or they will be pink

rich adder
#

if you dont have much done inside this project, I suggest you just start from template preconfigured for you

ornate swift
#

thanks!

tepid stratus
#

I'm having an issue with a collider, can I talk with someone in DM's about it?

#

I hope I posted this in the right channel, sorry if I didn't

tepid stratus
#

Uh alright, I'm very new to Unity so sorry if it's a dumb question

#

I have this trash can which consists of the base and the lid which are children of an empty object

#

and I'm trying to use the void OnMouseDown() method in a script in the empty object

rich adder
tepid stratus
#

The script is a component of the TrashCan object

rich adder
tepid stratus
#

Oh wait whoops, that was an older screenshot wait a second

#

The script did work when I used a simple rectangle with a box collider, but not when I put it in the empty object with the 2 children

rich adder
#

only the script with the collider clicked

tepid stratus
#

Oh okay, can I make it so the signal does go through to children?

rich adder
#

depends what you need it for there is many ways

tepid stratus
#

For now I just want a simple Debug.Log message every time I click on the trash can

#

In the future I would like the lid to move up but I don't know if that changes anything

rich adder
#

why not just put the script on the lid?

#

or you want the whole thing to be clicked ?

tepid stratus
#

I would like the whole thing to be clickable

#

and then send a log message

rich adder
#

if you put a rigidbody and turn it kinematic the children can also be clicked

tepid stratus
#

Does adding a rigidbody add gravity to the object?

rich adder
tepid stratus
#

Alright, let me try real quick

cunning heath
#

Hey, I need some help. I am trying to use Editor scripts to create copies of a prefab and before making the copy access and modify some variables inside the prefab which I have linked to it using another script that I attached in unity. The code is like this

GameObject cellobj=AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Prefabs/cell.prefab");
var attr = cellobj.GetComponent<cell_attr>();
Cell newCell=PrefabUtility.InstantiatePrefab(cellobj) as GameObject; 

But it gives me an error

The type or namespace name 'cell_attr' could not be found (are you missing a using directive or an assembly reference?)

How do I access and modify cell_attr for this gameObject copy before instantiating the prefab.

tepid stratus
cunning heath
#

int

#

or object

rich adder
#

you can't use variable in there

#

you need a T type Monobehavior

cunning heath
#

I am using this inside an editor script btw

rich adder
cunning heath
#

I use this for checking some conditions etc

rich adder
#

ok well regardless, your code error is telling you your type doesn't exist

polar acorn
#

Is cell_attr a component

cunning heath
#

I will be back in 10 minutes need to take some screenshots

rich adder
#

if its code please dont screenshot it 🙂

cunning heath
#

no the unity editor

#

Xd

#

So blank path is the prefab I am loading.

How can I get the array UpNeighbours which contains objects to other prefabs in an Editor script.

wintry quarry
cunning heath
#

Yes but if I make a gameobject of blank tile can I get this

rich adder
#

although isn't that a Unity class 🤔

wintry quarry
#

It's a custom one with the same name

rich adder
#

Ahh makes sense

wintry quarry
#

You seem to be trying to make an editor tool before learning the very basics of Unity TBH @cunning heath

cunning heath
#

Sorry I am pretty new to Unity I also apologize for the slow response.

wintry quarry
#

You might be better off starting with basic Unity tutorials first to learn the basics

#

Before doing something more advanced like editor tooling

#

!learn is a good place to start

eternal falconBOT
#

:teacher: Unity Learn ↗

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

cunning heath
#

Thanks will check it

cunning heath
# rich adder its inside `Tile`

So the issue is Tile is a script attached to the prefab. I want to modify the values from the Tile script for a specific prefab

#

In another editor script