#💻┃code-beginner

1 messages · Page 812 of 1

finite flower
#

no, it's to rotate something towards something

naive pawn
#

do you need the clamp thonk

finite flower
#

yes

naive pawn
#

how would it rotate to look at something behind and above you

#

if you just clamp it'd just look up and never get there

#

you'd probably need some more logic to handle that

finite flower
naive pawn
#

seems like that kinda defeats the point of making something look at something.

#

what's the overall goal here

finite flower
#

I want it to be able to look left, right, up and down, but only 90 degrees

naive pawn
#

limited from the starting rotation, or from the current rotation?

finite flower
#

from the current rotation (Idk how that changes because it's a child of the player)

#

it's a flashlight that follows the camera

naive pawn
#

and you want it to.. lag a little, from the camera?

#

or what

elfin pike
#

Have anybody made cinemachine pixelperfect solution to smoothly move between pixels

midnight plover
#

You want to aim with the flashlight like with a gun, right?

#

But separated from the cameras view

finite flower
#

It's a third person game and the light is mounted to the characters shoulder. I want it to aim where the camera is looking, but no more than 90 degrees from where the player character is facing.

naive pawn
#

i see, i don't think clamping particularly makes sense then
especially when working with a direction vector

#

could probably modify lookVector so it's not behind the player

midnight plover
#

you could clamp the euler angles or use quaternion.angle to check if its within your ranges for example.

naive pawn
#

does unity even have built-in utilities to convert from a direction vector to euler angles

timber tide
#

I wouldn't child it and just keep the max rotation values it can move

grand snow
#

LookRotation is to a quaternion but this is a good lesson that we want to work in Quaternion as much as possible

finite flower
elfin pike
finite flower
naive pawn
hexed terrace
timber tide
#

Well, it should be child to the body but not the face/camera more specifically

grand snow
elfin pike
naive pawn
midnight plover
finite flower
timber tide
#

it only needs to rotate on two axis as well. Not like a flashlight should rotate on the z. It's more that you want to clamp the y

#

well, clamp both y and x

finite flower
#

at this point I'm just gonna scrap what I have and put a Cinemachine brain on it

timber tide
#

if we are to use local rotation, 0,0,0 rotation faces forward. You want to clamp the y and x to angles of 180ish

finite flower
#

and only the Y

#

180 is behind the character

timber tide
#

well 180 from left to right

#

or -90, 90 ye

#

euler should be fine, just don't modify the z

finite flower
#

I'm just gonna not worry about clamping it and figure it out later

timber tide
#

I'm just saying that if it's child to your character body then if it rolls, technically you don't need the flashlight to also roll

#

you just focus on that local rotational values

#

I'm feeling that trying to slerp from values not inside of that local rotational space may cause problems too so may need to do like the inverse quaternion method

#

too sleepy for this

stoic sage
#

Does anyone have any good tutorial or a forum on 2d hitboxes

radiant voidBOT
stoic sage
naive pawn
#

hitbox is a concept, it's probably not gonna be called that in the tutorials

#

they'll be referring to colliders and stuff

rich adder
sour fulcrum
#

Can someone point out why I'm an idiot or if this is a problem with the serialized dictionary I'm using?
Code

    public bool TryGetValue(string category, out string value)
    {
        if (!valuesDict.ContainsKey(category))
        {
            string s = "Failed Check For: \"" + category + "\"\nDict Includes: ";
            foreach (string k in valuesDict.Keys)
                s += "\n\"" + k + "\" (" + (k == category) + ")";
            Debug.Log(s);
        }
        return (valuesDict.TryGetValue(category, out value));
    }

Log

Failed Check For: "Location Type"
Dict Includes: 
"#" (False)
"Name" (False)
"Directory Category" (False)
"Print Types" (False)
"Plan Type" (False)
"Description" (False)
"Location Type" (False)

I don't get why Location Type is returning false

naive pawn
rich adder
naive pawn
#

if the lengths are the same, log out the charcodes to see if they're all the expected ascii

sour fulcrum
#

heard

#

i think there is a tiny invisible fucker

#

many thanks

#

is there a nice way to clean those up?

naive pawn
#

depends on what the tiny invisible fucker is, exactly

#

and where it's from

sour fulcrum
#

this is a google sheet off a www processed with my own csv parsing code

naive pawn
#

is the invisible character in the dict or in the input category

#

(and what is the invisible character)

sour fulcrum
#

in the dict but both come from that process, checking now

naive pawn
#

oh, a line ending

#

both cr and lf are whitespace so you could just trim the string

#

(or maybe check the csv - if it explicitly has the \r\n line ending, check the source sheet, if not, check your parsing code)

rancid tinsel
#

@sour fulcrum

naive pawn
naive pawn
#

if you close out of unity (hopefully forcing a save, as the autosave seems to not work in your case), do you see the value in the SO .asset file change

rancid tinsel
#

but what rob said in the other chat seems to do it

#

the save project

naive pawn
#

oh, nice

sour fulcrum
#

was a hanging line ending on my string[] array of the csv row

echo copper
#

what does that means?

naive pawn
#

you have an animation event set for a nonexistant target

echo copper
#

is animation event a script?

rich adder
#

its in your animation clip

errant breach
#

Hello, so despite creating a new projet and using an updated version fixing this issue, i still have this issue when rotating group. I dont know what im doing wrong but im pretty sure this is a common issue, does someone have an explanation on how to fix that please ? I would be very grateful.. Thanks !

hexed terrace
errant breach
#

Both, because i will soon need to rotate my spaceship (barrel roll, etc) during the game with code and just like last time i will have the same issue. Im sorry if i am in the wrong channel but i was told to come here and i didnt find another place to ask for that. If im at the wrong place, feel free to tell me when i need to go

hexed terrace
#

your scale's aren't uniform (all the same, eg: 1,1,1)

#

Change teh scale for the gameobjects that move/ rotate to 1,1,1. And set the scale of children that don't need to move or rotate to the scale you want them to be

errant breach
#

Soo it's that simple, woah. Thank you ! Thanks for the redirection too.

errant breach
#

now i have a question about an error i dont understand. Despite looking on the web, i have no solution for something that simple. Do you guys know how i can fix that please ?

naive pawn
#

you have a stray ; there

#

it's saying Move needs a body, aka the {}
the body you wrote isn't being picked up because there's a ; that completes the method declaration

errant breach
#

Too much python be like

#

Thank you ! 😅

naive pawn
#

except with labels, switch/case, object initializers, i guess

errant breach
#

Im blind btw, sorry for taking your time

stoic sage
#

is it normal that i took so much time to understand colliders

#

2 fucking hours

#

just to make a collider trigger work

sour fulcrum
#

can be

polar acorn
#

It will be faster next time

stoic sage
#

dude i swear to fuck why is showing an error

#

yes i did reference it in the engine

#

ok why did it work when i removed the debug log?

#

huh

polar acorn
#

What does the error say

stoic sage
#

that hearDisplay is apparently not referenced when it literally was

#

no matter

#

it works now ig

polar acorn
#

What is the exact error it's giving you

stoic sage
#

nevermind

polar acorn
# stoic sage

The variable hearts of Hitbox has not been assigned. You probably need to assign the hearts variable of the Hitbox script in the inspector.

stoic sage
#

i asigned the script itself im not sure how to assign the variable itself tho

hexed terrace
polar acorn
# stoic sage

So, this Hitbox has hearts set, so the error isn't talking about this one

stoic sage
#

oh

#

right

#

i referenced it into the script only

#

not the object

hexed terrace
#

you're doing it in a poor way already

#

Just do ⁨⁨⁨[SerializeField] private HeartDisplay heartDisplay⁩⁩⁩ -> assign in the inspector
Remove the gameobject field, and remove the getcomponent from ⁨Awake()⁩⁩

stoic sage
#

FINALLY OML

#

thanks yal

#

yall

#

althought a small issue

#

collision triggers twice instead of once

#

so it takes away 2 hp instead of 1

#

what could be the issue?

naive pawn
#

could be quite a few things

polar acorn
#

Show the inspectors of both objects

naive pawn
#

give some info about your setup so we don't have to guess through the plethora of possibilities

stoic sage
#

hitbox and player or the heartdisplay

polar acorn
rich adder
verbal dome
#

Does the other object have 2+ colliders?

stoic sage
#

huh

#

weird i thought i removed the second one

#

triggers once now yeah

#

thanks

#

man ive been making too many dumb mistakes

hexed terrace
#

they're only dumb if you keep making the same ones and don't learn from them

night gate
#

does anyone know how to instead of painting a texture on a surface on particle collision, instead create a 3d mesh

#

i wanna clarify i dont mean instantiating a mesh object on collision, i want to know if i can make a texture that instead of being a 2d layer of paint, is instead uniform 3d meshes

#

i feel like theres a specific channel for this but idk what itd be

hexed terrace
#

are you doing it via code?

wintry quarry
night gate
#

and i wanna display that within every x amount of space covered within a texture paint

sour fulcrum
night gate
#

so like if it covered a 10x10m area, id have one placed at every 1x1 position

verbal dome
night gate
verbal dome
#

Why are you asking this in the code channel though?

#

Well, you could write your own tool, so maybe that's code related.

rough granite
#

There any good sources for learning HLSL?

rich adder
#

they developed it after all

rough granite
#

They did? Didn't know this, though i guess i know next to nothing about it

slender nymph
vestal cosmos
#

im trying to put the spacebar as the jump key how do i spell it so it rigisters

#

im using if(Input.GetKey(" ")

slender nymph
#

use keycodes then you can use the autocomplete in your configured IDE instead of relying on strings

vestal cosmos
#

what are keycodes

vestal cosmos
#

k thank you i will try that now

spiral oak
#

Is there any way I can prevent my AnimationTree from modifying the transitions between the animations??

slender nymph
#

is that a code question?

spiral oak
#

Sorry wrong server 😭

#

idk why I had this open

vestal cosmos
#

that worked but how do i make the jump smoother as right now it look as it if it is teleporting

wintry quarry
#

the fix would be to fix that code. You'd have to share the code if you want more details

vestal cosmos
#

if (Input.GetKeyDown(KeyCode.Space))
{
transform.Translate(new Vector3(0, upwardForce * Time.deltaTime, 0));

}

#

public float upwardForce = 250f;

wintry quarry
#

this is bad for several reasons

vestal cosmos
#

its my second day

wintry quarry
#

That's nice, and I'm telling you what's wrong

#

Are you moving your character via a Rigidbody?

vestal cosmos
#

yes

wintry quarry
#

Share your full script

#

!code

radiant voidBOT
wintry quarry
#

what you're doing here just moves the object instantly in one frame. TO have a real jump you want to be adding an upwards force or modifying the vertical velocity of the RIgidbody

vestal cosmos
#

which i do how

wintry quarry
#

I can show you if you share your code

vestal cosmos
#

k give me 2 mintues

#

im using pasteof code .org but i dont know hwo to share it to you

wintry quarry
#

save it and share the link

#

the LINK

naive pawn
#

not save the file

wintry quarry
#

not the html of the webpage lmao

naive pawn
#

there's a save button on the website

solar hill
#

bless his heart

naive pawn
#

you need to save the paste, not the entire site lmao

vestal cosmos
#

sorry

wintry quarry
#

Just press the "paste it" button and then copy the URL from your web browser

vestal cosmos
#

i think thats it

frail hawk
#

bad code

vestal cosmos
#

i know

frail hawk
#

line 15-33 could be replaced with 2 lines of code

naive pawn
#

AddForce with continuous forces should be in FixedUpdate, and should not have deltaTime applied - it will apply deltaTime for you

wintry quarry
# vestal cosmos https://paste.ofcode.org/VYxfV3PhPuPSzkYyQLbiTP

the jumping would just be another force.

However your code has several issues:

  1. You should not be doing physics in Update. Only in FIxedUpdate. (jumping can be the one exception to this for reasons that are complicated to explain - but basically because it's a one-off thing and not a continuous force)
  2. you should not multiply forces by Time.deltaTime
vestal cosmos
#

ok

vestal cosmos
vestal cosmos
frail hawk
#

you might want to google that

vestal cosmos
#

i will

vestal cosmos
#

k thank you all for the help i feel like this is not going to be the last time

finite flower
#

How would I get the relative velocity of my player? Cause the player rotates based on the camera, but rb.linearVelocity returns the world space values, not relative values.

finite flower
# wintry quarry relative to what?

So, no matter where the camera is looking (third person), when the player is moving forwards, I want the forwards vector to be positive, etc

#

or where the player is looking

#

moving forwards = positive forwards velocity

wintry quarry
#

then yeah just convert the world space vector into the camera's local space

finite flower
#

oh, no, I think I figured it out

#

how do I make it relative to something 😅

#

I know what I need to make it relative to for it to work

grand snow
#

I presume your camera is at an angle so that makes it a tad harder

naive pawn
#

sooo you're just going to ignore what digi sent?

finite flower
grand snow
keen dew
#

Setting the velocity to the player model's transform.forward * speed makes it go forward relative its own rotation. If the player can tilt up and down you can set the forward vector's Y to zero first

finite flower
grand snow
#

then get it and transform the vector to be local

finite flower
verbal dome
#

var relativeVel = transform.InverseTransformDirection(rb.linearVelocity)

#

There's not much to it

finite flower
#

Do I not put the forward vector there?

grand snow
#

what are you on about

#

if you want velocity to be "local" to a transform then you use InverseTransformDirection on that transform

verbal dome
grand snow
#

Are you sure you know what you are asking? Do you actually not need this?

keen dew
#

This is probably an XY problem

finite flower
grand snow
#

your player has a Transform btw

finite flower
#

playerVelocity = playerVis.transform.InverseTransformDirection(rb.linearVelocity);
This is what I currently have. playerVis is the variable for my chracters physical body, not the player object, because I want forward to be where the chracter is facing.

grand snow
#

that is correct

#

now Z+ will be forward relative to playerVis.transform

finite flower
#

This is what I'm getting when I'm standing still.

#

And those are constantly changing

#

regardless of if I'm moving or not

keen dew
#

If you just want to know if the player is moving forwards or backwards then it's Vector3.Dot(transform.forward, rb.linearVelocity). If that's > 0 it's moving forwards, < 0 it's moving backwards

grand snow
#

oh yea good idea. dot product is great

naive pawn
#

probably with a little epsilon to account for floating-point imprecision

finite flower
slender nymph
#

transform.forward is also in world space so that doesn't really matter

keen dew
#

Vector3.Dot returns a single number that isn't in any space so that doesn't make sense. If it doesn't do what you expect then you're plugging in wrong values

blissful stratus
#

how can i remove this?

finite flower
#

It's working perfectly when I use transform.up, giving 1 when I jump and -1 when I'm falling, but for some reason the number just freaks out in any direction when I use transform.forward 😭

slender nymph
# blissful stratus how can i remove this?
  1. not a code question
  2. unless you want to pay to digitally sign your game you'll need to select the option you've cropped out that lets you continue attempting to run it anyway
finite flower
blissful stratus
strong berry
#

Does anyone have a clear diagram of a basic block of code handy? Like with what a namespace is, what a class is, what a variable is, etc. clearly labeled? I keep running into information that seems to contradict itself and I really just want to understand these basic terms finitely. Even my textbook doesn't name them in order or in context.

grand snow
cosmic quail
finite flower
#

How do I limit a float to whole numbers? Normalizing the numbers isn't working.

verbal dome
#

You mean "Round" it?

slender nymph
finite flower
#

it's for being able to read the number reasons. I'm getting 1.13495807134958713409 kind of number every frame and it's impossible to debug that

slender nymph
#

right so that would be "display purposes"

finite flower
#

In the inspector?

slender nymph
#

don't rely on inspector values for debugging things

verbal dome
#

You can use Debug.Log or OnGUI+GUILayout.Label to debug it with formatting

grand snow
#

or the magic of a debugger ✨

finite flower
#

Okay, so yeah, Vector3.Dot is giving seemingly random values 😮‍💨

grand snow
#

nah its bad input

#

If you just want to know if something is moving up in world space then use Vector3.up

finite flower
#

no

#

I want to know if it's moving forwards

#

the objective has not changed

grand snow
#

Then you need a more reliable reference for what "forward" is

verbal dome
grand snow
#

oh and you should normalise the velocity first before doing Dot()

verbal dome
#

Does that matter?

finite flower
#

and just random

grand snow
#

if unity doesnt normalise it then yes

finite flower
verbal dome
#

The sign of the result value of Dot would still be correct for non normalized input

#

In fact you can even use it to check the relative forward speed of the vector

#

For example Dot(v3.forward, v3.forward * 5) would return 5

#

Which is positive

#

So its moving forward and at speed 5

grand snow
#

but when we want a nice -1 to 1 range then normalising the inputs helps

finite flower
#

except when it doesn't

#

playerVelocity = Vector3.Dot(Vector3.Normalize(playerVis.transform.forward), Vector3.Normalize(rb.linearVelocity));

grand snow
#

TRANSFORM THE VELOCITY

finite flower
#

Yes, those are words

naive pawn
#

if you don't understand then say so instead of ignoring the advice

grand snow
#

we tried folks 🧱

finite flower
grand snow
#

scroll up and read stuff

verbal dome
grand snow
#

yes but what if they want a specific range that means "forward"?

finite flower
verbal dome
naive pawn
#

help is a two-way street

#

we cannot help if you refused to be helped

verbal dome
finite flower
naive pawn
naive pawn
finite flower
naive pawn
# grand snow yea both work

had a convo recently about this, defining angles would be easier than defining a dot product threshold since dot product isn't linear over angle

verbal dome
#

They only need to know if moving backwards or forwards, and a dot product of the world space velocity and some world space "forward" direction gives that. Which they are doing

naive pawn
grand snow
naive pawn
#

also, giving advice about getting help is also "helping"

naive pawn
verbal dome
#

Most of the code shown here should've worked so it's an input problem and/or some feedback loop

naive pawn
#

but nah 2 normalized vectors at 45° from each other have a dot product of sqrt2/2, since it's the cosine of the angle

finite flower
naive pawn
naive pawn
#

and that's the rigidbody velocity?

finite flower
#

No, that's the value that's being returned when I use Vector3.Dot

slender nymph
#

can you screenshot the values? because i'd bet they are just really small numbers in scientific notation

naive pawn
#

ok, so that's.. not what i asked lol

#

(for future reference, a less cropped image would help give crucial context.)

finite flower
#

It does the same thing

naive pawn
#

what same answer? that's the dot product?

finite flower
#

Those Vector3 values were from transform.InverseTransformDirection

finite flower
naive pawn
finite flower
#

Generally between 10 and -10

naive pawn
#

and they're definitely like, 7.43482 and not 7.43482e-6?

#

yeah yknow what just show more context directly please

#

feels like a very prolonged game of telephone here...

#

(use mp4 so it embeds in discord)

finite flower
#

I know

naive pawn
#

i don't know if you know.

finite flower
#

I have to rerecord cause I need to revert the script

stoic sage
#

how can i highlight hitbox object only for inspector

#

so i dont have to move an invisible object in the inspector

solar hill
#

what

#

can you clarify what you mean

naive pawn
#

ok so it's basically just not changing at all, just microscopically fluctuating

solar hill
finite flower
#

That's using this playerVelocity = playerVis.transform.InverseTransformDirection(rb.linearVelocity);

naive pawn
#

right, and it seems to be relatively stable, as revealed by your console showing 2 digits being perfectly stable

verbal dome
#

And I bet the Y value is large because of gravity/some imperfect character controller code

naive pawn
#

i'm confused. was this the part that had issues? that's what i gathered from backreading and i'm not so sure i got it right

verbal dome
#

Make sure that the animator isn't modifying the root object's transform also

finite flower
naive pawn
#

yeah both of those work

hushed sky
#

could someone help me with this? im pretty new on Unity, im searching to change the image of a normal button with a custon image so is not just a square. I found the package manager is it there? or do i need to download from some place in internet a png?

naive pawn
#

those were offered as alternatives, not that one was better than the other

#

so i'm still confused. what's the issue

hushed sky
#

my point is im trying to find a safe place for unity to download images for the button

hushed sky
#

manually like in the inspector

#

is there any safe place dedicated to unity things?

#

instead of just take it from google search?

verbal dome
#

Asset store

hushed sky
#

where would that asset store be?

verbal dome
#

This is a code channel. Not a general beginner channel

finite flower
hushed sky
#

there is many channels and i cant find one more suited rn

slender nymph
finite flower
#

it's returning a value that is positive if the player is moving +Z or +X in the world tho

finite flower
verbal dome
#

@finite flower Have you checked the value of rb.linearVelocity when you are standing still?

slender nymph
finite flower
#

I did and all of it is saying I should be getting 1 to -1

#

not 0.000007

polar acorn
#

Well, 0.000007 is between -1 and 1

verbal dome
#

So check your input values

#

If you are expecting something else

slender nymph
naive pawn
#

(if the vectors are normalized)

verbal dome
#

Is the rigidbody even dynamic? 🤷‍♂️

finite flower
verbal dome
#

So is the rigidbody kinematic?

finite flower
#

no

slender nymph
#

How are you moving it

finite flower
#
// The math for figuring out movement
        moveVec = move.ReadValue<Vector2>();
        moveLike = new Vector3(moveVec.x, 0.0f, moveVec.y);
        moveLike = Vector3.ClampMagnitude(moveLike, 1f);
        
        if(isClimbing)
        {
            x = playerVis.transform.up * moveLike.z;
            z = playerVis.transform.right * moveLike.x;
            isJumping = false;
            //rb.useGravity = false;
        }
        else if (!isClimbing)
        {
            x = cam.transform.forward * moveLike.z;
            z = cam.transform.right * moveLike.x;
            x.y = 0.0f;
            z.y = 0.0f;
            //rb.useGravity = true;
        }
        
        direction = x + z;

        float xSpeed = playerSpeed * 0.01f;

        finalMove = Vector3.Lerp(finalMove, direction * xSpeed, friction);
        normalizedMove = finalMove + Vector3.up * velocity.y;
        rb.linearVelocity = normalizedMove;
#

playerSpeed is 450 btw

verbal dome
#

And is this a different script? Are you referencing the correct rb?

tribal urchin
#

I need help how do I make this block trigger an animation I’m trying to make a titanic sinking map ?

verbal dome
tribal urchin
#

And also to trigger the sound source

naive pawn
tribal urchin
#

Ik

naive pawn
#

anyways, give it a collider and something implementing IPointerXHandler and use a physics raycaster, iirc

finite flower
rough granite
verbal dome
# tribal urchin It has a box collider

You can see example code in the link I posted. Then you need to find out how to reference the animator and audio source and play them inside OnPointerClick

naive pawn
#

i just said to use IPointerXHandler

verbal dome
tribal urchin
naive pawn
#

it doesn't work on its own, no

verbal dome
#

Yeah this is a decent usecase for unity events

grand snow
#

not present in that example but you can if you wanted

rough granite
verbal dome
#

Oh my eyes garbled "Unity EventSystem" into "UnityEvent System" lol

naive pawn
#

it's what triggers the pointer event handlers

#

you may be thinking of the MouseXHandler stuff?

rough granite
naive pawn
#

afaik, you need a raycaster to trigger the events to begin with

ivory bobcat
grand snow
#

Hmm if only there was a cool example that explained all this 🤔

rough granite
#

Cause i was thinking of a way i would've handled what they asked and you gave a different one. Where i would used the IPointer enter and exist to toggle a bool i misread you saying to use a raycast

naive pawn
#

i gave the one you were thinking of

#

(are you thinking of PointerExit, PointerExist is not an event)

ivory bobcat
rough granite
naive pawn
#

i guess go back and check then

grand snow
rough granite
grand snow
#

This confusion is why i made a complete example

rough granite
#

yeah me clicking the link would've helped ~_~

naive pawn
strong berry
naive pawn
#

on point 1, some people don't lol. i'm not in your head shrugsinjapanese

#

it's hard to clarify apparently incorrect resources without seeing the actual resources though

tribal urchin
#

To clarify the video is an example of what I'm trying to do but in my VR map can someone help me?

naive pawn
#

oh, this is vr?

tribal urchin
#

Yea

#

The video is a example of what I’m trying to accomplish to help clarify

naive pawn
#

i assume the intended input method in the vr version would be using the hand controls then?

#

i don't know what they're called

naive pawn
#

you wouldn't be using a raycaster for that i guess. the folks in #🥽┃virtual-reality would probably be able to give better advice about how to handle that

surreal shard
#

hi, i'm trying to get the camera to follow the player with the SmoothFollow script but the camera keeps snapping to a random position and stays there

surreal shard
#

i should probably post some screenshots wait

#

it's a script from standard assets as far as i can see

#

sorry if i'm being confusing i only recently started learning unity i know nothing

rich adder
#

probably even better new, it uses cinemachine which you should learn anyway

surreal shard
#

the course i'm following uses this version of unity

#

i should

#

go find another source to learn from shouldn't i

rich adder
#

is not that seriously it can be easily be patched with tool, but you can use latest LTS anyway if you want its the same editor..

surreal shard
#

this is what my screen looks like rn, the camera is supposed to follow the ball and the ball has some player controls on it that work fine

#

but instead it just snaps here, about 150 units away, and stays there

surreal shard
#

so to avoid that i switched to the version they specify

radiant voidBOT
# rich adder !input
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

surreal shard
#

did that

#

didn't work

rich adder
#

can just put it to Both and it works fine

surreal shard
#

ig i'll try again hold on

#

i don't remember seeing the both option actually

rich adder
#

its there

#

!code

radiant voidBOT
rich adder
surreal shard
gilded harbor
#

Okay, I figured out the clamp issue for now. Now i'm having an issue with my rotator script. It works as intended for the most part, I mousepress an object, a ray detects the object and sends a signal to rotate the object depending on where i'm pressing. For some reason though, clicking on the right side (rightplane.name) makes the object spin endlessly, even though the left side is working fine. Why?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class RotatorLogic : MonoBehaviour
{
    public float rotSpeed;
    public Collider leftplane;
    public Collider rightplane;
    public Transform pivot;

    public Camera cam;

    private RaycastHit israytouching;

    public string raycastedobject;
    // Rotation Settings
    private float rotatespeed = 700f;
    

    private bool mousepressed;


    private void Update()
    {

        Vector3 mousePosition = Input.mousePosition;

        Ray myRay = cam.ScreenPointToRay(mousePosition);

        bool RayTouching = Physics.Raycast(myRay, out israytouching);

        if (RayTouching)
        {
            raycastedobject = (israytouching.transform.name);
        }

        if (Input.GetMouseButton(0))
            mousepressed = true;

            if (raycastedobject == leftplane.name && mousepressed)  
            {
                pivot.transform.Rotate(0f, rotatespeed * Time.deltaTime, 0f);
            }
            if (raycastedobject == rightplane.name && mousepressed)
            {
                pivot.transform.Rotate(0f, -rotatespeed * Time.deltaTime, 0f);
            }
        else
            mousepressed = false;
        }
}
rich adder
#

you else never runs

#

right now the else is going based on if (raycastedobject == rightplane.name && mousepressed)

#
 if (Input.GetMouseButton(0))
            mousepressed = true;```
one reason writing if staments like this can mess you up
#

so yeah brackets are important for if blocks

gilded harbor
# rich adder bracket issue

Oh my god thank you lol. I had to look up how to format an if else statement. I have a lot more learning to do. Thank you so much!

rich adder
#

btw you could technically just write it as mousepressed = Input.GetMouseButton(0);

#

since you have && mousepressedanyway

gilded harbor
#

Could I do that in the start function?

rich adder
#

no because it needs to poll it every frame otherwise it stays in one state, Start only runs once

gilded harbor
#

Thank you, that helps clean up this mess a little bit 🙂

rich adder
#

btw could also skip the whole string bit too, raycasthit which you named israytouching(confusing name btw is not a bool)
you can directly check collider
israytouching.collider == leftplane or israytouching.collider == rightplane
the "drawback" is you need to put it inside RayTouching otherwise iirc you get a null collider not the last touched.

#

fine how you do it for now, if it works it doesn't matter I suppose..

rough granite
rich adder
rough granite
#

Yeah fair, they also could've gone the route of deleting that bool instead of making it = Input.GetMouseButton(0) as it's seemingly useless in the given context

gilded harbor
#

Even if my current script already works, I'll do anything to help learn what exactly does what and better ways of doing things. Especially if it prevents unnecessary giant if/else statements.

rich adder
#

mousePressedUI_Icon.gameObject.SetActive( mousepressed)
etc

crimson sluice
#

I’m having trouble with the input system code

rich adder
ivory bobcat
crimson sluice
#

Like the inputs aren’t showing on the console

#

Sorry I’m not the best at explaining things I’m very new to all this

rich adder
ivory bobcat
crimson sluice
#

Ok I gotchu so I’m using the system Input and I was having some issues with the c# script where I was having errors I just don’t know what to really put in for the c# for the charter inputs?

#

I don’t know if that helps at all I can give you them guys my code when I get home later tonight

golden canopy
#

it was some weird unity glitch mb

naive pawn
kind skiff
#

I am using scriptable objects but for some reason it is having this error. It keeps happening where at the start of the creation for the scriptable object it's fine but after some time it keep appearing this error. Do anyone know how to fix it?

boreal sonnet
#

Remove the missing script and reassign

#

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

public class ObjectPooler : MonoBehaviour
{
public static ObjectPooler SharedInstance;
public List<GameObject> pooledObjects;
public GameObject objectToPool;
public int amountToPool;

void Awake()
{
    SharedInstance = this;
}

// Start is called before the first frame update
void Start()
{
    // Loop through list of pooled objects,deactivating them and adding them to the list 
    pooledObjects = new List<GameObject>();
    for (int i = 0; i < amountToPool; i++)
    {
        GameObject obj = (GameObject)Instantiate(objectToPool);
        obj.SetActive(false);
        pooledObjects.Add(obj);
        obj.transform.SetParent(this.transform); // set as children of Spawn Manager
    }
}

public GameObject GetPooledObject()
{
    // For as many objects as are in the pooledObjects list
    for (int i = 0; i < pooledObjects.Count; i++)
    {
        // if the pooled objects is NOT active, return that object 
        if (!pooledObjects[i].activeInHierarchy)
        {
            return pooledObjects[i];
        }
    }
    // otherwise, return null   
    return null;
}

}

#

this is the ERRor ------- MissingReferenceException: The object of type 'UnityEngine.GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <18b3b31e3d8341f487466ebb6800bc67>:0)
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <18b3b31e3d8341f487466ebb6800bc67>:0)
UnityEngine.GameObject.get_activeInHierarchy () (at <18b3b31e3d8341f487466ebb6800bc67>:0)
ObjectPooler.GetPooledObject () (at Assets/Scripts/ObjectPooler.cs:37)
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:38)

#

this is error shown in Console when i try to test the game ? the object has been assigned in inspector . (Object Pooling)

kind skiff
boreal sonnet
#

after one fire --this error shows up

kind skiff
#

Can you check whether there is another script that is destroying the objects?

#

If you're returning to the pool the object will not be destroyed unless you tell it to

boreal sonnet
kind skiff
boreal sonnet
#

the player has only one script attach to it but the others has 2 scripts one to -- move and one to Destroy

kind skiff
#

The object pool's main goal is to make it efficient by reusing the objects and do not need to keep on creating and destroy the objects

boreal sonnet
#

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

public class PlayerController : MonoBehaviour
{
private float horizontalInput;
private float speed = 20.0f;
private float xRange = 20;
public GameObject projectilePrefab;

// Update is called once per frame
void Update()
{
    // Check for left and right bounds
    if (transform.position.x < -xRange)
    {
        transform.position = new Vector3(-xRange, transform.position.y, transform.position.z);
    }

    if (transform.position.x > xRange)
    {
        transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
    }

    // Player movement left to right
    horizontalInput = Input.GetAxis("Horizontal");
    transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);


    if (Input.GetKeyDown(KeyCode.Space))
    {
        // No longer necessary to Instantiate prefabs
        // Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);

 [       // Get an object object from the pool
     this is where the error shown------<<<<<<<<<<<<<<<<<<<<<<<<<<-[[[[[[[   GameObject pooledProjectile = ObjectPooler.SharedInstance.GetPooledObject();]]]]]]]>>>>>>>>>>>>>>>>>
        if (pooledProjectile != null)
        {
            pooledProjectile.SetActive(true); // activate it
            pooledProjectile.transform.position = transform.position; // position it at player
        }
    }



}

}

boreal sonnet
kind skiff
boreal sonnet
#

if (Input.GetKeyDown(KeyCode.Space))
{
// No longer necessary to Instantiate prefabs
// Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);

        // Get an object object from the pool
        GameObject pooledProjectile = ObjectPooler.SharedInstance.GetPooledObject();
        if (pooledProjectile != null)
        {
            pooledProjectile.SetActive(true); // activate it
            pooledProjectile.transform.position = transform.position; // position it at player
        }
    }
kind skiff
boreal sonnet
#

no

kind skiff
boreal sonnet
#

public GameObject GetPooledObject()
{
// For as many objects as are in the pooledObjects list
for (int i = 0; i < pooledObjects.Count; i++)
{
// if the pooled objects is NOT active, return that object
if (!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
// otherwise, return null
return null;
}

kind skiff
# boreal sonnet no

but you mentioned previously that the projectile throwned is getting destroyed

kind skiff
#

the object gets destroyed after it got returned to the pool

#

which is causing the error

boreal sonnet
#

i dont know how should i fix it?

sour fulcrum
#

find wherever you destroy it and dont do that

boreal sonnet
ivory bobcat
#

!code

radiant voidBOT
sour fulcrum
#

if you want to use a pool or not use a pool thats a whole different thing

#

but pools are built for not destroying

kind skiff
#

Then when you retrieve from the pool reset the velocity, position and direction of the bullet

kind skiff
ivory bobcat
kind skiff
#

so we reuse them to make it efficient

ivory bobcat
#

Either way, the error was informing you that you've destroyed an object but you were still trying to use it somewhere..

boreal sonnet
#

ohhh okay thanks for that👍

#

yeah my fault

kind skiff
# boreal sonnet yeah my fault

Well a good way of learning is through tutorial videos or ai. I find myself being able to learn very quickly and efficient from ai as it is able to provide me with examples of the implementation of the code.

#

Of course if you just ask it to generate everything for you without every reading and trying to understand the logic behind of it you will not be able to learn

sour fulcrum
#

its that time of the day where we gotta highly recommend that beginners should not use ai to learn nor should people suggest it

ivory bobcat
#

I would not recommend learning something from scratch with ai. It's okay if you're simply wanting to critic it's output or have it do tedious tasks though.

sour fulcrum
#

anyone curious can just search "ai" in this channel

#

make a conclusion however they want

ivory bobcat
#

It's very constructive in how it presents is suggestions/arguments and output but it's unaware of mistakes and flaws without curation.

kind skiff
#

without understanding them

#

is that what you meant?

sour fulcrum
#

ai will lie to you and you won't know unless you know the topic <-> if you know the topic you don't need to use ai to learn

kind skiff
ivory bobcat
#

And if the person is unaware of mistakes created by ai, the solution could be non functional or even completely wrong.

kind skiff
#

But I use it as a personal mentor that asks it to explain code for me

#

And of course I do not trust it so I always fact check

#

Whether the response from ai is correct or not

sour fulcrum
#

but then you could just skip the ai gaslighter and fact check directly lol, like everyone learning online for the past two decades

kind skiff
#

You can also ask it to cite sources where he get the conclusion or answer from

kind skiff
boreal sonnet
#

well i'm learning from scratch through tutorials .. just trying to understand things

#

is it okay to befriend you guys ?

ivory bobcat
boreal sonnet
#

to help understand one another or to explaining things

ivory bobcat
boreal sonnet
#

right now the builtin one....why is there any issues with that?

kind skiff
ivory bobcat
#

Not that I'm aware of.

brisk ibex
#

I'm using an external editor to edit unity files. Currently I have to switch to vscode and regenerate the project files in order for the csproj files to update and my language server to pick up on new scripts. Is there any way I can automate this?

#

Is there any way I can roll my own "external editor" plugin/package?

#

I've noticed vscode and vs support seem to be built in packages or whatever the term is so that seems like a decent direction to check out but wanna check first.

kind skiff
ivory bobcat
# boreal sonnet right now the builtin one....why is there any issues with that?

Yours look similar to the older self made one that unity learn used to demonstrate in their tutorials
https://learn.unity.com/course/planning-for-top-performance-companion-toolkit/tutorial/introduction-to-object-pooling
Example excerp:cs GameObject bullet = ObjectPool.SharedInstance.GetPooledObject(); if (bullet != null) { bullet.transform.position = turret.transform.position; bullet.transform.rotation = turret.transform.rotation; bullet.SetActive(true); }

brisk ibex
midnight plover
brisk ibex
ivory bobcat
#

Where the newer builtin type would instead have you creating a script with the ObjectPool type and subscribing delegates etc

brisk ibex
#

self answer I'll just look at this haha

midnight plover
#

😄 neovim, alrighty

brisk ibex
#

last time I used unity I hand rolled script for this, this is new and seems like exactly the direction i was going anyway haha

midnight plover
#

Coming from server or data scripting having a look into Unity meanwhile? 😉

ivory bobcat
brisk ibex
#

more of a general systems/general pl background

ivory bobcat
# ivory bobcat The newer tutorial would be this one but it's at an intermediate level <https://...

You should be able to get a sample of the project as well if it's a bit overwhelming

Although you can create your own custom system to implement object pooling, there is a built-in ObjectPool class in Unity you can use to implement this pattern efficiently in your project (available in Unity 2021 LTS and onwards).

Let’s check out how to leverage the built-in object pooling system using the UnityEngine.Pool API with this sample project on the Unity Asset Store. Once you open the sample project, go to Assets>7 Object Pool >Scripts > ExampleUsage2021 for the files.

midnight plover
brisk ibex
brisk ibex
#

Same approach I had via the edit pipe but it still doesn't support regenerating project files automatically?

#

Given the unity shipped plugin for VSCode seems manual this seems to be more of a unity thing ig?

#

How do you guys live like this? Surely spamming a button everytime a script is added isn't the usual workflow for an average vscode user? How else does the csproj get compile directives etc?

midnight plover
#

VSCode updates automatically, no need to "spam a button" 😄

midnight plover
brisk ibex
#

Same issue still 🙂

#

I have that part down pat

#

I can double click scripts in unity and they pop up in neovim. working good.

My issue is specifically with the regenerate project files button spam

#

it seems whenever you add a script it needs to be added to some project metadata eg:

midnight plover
#

Ah my bad, just reread the article. Its exactly what you mentioned about regenerate buttoN 😄

brisk ibex
midnight plover
brisk ibex
#

with the <compile />s like above?

midnight plover
#

I am using vscode and yes, it does with itemgroup Compile and also None include, depending if its a package or not

brisk ibex
#

given that's a "executeMethod" I could probably roll a really nice solution using an actual edit plugin like the github I linked above but maybe I can find a semantic to automatically detect when SyncSolution needs to be done.

#

This is what I'm doing atm btw, it's literally just a dash shell script which I'm setting as the external editor lol

midnight plover
brisk ibex
#

which is odd but I'm sure there is a reason why it's not triggered.

#

This is the setup for the above shell script for ctx

#

Doing unity work for uni atm haha

midnight plover
brisk ibex
midnight plover
#

You were talking about LS(P?) I guess. Maybe you have to restart that to get the latest state

brisk ibex
#

I did some more research and it seems "more supported" external editors definitely call back into unity asking it to regenerate the project files via UnityEditor.SyncVS.SyncSolution so I guess that's definitely what I'll use.

#

I reckon I'm solid with that.

#

Thank you for the idea to search blog posts though, thats how i found that invocation ❤️

chrome apex
#

I have a stupid problem. I made a complex dual rig for my character, with a billion joints and a script and all that.

It works but I did it just for the right hand for testing. Now I have to do it for the left hand.

Is there a quick way to do this or am I manually adding everything here?

midnight plover
midnight plover
chrome apex
midnight plover
lapis cedar
#

hello

chrome apex
#

it even works

#

I'm also enticed to spend 10 hours programming and automating solution that would otherwise take 1 hour to do manually

midnight plover
chrome apex
#

but each body part had one

#

and each finger had 3 (for index 1, 2 and 3 for example)

#

then I had to do and adjust colliders and script references, etc etc

midnight plover
#

yeh, standard bone rig. Most of the time you are faster doing it manually unless you would have to do it several times, than I would have written a script 😄

chrome apex
#

yeah, I'm glad I did it in an hour

#

Spending 10 hours on automating it vs an hour manually is just peak programming

#

people who do that are my spirit animals

naive pawn
#

-# [insert xkcd here]

real thunder
#

Are Unity build in pools objectively better in any way than just making a list of something yourself?

real geyser
#

hey, noob here, how do i make impossible geometry? something like this

safe rose
#

Hey everyone — quick question for anyone here who started in GDevelop before moving to Unity.

We’re a small indie studio and we prototype in GDevelop a lot. The problem we kept hitting was that when we wanted to move a project into Unity, we had to rebuild everything from scratch — which was brutal.

So we built a tool that converts GDevelop projects into Unity projects with generated C# scripts.

It recreates:
• Scenes
• Objects (as prefabs)
• Event logic (converted into readable C#)
• Basic physics & collisions

It’s rule-based conversion (not AI generated), and the output is a normal Unity project you can open and edit.

It’s not perfect — complex logic still needs cleanup — but it gives you a working starting point instead of a blank project.

Curious:
Would something like this have helped you when learning Unity?

Happy to answer questions about how it works.

timber tide
real geyser
#

can make it so you can go through it? i watched some stuff but never found one that you can be in

timber tide
#

it's more of a visual thing, if you want to go through the space that's some extra logic going on

#

for one, a mask isn't volumetric. It's just a looking glass, but once you enter that area you need expand how that camera renders it. This can be tricky if you do want to use the same physical space.

real geyser
#

damn

timber tide
#

So, the stencil idea may not be ideal, but rather you use a render texture to project the image of another area and when you exceed the rendering* then you teleport the player to it.

errant breach
#

Hello ! Im making a SpaceShooter but im experiencing an issue.
If i go down and i touch a wall, i stop. Which is intented.
But if i go both down and left (for exemple) and touch a wall, i will also stop but i wont be able to go left again.

Do you know how i could fix it please ? Thank you !

real geyser
#

the texture is a plain tho, can there be seemles alternative?

#

my idea is like the room appears based on where the player is

#

is that ideal?

#

lik one way platform but in 3d kinda way

timber tide
#

it's a similar concept to how Portal does it if you do want to enter it

#

Two cameras, project the other camera's image when looking into it

real geyser
real thunder
#

I wonder does Portal create duplicates of an object for physics?

#

when an object is partially on two sides

#

well, I guess u only need to duplicate a collider

real geyser
errant breach
timber tide
real geyser
timber tide
#

It's not impossible geometry. It's just portal logic

#

Stencils allow you to store multiple different geometries in one space, but portals is different areas of rendering

real geyser
#

woah i thought this was something way more complex haha

#

just watched brackeys video on it

timber tide
#

If you enter the space -> teleport them to another area

real geyser
#

ok thanks 🙂

hexed terrace
#

nm, I see that's been suggested now

keen dew
#

!code

radiant voidBOT
real geyser
#
// woah
errant breach
naive pawn
lunar axle
#

so ive ran into a problem of unity editor loop really ruining the frame rate here, how can i fix the editor?

errant breach
real thunder
#

best I could do is to keep everything I can closed

#

like no active inspector

lunar axle
#

so it shouldnt be this bad.

silk scroll
#

I've been seeing a lot of things saying to make your own timescale for time control, but how do you actually go about doing that?
I have a [SerializeField] public float enemyTimeScale = 1.0f; so far, and I'm simply multiplying Time.deltaTime by the enemyTimeScale in all the movement code.
Where do I go from here?

#

The movement is controlled by the new value but how do I get the rest of the script to abide by my timescale?

real thunder
#

...pretty sure you don't need [SerializeField] with public but it's unrelated

silk scroll
#

i definitely don't I'm just prototyping and my code's a little messy as a result

real thunder
#

animator have some thing for custom timescale too iirc

#

also you should probably use Time.unscaledDeltaTime or how that was called

#

as a basis

#

in case you want to modify default one

#

also can you explain what do you mean by "time control" exactly?

silk scroll
#

The goal here is for the player to have a time freezing ability that affects everything but them.

real thunder
#

if it's just everything slowed down but player don't I would just modify Time.timeScale

timber tide
#

really not that complicated, you continuously check the custom timescale in update

real thunder
#

and make some changes for the player so it's not affected

silk scroll
#

so the player should be operating on a different timescale instead?
That might be simpler

#

But I did see a few things saying not to bother using Unity's built in timeScale to do things

timber tide
#

yeah, if you're trying to do a slow down mechanic where only one object is affected.

silk scroll
#

wait, if I multiply the regular timeScale by the player's own time scale that wouldn't work, because I'm setting unity's timeScale to 0

#

meaning the player's not gonna be doing anything still

lunar axle
#

try using Time.unscaledDeltaTime or u can calculate deltaTime in Update() or smth

timber tide
#

oh yeah than gotta use unscaled, otherwise just hook everything into your own set of timescale interfaces and not touch Unity's stuff

humble bronze
#

Dumb question but how much can i have happen on start before its a problem ?
is there a limit or can that one start frame take very very long? or would it crash ? i know i should only worry about optimising when it is problematic but i am curious

timber tide
#

well, ideally you don't want your program to become unresponsive, and considering gamers yell at the slightest hitch, you might want to make sure you're not instantiating too much at once, but not likely to be an issue until very later into your projects.

humble bronze
#

oke thank you

chrome tide
#

you can always just extend the initialization in a coroutine (do one thing at a frame, wait) and halt the update until you think the init is done.

silk scroll
#

The player still freezes using unscaledDeltaTime, then shoots forwards when time unfreezes. I think it's because I'm using a Rigidbody.

timber tide
#

that's probably a bit more complicated if you're using forces

#

I think you may be hardbound to using unity timescale methods

silk scroll
#

At the minute movement is handled by rb.MovePosition

timber tide
#

that should be fine then

keen dew
#

This is the wrong place but did you also add the package to the project?

low copper
#

Yes, it is installed/files present. What is the correct place?

keen dew
low copper
#

ok. Thanks

timber tide
#

really I hate messing with unity time methods

silk scroll
#

Yeah I might stick to giving the enemies their own timescale to operate on.

#

I'm just not sure how to apply the multiplier to coroutines

timber tide
#

coroutines are just mini update loops

chrome tide
silk scroll
#

If I multiply the WaitForSeconds that I have with my timeScale, that's going to make it wait for 0 seconds, since time is stopped

chrome tide
#

oh, right :P my bad. then maybe dividing instead of multiplying could work. and for the 0 seconds - you would need to check if the timeScale is equal to that and just halt the coroutine with yield return null until its value doesn't change. otherwise you'll get a division by zero error anyway

silk scroll
#

where would i place the timescale check and halt?

chrome tide
#

you'd need to check it before you do the t / timeScale calculation. e.g.:

while Mathf.Approximately(timeScale, 0f)
{
    yield return null;
}
yield return new WaitForSeconds(5f / timeScale);

just a simple code snippet, you may need to adjust it to your needs. best to use Mathf.Approximately() instead of == to avoid problems with floating point precision.

real thunder
#

are you sure you have to use approximately

low copper
#

I have a LoadScene() method in my SceneManager, that I want to to return a AsyncOperation if SceneManager is set to load async, else I want it to return true (or whatever...this side doesn't matter much). Any suggestions on how to handle the fact that I have to declare a return type that handles both branches?

chrome tide
#

because a negative timeScale wouldn't make sense anyway

real thunder
#

would the world explode if timeScale was only tiny bit larget than zero?

chrome tide
#

idk, it depends on the precision in the / operation

real thunder
#

oh right, division

rich adder
real thunder
#

yk what that would be fucked up anyway if you change your timescale
because wait for seconds being set only once and not updated once timescale changing

#

or am I wrong

low copper
rich adder
chrome tide
# real thunder or am I wrong

you're talking about a scenario when the timeScale changes in the middle of the WaitForSeconds? yeh that would be kinda fucked but the seriousness of this problem depends on the context.

chromity decided to use coroutines so i just went with that in help context, but i think that a private float timer that she would constantly add Time.deltaTime to would be more precise, but that wouldn't work in coroutines context and would need to be called in Update. would work well with state machine i think

low copper
#

@rich adder But I don't want to load all scenes async. Sometimes I want to run SceneManager.LoadScene()

real thunder
#

yeah I think they would have to replace all enemy related coroutines with timers

chrome tide
#

yeh, though i don't know if it would be worth the struggle if it's not something extremely critical to how the enemies work. though it may surely look weird when they change the timescale and an enemy still works at a different one

rich adder
real thunder
#

idk about you but I personally feel like coroutines are by default a hacky solution

chrome tide
#

i feel like they surely exist for a reason, though i dont use them really bc i'm addicted to state machines. i don't think they are certainly bad tho

low copper
#

@rich adder : I use synchronous loading when I need to know I have the scene available next frame

real thunder
#

they generate a bit of garbage and an internal timer every time you use them

#

something like that

chrome tide
#

the new WaitForSeconds may generate some garbage but that wouldn't be a problem in a game that uses coroutines wisely.

#

games are doing much more expensive stuff every frame.

real thunder
#

eh I guess

#

I use them for things happening rarely

#

however when I was starting out I went straight to generating dozens per second

#

then I got a tip to replace many coroutine events with a binary tree

#

mindblowing

twin pivot
#
        switch (attackType)
        {
            case GameStats.AttackType.Straight: attackRB2D.AddRelativeForceX(speed, ForceMode2D.Impulse);
                break;
        }
```It's not adding force relatively to the rotation, am i misunderstanding what ``AddRelativeForceX`` does?
chrome tide
rich adder
chrome tide
real thunder
silk scroll
#

I can see this quickly becoming an issue with the coroutines since they're being used for my enemy's shooting at the minute

#

I'm gonna look into changing how the shooting is handled since enemies will be doing that
a lot

chrome tide
#

are you referencing to the timescale change mid waitforseconds?

real thunder
#

if it's tied to shooting you may use animation events

silk scroll
#

Yea that and some garbage too

chrome tide
verbal dome
rich adder
# real thunder that's like... the same as using wait for seconds but without garbage? 🤨 no wa...

Im on metro so i get bad service rn. there will be a little garbage but imo a bit better than a new waitforseconds object if you have It in a while loop and has to change value each time as well . Update is good too but gets messy when you need multiple timer types. With corooutine I find it neater plus I have a generic one that r may invoke an action you can pass in the method .

The same coroutine can be called with different parameters and run independently, not true async but the similiar concept.
update loop gets tricky with that

verbal dome
twin pivot
verbal dome
twin pivot
#

ahh. I cant believe i missed that

twin pivot
real thunder
twin pivot
# twin pivot apparently that wasnt the problem
    private IEnumerator SpawnAttack()
    {
        for (int i = 1; i <= attackLevel * attackPerLevel; i++)
        {
            GameObject _attackObject = Instantiate(_attackPrefab, gameObject.transform.position, gameObject.transform.rotation);
            RuneAttackPatterns attackBehavior = _attackObject.GetComponent<RuneAttackPatterns>();
            _attackObject.transform.LookAt(enemies[1].transform);
            attackBehavior.Attack(GameStats.AttackType.Straight, 1);
            yield return new WaitForSeconds(attackDelay);
        }
    }
```this is the code im using fire the projectile along with the previous code
verbal dome
#

I would not use LookAt in a 2D game like this. Set transform.right or transform.up to the direction towards the enemy instead

#

LookAt makes transform.forward face the look pos which is usually incorrect in 2D

#

Only thing keeping the rotation looking sane here is the rigidbody

twin pivot
#

i do want it to go towards the look pos

wintry quarry
#

yes but that's not the right way to set the rotation in 2D

verbal dome
#

I suppose it's .right in your case as you were adding relative X force

twin pivot
#

ah thanks

twin pivot
verbal dome
#
var dirToTarget = enemies[1].transform.position - _attackObject.transform.position;
_attackObject.transform.right = dirToTarget;```
#

Basically "Make my right side face the enemy"

wintry quarry
#

this^ yeah

twin pivot
#

i see thanks

wintry quarry
#

it could be .up or .right depending on how your sprite is laid out

#

usually .right

twin pivot
#

i have it at (0,270,0) rotation cause LookAt was causing it look wonky otherwise lol

wintry quarry
#

btw is enemies[1].transform inentional? Why the magic [1] there?

twin pivot
#

that was from a sleep deprived session of coding where i just wanted a working prototype so i might have a lot of technical debt here

real thunder
#

worst part about it you don't remember your debt next day

#

or at least me those scenarios

twin pivot
#

im still having the same issues with it not being relative for some reason

verbal dome
#

In what method do you add the force?

#

If Awake then that's too early

twin pivot
#
attackBehavior.Attack(GameStats.AttackType.Straight, 1);
```right here
verbal dome
#

Only thing I can think of right now is that the rigidbody and transform rotation isn't synced yet at this point

twin pivot
verbal dome
#

@twin pivot Add this to the start of Attack method and tell me what it prints when you are facing upwards:

Debug.Log("RB angle: " + attackRB2D.rotation + ", transform z angle: " + attackRB2D.transform.eulerAngles.z + ", transform right: " + attackRB2D.transform.right);```
#

I edited it a bit

twin pivot
verbal dome
#

Is it always 0 at that point no matter where you face?

#

The angle

twin pivot
verbal dome
#

Then yeah that tells us the rigidbody is not synced with transform

copper hound
#

hi, i ran into a bit of a problem, using NGO system whenever i try to go to next scene, the player/s isnt spawning in, what could be the fix here ?

verbal dome
#

@twin pivot Simplest fix, instead of AddRelativeForceX use AddForce(attackRB2D.transform.rotation * new Vector2(speed, 0), ForceMode2D.Impulse)

#

Another fix would be to set the projectile angle with rigidbody.rotation instead of using transform.

twin pivot
real thunder
#

So I made a pool of bullets
it seems that despite I get a bullet out of the pool and teleport it at the barrel point at the same frame it renders on the old spot for some time
unless I set a transform position too
how does that works exactly?
I can't expect them to by synced?

#

I suspect that till new fixed update kicks in the rigidbody is on the old position?

keen dew
#

Setting the transform position is how you teleport things with a rigidbody. You don't need to touch the rigidbody position.

wintry quarry
real thunder
swift crag
#

which means your attempted move will be ignored

#

If you need the Transform to wind up in the right position instantly, then setting both positions will work, as will setting the Transform's position and then calling SyncTransforms

swift crag
wintry quarry
#

I was explaining the rendering issue

swift crag
#

oh, I see

#

I was reading that backwards

#

I'm so used to SyncTransforms being used to solve the opposite problem

#

I wonder how hard it'd be to make a little demo game that shows the various ways you can have problems with transforms and rigidbodies

#

You'd have to find a way to give a "slow motion" view of what would normally be single-frame or single-physics-tick discrepancies

real thunder
#

I use a script capable of changing framerate into terrible values and a script to change timescale for those purposes

#

to see if something goes wrong

#

last time I was making a game with a "teleport everything to 0 0 0 if too far" system
unpleasant

swift crag
verbal dome
#

Can confirm that having a dedicated slow-mo button is great for debugging interpolation/rb/framerate related issues

swift crag
#

off-by-one-frame options are really easy to spot when the frames are big

#

I should add that to my game

#

I have the opposite: a mode that turns off all rendering and then cranks up the timescale to absurd values

#

it's useful for quickly "soak testing" the game to see if anything bad happens over time

real thunder
#

my side mouse buttons increase/decrease timescale inbetween values like 0.01 0.1 0.5 1 2 ect

swift crag
#

I'll try adding a "debug mode" slow motion that doesn't do that

real thunder
#
public class TestGameSpeed : MonoBehaviour
{
    public float[] time_values;
    public int framerate = -1;
    public float gameSpeed = 1;
    void Start()
    {
        if (Application.isEditor)
        {
            Application.targetFrameRate = framerate;
            Time.timeScale = gameSpeed;
        }
    }
    void OnValidate()
    {
        Application.targetFrameRate = framerate;
        Time.timeScale = gameSpeed;
    }
    void OnApplicationQuit()
    {
        Application.targetFrameRate = -1;
        Time.timeScale = 1;
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse4))
        {
            if (Time.timeScale == time_values[0])
            {
                Time.timeScale = time_values[1];
            }
            else if (Time.timeScale == time_values[1])
            {
                Time.timeScale = time_values[2];
            }
            else if (Time.timeScale == time_values[2])
            {
                Time.timeScale = time_values[3];
            }
            else if(Time.timeScale == time_values[3])
            {
                Time.timeScale = time_values[4];
            }
        }
        else if (Input.GetKeyDown(KeyCode.Mouse3))
        {
            if (Time.timeScale == time_values[4])
            {
                Time.timeScale = time_values[3];
            }
            else if (Time.timeScale == time_values[3])
            {
                Time.timeScale = time_values[2];
            }
            else if(Time.timeScale == time_values[2])
            {
                Time.timeScale = time_values[1];
            }
            else if(Time.timeScale == time_values[1])
            {
                Time.timeScale = time_values[0];
            }
        }
    }
}

this script is horrible
I like it

slender nymph
#

you know you can just increment/decrement the index, use the % operator until it is within range, then just use that value instead of . . . that, right?

real thunder
#

originally there were more elses
can't send more without nitro

real thunder
#

yeah usually I increment decrement index... but then I clamp it with < 0 / > length
how would % helps?

midnight tree
slender nymph
midnight tree
real thunder
#

I do use switch but rarely and I have to look up on syntax every time
this time it just started with 2 speeds and then ctrl c ctrl v go brrr

midnight tree
#

So maybe there is an error in if else logic... lol

Press F

real thunder
#

...right, the advantage is that I don't have to store current timescale anywhere and don't need to interate through array to see what timescale value index is now

#

now script feels even more cursed

slender nymph
#

well what does it look like now

real thunder
#

I don't really have a motivation to change it since it work but sure hold up

#
public class TestGameSpeed : MonoBehaviour
{
    public float[] time_values;
    public int framerate = -1;
    public float gameSpeed = 1;
    public int picked_index = 3;
    void Start()
    {
        if (Application.isEditor)
        {
            Application.targetFrameRate = framerate;
            Time.timeScale = gameSpeed;
        }
    }
    void OnValidate()
    {
        Application.targetFrameRate = framerate;
        Time.timeScale = gameSpeed;
    }
    void OnApplicationQuit()
    {
        Application.targetFrameRate = -1;
        Time.timeScale = 1;
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse4))
        {
            if(picked_index + 1 < time_values.Length)
            {
                picked_index++;
                Time.timeScale = time_values[picked_index];
            }
        }
        else if (Input.GetKeyDown(KeyCode.Mouse3))
        {
            if (picked_index - 1 >= 0)
            {
                picked_index--;
                Time.timeScale = time_values[picked_index];
            }
        }
    }
}
slender nymph
#

