#💻┃code-beginner

1 messages · Page 582 of 1

willow torrent
#

im a beginner and even i can see the frustration...

rich adder
#

what is rayhit hitinfo

swift crag
#

Perhaps you are unclear on what this means:

out RaycastHit hit
#

You are declaring a new variable here.

  • The type of the variable is RaycastHit
  • The name of the variable is hit
warm rock
#

OH

#

that was a name

swift crag
#

In your code, you declared a variable named rayhit, with a type of RaycastHit.

You then tried to declare another variable named hitInfo with a type of rayhit

#

These two rayhits have nothing to do with each other. The first one is the name of a local variable. The second one is the name of a type (which does not exist)

rich adder
#

hitInfo is the name of the parameter of that method, its not what you need to name your variable or put that there

warm rock
#

ok no errors, gonna see the output now

#

now i feel so stupid after annoying u all that much

swift crag
#

it's just not mandatory

rich adder
#

yeah thats what I meant lol

#

my typing skills are D--

swift crag
#

i was fairly confused reading that

willow torrent
#

so uh

#

does anyone have any leftover patience to help me with a (what i hope to be) simple fix?

swift crag
#

ask your question and someone might be able to help (:

verbal dome
#

Just ask :p

rich adder
hot laurel
warm rock
#

i think output is joking now

swift crag
#

The default ToString() implementation just gives you the type name

willow torrent
#

why is it yellow

rich adder
swift crag
#

You will need to log a specific member of RaycastHit

hot laurel
warm rock
swift crag
#

such as collider or gameObject

swift crag
rich adder
#

also when you click the Pink hyperlinks they explain

warm rock
#

pink hyperlinks?

swift crag
#

the what?

rich adder
#

hyperlinks?

warm rock
#

oh that

swift crag
#

you can inspect the RaycastHit type, yes

#

you can also check the Unity documentation for a list of its members

warm rock
#

and its still same

swift crag
rich adder
warm rock
#

after adding the .collider in the end of hitInfo

polar acorn
eternal falconBOT
swift crag
#
public class Foo {
  public int field;
  public int property => 123;
  public int Method() { return 321; }
}
#

fields, properties, and methods are the most common kinds of members

polar acorn
warm rock
rich adder
#

also they have !Physics.Capsulecast

#

so its if NOT hitt

warm rock
#

ik that part

rich adder
warm rock
#

ok

#

!code

eternal falconBOT
rich adder
#

well looking a hitInfo when something is not hit makes no sense

warm rock
willow torrent
#

anyway. i am having issues with movement and the camera. I have a 3rd person game and its basic WASD movement. I have it set so if the player moves their mouse, the camera and the player will follow the position of the mouse (like in marvels rivals) but for some reason it wont look up or down.

https://paste.mod.gg/psnoarwvxqku/0

polar acorn
rich adder
warm rock
willow torrent
polar acorn
rich adder
#

Time.deltaTime is meant for keep things consistent through different FPS.

willow torrent
#

oh okay didnt know that thank you

warm rock
rich adder
#

see whats happening in the inspector etc.

warm rock
#

no output... does that mean the player is hitting nth? why is it not moving then

willow torrent
rich adder
#

also mixing new input system with old input system is weird lol

#

why are movement keys in InputSystem but the mouse uses Input class

willow torrent
#

dude its been rough. i havent ever used the input system so when i wanted to use it i kept getting videos from like 3 years ago and sometimes itd work and sometimes it wouldnt

rich adder
willow torrent
#

see thats what i had before but then the camera wouldnt follow for some reason

#

ill update the link with the previous code

warm rock
#

so the problem here is in another script?

rich adder
warm rock
#

no one said anything (I can't see a message replying or anything)

warm rock
#

i changed the value and made it not !

willow torrent
#

updated

warm rock
#

it still didnt fix it

#

it didnt give any output

rich adder
warm rock
rich adder
# warm rock

if its not logging then the conditions arent true

#

go into playmode , open the Physics Debugger and set it to Queries , lets see where its going

warm rock
#

this? debugger?

rich adder
warm rock
#

i cant see Physics Debugger

rich adder
#

oh so because it has debugger in the name you figure, just grab any

rich adder
willow torrent
#

i think i lied ngl i didnt have it set for the mouse

willow torrent
#

when you said that i could use readvalue<> I thought i did but i didnt

rich adder
warm rock
#

i dont have Rigidbody or the other thing

rich adder
#

is that the Queries tab ?

warm rock
#

oh there are tabs, my screen is just black in some areas i couldnt see it

#

what after it, it says Spheres and stuff

willow torrent
rich adder
rich adder
#

screenshot in playmode , lets first see where your capsulecast goes

rich adder
warm rock
rich adder
# warm rock

is this in playmode ? make sure you smash some keys for movedir

#

cause I aint seeing a capsulecast rn

warm rock
#

its playmode

rich adder
#

make sure movedir has some values so we can see

warm rock
#

i will try to make it [SerializeField] or smth for now

willow torrent
warm rock
#

I cant make it public/ Serialized

#

idk what to do now... its been like 4 hours trying to figure it out

rich adder
verbal dome
#

Add a [SerializeField] Vector3 testMoveDir;
And add this to your Update cs if(testMoveDir != Vector3.zero) moveDir = testMoveDir;

#

Now you have a separate variable for testing

#

You can remove it later

warm rock
rich adder
#

I mean all you needed was to press your movement keys but ok

warm rock
#

the player rotates head

#

like he is moving

#

but doesnt move

willow torrent
rich adder
#

ok but if you had values in the moveDir you can see where the cast is going

verbal dome
#

Why are you doing custom collisions btw

verbal dome
warm rock
verbal dome
#

Yes

rich adder
warm rock
#

im following a tutorial... i dont remember who here recommended it to me

willow torrent
rich adder
warm rock
#

i will try reverting what i did and go back to normal Raycast

swift crag
#

I don't see how you can explain any more clearly than that:

  • Add a field to your class named testMoveDir
  • Use it to set moveDir (instead of using keyboard input)
warm rock
#

if it works then its fine

warm rock
#

i dont understand the 2nd part

swift crag
#

what about this statement is unclear?

if (testMoveDir != Vector3.zero)
  moveDir = testMoveDir;
warm rock
#

do i just add that

swift crag
#

to your Update method, yes

warm rock
#

ok

swift crag
#

presumably after the existing moveDir calculation

willow torrent
rich adder
swift crag
warm rock
#

i get this error when making the [SerializeField]

rich adder
#

just show what u wrote

warm rock
#

'SerializeField' is a type, which is not valid in the given context

rich adder
#

oh god did you put in update..

warm rock
#

i wrote
[SerializeField] Vector3 testMoveDir; before update

#

time to ask ChatGPT to help with u

swift crag
#

You cannot declare a field in the middle of a method. That would not make any sense.

warm rock
#

but its not in update

swift crag
#

Show me what you actually wrote, then.

warm rock
#

ok

#

!code

eternal falconBOT
willow torrent
warm rock
swift crag
#

testMoveDir does not exist anywhere in this script file

warm rock
#

oh thats the before script

#

i forgot i reverted everything i did

swift crag
#

I want to see what you actually did

warm rock
#

ok

swift crag
#

That looks fine to me. Are you sure you were getting an error?

#

Perhaps you had a typo, or you originally wrote something like

#

private [SerializeField] Vector3 testMoveDir;

warm rock
#

not its [SerializeField] vector3 testmovedir

#

not private

swift crag
#

Right; I'm just trying to think of ways you'd have gotten that compile error

abstract copper
#

So im working on a tycoon game where u build stuff like a city builder and was wondering what would be a good way of retriving the selected building to build? Although i do not have any way of selecting it currently still early in development but i wanted to know what would be the best and efficent way of doing it

warm rock
#

i will just reset the part of Raycast

#

and see if it works

hot laurel
languid spire
swift crag
#

well, now it has a typo (:

#

the actual code does not have that typo

warm rock
#

my hands stopped working for a bit

languid spire
#

programming is an exact art. If you cannot be exact don't do it

warm rock
#

gonna just reset the code to what it was before the part of CapsuleCast

willow torrent
#

@rich adder come back

warm rock
#

i think i will start from the start of the Raycast part

rich adder
#

if they are its likely issue with rotation itself

willow torrent
#

thats the thing i dont know what they are supposed to be

rich adder
#

send code again

willow torrent
rich adder
willow torrent
#

yes

rich adder
#

could be overriding it with this rb.rotation

sage peak
#

Can someone tell me why the hell this doesnt work??

using UnityEngine.Click;

public class SwitchSceneOnClick : MonoBehaviour
{
    // This method is called when the player clicks on the collider
    void OnMouseDown()
    {
        // Load scene 2 when the object is clicked
        SceneManager.LoadScene(2); // Make sure scene 2 is in your build settings
    }
}
wintry quarry
#

Is the code actually running? Are there errors in the console? What's happening?

sage peak
#

Its supposed to sietch to scene 2 when I click the object, yet nothing happens

#

No errors

willow torrent
wintry quarry
#

Debug.Log to make sure the code is actually running

#

but uh

#

if you're using the new input system, OnMouseDown is not a thing anymore

willow torrent
#

rb.rotation = Quaternion.Euler(currentRotation); is what you are talking about right? @rich adder

rich adder
willow torrent
#

idk what the issue is

warm rock
#

ok so i gave up, i will start from the beginning again

obsidian plaza
#

and i imagine you have a collider on that object?

lean cipher
#

Does anyone know why the transition is getting spammed?

rich ice
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

obsidian plaza
#

ur fr

#

is it !code

eternal falconBOT
obsidian plaza
#

put a log in Jump() just to make sure it isnt being called every frame

lean cipher
obsidian plaza
#

ty

lean cipher
#

myb im new to this

lean cipher
#

only gets called once per jump

slender nymph
lean cipher
#

is there anyway i can exclude jump from any state?

slender nymph
#

no because Any State refers to any state.

lean cipher
#

yeah

#

damn

#

ok i just deleted the transition and remade it and it works now

#

idk why

#

but yipppie

wintry quarry
sage peak
wintry quarry
wintry quarry
#

If you are using the new input system you should be using IPointerDownHandler

wintry quarry
wintry quarry
#

or just... like... how do you not know lol

#

all your input handling code would be different in the two systems

frigid sequoia
#

I wanna have like a Dictionary for each Enemy prefab that basically holds the list of players and the "aggro" value they have on them (this being different for each enemy, so it's not like a value of the player itself). My question would be, if I want to do a loop to check for the highest aggro player, would this be okay to do on the Update method if the enemy and player count can reach like 20 each or would it be like kinda too much processing to do on each frame?

lofty sequoia
#

I always advocate for event driven code over looping in the Update

#

If you set a hard limit to only do it in one class and never have too many instances, probably ok

slender nymph
#

yeah event drive definitely better than looping each frame, however that's not a lot of looping being done so there likely won't be much impact on performance

lofty sequoia
#

I'd recommend making it event driven and generic so that you can reuse the code later if need be

frigid sequoia
#

So how would I do it event driven?

#

Like just update it whenver aggro is changed?

#

Cause that's probably just gonna be each frame anyways

lofty sequoia
#

yeah on aggro changed probably

frigid sequoia
#

Ya, this is meant to be like something like WoW, where basically any and all action just updates it so.....

wintry quarry
frigid sequoia
wintry quarry
#

so you can have tanking etc

night mural
frigid sequoia
#

The concept is basically kinda of an autobattler where u are like a raid leader managing a bunch of idiots

frigid sequoia
#

It would be great if I knew how they do it XD

night mural
#

I expect it's just a list of values which get updated when 'threat causing' events are processed

frigid sequoia
#

Honestly, this whole concept seems like a nightmare to code with how little do I know

night mural
#

you need to be updating things like health constantly anyway, which threat levels are tightly related to

night mural
lofty sequoia
#

sounds like a priority queue would be a good data structure to use

ivory bobcat
frigid sequoia
#

Well, basically I would want to make it so the player can like basically customize what each member of the team is gonna do on each fight before hand, si kinda of superbasic AI but highly customizable

night mural
#

in an autobattler, I'd expect there to be a lot going on every frame while the battle is happening

frigid sequoia
#

Yeah, I don't know how to do that

night mural
frigid sequoia
frigid sequoia
ivory bobcat
#

There are more frames than dots if you're referring to something other than game frames per second

#

The easy answer would be when an ability or effect is read from the stack or queue

night mural
#

you'll have enough going on that 'every frame' seems like a reasonable enough starting point for processing any of this

frigid sequoia
#

So maybe I could have like a method that is called each second to Update the aggro, and calculate dots and all, those kinda of things don't need to happen each frame

night mural
#

both in terms of keeping the threat list up to date and retargetting, neither of which will require many resources

frigid sequoia
#

A 1 sec margin of error I would say is fine

wintry quarry
#

I mean how many characters would even be involved in a fight?

You can just have Dict<character, float> for each threat level and then the enemy can, once every 100ms or something, jsut iterate over the whole dict and see whose threat is highest.
What would there be like 40 max?

ivory bobcat
simple cedar
#

Hi I'm looking for someone who knows very well in vehicles I have a problem it's been 4 hours that I've been on it ^^

night mural
#

update your threat list when you do the damage

frigid sequoia
#

I mean, I am kinda just managing smaller numbers rn, but the idea would be like usually you would be dealing like a one big enemy (maybe able to summon a bunch of goons) and like... 10-20 players and MAYBE like 5 pets or something like that?

night mural
#

right, none of this will be so much that you need to worry about scale

#

you should just do it and see

wintry quarry
night mural
#

my advice would be to skip all of this

#

if you have dozens of characters on screen, each with individual threat lists and all interacting with each other, that's going to be a soup that the player can't parse anyway

#

this system will be invisible

#

and your real problem (which you have identified already) will be giving the player control of this in a way that feels like their decisions matter

#

so I would actually start there

ivory bobcat
night mural
#

WoW's threat system is designed around a very different kind of gameplay than you're going to have and probably doesn't make sense for your gameplay goals

frigid sequoia
#

But they would just target whatever is closset/has less health if they have like no command

#

So players would not follow the same aggro rules than enemies

night mural
#

if I think about other autobattlers like TFT, everyone just attacks their closest target until it dies or they get stopped from attacking in some way (e.g. CC or they go out of range)

#

and the way that players do what you are describing is by trying to position their people so that the closest thing is the one they want

#

or, knowing that this character will jump to the backline, so positioning them to do that optimally

#

you might be able to design around it, but generally 'who should this character be attacking' is either an obvious answer that you can specify beforehand (healer-dps->tanks), or super dynamic (like an RTS)

#

which is maybe fine, but I bet you could start with a much simpler system that accomplishes similar goals more directly

#

e.g. what if you can put your people into control groups, then tell a specific group to target a specific enemy/area?

#

no need for any kind of threat lists at all

night mural
#

if that's what you want, assign tags to the types of units and let the player set the prioriites of those tags, and then you can do targetting based on them without needing any kind of threat list

frigid sequoia
#

The idea is that this would not work either like tft (where you just drag them near their preferred target) not like a rts where u can just issue them commands over the game

#

You have like extremely limited control during the actual fight (like maybe u have like 4 buttoms with commands like "these players move to the previously marked waypoint") and the rest must be issues before the fight begins

#

The gimmick being that organizing them is the actually challenging part rather than creating a team comp

swift crag
#

maybe i don't need an elaborate exposure-based vision system where enemies can see you more clearly if they're dark-adapted

night mural
frigid sequoia
#

It's kinda of a... complex puzzle solving?

night mural
frigid sequoia
#

But ya, maybe I can just scrap the whole aggro system and say that enemies just swap aggro between tanks while there are any and else they just hit whatever is closest

night mural
night mural
night mural
night mural
#

give them a button where they can select a tank to AOE taunt

#

or do a big stun or something

#

sort of like minion masters/clash of clans, where it's an autobattler, but you also have various buffs/spells that you can throw out

#

and if your gimick is realtime zone and aggro management during the battle, I can totally see that (have the spells create walls or push units around which causes them to 'retarget nearest', or push/pull them into an area or towards a unit/trap, etc)

frigid sequoia
#

I just thought it would e funny to have stuff like, if you have like a overgeared dude that is popping out to take away aggro from enemies just like would happen in any of those games

#

So you have like sorta of a extra layer of stuff to think about

#

But maybe having a whole system just for that is kind unnecessary, and also not really that fun of a system

night mural
# frigid sequoia I just thought it would e funny to have stuff like, if you have like a overgeare...

right, it's good to keep stuff like this for your final vision! but if you're still just testing out your mechanics, you need to build a whole character, gear, stats, and threat systems in order to get something like that working...only to find out that with all that complexity, it's hard for the player to tell that their actions through these varying systems combined into this specific effect in the battle

#

instead you could just be like 'this is the high damage archer character and their attacks have a 50% change to pull aggro' and now:

  1. the player understands directly from that description how this character works without having to infer it from emergent interactions between multiple complex systems
  2. you can implement that quickly to see if it's even fun or interesting and then iterate from there
#

you could also try it more systemically 'if a character takes more than 10% of their health in one blow, they switch to that target'

#

go for the simplest route to the outcome you think you want so that you can see if that's true and hone the specifics

mystic lark
#

is there any way i can put the object that is coliding with this object into an array but without tags and that?

mystic lark
#

tnks

slender nymph
potent hornet
#

Let's say:

I have a public variable in my code --> my code works

I change that public variable into private, and suddenly my code doesn't work and I get an error thrown about some object not being referenced

What's weird to me is that I'm only changing it to private so I don't have to look at it in the editor, I don't reference that public variable in any other script. Is there a reason why changing a variable from public to private would do this?

wintry quarry
#

private are not

mystic lark
potent hornet
#

but why does that change whether the code runs

wintry quarry
#

It doesn't change whether any code runs

potent hornet
#

I didn't set a value in the inspector in the first place

#

Should've mentioned that

wintry quarry
slender nymph
wintry quarry
mystic lark
#

ok ill try

potent hornet
#

The error I get: "Object reference not set to an instance of an object"

The error happens somewhere in the RemoveButtons loop. When it's called the first time, moves_to_select.Count is 0

wintry quarry
#

as an empty list

#

when you make it private, it's not serialized so it remains null

slender nymph
#

also keep in mind that = new() is only applying to the second one

wintry quarry
#

your field initializer is only applied to the second variable as well

#

yeah

potent hornet
#

Ic

#

Thank you

mystic lark
#

I am getting an error that i cant delete objects inside prefabs i tried searching and i cant find any answers just more poeple with the same problem ?

wintry quarry
#

don't do that

north kiln
#

You need to destroy whatever you've instanced instead

wintry quarry
north kiln
#

though it's weird that your list would have anything but instances in it

mystic lark
wintry quarry
#

that doesn't matter

#

once you instantiate it, it's not a prefab anymore

north kiln
#

It would be helpful to see the entire stack trace

wintry quarry
#

The only way I can see this error happening here is if you dragged and dropped a prefab into the list in the inspector, or if some other script added one to that list

north kiln
#

The script hasn't been saved

#

so what we're looking at is different, so perhaps the list is public

wintry quarry
#

oh that too

north kiln
#

and has something assigned in the inspector

mystic lark
#

its saved i have a prefab with 4 objects in it and i want to dellete the part of the prefab that collides with the trigger so i put them in a list and del them after the list size is 10

wintry quarry
north kiln
#

If you saved it and it's the same as what you showed above then it wouldn't be firing errors

wintry quarry
#

It might even be a totally different script causing this error

acoustic belfry
#

whats the best way to make a player shoot in a 2D space following the mouse? cuz i made this script but the proyectiles dont follow a normal speed, i mean, for example when the player falls from a high place with a lot of speed, when i shot the proyectiles down they go up instead of being shot down due the speed of the player falling

#

btw this is the script

#
    void rifle_shooting()
    {
        Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mouseposition.z = 0;
        Vector3 shootDirection = (mouseposition - transform.position).normalized;

        GameObject riflebullet = Instantiate(rifle_bullet, transform.position, Quaternion.identity);
        riflebullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(shootDirection.x, shootDirection.y) * rifle_bulletspeed;

    }```
warm charm
acoustic belfry
# warm charm Try adding the player's rigidbody linearvelocity to the bullet.

like this?

void rifle_shooting()
{
    Rigidbody2D playerRigidbody = GetComponent<Rigidbody2D>();

    Vector2 playerVelocity = playerRigidbody != null ? playerRigidbody.velocity : Vector2.zero;

    Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    mouseposition.z = 0;

    Vector3 shootDirection = (mouseposition - transform.position).normalized;

    GameObject riflebullet = Instantiate(rifle_bullet, transform.position, Quaternion.identity);

    Rigidbody2D bulletRigidbody = riflebullet.GetComponent<Rigidbody2D>();
    if (bulletRigidbody != null)
    {
        bulletRigidbody.velocity = new Vector2(shootDirection.x, shootDirection.y) * rifle_bulletspeed + playerVelocity;
    }
}
#

sorry if its wrong, i just i didnt fully understood how...and due how slowly the game test runs due my shitty cpu i wanted to make sure before testing

warm charm
#

Looks good. It should conserve the player's momentum.

acoustic belfry
#

nice

#

thanks :3

warm charm
#

Probably change velocity => linearVelocity in the future, as velocity is deprecated.

acoustic belfry
#

oh, right, i forgot

warm charm
#

But it does the same thing, it was deprecated in 6.

acoustic belfry
#

ah, makes sense

#

well, thanks :3

#

em...for a strange reason when i jump the bullets go up, why this happens?

#

i mean, i guess is supossed to maybe the values of the player changing for make it jump...but how do i fix it, also this is a hypothesis

warm charm
#

Are your bullets being childed to your player?

acoustic belfry
#

idk, maybe?

#

i mean cuz is a prefab that spawns

#

so technically aren't in the player arquitecture

#

but comes from it

#

so...maybe?

warm charm
#

Check your scene tree during play and see if your bullets appear at the root of the tree or under your player, if so then when the player jumps the bullets will also jump with them

acoustic belfry
#

nah they dont

candid path
#

Could someone explain to me why the 'bundle' bar does not appear and what to do about it?

acoustic belfry
#

mmm and honestly, the script still doesn't work at all, the bullets still dont follow very well the movements, better than before, but not perfectly

#

and at this point i dont know what to do

warm charm
acoustic belfry
#

its like a run shooter plataformer

#

where the bullets aim to the mouse

#

i mean, you aim to the mouse

#

and also an important detail of the game is that you move, a lot

warm charm
#

Got it, I have a small prototype like it, let me copy the code.

acoustic belfry
#

is more like a Doom Eternal/UltraKill but in 2D

acoustic belfry
rustic pasture
#

Hi im new to unity and im trying to get my script to recognize the prefabs i made but its not being detected. Below in the picture is the error im getting

rustic pasture
#

Sorry if im unclear im still new

#

i made a prefab extrapoint is a target that will spawn in and give you extra points when clicked

#

its a 3d object

polar acorn
rustic pasture
#

should i write script for those individually then link them back to the game manager?

polar acorn
#

Is there a script of any sort on these objects you intend to be using?

rustic pasture
polar acorn
#

First off, you should decide what you are going to need these objects for

#

Do they just have to, like, exist? Or are you gonna need them to do anything?

rustic pasture
#

For context you just click targets and get points

warm charm
# acoustic belfry interesting :3

I can paste the whole files but they're rather big.

I think removing the player's velocity from the calculation could be a start. I was thinking from an Asteroids perspective when suggesting that. You might need to adjust the speed of the bullet to start. Maybe like "bulletSpeed = playerVelocity.magnitude + initialBulletSpeed"

rustic pasture
#

they spawn randomly and those prefabs are supposed to be dsifferent targets one gives you extra points and disappears faster and the other takes away if clicked

warm charm
cosmic dagger
#

Mainly, you'd use the type you need to avoid calling GetComponent. There's no reason to use a GameObject variable . . .

hollow zenith
#
        // the private backing field
        private int _maxHealth;

        // read-only, returns backing field
        public int MaxHealthReadOnly => _maxHealth;

        // equivalent to:
        // public int MaxHealth { get; private set; }

it says to use expresion-bodied properties to "shorten", but isn't the second method shorter?
This is from Unity code style guidelines.

#

I always felt like specifying a backing field manually is more code, is there any benefit to it that you can't achieve with a 1 liner?
The only reason I can imagine is to make sure that it's clear to other coders that this field is meant to be readonly.

polar acorn
#

It's easier to expand functionality later. That's basically it

wintry quarry
polar acorn
#

Also yes, you could just call them both MaxHealth

wintry quarry
#

Wait sorry the second one IS the expression -bodied member

hollow zenith
#

I just copied it, but I didn't notice that, it makes sense now that I look at it 😄

#
member => expression;
#

This is what I found, so I assumed it's the first one

wintry quarry
#

I misunderstood what you meant by first and second here

#

I was considering the field alone as the first

hollow zenith
#

by first i mean first 2 lines of code since they belong to the same property

#
        // - Use the expression-bodied properties to shorten, but choose your preferrred format.
        // - e.g. use expression-bodied for read-only properties but { get; set; } for everything else.
#

This is actually interesting, because that's the code I got from someone here in the past for "serialized readonly property" 😄

#
public string WeaponName => weaponName;
[SerializeField] string weaponName;
teal viper
#

I mean, the comments say it all "choose your preferred format"

hollow zenith
#

Yeah, I just got confused when it says "to shorten"

teal viper
#

They probably imply that you can define quite a bit of logic in getters/setters, which would indeed be longer.

#

The auto properties approach would be the shortest one no matter how I look at it.

hollow zenith
#

yeah I think they referred specifically to this:

member => expression;

It's just that their example uses a backing field

teal viper
#

There's a difference between using a backing field or not, and properties vs auto properties.

#

And separately + expression bodied members.

hollow zenith
#

What do you mean by separately?

#

But wouldn't that mean that I should never use: public int MyProp { get; private set; }

#

I mean except but choose your preferrred format., but I am trying to see their point 😄

#

actually it's referring to shortening, next line:

        // - e.g. use expression-bodied for read-only properties but { get; set; } for everything else.

Enforces that I use expression-bodied for read-only if I want to follow their style guidelines

teal viper
hollow zenith
#

Yeah that definitely makes much more sense

#

and I can see a shorthand version being easier to read, especially as you add more of these properties 😄

teal viper
teal viper
hollow zenith
#

They do mention it, just not as read-only

buoyant finch
#

the movement now works but now the animation freezes even when the z key is released and it stays in the run blend tree without switching to the walk one and the freezing animations are now also staying for longer like one state is being repeated for 3 keys or so script - https://paste.ofcode.org/Ftdf37bDpS8fGPqRz2VNDZ pls help fix it

hollow zenith
#

Also this is just a guess, but this code will become a pain to maintain as you add more states.
Check out some state handling guides out there.
Once you add jumping, attack you will have to handle these while your character is: idle/walking/running and later crouching/sliding or w/e you add.

With so many if/else statements it's difficult to read as well.

#

for example you can return after line 85 and remove else block

#

to reduce 1 nested block

buoyant finch
buoyant finch
#

I will refactor the code later once I get this right

hollow zenith
#

My suggestion is to simplify it:
Remove all code and simply make character play running animation when you press A then make it play Walk animation when you press S then with D you play Idle animation

#

See if that works

#

If that works then you are good to go, if it doesn't then it's an issue with an animator(probably)

hollow zenith
#

Also did u use chat gpt to write this code?

#

it looks like it

#

You shouldnt have comments on every single line of code

#

Never write comments that are useless, it makes it difficult to read code

buoyant finch
#

ok so when I use the z key and move it shows only moving and not running

#

also the frames which are of 4 are extended till 6 or 7

hollow zenith
#
    private void UpdateAnimator()
    {
        if (isMoving)
        {
            animator.speed = 1f;
            return;
        }

        if (isRunning)
        {
            AnimatorStateInfo currentState = animator.GetCurrentAnimatorStateInfo(0);

            if (currentState.IsName("Run"))
            {
                animator.speed = 1f;
            }
        }
        else
        {
            AnimatorStateInfo currentState = animator.GetCurrentAnimatorStateInfo(0);
    
            if (currentState.IsName("Walk"))
            {
                animator.Play("Walk", 0, currentState.normalizedTime);
            }
        }
    }
#

Not perfect, but it should do same thing and be a bit easier to read

buoyant finch
hollow zenith
buoyant finch
teal viper
buoyant finch
hollow zenith
buoyant finch
hollow zenith
hollow zenith
#

are you copy pasting whole class from chat gpt each time?

buoyant finch
teal viper
#

Basically the "equivalent" is sort of a lie

hollow zenith
#

I thought they do the same thing which is to make this property a read only?

#

I always used the second one, unless I needed to do explicit setters(for null checks and what not) then I'd have to make my own backing field anyway.

#

They don't show much for these examples tho, so I am still lost on that part, but maybe there is more in the book.

teal viper
#

An actual equivalent is the one that is below that comment with a backing field. Aside from the part that the setter is public

hollow zenith
#

I see

#

Btw if a property getter/setter would span multiple lines is it still a good idea to use a property?

#

I can probably use some math functions usually or ternary operator but if I want to do some checks, would a method be a better choice?
I can still use expression-bodied property and call a function right?

#

maybe I am confusing it with something else, I can't find that example now

teal viper
teal viper
hollow zenith
#

So clamping a value would be modifying it, but I'd still keep it in a property probably
Other than that I think any logic would be used to modify the property or throw an error maybe?

#

If there is logic in a property then it will modify a property, otherwise what is the point of it(other than to throw an error/warning)

#

Maybe I am overthinking it, but any logic is modyfing something 😄

teal viper
#

The rule of thumb is be consistent in your code.

#

Everything else is up to you

teal viper
hollow zenith
#

Makes sense, I did realize that I follow a lot of these guidelines already, but that's probably VS helping me along the way.
I am glad that I don't have to istall Eslint or other things to get these benefits 😄

teal viper
#

The conversion logic could be in the property

hollow zenith
#

so getter and setter would be of different type?

acoustic sequoia
#

hey everyone, I'm using transform.up and a direction in my 2d game to have an enemy object always look at the player. but when i'm crossing over the southern cardinal direction, the enemy flips it's rotation. how do i prevent this?

hollow zenith
#

or you mean a backing field specifically

acoustic sequoia
#

here is my code

  transform.up = direction;```
hollow zenith
#

So you have to convert back and forth, I can't imagine a use case for it atm, but I suppose there might be one
maybe using same backing field with multiple properties?

teal viper
teal viper
#

And vice versa

hollow zenith
#

Yeah I just asked chat gpt to give me an example and it converts a Vector3 to an array of floats.

acoustic sequoia
# rich adder wdym like its too fast ?

no, i think i solved it with this code

transform.rotation = Quaternion.LookRotation(Vector3.forward, direction);

which replaced

transform.up = direction;
acoustic sequoia
rich adder
acoustic sequoia
acoustic sequoia
#

the red point is the enemies relative point for the other two

rustic pasture
#

Hi im having trouble solving an error

rich adder
wintry quarry
rich adder
#

are you trying to Instantiate an object that was destroyed?

rustic pasture
#
{
    [SerializeField]
    private Target targerPrefab;
    [SerializeField]
    private DontHit DontHitPrefab;
    [SerializeField]
    private ExtraPoint ExtraPointPreFab;
    [SerializeField]
    private float spawnTime = 0.5f;
    private float spawnTimeCurrent = 0f;
    [SerializeField]
    private int points = 0;
    int count = 0;
    // Update is called once per frame
    void Update()
    {
        spawnTimeCurrent += Time.deltaTime;
        if(count < 100)
        {
            if (spawnTimeCurrent > spawnTime)
            {
                count++;
                SpawnNewTarget(Random.Range(0,3));
                spawnTimeCurrent = 0f;

            }
        }
    }
    private void SpawnNewTarget(int type)
    {
        if (type == 0)
        {
            Target temp = Instantiate(targerPrefab, new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), 0), Quaternion.identity);//create a temp version of this object
            temp.gameManager = this;
        }
        else if (type == 1) 
        {
            DontHit temp = Instantiate(DontHitPrefab, new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), 0), Quaternion.identity);//create a temp version of this object
            temp.gameManager = this;
        }
        else 
        {
            ExtraPoint temp = Instantiate(ExtraPointPreFab, new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), 0), Quaternion.identity);//create a temp version of this object
            temp.gameManager = this;
        }
    }
    public void addPoints(int additionPoints)
    {
        points += additionPoints;
        Debug.Log("Player points "+points);
    }
}```
#
{
    public GameManager gameManager;
    [SerializeField]
    private int myPoints;
    private float timeLeftOnScreen = 3f;

    void Update()
    {
        timeLeftOnScreen -= Time.deltaTime;
        if (timeLeftOnScreen <= 0)
        {
            Destroy(gameObject);
        }
    }

    private void OnMouseDown()
    {
        myPoints = -50;
        gameManager.addPoints(myPoints);
        Destroy(gameObject);
    }
}``` This is the code for one of my other objects
rich adder
rustic pasture
#