you've still got repeated code here that could be consolidated, but it's certainly better than it was

real thunder
#

what repeated code

slender nymph
#

you can consolidate the if statements to a single clamp call and the assignment to timeScale could be one line instead of two. your outer if statements really only need to handle incrementing/decrementing the index variable

#

although personally i would change it so that you've got a property that assigns to the timeScale in its setter

swift crag
#

so essentially

// change index, either up or down
// adjust timescale

#

(rather than repeating that logic for both the "increment" and "decrement" cases)

slender nymph
#

like this:

public class Whatever : MonoBehaviour
{
  private float[] _timeValues;
  private int _index;
  public int TimeIndex
  {
    get => _index;
    private set
    {
      if(_index == value)
        return;
      _index = Mathf.Clamp(value, 0, _timeValues.Length - 1);
      Time.timeScale = _timeValues[_index];
    }
  }

  private void Update()
  {
    if(Input.GetKeyDown(upKey))
      TimeIndex++;
    else if (Input.GetKeyDown(downKey))
      TimeIndex--;
  }
}

alternatively you could use a method rather than a property, but then you wouldn't be able to increment/decrement in place or you'd need another variable

real thunder
#
void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse4))
        {
            ChangeTimeScaleInStep(picked_index++);
        }
        else if (Input.GetKeyDown(KeyCode.Mouse3))
        {
            ChangeTimeScaleInStep(picked_index--);
        }
    }
    void ChangeTimeScaleInStep(int step)
    {
        picked_index = Mathf.Clamp(step, 0, time_values.Length - 1);
        Time.timeScale = time_values[picked_index];
    }

like you expect something like that?

#

as I see yes

slender nymph
#

clamp returns the clamped value, it doesn't do it in place so you need to assign the result of Clamp back to something

real thunder
#

oh right, derp

slender nymph
#

also just FYI, but C# doesn't typically use snake_case, you should be using camelCase for non-public values and PascalCase for public ones (or camelCase for public fields per unity standards)

real thunder
#

I was always doing camelCase

#

but at some point I realized it's more comfortable to read snake_case

#

as a bonus it makes it easier to tell apart unity API from mine

slender nymph
#

well, just so long as you are consistent with it and are aware that it will probably be pointed out to you a lot when you ask for help

real thunder
#

I used ++ like it represent number and clamp like it's a method

#

oh boy I only now learn that there are ++i and i++ different operands

tender mirage
polar acorn
#

++i will increment the value before returning it. i++ will return the value as it is, then increment it.

#
int i = 3;
Debug.Log(i); //prints 3
Debug.Log(i++); //prints 3, then changes i to 4
Debug.Log(++i); //changes i to 5, then prints 5
frail hawk
#

dont ask me where you´d use the preincrement

tender mirage
#

Thank you, i was really trying hard to think of something.

real thunder
#

doesn't work with postincrement

polar acorn
real thunder
#

yes, this code doesn't work 😢