Im trying to refrence them from a folder

#

but its seems not to be working and im a bit confused on that aspect

#

I have a prefab folder with the prefabs in it

#

but my main script cant find them

slender nymph
rich adder
rustic pasture
wintry quarry
rich adder
wintry quarry
#

and that means you deleted them or destroyed them

rich adder
#

these might have been scene objects, they don't look like prefab. shouldn't they be blue

wintry quarry
#

Yeah I would guess they weren't actually prefabs in the first place

rustic pasture
#

oh so i just made them incorrectly?

wintry quarry
#

No those are fine

rustic pasture
#

this is my prefab folder

wintry quarry
#

but you need to drag those into the slot

rich adder
wintry quarry
#

not ... something else

rich adder
#

you maybe put the original ones?

#

in the scene/hierarchy

rustic pasture
rich adder
#

show that

rustic pasture
#

i cant drag the other two prefabs i made into it

rich adder
#

screenshot the whole window dont crop

rustic pasture
wintry quarry
#

Do the prefabs have the appropriate components on them?

#

You need the DontHit and ExtraPoint scripts on them, respectively

#

I would guess you don't have those

#

show the inspectors of the prefabs (ideally the whole unity window with them selected)

rustic pasture
#

omg yes that what it was

#

im so sorry for the silly question xd