#

I had to replace with pre increment

tender mirage
#

I guess maybe in a enum? You can loop and wrap the value around. And if Enum.GetValues(oftype(MyEnum).Length is exceeded. You can wrap it back around to zero and you would use ++i for the value change

slender nymph
polar acorn
hushed sky
#

which channel is there for help with unity problems?

polar acorn
#

Any of them. Whatever's closest to the subject of your question

frail hawk
#

you already posted it in the right channel

hushed sky
#

unity talk?

frail hawk
#

yes

spark whale
#

(i think this is the right place for me to post this?) For reference I don't know much about programming outside of a few months of C++ (not very useable in unity, I'm aware).
I'm following a tutorial for animating a sprite sheet for a top-down game, recreated the script from the video, IIRC it's for handling the animations alongside movement, but when I go to compile to test the game, I get the error code "The type or namespace name 'animator' could not be found (are you missing a using directive or an assembly reference?)".
I think I grasp the general idea of what it means (it can't link "animator" in the script to anything else, i think? I'm probably wrong), but I'm confused on how to fix itand what it fully means.
This is probably something very simple though.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class playermovement : MonoBehaviour
{
    private float moveSpeed = 5f;
    private Rigidbody2D rb;
    private Vector2 moveInput;
    private Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<animator>();

    }

    // Update is called once per frame
    void Update()
    {
        rb.velocity = moveInput * moveSpeed;
    }

    public void Move(InputAction.CallbackContext context)
    {
        animator.SetBool("iswalking", true);

        if (context.canceled)
        {
            animator.SetBool("iswalking", false);
            animator.SetFloat("lastinputx", moveInput.x);
            animator.SetFloat("lastinputy", moveInput.y);
        }
        moveInput = context.ReadValue<Vector2>();

        animator.SetFloat("inputx", moveInput.x);
        animator.SetFloat("inputy", moveInput.y);
    }
} ```
sour fulcrum
#

!ide

radiant voidBOT
sour fulcrum
#

your code has animator not Animator in the getcomponent

#

ideally your ide should be yelling at you about that

spark whale
#

but it isn't configured, I see

#

it completely left my mind that C# is case-sensitive, thank you, I'll work on configuring my IDE now

sour fulcrum
#

yellow are variables
red are types

stuck parrot
#

can someone help me with my camera control script? I get an error and I cant figure out how to fix it

using UnityEngine.InputSystem;
public class CameraController : MonoBehaviour
{
    public float sensitivity = 100f;
    public float pitchClamp = 90f;
    private Vector2 lookInput;
    private float xRotation = 0f;
    private float yRotation = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }


    public void OnLook(InputAction.CallbackContext context)
    {
        lookInput = context.ReadValue<Vector2>();
    }

    private float GetXRotation()
    {
        return xRotation;
    }

    void LateUpdate()
    {
        float mouseX = lookInput.x * sensitivity * Time.deltaTime;
        float mouseY = lookInput.y * sensitivity * Time.deltaTime;
        yRotation += mouseX xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -pitchClamp, pitchClamp);
        transform.eulerAngles = new Vector3(xRotation, yRotation, 0f);
    }
} ```
#