wintry quarry
#

Seems like you had them at one point and deleted them

rustic pasture
#

So just for my clarification the reason why it wasn't working was because i didn't have the right components attached to the prefab?

wintry quarry
#

You had a reference to the component on the prefab originally

#

later you deleted the component from the prefab

#

so the reference was broken

#

Also you weren't able to reassign it because the prefab now was missing the expected component

rustic pasture
#

ooh thank you that makes sense

#

i def not be making that mistake again lol thank you so much! @wintry quarry @rich adder

buoyant finch
#

hello so I have this code which has all the movement needed but the issue is that I have an animation freezing system and the walk animations freeze and after 4 frames they should reset the walk animation but they continue by repeating for 6 to 7 frames and then are switched pls someone explain how to fix it all the animations are of 5 fps

teal viper
buoyant finch
teal viper
buoyant finch
teal viper
#

Also, your UpdateAnimator() method definitely seems suspicious. Why would you need to modify the animator speed? It's really sketchy.

buoyant finch
buoyant finch
teal viper
teal viper
#

The animation is not updated by frame. It's updated with delta time.

buoyant finch
buoyant finch
teal viper
#

Honestly, just don't use animator

#

It's not meant for frame precise control. Change the sprite via code or something

buoyant finch
teal viper
#

Besides, it doesn't look like you're too far in to refactor your system.

buoyant finch
teal viper
buoyant finch
#

there must be anything which can be done right?

teal viper
#

Sometimes that something is to realize that your approach is not gonna work and rework it.

buoyant finch
teal viper
#

If you really wanted to, you can do that I guess. But I wouldn't recommend that

buoyant finch
buoyant finch
teal viper
teal viper
buoyant finch
teal viper
#

You can implement it as a separate script and call it's methods from your script.

acoustic sequoia
#

hey why is this returning null?

private void OnCollisionEnter2D(Collision2D other) {
  if(_hasHit) return;
  _hasHit = true;
  other.gameObject.TryGetComponent<IDamageable>(out var damageable);
  Debug.Log(damageable); <-- NULL
}
verbal dome
acoustic sequoia
verbal dome
#

How does that prove that the collided object has it 🤔

acoustic sequoia
#

because there are only two items in my game rn, 1 = the bullet, and two the snake

verbal dome
#

Try Debug.Log($"Collided with {other.gameObject.name}", other.gameObject);

burnt vapor
#

Generally, you see what is null, then you try to figure out why it's null. You claim the object has the interface, which is fine, but now you should check if you actually collide with the object that has the interface

burnt vapor
# acoustic sequoia hey why is this returning null? ``` private void OnCollisionEnter2D(Collision2D...