in late update yRotation the xRotation variable is marked as an "expected error"

sour fulcrum
#

show the error

stuck parrot
#

says compiler error but I dont know what went wrong

polar acorn
#

Lines need to end in a ;

stuck parrot
polar acorn
#

It's underlined in red

cosmic dagger
#

it's underlined where the error is at . . .

#

place that on a new line and you're good . . .

stuck parrot
#

yes I saw the underline but for some reason didnt notive the missing ;

supple flume
#

can someone explain how does insideUnitcircle work
the docs cover so lil about it

#

circle my bad not sphere

frail hawk
#

well it simply returns you a point inside a circle

supple flume
frail hawk
#

imagine you have a circle and you want some random point on that

#

it doesnt have a position it simply returns you a vector2

#

could you tell us what you want to do maybe there is something you are missing

frosty hound
#

To be clear, it's not giving you a position within a circle from a given point

#

As in, not a point around say, your character.

stuck parrot
#

does anyone have experience in how to make a camera movement work. rotating the camera around the character uning mouse or right joystick? I have a look action in the input system that reads delta mouse or right stick as a vector 2 value but it doesnt seem to work

hallow sun
stuck parrot
frail hawk
#

yeah but that would not rotate the cam around your object anyways

hallow sun
#

oops guess im old

stuck parrot
# hallow sun oops guess im old

not what i meant 😄 im just learning unity for about a month now and didnt do coding in my life. all of the millions of different things are overwhelming and since i started learning the new input system i kinda try to ignore the old input method 😅

frail hawk
#

what kind of behaviour do you want exactly nuke

#

you want the cam to move around the player in a circle while always looking at it?

#

but with user input if i understood correctly

stuck parrot
supple flume
stuck parrot
hallow sun
#

The easiest fix for this is to rotate the player too and use transform.forward instead of Vector3.forward

supple flume
#

but what i need is
i want stuff to happen only on the edges of a circle
like this on the edges

frail hawk
#

you might want to open a thread for that nuke

stuck parrot
#

im a compleete noob at discord and unity and coding too

supple flume
solar hill
#

the thread

#

here

frail hawk
rough granite
slender nymph
hallow sun
stuck parrot
supple flume
frail hawk
#

then simply random one element from the list

supple flume