Also, a Try-method exists because it does a graceful attempt at something. The boolean it returns indicates if it succeeded, and one or more out parameters return a valid result, assuming the boolean returns true. In this case you don't check this boolean at all and assume that whatever you hit has the interface. You should definitely check this.

-other.gameObject.TryGetComponent<IDamageable>(out var damageable);
+ if (!other.gameObject.TryGetComponent<IDamageable>(out var damageable))
+ {
+   return;
+ }
#

If you don't do this you might as well be using the original GetComponent method and get a more clearer exception

astral falcon
#

I am actually wondering, if an interface is found by getcomponent at all?

verbal dome
#

Yeah it is

#

That's the reason that Try/GetComponent doesn't have a where T : Component constraint

#

To support interfaces

astral falcon
#

Using this so rarely, I actually forgot if or if not, thanks 🙂

verbal dome
#

I think damage dealing is pretty much the only place I use it 😁

buoyant finch
#

In this script the running animation works and all but upon freezing the sprite and pressing the button the next sprite isn't played as instead of the walk frames the idle frames are displayed pls someone help here is the script https://paste.ofcode.org/mZcUDYjMKTipzcfEw3EVnR

tough tartan
#

Learn how to create your own classic First Person Shooter in Unity!

Get the assets for this series here: https://www.dropbox.com/s/juihs7yq93x1aon/GPJ_FPS_Assets.zip?dl=0

Don't forget to hit that like button and if you'd like to see more gaming goodness then subscribe for more!

Support the show by pledging at http://www.patreon.com/gamesplu...

▶ Play video
#

Do i need an older version to allow it to work?

tough tartan
#

Yes

#

the movement is fine but the looking around isnt

verbal dome
#

What is your mouseSens set to in the inspector

tough tartan
#

im checking hold on

verbal dome
#

Roger that. Holding on.

tough tartan
#

which is what the dude in the video has

verbal dome
#

Show the inspector of your character

#

With its components visible

tough tartan
#

Okay

verbal dome
#

No other components? No animator?

#

Just making sure that nothing else is modifying its rotation

tough tartan
#

Nope nothing

verbal dome
#

Try changing transform.rotation = ... to rigidbody.MoveRotation(...)

#

That's the correct way anyway

#

When you have a rigidbody

tough tartan
#

Okay i will try

verbal dome
#

It will only take the Z angle btw, not XYZ

tough tartan
#

tes

#

Would this be changed onto line 30?

verbal dome
#

Whatever line starts with transform.rotation =

#

What else could I mean 🤔

tough tartan
#

Its a whole lotta red

verbal dome
#

You replaced rigidbody with your own rigidbody variable name, right?

tough tartan
#

Yeah its red itself

#

oh wait

#

sorry

#

Im running to see

#

still nothing

verbal dome
#

Debug.Log the moveInput before you rotate the character

#

Also make sure you haven't constrained the rigidbody's rotation in the constraints tab

tough tartan
#

like how would i find the constraints tab

verbal dome
#

In the rigidbody inspector.

tough tartan
#

Theres nothing on

tiny wind
#

Hi, I have a problem where my player doesnt play the hurt or die animation when taking damage

 public void TakeDamage(float _damage)
 {
     currentHealth = Mathf.Clamp(currentHealth - _damage, 0, startingHealth);
     
     if (currentHealth > 0)
     {
         anim.SetTrigger("hurt");
         //iframes
     }
     else
     {
         if (!dead)
         {
             anim.SetTrigger("die");
             GetComponent<PlayerMove>().enabled = false;
             dead = true;
         }
     }
 }

this is the code for it, im just follwing a tutorial

tough tartan
verbal dome
#

Ok, just had to check that it isn't an input problem

verbal dome
#

And have you set up the animator properly to use those triggers

tough tartan
#

would u think its a problem with me using a later version of unity

verbal dome
#

Nope

tough tartan
#

Cuz the video uses 2019

verbal dome
#

None of this has changed except for velocity -> linearVelocity which you already changed

tough tartan
#

This is needed for my cs project and i cant find any tutorials that work properly

verbal dome
# tough tartan

Oh btw I misspoke, I meant debug the mouseInput not moveInput

tough tartan
#

oh okay

#

Its just saying 0.00, 0.00

#

when i move it

verbal dome
#

Are you clicking the game view to focus on it?

tough tartan
#

yep

verbal dome
#

It won't detect mouse if you dont

tiny wind
#

i think

verbal dome
tough tartan
#

😭

verbal dome
#

Ugh

tough tartan
#

Okg bro

tough tartan
#

Thnk u for ur hlp

hexed terrace
faint tulip
#

ohh sorry thanks

buoyant finch
#

In this script the running animation works and all but upon freezing the sprite and pressing the button the next sprite isn't played as instead of the walk frames the idle frames are displayed pls someone help here is the script https://paste.ofcode.org/mZcUDYjMKTipzcfEw3EVnR

frigid sequoia
#

Quick question, the || here is kinda redundant right?

wintry quarry
#

Well you would have already gotten a null reference exception by then

stiff birch
wintry quarry
#

It would work if it was arranged the other way around

stiff birch
#

But you should change the order

frigid sequoia
#

I am wanting to check for "as long as the list does exist and it's not empty"

wintry quarry
#

Just reverse the order of those checks

#

You can also just simplify that a bit

#

aggroTarget == null && heavyAggroPlayers != null && heavyAggroPlayers.Count > 0

#

No need for the negation and parentheses etc

frigid sequoia
#

Ya, seems better, thxs

burnt vapor
#

By default if it is null, then the null conditional with ? automatically returns false

#

It's the same as checking null, and then doing the operation, so the result is the same.

frigid sequoia
#

So if there is not much difference I am gonna stick with that one

burnt vapor
#

There are differences when gameobjects are involved. Not here, though.

keen sierra
#

i have this code but my player doesnt move or anything is there something wrong

#

using UnityEngine;

// Controls player movement and rotation.
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f; // Set player's movement speed.
public float rotationSpeed = 120.0f; // Set player's rotation speed.

private Rigidbody rb; // Reference to player's Rigidbody.

// Start is called before the first frame update
private void Start()
{
    rb = GetComponent<Rigidbody>(); // Access player's Rigidbody.
}

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


// Handle physics-based movement and rotation.
private void FixedUpdate()
{
    // Move player based on vertical input.
    float moveVertical = Input.GetAxis("Vertical");
    Vector3 movement = transform.forward * moveVertical * speed * Time.fixedDeltaTime;
    rb.MovePosition(rb.position + movement);

    // Rotate player based on horizontal input.
    float turn = Input.GetAxis("Horizontal") * rotationSpeed * Time.fixedDeltaTime;
    Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
    rb.MoveRotation(rb.rotation * turnRotation);
}

}

wintry quarry
burnt vapor
eternal falconBOT
burnt vapor
#

Preferably just use one of the paste sites with this much code

keen sierra
#

wdym correctly

burnt vapor
#

Properly formatted and using a paste site when you use large code blocks

#

See bot message

keen sierra
#

oops

frigid sequoia
#

Okay, this is kinda of a dumb question but, what's the thing that I am wanting to use here?, cause I do remember there was a thing for this, I just don't remember the name to look for it

keen sierra
#

no idea

frigid sequoia
#

Ya, exactly, thank you

#

I forgot the name of that

keen sierra
#

284?

frosty hound
# keen sierra 284?

@keen sierra Don't crosspost. And if you're not actually helping anyone or asking a question, don't post.

compact stag
#

hey guys! i was looking to make a platformer, i was wondering how would i be able to tell in which ground my player would be stepping in? as i want to make a special effect depending on what the player is stepping on

should i make a script and apply to every ground, then use a onCollisionEnter to check if the ground's tag or name is something in specific? or is there a better way?

verbal dome
grand snow
#

and to use a custom component to store the data

verbal dome
#

You can then get a component or a tag or something that stores which type of surface it is

#

The raycast could be triggered by an animation event

grand snow
#

I would do a component that references a scriptable object with the data (sound, effects), tags not so good

compact stag
#

what is a raycast? i see a lot of people talking about it

compact stag
compact stag
#

how can i know whats the best way to do something? is it just experience?

#

or how can i debug my code to find the best practices/best performance optimization

verbal dome
#

You can use the profiler to see what is slowing your game down, but don't worry about it until you actually have bad performance

compact stag
#

alright! but how can i find out what is good practice and what i can do to write better code?

#

i was thinking of using leetcode but i'm not sure

grand snow
#

ha not really gonna teach you what you want atm

buoyant finch
#

in this script I included a function to freeze animations and play them to complete them frame by frame but I want it for only walk and not for run but the run animation freezes and doesn't switch to the idle animation frames which I want pls help here is the script https://paste.ofcode.org/8F5y2sKHDeDp4UHvBXZ6gu

rugged ferry
#

I am a little confused as to how co-routines work

#

I have a script which waits for 5 seconds (yield return new waitforseconds(5))

#

but while this 5 seconds elapse the other part of my script can still execute

#

how does that work?

#

I thought waiting these 5 seconds would halt the whole script

timber tide
#

nah, coroutines are single threaded. If it halted completely unity would freeze on you

#

basically what it does is exits the code at the point and picks back up when those 5 seconds are up

rugged ferry
#

so each cycle it goes there and checks if 5 seconds elapsed?

timber tide
#

pretty much

rugged ferry
#

if it hasnt it goes to the next function?

#

okay thanks

timber tide
#

well, you can think of them as mini update loops.

rugged ferry
#

mmm i see

timber tide
#

they have independency from each other and have less overhead of a gameobject*

cedar iron
#
private bool isRunning;

isRunning = Input.GetButtonDown("Run");```



i made the keybind in input manager, but it doesn't seem to change weather I'm holding shift or not, it's always false.
#

Suspecting that isRunning = Input.GetButtonDown("Run"); is my mistake

wintry quarry
cosmic dagger
cedar iron
#

Really? It's inside the void update

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

public class PlayerMovement : MonoBehaviour
{

    public CharacterController controller;

    public float speed = 6f;
    public float gravity = -14f;
    public float jumpHeight = 1f;

    public Transform groundCheck;
    public float groundDistance = 0.2f;
    public LayerMask groundMask;

    private Vector3 velocity;
    private bool isRunning;
    private bool isGrounded;

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

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
        isRunning = Input.GetButtonDown("Run");

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        if (isRunning == true)
        {
            speed = 8f;
        }
        else
        {
            speed = 6f;
        }


        float x = Input.GetAxisRaw("Horizontal");
        float z = Input.GetAxisRaw("Vertical");

        Vector3 move = Vector3.ClampMagnitude(transform.right * x + transform.forward * z, 1);

        controller.Move(move * speed * Time.deltaTime);

        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }
}
wintry quarry
#

Read the documentation for what GetButtonDown does

cedar iron
#

How do I fix that

wintry quarry
#

Use GetButton instead probably

cosmic dagger
cedar iron
#

I see

buoyant finch
#

in this script I included a function to freeze animations and play them to complete them frame by frame but I want it for only walk and not for run but the run animation freezes and doesn't switch to the idle animation frames which I want pls help here is the script https://paste.ofcode.org/8F5y2sKHDeDp4UHvBXZ6gu

cedar iron
#

Input.GetButton is like you said thx

#

Works like expected

balmy charm
#

Hey can someone help me understand what would be the best way to make enemy ai for a 2D top down game

rich adder
balmy charm
#

like that i can have good controll of the states and behaviours mostly that and not tooo hard to implement

wintry quarry
balmy charm
#

sorry i was talking about enemy combat mostly

#

with different attacks

night mural
#
  1. be able to describe exactly how you want the AI to behave
  2. program that
    it sounds like you should spend some more time on 1
balmy charm
#

i can send a video

#

making it

night mural
#

you might have better luck watching the video

true owl
#

does anyone know how i can freeze the game for a couple frames

verbal dome
true owl
#

interesting

verbal dome
#

Unless by freeze you mean actually freezing the application lol

#

Is this for an impact effect when you hit?

balmy charm
#

the video of 10s got above the limit of discord TT

verbal dome
#

Think you can use Streamable

true owl
#

hitstop

chrome apex
#

so let's say I have a bunch of balls dropping down from somewhere and I want to add an explosion force on mouse click on mouse location that would affect all of the balls

#

do I need to add them to an array and get all of their rigidbodies and then add an explosion on mouse position?

#

seems a bit strange

wintry quarry
#

(or Physics2D.OverlapCircle if 2D)

chrome apex
wintry quarry
#

Like I said, you use OverlapSphere

#

so you can get to the RB from the collider

chrome apex
#

yea yea, I get that, it's just weird because

#

ah no wait I get it

#

explosion force creates a position

#

and adds a force to the rigidbodies I reference

wintry quarry
#

you would call AddExplosionForce on each Rigidbody you detected yes

chrome apex
#

ye ye

#

I was confused as to how the position works there

wintry quarry
#

You could also just calculate the force manually based on distance etc and use regular AddForce

#

in impulse or velocitychange mode

chrome apex
#

nah this is ok

#

I was like how can I add the same force to each

#

but I get it, it's automatically applied based on distance

wintry quarry
chrome apex
#

yep yep

#

thanks

rocky canyon
#

is there anyone here that uses snake_case_for_anything?

west radish
#

I think the only times I have is when I have some placeholder property with a descriptive name

#

its not really a naming convention I like looking at, so thats a big reason I avoid it

slender nymph
#

i use it in python but that's only because it's the standard for that language

night mural
swift crag
#

I often use it in HLSL

hot laurel
#

looks valid for hlsl since its similar to c++ syntax

hot laurel
rocky canyon
#

"screaming snake case" 🤣

swift crag
#

SCREAMING_CASE, indeed

rocky canyon
#

hilarious that thats a legit terminology 😄

hot laurel
#

if you rly want to use it for something then only native functions may be the appropriate place, so you know instantly what you deal with when you see it

nova ivy
#

Hello, I'm having an issue trying to assign a game object in my inspector, no matter what game object I pass it it says "type mismatch"

slender nymph
#

you can't drag scene objects into prefabs

true owl
#

is it possible to do like a little camera shake on a cinemachine follow camera when the user does a specific action?

#

nvm

#

figuring it out

nova ivy
true owl
#

It gives me this error when i run it

#
NullReferenceException: Object reference not set to an instance of an object
PlayerMovementScript.OnDash (UnityEngine.InputSystem.InputValue value) (at Assets/Scripts/PlayerMovementScript.cs:211)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)
wintry quarry
#

not the script you shared

true owl
#
 CinemachineShake.Instance.ShakeCamera(5f, .1f);
wintry quarry
#

Assets/Scripts/PlayerMovementScript.cs:211
Line 211^

true owl
#

this is the line i use in my player input script

wintry quarry
#

Which means most likely you simply don't have one in your scene

true owl
#

i have it tho

#

nvm

#

i figured it out

#
public static CinemachineShake Instance = new CinemachineShake();
#

changed this line in my CinemachineShake script

wintry quarry
#

this is a terrible idea

true owl
#

how come

wintry quarry
#

You can't new a MonoBehaviour

true owl
#

oh

#

i just wanted to create a single instance to use

#

singleton pattern or wtv

wintry quarry
# true owl

This is not the CinemachineShake component

#

You need an object with the CinemachineShake script attached to it

true owl
#

I do have it

wintry quarry
#

(and your script also requires it has a CinemachineCamera on it too)

true owl
#

the follow camera

wintry quarry
#

where

#

show it

true owl
#

sorry mb

#

ignore all the cinemachine stuff on the right

#

i clicked a lot of stuff

naive pawn
true owl
#

oh

wintry quarry
# true owl

That object doesn't even have a CinemachineCamera on it

true owl
wintry quarry
#

it seems to be an actual unity camera

true owl
#

mb on the screenshot

#

the main camera has cinemachine brain

#

the follow camera is cinemachine camera

wintry quarry
#

good

#

but you just changed all that it seems

#

so... pause the game, make sure the scene is saved with the correct setup

#

and try again

true owl
#

what should i do abt the line

#
public static CinemachineShake Instance = new CinemachineShake();
wintry quarry
acoustic sequoia
#

hey everyone,

i want to know what the correct approach is to solve my logic.

i have a snake enemy that has body parts in a List<BodyPart>. each bodypart has an id for order.

when one of the body parts is removed, how do i correctly update the id's of the body parts so their is no gaps in the itterator on every frame.

body parts can be removed in any order or random selection.

should i ditch the id strategy? what are your thoughts?

wintry quarry
#

the List itself maintains the order

true owl
#

hitting me with a similar issue

NullReferenceException: Object reference not set to an instance of an object
PlayerMovementScript.OnDash (UnityEngine.InputSystem.InputValue value) (at Assets/Scripts/PlayerMovementScript.cs:211)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)```
wintry quarry
true owl
#

sure

#

all this is in the OnDash()

wintry quarry
#

that really seems to be pointing to there not being a CinemachineShake in the scene, assuming Awake actually ran on it

acoustic sequoia
true owl
#

should i have used start instead

wintry quarry
#

Then you can do cs public void RemovePart(BodyPart part) { listOfParts.Remove(part); }

acoustic sequoia
naive pawn
#

it's a loop

wintry quarry
naive pawn
#

it is fast

wintry quarry
#

it will be faster

acoustic sequoia
#

so using an id is faster?

wintry quarry
#

You only use a List if you need an ordering

naive pawn
wintry quarry
#

Again, use a HashSet here if order doesn't matter.

acoustic sequoia
#

order matters

wintry quarry
#

How many body parts are there in the list?

#

Is it more than 100?

#

If not, don't worry about it.

naive pawn
acoustic sequoia
#

anywhere between 10-30

wintry quarry
#

The list will be fine

#

revisit it if you find a performance issue

acoustic sequoia
#

but there can be 10-20 of those on screen. (all sperated)

wintry quarry
#

Yeah but how many are getting hit in a single frame?

naive pawn
#

so 600 parts? not really an issue

wintry quarry
#

Try it and see

#

it's really going to be fine

naive pawn
#

sounds like you're hitting premature optimization

acoustic sequoia
naive pawn
#

if you don't have issues, no need to hyper-optimize it

#

just don't make it overly bloated

wintry quarry
acoustic sequoia
#

ok thank you

naive pawn
#

the list is gonna be pretty readable anyways; that's gonna be more important

buoyant thistle
#

How can i get gameobjects to attatch to a specific spot on other object, lets say attach a circle tp the corner of a square vs the center

true owl
#

@wintry quarry i used start instead of awake and it works now

#

thanks

#

nvm

#

hold on

burnt vapor
#

You should not just change behaviour from running in Awake to Start to fix a bug. That makes a massive difference

#

Maybe share some context since, at least for me, it's not clear what the issue is

acoustic sequoia
#

@wintry quarry
i'm getting this error: MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.

pointing to this code:

                var dir = (_tail[0].position - _player.position).normalized;
                _tail[0].rotation = Quaternion.LookRotation(Vector3.forward, dir);
                _tail[0].position = position;

                for(var i = 0 ; i < tailLength - 1 ; i++) {
                    var a = _tail[i];
                    var b = _tail[i + 1];

                    dir = (b.position - a.position).normalized;
                    b.rotation = Quaternion.LookRotation(Vector3.forward, dir);
                    b.position = a.position + dir * constraintDistance;
                }
            }```
#

oh wait i think i know what the issue is

wintry quarry
grand snow
#

it really is

acoustic sequoia
wintry quarry
#

What I said was:

myList.Remove(something);```
#

you destroyed something without removing it from the list

#

so now you have a stale reference to a destroyed object in the list

acoustic sequoia
wintry quarry
acoustic sequoia
#

omg im destroying the wrong object

wintry quarry
#

Also you should probably do some bounds checking in that code

acoustic sequoia
#

oh yeah, i will. you mean if tail[1] doesn't exist?

#

@wintry quarry

so from this code public void DamageBody(SnakeBody body) { var item = _tail[1]; if(item != null) { _tail.RemoveAt(1); _tail[0].position = item.position; Destroy(body.gameObject); } else { Debug.Log("Snake Dead"); } }

the line here: _tail[0].position = item.position; isn't working.

i have a manager that is running the snakes movement in update. shoud i move that to late update to get the position to change? or how would you solve it..

hot laurel
#

i would just declare array that can fit max size of snake tail, and store there gameObject which would be activate/deactivate, so you dont have to destroy them or remove list entries

acoustic sequoia
#

ok new question unrealated, should be pretty easy but im not sure what to look up..
Quaternion.LookRotation(Vector3.forward, dir);
when i calculate dir (it is correctly working). how do i clamp the direction to be a maximum of x amount of degrees? to prevent turning to sharp

proper needle
#

How is private not valid (I changed it to public and it says public isnt valid either)

burnt vapor
rich adder
eternal falconBOT
proper needle
slender nymph
#

if only there were some sort of bot message that would give context

burnt vapor
rich adder
#

its not configured because it should underline the error red and also help you identify issue

acoustic sequoia
proper needle
hot laurel