#💻┃code-beginner

1 messages · Page 826 of 1

ivory bobcat
#

Show an image of the Unity Package manager and External Editor

drowsy sigil
#

How do I ignore specific LayerMasks when Raycasting.

ivory bobcat
#

It would have something to do with that parameter

drowsy sigil
ivory bobcat
drowsy sigil
#

Yea but im very confused on how it works and I don't understanding a single word that the Unity is saying. My english isn't the best

ivory bobcat
#

Show what you've tried

frail hawk
#

do you want rc only detect colliders on a specific layer?

#

because i am assuming you phrased you question not correctly

vast matrix
#

I am trying to make a bird like enemy that swoops down onto the player and damages them if they're too high. I have all the checks done (damage and checking if the player is too high) but how would I get the enemy to swoop down onto the player?

frail hawk
#

but you´d also want to go back to the initial position, so you need to save that position before the movetowards

ivory bobcat
#

We're not certain without knowing more about what they're doing (physics base, animation etc)

vast matrix
sage mirage
#

Hey, guys! I want to attach my prefab on the field in the inspector. How I am supposed to do it through code, because GameObject.Find() works only for objects active in the hierarhcy.

#

If I want to attach my prefab for example?

#

I have tried

#

enemyPrefab = Resources.Load<GameObject>("Enemy");

#

But this doesn't work

frail hawk
#

you need to instantiate it first

sage mirage
#

so after the instantiation I can do GameObject.Find()

#

yes but what if I want to attach it earlier

#

I mean with drag and drop it works

#

from the prefabs folder

frail hawk
#

then you can do some kind of injection and let the object that instantiats your prefab, assign your prefab to the field

sage mirage
#

I mean

#

I don't know how to get access to my project assets

#

there is the Resources Class

#

but I am not sure how to do it

frail hawk
#

why do you need to do that before, any reason?

woven thistle
#

Could anyone help answer a few questions I have about a 2d game I am trying to start creating?

frail hawk
#

we dont know if we can answer them but we will try

woven thistle
#

I am just trying to start off with a basic character who can move up down left and right, and "You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings" keeps coming up

frail hawk
#

show your code , it seems like you are using the old Input class

muted sand
radiant voidBOT
# slender nymph !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.

woven thistle
#

using UnityEngine;

public class CMScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float moveAmount = 10;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
    if (Keyboard.current.rightArrowKey.wasPressedThisFrame)
    {
        myRigidbody.MovePosition(myRigidbody.position + Vector2.right * moveAmount);
    }
}

}

slender nymph
#

you should consider looking at the stack trace for the error so you can see where it actually originates from

muted sand
#

already tried this

slender nymph
#

screenshot your entire visual studio window with the solution explorer visible

muted sand
slender nymph
#

click the error error in the console to see the entire message, including the following lines

slender nymph
muted sand
slender nymph
#

google "vs solution explorer"
View > Solution Explorer

frail hawk
muted sand
#

okok

slender nymph
#

so you didn't follow the instructions in the link i sent

muted sand
#

nothing

slender nymph
#

did what specifically? there are several different steps

muted sand
#

If an assembly in the Solution Explorer is marked as (unloaded), right-click it and select reload project.

#

Restart your computer.

slender nymph
#

then you've missed something else in the steps. or you lied 🤷‍♂️

muted sand
#

nope

#

opopup

woven thistle
slender nymph
#

did you look at the stack trace yet

muted sand
slender nymph
#

not you

muted sand
#

okay

frail hawk
#

double click on the message

muted sand
#

for whatever reason .net wasnt installed apparently

frail hawk
woven thistle
frail hawk
#

yep

woven thistle
slender nymph
#

just look at the fucking stack trace so we can actually find out where this error is coming from

woven thistle
#

who are you talking to

slender nymph
#

you. the person i have told to look at the stack trace several times now.

woven thistle
#

I thouoght you were talking to vincordian. What is the stack trace?

slender nymph
#

i already answered that the first time you asked before you deleted that message

woven thistle
#

Im still not sure what the stack trace is.

woven thistle
#

the error is in if (Keyboard.current.rightArrowKey.wasPressedThisFrame)

slender nymph
#

prove it. show the stack trace

woven thistle
#

does this help

slender nymph
#

holy shit dude, that's an entirely different error

#

!ide 👇 get your IDE configured then use the quick actions to add the correct using directive

radiant voidBOT
west quail
#

i just switched the il2cpp backend but for some reasons i cant add the "using" statements for il2cpp things

#

i wanna use il2cppreferencearray but cant do it without em

slender nymph
#

isn't that something in the native code, not c#? or is this using a modding library? if the latter then ask for help in that modding community's help channels

west quail
slender nymph
#

okay then what specifically are you trying to do with "il2cpp things"

grand snow
west quail
grand snow
#

Yes we do not ever have to think about mono or il2cpp

#

c# is used as normal

west quail
#

gotcha

jovial heron
#

i'm creating an enemy base of which other enemies extend there are 3 states every enemy must have Idle Follow and Recover .I wanna make it so that these are the defaults and the specfic enemy can add his own states later but i couldn't find a way to add states to an enum . How should i approach this

grand snow
#

What is a "state" in this case?

jovial heron
#

like if enum enemyState has 3 values idle follow and recover those would be 3 states

grand snow
#

Okay so as I said, the enum def would need to be updated to support new values

#

a switch statement for states that has a default: case could throw and report missing "state implementations" if new ones are added later

jovial heron
#

ok so how should i approach this if i want default enemy states

grand snow
#

abstract functions in the base type

#

as abstract properties/functions must be implemented

#

this however requires the class to also be abstract (e.g. EnemyBase is abstract, CoolEnemy : EnemyBase)

jovial heron
#

my base is abstract

#

what should i more specifically to make default enemy states

grand snow
#

I guess have the function be virtual so overriding it is optional

#

We are limited with what we can enforce at compile time, we dont have static assert 🙁

jovial heron
#

my problem is quite general i suppose so if you have ever made a game with a base for enemies how did you handle default states?

grand snow
#

If a state is implemented as a function then make it virtual
If a state is a whole object then perhaps they can be optionally provided in the constructor via an override

#

(This means you can either provide your own or not)

jovial heron
#

a state is a function ig i can make it virtual

#

i can't really see well how this will go since this is my first enemy base

#

but i'll try

robust condor
#

Does anyone have a up2date dots sample project with netcode that works with colliders and player input? They removed the physics shapes and stuff and I donno how to get the boxcolliders to work with netcode

mental escarp
#

could i get some help with checking if my agent has reached its destination and set the ismoving bool to false? i dont really know how to code at all im just following tutorials right now 😅

#

basically i want the walk animation to change back to idle when the destination is reached, i tried setting movement parameters and things like that but had no luck, any help would be greatly appreciated (ignore that im using bandicam please and thank you :) )

rich adder
#

also you should def be configuring your code editor properly

mental escarp
#

unfortunaltey i dont know how to do either of those things 😅

rich adder
#

the editor . follow these instructions 👇

#

!ide

radiant voidBOT
mental escarp
merry carbon
#

is there anywhere i can find a guide with visual scripting for an inventory system

#

i couldnt find any on youtube elol

sour fulcrum
rich adder
#

not easy thing to find a specific guide on..

#

you'd have to already be very familiar with all the nodes involved to make something like that

muted sand
#

what should i do for cameras movement?
should i move the parent of the camera so that it'd move any accessories the player has also?
i don't know any other way to do it, as multiplayer games would need this visualization
thanks in advance

eager spindle
#

In a multiplayer game, have the camera as a child of a gameobject. Make a script for the gameobject to follow the player.

muted sand
wintry quarry
#

I recommend using Cinemachine for all Unity games.

visual junco
#

Ton of people talk about developing small games for your first Unity projects
That's fine, but it shouldn't stop you from wanting to develop something bigger

Why not plan a decent size game, and treat each mechanic as a whole project so you technically are making small projects, but it's slowly forming a game you want

#

just my opinion on a common saying for beginners

sour fulcrum
#

People just don’t do great with that approach

#

A working game and additions to said game are very valuable, rewarding dopamine treats to consume while learning independently

#

Working on chunks of a bigger game just leaves you with a heart and a kidney on the pavement, comparatively

#

Obviously everyone is different tho

visual junco
#

Yeah I guess everyone is different

#

to me it's been very very rewarding and seeing each mechanic work feels like a huge reward
Like when I got an AI system for police officer working, or the player's movement & camera control

#

I just envision everything coming together

sour fulcrum
#

Very popular explanation on mvps

visual junco
#

Yeah makes sense

cinder path
light dune
#

is there a way to apply post processing to UI without it being worldspace?

night raptor
naive pawn
#

!collab

radiant voidBOT
# naive pawn !collab

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**

#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**

ancient nimbus
#
        {
            Mathf.Lerp(CinemachineNoise.AmplitudeGain, IdleAmplitudeGain, AccelerationTime * Time.deltaTime);
            Mathf.Lerp(CinemachineNoise.FrequencyGain, IdleFrequencyGain, AccelerationTime * Time.deltaTime);
        }
        else if (IsGrounded & IsWalking & !IsJumping)
        {
            Mathf.Lerp(CinemachineNoise.AmplitudeGain, WalkingAmplitudeGain, AccelerationTime * Time.deltaTime);
            Mathf.Lerp(CinemachineNoise.FrequencyGain, WalkingFrequencyGain, AccelerationTime * Time.deltaTime);
        }
        else if (IsGrounded & IsSprinting & !IsJumping)
        {
            Mathf.Lerp(CinemachineNoise.AmplitudeGain, SprintingAmplitudeGain, AccelerationTime * Time.deltaTime);
            Mathf.Lerp(CinemachineNoise.FrequencyGain, SprintingFrequencyGain, AccelerationTime * Time.deltaTime);
        }```

The noise won't change from idle to walk/run (it's stuck at Idle, because i put the noise to be at idle at the start) , can someone tell me why it isn't working? all variables are changing fine, and i also put this code in FixedUpdate
frail hawk
#

and you dont have any errors? because it has to be && instead &

naive pawn
#

probably just didn't save & recompile

drowsy sigil
#

if I want to rotate my player smoothly toward a target, should I be using Quaternion.Slerp or Quaternion.RotateTowards? And is there any reason to ever touch transform.eulerAngles? Im really confused on what to choose

frail hawk
#

there is also Quaternion.Lerp

#

the difference between Lerp and RotateTowards is that you have an ease while with the other you dont

drowsy sigil
#

ok

naive pawn
frail hawk
#

and transform.euleranlges is just the rotation itself

naive pawn
#

oh you're talking about wronglerp?

naive pawn
night raptor
#

Since you can do transform.rotation = Quaternion.Euler(...), there's no need to set .eulerAngles either (those would be equal), but setting them is totally fine too. Just getting eulerAngles often causes more harm than good

#

This is literally what transform.eulerAngles does btw:

{
    get { return rotation.eulerAngles; }
    set { rotation = Quaternion.Euler(value); }
}```
sour fulcrum
#

Lowkey had no clue about that setter

#

That’s convenient tech

night raptor
#

I often feel like eulerAngles are bit of sketch and set rotations with Quaternion.Euler only to remind myself that they are equal

#

Of course for a lot of rotation stuff quaternions are superior

jovial heron
#

i have this enemybase code that has a default enum states(the states that every enemy will have) but when i go to the specefic enemy code i realized that adding new states is impossible since that would require modifying the enum's value , and the enemybase must have enum with default values otherwise i would have to program them one by one for every enemy. how do I handle this ? i don't mind changing the way this whole thing works but i want smth fairly easy to understand for a beginner and efficient if you would suggest to implement big changes

grand snow
#

Perhaps using int as the key and elsewhere the enum can be casted to int or constants can be used

#

Or you use generics to let you change the key type

jovial heron
grand snow
#

Generics would be best to allow any super class to use its own enum but that may introduce new issues.
Perhaps you need a special key type so you can have inbuilt states and custom states?

jovial heron
#

for smth maybe more flexible and commonly used for enemy bases

grand snow
#
public enum StateType { Default, Custom }

public struct StateKey
{
  public StateType stateType;
  public int stateId;
}
#

Can be used with a Dictionary for example

jovial heron
#

ok that would work

#

like a dictionary for the specific enemy?

#

wouldn't a map be better?

grand snow
#

A dictionary is a "map"

#

A type that efficiently maps a key to a value

jovial heron
#

thx for help

random badger
#

Anyone know how to walking animation in unity?

#

Is there any script I need to write?

queen rune
#

how do i start learning c#?

naive pawn
queen rune
#

there's a crap ton of resources and i'm a bit overwhelmed

naive pawn
naive pawn
queen rune
#

how'd you learn

naive pawn
queen rune
#

ah

#

reading isn't my learning style

#

i'll probaby try something on youtube

sour fulcrum
#

to be completely honest with you at some point reading is just neccasary for learning a language

#

especially programming

naive pawn
#

i'd really recommend article resources, much easier to skim or search through

queen rune
#

reading i understand will be nesesecary at SOME point but for now while i'm getting started i'd prefer a video series

sour fulcrum
#

sure but like

#

keep in mind a majority of the learning process will be reading

queen rune
#

i'm not saying i can't read

#

i'm saying when i'm learning something i've got no knowledge of i'd prefer visual learning, when i get a feel for the language i'll peek at the docs

naive pawn
#

reading is visual learning though?

queen rune
#

maybe i worded that wrong idk

#

whats the word

naive pawn
#

you still have to read the code someone else writes in a video lol

queen rune
#

well yeah a programming language is written

naive pawn
#

there's a certain format of how guides/docs are laid out, if you learn that now you can save learning it when you're dealing with more complex topics

#

it's not a requirement to only use text resources of course, but yeah i'd recommend at the very least familiarizing yourself with them

random badger
#

I try to make sense of it

unreal quartz
#

Good evening

visual junco
#

make sure you understand what you're coding instead of just mindlessly typing stuff you don't

#

understanding the content makes it way easier

#

I'd recommend the youtuber BroCode

fickle rose
#

so uhhhh for some reason my canvas wont listen to any type of input whatsoever. When I hover over a UI button, nothing happens, let alone clicking it. It's SUPPOSED to change scenes, but for some it doesnt do anything. Any ideas?

#

I have added the command its supposed to run, and it used to work but i come back and it doesnt anymore

slender nymph
#

do you have an event system in the scene?

wheat coral
stark helm
#

Guys im making a prototype, should I make a script for each mechanic or can I group them in a big script?What is your opinion on this?

slender nymph
#

typically one big script for everything is a bad idea though

rich adder
cosmic quail
stark helm
#

How do I make hitboxes for combat?

#

Most tutorials last 30 minutes

#

Using colliders?

slender nymph
#

if learning for 30 minutes is too much for you, then you should consider something besides game dev as a hobby/career path

stark helm
#

This is a help channel

slender nymph
#

yeah, this is a help channel not a spoon feeding channel

stark helm
#

I just want to know the most used method

#

then I learn myself

#

I wont spend 30 minutes on tutorials before knowing what to use

slender nymph
#

here's a hint: tutorials typically tell you what to use

stark helm
#

But 30 minutes is too long

#

For just some words

slender nymph
#

then game dev isn't for you. 30 minutes of learning is nothing

stark helm
#

Just tell me what yall use for combat

stark helm
slender nymph
stark helm
#

Bruh, tutorials scrolling aint helping me

#

How do I instantiate a hitbox and if it hits something getting the hit object back to the script that creates it?

frosty hound
stark helm
#

Thanks guys

#

Guys, how do I pause the game session

#

I mean I pressed to test my game as usual, but something is wrong

#

And I cant use my mouse

#

its locked

#

I didnt save the file yet

#

so i cant alt F4

grand snow
#

If its a build then its up to you to add this functionality

stark helm
#

I cant unlock it atwhatcost

grand snow
#

If esc does nothing then the editor may not be responding. then you are probably screwed unless it works again

grand snow
#

poor logic such as infinite loops will cause such issues

stark helm
#

Ima alt F4

#

Guys if Alt F4 doesnt work

#

then what is the next step

grand snow
#

task manager (to kill the process)

#

google can help you there

stark helm
stark helm
grand snow
#

cool i dont need a running commentary anymore thanks

stark helm
#

Can I like override the previous version

#

or I can just save the backup?

#

ok nvm

#

thanks

warm iron
#

I love spending 5 minutes figuring out how to re-open the inspector, I feel like a grandma 💔

wind pier
#

When I launch my game with this program, my character jumps about one time out of ten. Are there problems with the script?

rich adder
#

also 👇

radiant voidBOT
keen dew
#

Don't read input in FixedUpdate

naive pawn
mellow lance
#

I'm still new to Unity but Is this how a lot of games are designed or is my information incorrect/lacking?

  1. A "game manager" singleton is created in the main menu on an empty object (or a "bootstrap" scene before it) which holds and saves player data (progress/inventory/lv/exp/etc) regardless of the current scene.
  2. Other singletons are also created with it for core systems (like audio and stuff).
  3. An Event Handler class sits in your scripts folder that pretty much only holds action properties that transfer a value (example: player received damage equal to int value, or enemy id and damage in a tuple or class) accessed by all currently active scripts to make changes anywhere you need (like that game manager in #1)
  4. Game menu, garage/shop/etc, and each individual level each exist in its own scene.
naive pawn
#

that seems quite specific

#

that's one way, sure. it's definitely not the majority way - there's far too many ways to design the systems to say there's a main way

mellow lance
naive pawn
#

you're basically asking "what's the main way to make a game"

#

there's not going to be a singular answer for that

modern lodge
#

^^ depends on your games needs

mellow lance
#

still trying to figure out the norms 😛
(barely even know how to move a character yet, but trying to learn this stuff first as a foundation)

naive pawn
#

yeah no this is not really a proper foundation lol

wind pier
naive pawn
#

figure out the small stuff first

#

none of the big stuff will make sense unless you understand the small stuff

naive pawn
wind pier
#

isGrounded is checked by default and is Jumping is not checked

naive pawn
#

that part shouldn't be an issue then. might just be the input reading in fixed update 🤷

hazy portal
#

How does one learn about new tools that could make code more efficient? Its my third day using Unity and I made flappy bird and pong but after I went through my code I saw how messy it was but I have no clue how I'd go about making things more efficient since im learning through the documentation

wind pier
#

Maybe, because the game I'm playing comes from a tutorial that's 6 years old.

#

but not because

naive pawn
hazy portal
naive pawn
#

yeah

hazy portal
#

or are there any resources

#

oh I see thank you!

naive pawn
#

there probably are some

#

but it's not going to replace actual learned experience

#

skill comes from both knowledge and experience

#

sometimes a lot of knowledge can substitute for a little lack of experience, or a lot of experience can substitute for a little bit of missing knowledge

but it's much more beneficial to just get both

hazy portal
#

But I feel like getting the knowledge in the way that I'm learning is difficult. I know from experience with another game engine that you could make two scripts communicate but I never would've found this out if I didn't watch an old youtube video a long time ago. Things like that are gamechanging but I have no sense of how many more valuable tools there are similar to that and what they are

feral hawk
#

Yo can someone tell me how to make a multiplayer main menu screen

#

kinda like 1996 main menu doom feel

slender nymph
#

why does the main menu need to be multiplayer

feral hawk
#
  1. servers 2. create server
slender nymph
#

that's just UI, that's not it being multiplayer. do you not know how to make UI?

feral hawk
#

oh thats what i meant

slender nymph
#

check the docs pinned in #📲┃ui-ux to learn how to use unity's UI system

naive pawn
# hazy portal But I feel like getting the knowledge in the way that I'm learning is difficult....

ive found out about quite a bit of stuff just hanging out here tbh. also checking out more advanced/system tutorials and such, sometimes they include patterns or stuff that can act as a starting point for further reading.

i've also found that experience in other languages/ecosystems can expose you to many more patterns or designs, which, while maybe not directly applicable, can still be adapted or trigger further reading

#

there's also that one website for game design patterns or something along those lines

hazy portal
#

Theres a website for that??

#

ah

naive pawn
#

it's not all applicable, i think it's targetted for c++ or something, but it does give a lot of keywords and ideas to research further

hazy portal
#

Thank you thats gonna be a big help

naive pawn
#

note that adjacent fields can also help, like math (especially vector math) and physics (especially kinematics)

distant escarp
#

would this code accurately give me the normal of the player's position on a wave (please imagine that the SampleWaterHeight function gives the height of the water for the coordinates given)

` public Vector3 SampleWaterNormal(Vector3 worldPosition)
{
Vector2 xz = new Vector2(worldPosition.x, worldPosition.z);

    float waterLeft = SampleWaterHeight(xz + Vector2.left);
    float waterRight = SampleWaterHeight(xz + Vector2.right);
    float waterForward = SampleWaterHeight(xz + Vector2.up);
    float waterBack = SampleWaterHeight(xz + Vector2.down);
    
    Vector3 normal = Vector3.Cross(
        (waterLeft - waterRight)*Vector3.left,
        (waterBack - waterForward)*Vector3.back
    ).normalized;

    return normal;
}`
swift crag
#

That is an approximation of the normal vector, yes.

#

although it may be inverted

#

although, hm, i'm not so sure on second thought

#

The goal here is to find two tangent vectors on the surface of the water

#

Crossing those will give you the surface normal

#

You're not calculating that; you're creating a left-vector and a back-vector whose lengths depend on how quickly the water's height is changing

#

But that doesn't give you two vectors that are tangential to the water's surface!

#

this will always give you a down-vector, yeah

#

it's pretty much just Vector3.Cross(Vector3.left, Vector3.back)

#

You want to do something more like this

#
Vector2 waterCoord = new Vector2(worldPosition.x, worldPosition.z);

Vector3 centerPos = worldPosition;
Vector3 leftPos = worldPosition + Vector3.left;
Vector3 backPos = worldPosition + Vector3.back;

centerPos.y = SampleWaterHeight(waterCoord);
leftPos.y = SampleWaterHeight(waterCoord + Vector2.left);
backPos.y = SampleWaterHeight(waterCoord + Vector2.down);

This gives you three points that are on the surface of the water. Therefore, you can do this:

Vector3 tangent = leftPos - centerPos;
Vector3 bitangent = backPos - centerPos;
Vector3 normal = Vector3.Cross(tangent, bitangent).normalized;
#

I'd just make the Y component of normal positive at the end

willow hill
#

Hey, I'm looking for some advice on how to handle something that I think is super simple, but my intended approach might be far more expensive than it needs to be.

I'm making a 2D arcade platformer (single screen levels). The ground tiles may have grass on them, which is a separate game object rather than a tile, as it needs to be able to interact with actors in the game in a variety of ways.

When a player/enemy walks through some tall grass, I want it to animate (rustling). What can I do besides using OnTriggerStay2D, check the hitCollider to see if it has a MovementController (custom raycast movement), check that the velocity is over some threshold, then play the rustle animation (if it isn't already playing).

rich adder
willow hill
# rich adder if its working fine what makes you say its expensive

I haven't actually made it yet-- just thinking about it while I make the grass assets.

I've read that it's not wise to use GetComponent in Update/FixedUpdate/OnTriggerStay, due to it being relatively slow. In fact, I've alleviated performance issues in previous projects by removing/reworking instances where I had that kind of thing happening. But, in those cases, there were a lot more objects, so it might not be comparable.

rich adder
#

does the grass need to detect only player to do that?
if yes you can also just do this player side and on the grass you just have a script that controls animation itself but you detect grass from 1 player script

willow hill
#

It would be for players (game will be one or two player co-op), enemies, and possibly other objects that I haven't thought of yet.

rich adder
#

either options work , do whatever is easier for you to keep track

rustic moat
# willow hill I haven't actually made it yet-- just thinking about it while I make the grass a...

To answer your question, the more "clean" way would be to make a shader for the grass and have it use a gradient noise with the player position but that is probably way overkill for your project.

But absolutely you can just have a on trigger stay that checks if the object has tag "player" or "rustlesGrass" or something and then sets the bool for the animation. That will probably work perfectly for your project

grand snow
#

Just profile in the future to check if this causes performance issues

willow hill
willow hill
rustic moat
#

Definitely better than get component

grand snow
#

it is more advanced as the shader needs to be able to dynamically react/deform based on some world position

willow hill
grand snow
#

But the prior technique of just using 2d physics should be fine if you restrict how many can happen at once in a frame

grand snow
rustic moat
#

So then collider.attachedrigidbody.linearvelocity? Idk I haven't used 2D in a while but that's a thing in 3d for sure.

willow hill
rustic moat
#

I see.

#

Then yeah you probably just gotta do a get component and then you can cache those results in a list of player components or something so you don't have to do get component every time.

rich adder
#

just make it easier on yourself let the player pass its movespeed to the movable grass.
Make a component on grass that only receives a float

#

and unles you have Events for each movement, you would use Update anyway

grand snow
#

Perhaps an interface hmm? 🤔

rustic moat
willow hill
#

So the grass would have the interface? And players/enemies/etc would pass their movement controllers to be cached and queried (for velocity)?

rich adder
#

does grass needs to be really caring about where the speed comes from player ? enemy ? animal ?

willow hill
willow hill
rich adder
willow hill
rich adder
willow hill
rich adder
#

yeah so that comes into your design , it would be easier to just to have a component on player that rustles it ?

#

so the grass doesnt have to track the velocity , it just needs to know something moved it

willow hill
#

Maybe, but then that component would have to constantly check for overlapping grass.

Maybe that's a better way, though.

rich adder
#

only Enter/Exit

#

but even an physics overlap in update would be cheap anyway cause ur doing it from 1 player or two not every grass checking everyframe

willow hill
#

That's true. I think I'll try something like that.

Thanks for the input, everyone.

vast matrix
#

I am trying to make a bird-like enemy that swoops down on the player and attacks them. I am currently using Vector3.MoveTowards to move the enemy to the player but the problem is that the enemy moves in a straight line to the player and not in an archlike way. How would I get the enemy to move in an archlike way?

rich adder
#

some type of bezier curve?

#

or some type of sine

#

you could also do it a hacky way of still using moveTowards on the main object then have a child object that use Animator/Animations to do different patters of your choosing

vast matrix
#

Oh yeah I can just put multiple points along the route and animate in a sort of way that looks like its curving

muted sand
#

*If you have an action asset assigned as project-wide, the actions it contains are enabled by default and ready to use.

For actions defined elsewhere, such as in an action asset not assigned as project-wide, or defined your own code, they begin in a disabled state, and you must enable them before they will respond to input.*
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.19/manual/Actions.html

Does this mean that my actions (that are not project-wide) will not be enabled and will be disabled and I will have to enable them automatically?
And how do I know which is the default action map?
-# screenshot is attached
*I'm using Invoke Unity Events behavior for Player Input component for my player.

#

And should i use project-wide inputs or not?

slender nymph
#

the PlayerInput component handles enabling/disabling actions so that isn't something you need to worry about when using it

undone wave
#

There seems to be a discrepancy between the actual value of my list and the value shown in the inspector. How do I fix this?

void ReadSaveFile()
{
    string readSaveData = File.ReadAllText(saveDirectory);
    currentSave = JsonUtility.FromJson<SaveFile>(readSaveData);

    Debug.Log(currentSave.levels.Count);
    Debug.Log("Data loaded");
}
#
    ...
    Debug.Log(currentSave.levels.Count);
    foreach (LevelSaveDictionaryEntry entry in currentSave.levels)
    {
        levelSaveDataDictionary[entry.key] = entry.value;
    }
}

private void Update()
{
    Debug.Log(string.Format("currently {0} entries in current save file", currentSave.levels.Count));
}```
#

The console correctly logs the number of levels as 13:

#

but the inspector displays it as 0

sour fulcrum
#

gotta show where your field is defined too

undone wave
#
public SaveFile currentSave;

public Dictionary<LevelIndex, LevelSaveData> levelSaveDataDictionary { get; private set; } = new();

private void Awake()
{
    saveDirectory = Path.Combine(Application.persistentDataPath, saveFileName);
    if(File.Exists(saveDirectory))
    {
        ReadSaveFile();
    }
    else
    {
        WriteSaveFile(defaultSave);
        ReadSaveFile();
    }

    Debug.Log(currentSave.levels.Count);
    foreach (LevelSaveDictionaryEntry entry in currentSave.levels)
    {
        levelSaveDataDictionary[entry.key] = entry.value;
    }
    WriteSaveFile(currentSave);
}

void WriteSaveFile(SaveFile saveFile)
{
    string writeSaveData = JsonUtility.ToJson(defaultSave);
    File.WriteAllText(saveDirectory, writeSaveData);
    if (saveFile.Equals(defaultSave)) Debug.Log("Data saved with default data");
    else Debug.Log("Data saved");
}

void ReadSaveFile()
{
    string readSaveData = File.ReadAllText(saveDirectory);
    currentSave = JsonUtility.FromJson<SaveFile>(readSaveData);
    Debug.Log(JsonUtility.FromJson<SaveFile>(readSaveData).levels.Count);
    Debug.Log(currentSave.levels.Count);
    Debug.Log("Data loaded");
}
#

(all of this is contained as top-level in the MonoBehaviour class)

wintry quarry
undone wave
#

Just ran WriteSaveFile(currentSave), and the json file also seems to have been saved using the correct data, it's just the inspector field that is errorneous

wintry quarry
#

It's not clear what logs we're actually looking at here

#

or what data you're saving

undone wave
#

here's a better snapshot of the console (without the Update loop)

wintry quarry
#

what are these "13" logs?

#

Show us the SaveFile code

undone wave
#

i'm pretty sure the first two 13's correspond to the Debug.Logs before "Data loaded"

wintry quarry
#
Debug.Log($"Data loaded with {currentSave.levels.Count} levels");```
#

for example^

undone wave
#

yeah that's what i did in the update loop above

wintry quarry
#

ok well can you show us the SaveFile class?

undone wave
#
[System.Serializable]
public class SaveFile
{
    public List<LevelSaveDictionaryEntry> levels;
}
wintry quarry
undone wave
#

oh yeah i'll check that

remote folio
#

Can I ask you a question about developing the MetaQuest 3 app here?

undone wave
#

oh oof the inspector was displaying the prefab for some reason

livid anchor
#

Hey folks. I'm trying to make some small effects in my game, namely the game become blander with a vignette effect when close to gameover. I'm using a global volume post process effects for that, however, I have some issues. The color adjustment works but the vignette do not. In fact even in the editor, when I change the intensity, the vignette doesn't appear anymore.
i read in a random post that you are not supposed to dynamically change those values ? What should I do ?

keen dew
elfin pike
#

If I have 30 entities, it would be logical to make script which controls all of them?

twin cloak
elfin pike
#

I have multiple NPCs, all of them have same rules, but order different, some of them have to travel longer distances. I think maybe books or enums for state they are in, to easier control in group

dark hatch
#

inputaction is set up normally

#

collider on obj is disabled

#

this is the rigidbody

#

linear damping set to 0 makes no change

naive pawn
#

and make sure your camera following is on LateUpdate

dark hatch
naive pawn
#

and have you set interpolation

#

and as mentioned previously, make sure you aren't touching transform anywhere else

dark hatch
#

i set it to interpolate

#

any idea what the problem could be?

naive pawn
#

the lack of interpolation

dark hatch
#

i've already checked that nothing is calling transform

dark hatch
naive pawn
#

i recall it being set by default, but ive seen a lot of people asking without that set, so 🤷

dark hatch
#

alright

#

thanks

naive pawn
dark hatch
#

no it is

#

i just didnt know that interpolation was to be on by default

naive pawn
#

ah ok, the way you followed up kinda seemed like it hadn't been fixed

#

i've seen a ton of people accidentally saying like, "does" when they mean "doesn't"

dark hatch
#

alr ty

toxic cloak
#

hello can anyone explain me is there any way to make the movement less snappy while sprinting if (isSprinting) { rb.linearVelocity = playerControls.MovementInput * playerStats.sprintSpeed; } else if(playerControls.MovementInput != Vector3.zero) { rb.linearVelocity = playerControls.MovementInput * playerStats.moveSpeed; }

#

i want it to rotate towards the movement input at a speed not instantly if that makes any sense\

naive pawn
#

could make it so you have some acceleration to get up to speed rather than snapping to the speed instantly

#

there's quite a few ways to achieve that

#

could use MoveTowards, or use wronglerp, for example

toxic cloak
#

the speed is okay the rotation is just instant

naive pawn
#

that's not affected by the code you showed then

#

but yeah, same answer really

#

make it so it isn't instant, use eg rotatetowards

toxic cloak
#

ah yes rotate toward thanks

solar tusk
#

My character moves forward and backward with walking animation. But how can I rotate it left and right.

toxic cloak
lunar axle
#

so i have a problem here:

i am working on my unity game and i am want to record the position/rotation of a rigidbody target with 100% accuracy. the problem is my map enviroment changes if i do for the 100% accuracy by tracking of the transform's position then the physics won't work, which leads to them going through walls, doesnt fall... but if i track physics (rigidbody velocity) then it wont have 100% accuracy as the last one. how can i combine the both (aka moving exact position but still have collisions and physics)

keen dew
#

What is it for? Following a target?

lunar axle
night raptor
#

Why does it need to be 100% accurate and what does that even mean?

keen dew
#

And if the map changes then how is it a replay if they take a different route

lunar axle
lunar axle
night raptor
lunar axle
keen dew
#

So if the replay would make the ghost go through the wall, what should happen instead? Should the replay end? Should the ghost stop? Should it go around? Something else?

rugged beacon
night raptor
#

I wouldn't suggest that

lunar axle
lunar axle
keen dew
#

I think you have to plan that a bit more in detail to make it clear to yourself how it should behave, then it becomes easier to see how it should be coded

rugged beacon
lunar axle
naive pawn
#

could do that then

lunar axle
#

Well tried but its not accurate

night raptor
#

Make it accurate then

lunar axle
#

Thats why i choose to record something else in the first place

lunar axle
keen dew
#

I don't see how it would work in practice in gameplay terms. As soon as the character gets stuck it would start going around randomly

night raptor
#

yup

naive pawn
#

if it's frame times that are the issue, you could probably just use the fixed time step

night raptor
#

Most games just have their ghosts simply going through the walls which probably also makes the most sense for the player. Removing the ghost if it goes inside wall would also be in my eyes a better option than it going crazy at the wall

#

I think also in mario kart (which you showed as example), the ghosts can go through barrels or other movable objects

sour adder
#

I have a replay feature in my space ship game. I record keypresses whenever they change and position and velocity minimum every 0.5 sec if no key-change. It is done with the fixed timestep resolution. It works well with collisions but is still not 100% accurate. I added a special kill-message if the player is killed to make it always work regardless of accuracy of the replay.

jaunty laurel
#

Hey, I'm trying to figure out procedural room generation from preset rooms. Are there any good resources you can point me to?

#

more specifically im trying to create a grid system that lets me move around points in the editor to dynamically resize the room before I run the game

night raptor
verbal dome
jaunty laurel
#

IE based on 4 coordinates make a room

night raptor
#

I don't understand what that means. What do those coordinates represent?

wintry quarry
#

your problem is currently underspecified

charred monolith
#

please help i dont know how to fis that

wintry quarry
charred monolith
wintry quarry
swift crag
#

you're going to have two scripts in your project that define the same class

#

If you recently renamed or moved a script, that's probably the offender

charred monolith
fossil linden
#

Quick question for beginner programming theres not anything different between unity 2019 and 6.3 right?

keen dew
#

Right, over 7 years they haven't done anything other than changed the version number atwhatcost

night raptor
#

In terms of "beginner programming", it isn't too far off though. Most things haven't changed at all. They have changed like .velocity into .linearVelocity and probably other similar small changes but nothing that would make it hard to follow an old tutorial for example. The new input and UI systems are noteworthy though the old systems still work (would prefer learning the new ones)

white shadow
#

Hiya I'm following this tutorial: https://www.sharpcoderblog.com/blog/creating-a-first-person-controller-in-unity

I plugged it all in and got the first error

The only controller in my project right now is the CharacterController so I plugged that in but that didn't work; what does it want?

polar acorn
polar acorn
#

Ah, better idea

#

You should definitely not use this website

ionic oxide
#

hi everyone i'm new to the server! i'm a beginner coder making a 2d game in unity, I was wondering, is anyone free to hop on a call with me and help me debug my code? Stuff isn't working and I don't really have anybody to help me haha

polar acorn
polar acorn
#

Here

#

As I said

ionic oxide
#

alr cool

#

so basically i'm making this 2d game that has a random map generator, and I wanted to have messages pop up on screen to show the user that they can do something eg. when they are within one tile of a closet a UI message shows up that says "press [E] to hide". I've created something called InteractionUIManager.cs and assigned it to an empty gameobject in my hierarchy but when I run my code it never seems to wake? I added a debug line that tells me if it calls Awake() but I never see the debug message. It is in scene during runtime though.

verbal dome
#

Show the code and check for errors in the console when playing

ionic oxide
#

do u want me to send the code here?

verbal dome
#

Yeah see !code

#

!code

radiant voidBOT
verbal dome
#

And the gameoobject that has the script, is it active?

white shadow
#

Thank you! That fixed the error and lets the game load in!

ionic oxide
#
using UnityEngine;

public class InteractionUIManager : MonoBehaviour
{
    public static InteractionUIManager Instance;

    public GameObject pressEUI;
    public GameObject pressPUI;
    public GameObject openDoorUI;

    void Awake()
    {
        Debug.Log("UI Manager Awake");

        Instance = this;
    }

    void LateUpdate()
    {
        if (pressEUI != null) pressEUI.SetActive(false);
        if (pressPUI != null) pressPUI.SetActive(false);
        if (openDoorUI != null) openDoorUI.SetActive(false);
    }

    public void ShowPressE()
    {
        Debug.Log("Show E called");

        if (pressEUI != null)
            pressEUI.SetActive(true);
    }

    public void ShowPressP()
    {
        if (pressPUI != null)
            pressPUI.SetActive(true);
    }

    public void ShowOpenDoor()
    {
        if (openDoorUI != null)
            openDoorUI.SetActive(true);
    }
}

and the thing is called in other scripts with lines like:

InteractionUIManager.Instance.ShowPressP();
white shadow
#

I cant move around in game but I'll see if I can fix that myself first :)

verbal dome
ionic oxide
verbal dome
#

Idk how error pause would fix that but good 😅

ionic oxide
#

lol idk either, so apparently the program is running but not doing anything

verbal dome
#

So the ShowPress methods are called but the UI objects are not being set active?

ionic oxide
#

yes exactly

verbal dome
#

If so, the null check fails (or something else is disabling them)

ionic oxide
#

oh

#

what do I do then 😨

verbal dome
#

Assign the UI objects that are null I presume

ionic oxide
#

they are all assigned tho?

verbal dome
#

Then the null checks don't fail and the objects are being set active 👍

wintry quarry
#

and add logging around the behavior that isn't working as expected

verbal dome
#
        Debug.Log("Show E called, UI exists: " + (pressEUI != null));```
ionic oxide
#

ok lemme try

verbal dome
#

It's likely that you have a duplicate of this component yeah

ionic oxide
#

okay i got: Show E called, UI exists: True

but i didn't see the text so now idek what's going on

ionic oxide
#

also idk if this means anything but if I stood within range the message kept sending over and over again

verbal dome
verbal dome
#

Maybe it's actually outside the view, or it is being disabled by something else, or its parent is inactive or something

ionic oxide
#

if i get rid of LateUpdate() then the UI stays active from the very beginning ...

verbal dome
#

Wait... I didn't even read the LateUpdate part

#

Why are you deactivating everything in LateUpdate?

ionic oxide
#

i need to deactivate them at the start no?

verbal dome
#

LateUpdate runs every frame!

ionic oxide
#

oh wait maybe i should have put that in awake

#

BRUH ALL THIS TIME

#

I WAS AGONISING WONDERING WHAT I DID

#

I'm so stupid

#

i can't this is worse than leaving out a semicolon

naive pawn
#

mistakes will happen - errors are explicit, bugs are silent

ionic oxide
#

lol thank you!! you will probably hear more from me today

#

thanks @verbal dome

white shadow
#

Got it!

past cloud
#

hey, im trying to make an animation play while holding down the left mouse button, but for some reason the animation only stays on the first frame

#
        if (Input.GetMouseButtonDown(0))
        {
            anim.SetBool("isAttacking", true);
            Debug.Log("Attacking!");
        }
        if (Input.GetMouseButtonUp(0))
        {
            anim.SetBool("isAttacking", false);
            Debug.Log("Stopped attacking!");
        }
#

this is my code

#

this is how my animator is set up

polar acorn
past cloud
#

its just while im holding mouse1 it just stays on the first frame of the animation

polar acorn
past cloud
#

yeah like the animations not even playing

polar acorn
#

Any State means any state

#

The condition is still true. So it transitions to itself again

past cloud
#

oh

#

thank you

#

that fixed it

#

so it just kept basically restarting itself?

polar acorn
#

Yes

jaunty laurel
#

can anyone help me understand scale in unity?

#

is there any way to have like a universal measure of size for an object

wintry quarry
#

the actual size of an object depends on the actual size of the mesh or sprite, multiplied by its scale

#

a basic Unity Cube is 1x1x1

#

and a basic unity sphere has a radius of 1

wintry quarry
jaunty laurel
#

yeah, like when I'm working on a prefab I dont know how it will relate to everything in my main scene without putting it in and comparing

#

suppose I have a wall or something, is there a good way to figure out the size of the wall in units rather than scale

wintry quarry
#

that seems like a good way to do it tbh.

wintry quarry
#

but the "size" of a 3D object can be vague

wintry quarry
#

like.. how "big" is a cat

swift crag
#

For models, you should make sure all of your meshes have a consistent scale

wintry quarry
#

but you won't get the same bounds size for a rotated wall as an axis-aligned wall for exampkle

#

so it's a rough estimate

swift crag
#

the usual convention is 1 unit = 1 meter

#

Blender defaults to this

jaunty laurel
swift crag
#

create all of your models with a consistent scale and everything will work out correctly

wintry quarry
#

Use ProBuilder or Blender and then those tools DO have size information available

#

if you're jsut scaling cubes - well you need to move on to a more powerful tool here.

jaunty laurel
jaunty laurel
#

got it

wintry quarry
#

Just make sure you import/export at a consistent scale and you're good

swift crag
#

It may be helpful to create prefabs with consistent scales

#

e.g. you prefab everything to fit onto a 4-by-4 meter grid

jaunty laurel
#

so the size from blender will be transferred if I load in the 3d model

wintry quarry
#

yes although there may be a conversion factor

#

which can be addressed in the unity import settings or the blender output settings

swift crag
#

blender's default "Apply Scalings" mode (All Local) gives you a model 100x smaller than you may expect

#

the imported model will be scaled up 100x to compensate

#

I prefer to use "FBX All" when exporting FBX files

#

this gets the scale right

#

therefore, a 1 meter cube in Blender will also be a 1 meter cube in Unity when the model has a scale of 1

wintry quarry
#

Basically I would take one example object from blender - put it in a scene with a unity cube or sphere, and get the size how you want it by changing blender export/unity import settings on it

#

Then reuse those settings for the rest of your assets

swift crag
#

I spend a huge amount of time bikeshedding the overall size of my models

#

(models of rooms to be used in a VRC world, I mean)

hot thorn
#

hey guys try this mousemovement script

using UnityEngine;

public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody; // Drag the parent Player object here
float xRotation = 0f;

void Start()
{
    // Keeps the cursor centered and hidden during gameplay
    Cursor.lockState = CursorLockMode.Locked; 
}

void Update()
{
    // 1. Get raw mouse movement
    float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

    // 2. Clamp vertical rotation so you can't look "inside" yourself
    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f); 

    // 3. Apply rotation to the camera (Vertical)
    transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    
    // 4. Rotate the player body (Horizontal)
    playerBody.Rotate(Vector3.up * mouseX); 
}

}

solar hill
#

what?

chrome tide
solar hill
#

it also screams "ai generated"

#

especially because of the comments

chrome tide
#

yeh, the comments

solar hill
#

"drag the parent player object here" yeah bro pack it up

dark hatch
#

its okay tho

#

can use ai to get started

solar hill
#

i just dont see the point

night raptor
#

The classic incorrect use of Time.deltaTime...

solar hill
#

lmao i didnt even notice it

dark hatch
#

it feels similar to the vid brackeys made, considering the xrotation variable

night raptor
#

They also fumbled the deltaTime

dark hatch
#

dont really feel like looking at that huge wall of text tbh lol

rich adder
swift sedge
#

the "first person movement" video

#

its not AI generated, it's just taken from Brackey's and reposted here

rich adder
#

the comments look suspicious of "AI"

wintry quarry
#

That deltaTime bug is never going away 😭

swift sedge
#

oh lol

#

that's why AI fails to think rationally

polar acorn
#

Good ol' Brackeys error

#

Will haunt us until the day we die

swift sedge
#

too bad Brackeys does Godot tutorials now

polar acorn
#

Now he's their problem

swift sedge
#

I've always wondered why the "mouse sensitivity" was so high

ionic zealot
#

I'm doing a unity project for school and im making an fps, im familiar or.. with unity before the update to it's movement

#

Now i cant find a good movement script

wintry quarry
#

Before what update

slender nymph
radiant voidBOT
slender nymph
#

but also yeah, movement hasn't really changed in a long time

wintry quarry
#

Any movement script from the last 15 years will basically work the same now as ever

slender nymph
#

literally the only difference is in the input, and even that doesn't require a code change, just a change in the settings that the relevant error message tells you about

ionic zealot
wintry quarry
#

I used to add velocity to objects and it never broke
Still works to this day

#

the only thing change you might be encountering is renaming rb.velocity -> rb.linearVelocity for Rigidbodies

ionic zealot
#

This was in the video that i used

slender nymph
#

that's because you copied it wrong

wintry quarry
#

this would not have worked 15 years ago either

#

you also need to get your Visual Studio configured properly so it shows errors

ionic zealot
slender nymph
#

!vscode

radiant voidBOT
wintry quarry
#

You copied incorrectly from the tutorial

#

(whatever tutorial you're using)

ionic zealot
#

But i retyped it, whats wrong? it's late and i need to make it in a day or so

wintry quarry
#

Frankly the code you justw showed us is nonsense

#

and doens't make sense

#

Go back to the tutorial and try again

#

You retyped it incorrectly.

ionic zealot
#

It's preety same

slender nymph
#

now compare that to your own code because it is, in fact, not the same

polar acorn
slender nymph
#

and digi is here just in time to tick the counter

polar acorn
#

Close enough isn't enough

polar acorn
# ionic zealot
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 202
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2026-03-23
polar acorn
#

There isn't a single thing the same between your PlayerInputController and theirs but the name

ionic zealot
polar acorn
slender nymph
#

we really need a bot for it so that we can get the real count and not just the ones you've witnessed. it would 100% be in the thousands by now

ionic zealot
#

Yea, coding sucks

slender nymph
#

it's much easier if you actually pay attention to the information provided to you

wintry quarry
# ionic zealot Yea, coding sucks

You need a certain mindset for it which right now you don't have. The computer is exacting, it can't just get the "gist" of what you mean.

ionic zealot
#

I am made for farm work, i dont know why i went to cs, it suckss, i could have a ranching job rn

ionic zealot
#

I fixed everything i could find, still i get an error

#

Assets\Scripts\PlayerController.cs(13,31): error CS0103: The name 'inputValue' does not exist in the current context

slender nymph
#

spelling is important. get vs code configured like you were instructed to before

slender nymph
naive pawn
#

that looks confiugred to me thonk there's also no errors in that code, is there?

past cloud
#

Why is my inspector not creating a sprite list?

polar acorn
past cloud
#

i did but it was being covered by a warning

#

so i just ignored the warning

#

how do i change the sprite an image is using?

rich adder
#

eg mything.sprite = newSprite

past cloud
#

getcomponent<image>() doesnt work

rich adder
past cloud
rich adder
night raptor
#

Probably using UnityEngine.UI or something

past cloud
#

how do i make it work

polar acorn
#

But not actually a folder in the file system

#

It's all those using statements on the top. If your IDE is configured you can usually just click the error and let it auto-import

past cloud
#

oh like an import

rich adder
swift crag
#

there are a ton of Image classes, so you have to make sure to get the right one, too 😉

rich adder
past cloud
#

after putting in using UnityEngine.UI i get this error

rich adder
#

thats just unity editor bugging out its not your code

#

you can just clear it, restart unity if it appears again

past cloud
#

ty

rich adder
polar acorn
#

Check the stack trace and see if any of those lines are in code you wrote

rich adder
#

also usually coming from UnityEditor instead of UnityEngine

#

it aint waking up 😢
*cues the RATM track - Wake up *

dapper field
#

What's the "industry standard" way to store player data / repeated item data? I don't want to declare each field at the top of the class every time, but I tried using a scriptable object & it doesn't "feel" right. (i.e. every item has a "value" field for its worth in gold, and a "rarity" field for its rarity, which I don't wanna copy-paste over every time)
The values aren't necessarily the same, just the variable and how it's accessed

grand snow
grand snow
#

But at some point the data has to be defined so sometimes you need to duplicate it

#

If this is purely about "I keep adding float value to my classes" then learn about inheritance

wintry quarry
#

Although it's a little unclear to me what you ean by "I don't want to declare each field at the top of the class every time" - when is that happening? Can you show an example of the code?

timber tide
#

Classes until later c# versioning

dapper field
# wintry quarry Make a class or struct

so like


public class PlayerData
{
  public int money;
  public string rarity;
}

public class Player
{
  public PlayerData = new PlayerData();
  //assume I actually made a constructor or a load system that sets the initial values
}

?

timber tide
#

That and for most cases you want to pass stuff around as a reference

sour fulcrum
#

this feels like inheritance + specifically interfaces

dapper field
grand snow
#

abstraction!

wintry quarry
#

If you do this:

[Serializable]
public class PlayerData
{
  public int money;
  public string rarity;
}

public class Player : MonoBehaviour
{
  public PlayerData data; // assign values in inspector.
}```
dapper field
# grand snow abstraction!

thing is that when I do that I have to do

public abstract class PlayerData : MonoBehaviour
{
  public abstract int money {get; set;}
}

public class Player : PlayerData
{
  public override int money {get; set;}
}

so I end up just having to declare it anyway (I get the benefits of having a superclass to refer to instead, I just was wondering if there was a better way to do it)

wintry quarry
sour fulcrum
#

you don't need that override

wintry quarry
#

don't make it abstract

#

You can make it virtual which allows for optional but not required overloading

grand snow
dapper field
#

I thought that made every child class refer to the same variable then? I don't want player A to share currency with Player B -- unless I misunderstood

wintry quarry
#

you're confusing types and instances here

grand snow
wintry quarry
#

it makes every type that derives from the parent have the same fields, but it doesn't make every instance use a shared dataset

sour fulcrum
wintry quarry
#

Yep^

#

that's what a static variable does

dapper field
#

I forgot that's what static things do

#

I'm gonna go bang my head against a wall

grand snow
#

tl:dr go learn about object oriented programming properly

#

dont learn from this chat

wintry quarry
woven bolt
#

Not super new to unity, but can someone help me import an FBX? I can get the model in, just cant get the textures

timber tide
#

Import textures separately

dapper field
woven bolt
dapper field
#

Overengineering cause I went down the rabbit hole of scriptable objects too

woven bolt
#

Itd be helpful if someone could guide me through it

timber tide
#

Gltf better if you want full asset import

grand snow
dapper field
slender nymph
#

this is a unity server

past cloud
#

hey, how could i go about making a time stop ability? i basically want to freeze the movement and animations of all entities besides my player

#

ive seen things about time.scale but it sounds like it pauses everything and i dont want that

slender nymph
#

either make sure they are moving in a way that uses Time.deltaTime and your player is not, or create your own global time scale value that those things use for movement or just an event they subscribe to that will disable related systems

past cloud
slender nymph
#

use an event instead

past cloud
#

how do events work

naive pawn
undone axle
#

I am using UGS for leaderboards. Whats the recommended way to implement some sort of profantiy or hate speech filter on names?

rich adder
#

a library specifically made for this is probably your best bet cause they might contain even variants using numbers as letters n all that

undone axle
#

I could totally put it in my unity code and list all the bad words... But filling my code with hateful speech seems not cool. I was just curious what people usually do. I don't need to stop all of it. I just want to put in some of the more hateful stuff. I guess I could maybe use cloud code when displaying the names on the leaderboard? Change the bad words to something funny or something?

#

That way I could just update the cloud code instead of making a new build if I want to change something

rich adder
#

whatever you choose to do the process is the same.
there are online APIs (will probably cost money) you can probably hit that do the same and its not in your code? but this is a library its literally built for this, there isn't some magic to make them change on their own without a reference point lol

undone axle
#

Yeah I guess I am asking where do people usually put the profanity check, at input, at display, in unity, in cloud code, etc

rich adder
#

in most cases before you even allow the input to be saved after the capture of it

#

look at other media, you usually can't even get passed the user input phase

half verge
#

hi

rich adder
half verge
#

i just said hi

#

what did i do

slender nymph
#

did you read the info in the link?

half verge
#

btw is this site real

wild cove
#

Hey, I'm having this problem with my game where it keeps saying the object that has the collect and destroy script has been destroyed although the cylinder (which has the script) is visibly and effectively still there. I don't know if it's a problem with my code or what. Help would be greatly appreciated thank you!

#

Oh, and also, when I collide with the object that should cause a screen to appear nothing happens

sour fulcrum
#

!code

radiant voidBOT
wild cove
#

And I'm thinking it's because it believes that the Object housing the script does not exist thus the script doesn't change anything, even though on other scripts like my score controller it understands and reads variables from the Collect And Destroy script.

polar acorn
#

So, probably your GameOverScreen. Which CollectAndDestroy is that referencing?

timber trellis
#

do people usually create test suites for games, or is everything done manually ?

floral zealot
#

I'm having a very strange issue where it appears that my float variable is presenting two values at once, and I can't use the one I need.
There are two scripts involved here: XPManager, and XPBarManager. XPManager is attached to an empty game object (also titled XPManager), and XPBarManager is attached to another game object (titled XPBar) that has children that make up the entire xp bar as a ui element.
XPManager has a public static float titled xp which is initialized as 0f and is incremented by 1 before invoking an "updateXPBar event".
The updateXPBar event has the XPBar game object tied to it (i don't know the terminology for that, sorry) in order to call XPBarManager.OnUpdateXPBar(). The plan is to use the static xp value from XPManager to update the xp bar ui.
The screenshot attached shows the inspector for XPBar, the noteable code from XPBarManager, and the output of a debugging print line. As you can see, the inspector and console show two different values.
There are no duplicate variable names here. barXp is also a float. I can provide any other info necessary.
Thank you to anybody who takes a look

#

XPManager shows the correct/intended values in the inspector as well. And XPBarManager has no other methods

#

Please ping me if you have any ideas!

polar acorn
wild cove
polar acorn
wild cove
#

Well I'm not exactly sure, when I click on it it doesn't highlight anything for some reason.

#

and when im in play mode it doesn't even show the error

#

but something is wrong because when I collide with this one rectangle thing it makes the dead boolean true, but the problem is the other script that should be reading the boolean from the other script isn't properly reading it and won't do anything when the boolean is true

#

Which is extremely weird because I have another script that references a variable from the collect and destroy script and it workks perfectly showing me the score on the top right.

floral zealot
#

The values in the XPBar and its XPBarManager script seem to update to the correct values after I exit playmode but not during. Does this sound like a familiar issue?

polar acorn
polar acorn
polar acorn
floral zealot
#

they both are..

#

dont tell me that's been the issue this whole time

polar acorn
#

You are probably calling the function on the prefab, not the one in the scene

#

So you're modifying the file, which has no effect on things that already exist but does change what they spawn in with

wild cove
#

I double checked and dragget it again

polar acorn
# wild cove What do you mean by this?

The one you've dragged in on game over screen and the one you're colliding with are probably two different objects.

Try logging something when this object is hit, and add in the second parameter , this). It will highlight the object that logged it when you click on that log

floral zealot
#

I believe we have sorted out the core of my issue, thank you so much digiholic! I've unpacked those objects from being prefabs and deleted said prefabs altogether, and it works with hard-coded xp, but wasn't working with instatiated xp because of issues with those and events. I think I'll be able to solve it using a spawner parent object which persists, and executing events from there via a method that all of the spawned/instatiated children can call. Thank you for helping me out

wild cove
# polar acorn The one you've dragged in on game over screen and the one you're colliding with ...

Well, yes they are different, because the capsule is the player and the thing it collides with is the "enemy" (the large box looking thing floating ahead of the cylinder) that will send the person playing to the game over screen, but when it collides with the capsule (I realize that I called it a cylinder earlier, sorry about that, that thing has a completely different purpose) it doesn't do anything, which I know has to be a problem with it not reading the bool from the collect and destroy script because I've tested by putting "game over" in the debug log when the enemy collides with the capsule.

#

And what do you mean add in a second paramater, to what?

polar acorn
#

You can log the one that's changing its bool, and the one GameOverScreen is referencing, and see if they're the same ones

wild cove
#

uhh, sorry but could you give me an example, im kinda dumb

#

I understand the point

#

I dont understand how to add this second paramater

rich adder
#

time to refresh on basic c#

wild cove
#

I'll watch a video on parameters cuz I don't understand them

#

So from what I understand parameters tell the computer what you're using in the code??

rich adder
wild cove
#

Ohh, so parameters are the things that tell you what to put in the method and kind of what the method handles and the method does things to the specific things put in place of the parameters

old lotus
#

is this the chat for understanding unity coding?

#

Okay so i can ask question for doing things like first person movement and camera controlls?

fickle plume
#

Start with Pathways courses.

old lotus
#

Okay thanks i was told to do that as well and im currently doing that i just seen someone asking questions and i thought this was also a way but thanks ill get to it now

fickle plume
rough venture
#

Hi! I don't understand why transform translate doesn't move the cube forward when rotated 45 degrees

using Unity.VisualScripting;
using UnityEngine;

public class Tester : MonoBehaviour
{
    [Header("Indstillinger")]
    public float forwardSpeed = 5;
    public float backSpeed = 2.5f;
    public float rotSpeed = 20;

    [Header("Stats")]
    public int coins;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            // Bevæg os fremad
            transform.Translate(transform.forward * Time.deltaTime * forwardSpeed);
        }
        if (Input.GetKey(KeyCode.S))
        {
            // Bevæg os baglæns
            transform.Translate(-transform.forward * Time.deltaTime * backSpeed);
        }

        if (Input.GetKey(KeyCode.A))
        {
            // Roter til venstre
            transform.Rotate(-transform.up * Time.deltaTime * rotSpeed);
        }
        if (Input.GetKey(KeyCode.D))
        {
            // Roter til højre
            transform.Rotate(transform.up * Time.deltaTime * rotSpeed);
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Coin")
        {
            Destroy(other.gameObject);
            coins++;
        }
    }
}```
#

It only works before the cube is rotated with 'a' and 'd'

sour fulcrum
#

what do those have in common?

#

(what are the speeds)

low dagger
#
public static List<Node> GeneratePath(Node start, Node end, float agentSize = 0.5f)
{
    Heap<Node> openSet = new Heap<Node>(nodes.Count);
    HashSet<Node> closedSet = new HashSet<Node>();

    foreach (Node n in nodes)
    {
        n.gCost = float.MaxValue;
        n.cameFrom = null;
    }

    start.gCost = 0;
    start.hCost = GetDistance(start, end);
    openSet.Add(start);

    while (openSet.Count > 0)
    {
        Node currentNode = openSet.RemoveFirst();
        closedSet.Add(currentNode);



        if (currentNode == end)
        {
            List<Node> path = new List<Node>();

            while (currentNode != start)
            {
                path.Add(currentNode);
                currentNode = currentNode.cameFrom;
            }

            path.Add(start);
            path.Reverse();
            return path;
        }

        foreach (Node connectedNode in currentNode.connectedNodes)
        {
            if (!connectedNode.walkable || closedSet.Contains(connectedNode)) continue;

            float newCost = currentNode.gCost +
                GetDistance(currentNode, connectedNode);

            if (newCost < connectedNode.gCost)
            {
                connectedNode.cameFrom = currentNode;
                connectedNode.gCost = newCost;
                connectedNode.hCost =
                    GetDistance(connectedNode, end);

                if (!openSet.Contains(connectedNode))
                    openSet.Add(connectedNode);
                else
                    openSet.UpdateItem(connectedNode);
            }
        }
    }

    return null;
}
```I am using Sebastian Lague's tutorial for A* pathfinding as a base but I keep getting this wonky line?
#

How do I fix it?

#

I can't seem to diagnose the problem

shadow briar
#

Hello,
So im just trying to make a simple enough damage system for a basic FPS project.
Interface with TakeDmg(float), and Heal(Float)
Health Script, MaxHealth, Current health and all that.

my initial thought was to put the interface on the Health script, and make all the damage logic based around interacting with the Health that has the iDamagable.
Just wondering if it would be better practice to put the idamagable interface on the scripts that are damageable.

So Crate, Player, Hostile as example, have the interface and could have a health script.
I mean as i write i am leaning more towards that - but was still unsure and just wanted more clarity and other opinions.

sour fulcrum
#

That's kinda what i have, where i have IHurtable, HealthBehaviour and two usecases PlayerBehaviour : MonoBehaviour, IHurtable and EnemyBehaviour : MonoBehaviour, IHurtable

and the interface is just

public interface IHurtable
{
    public int CurrentHealth { get; set; }
    public int MaxHealth { get; set; }
}

HealthBehaviour has the actual logic for handling health and whatnot and then stuff implementing IHurtable choose to fufill the interface promises by having a reference to a HealthBehaviour component eg.

public class PlayerBehaviour : MonoBehaviour, IHurtable
{
    [SerializeField] private HealthBehaviour health;

    public int CurrentHealth { get => health.CurrentHealth; set => health.CurrentHealth = value; }
    public int MaxHealth { get => health.MaxHealth; set => health.MaxHealth = value; }
}
shadow briar
#

hm alright, i see, interesting enough approach for me to see and gives a bit more insight in it, thanks for the input.

sour fulcrum
#

It’s one of those things that is pretty project & developer dependent imo so it’s totally valid if you find some version of a solution that’s most comfortable for you

cerulean badger
#

what's the best technical way to make a npc move in 2d top-down?

keen dew
#

As with all other "what's the best" questions, the answer is "there is no best" and "it depends"

cerulean badger
#

makes sense

humble summit
#

void SpawnCubicles()
{
foreach (Room room in rooms)
{
for (int x = room.x; x < room.x + room.w; x++)
for (int y = room.y; y < room.y + room.h; y++)
{
if (map[x, y] != 1)
continue;

        // Skip tiles next to walls
        if (IsWall(x + 1, y) ||
            IsWall(x - 1, y) ||
            IsWall(x, y + 1) ||
            IsWall(x, y - 1))
            continue;

        Instantiate(
            cubiclePrefab,
            new Vector3(
                (x + 0.5f) * tileSize,
                0,
                (y + 0.5f) * tileSize
            ),
            Quaternion.identity,
            transform
        );
    }
}

}

#

hello im using this code to spawn a cubicle prefab on the tile if the tile fits the criteria

#

now it fits the criteria correctly and spawns it

#

but instead of spawning the cubicle in the center of the tile it spawns it on the top right corner of the tile, and uses the pivot of the cubicle prefab to do s

#

so it looks like this

timber tide
#

You're positioning it with Instantiate so probably get an idea what the offset is doing

humble summit
#

i don't understand

timber tide
#

0.5f would imply that it's trying to center it, but your prefab pivot not represent that

#

Well, assuming in units of 1

timber tide
#

mess with the offset or pivot of the prefab

humble summit
#

so thats fine

#

so i think

#

offset i need to change

#

i don't know what i need to change in the offset then

timber tide
#

usually it's more like x * tilesize to get to the cell pivot, then to center you'd do tilesize / 2

humble summit
#

just remove the whole vector3?

timber tide
#

not the same

humble summit
#

i'm bad at this

timber tide
#

imagine it's the 10th x index, but you can't just say x * 10, because you need to also calculate the unit size

#

and once you get there, you only want to progress half a tilesize to center it

humble summit
#

could you please type out how it would look like

#

i can barely do mathematics

timber tide
#

so (x*tilesize) + (tilesize/2)

#

the extra offset could be a negative offset though depending how the grid pivot is setup

timber tide
#

sure

#

I guess there can be 4 different offset variations, (x, y), (-x, y), (-x, -y), (x, -y)

humble summit
#

oh this fucked everything up

#

majorly

real thunder
#

how bad is the idea to replace mesh of skinnedmeshrenderer on awake out of several veriants for mob look variety?
making a prefab for each random look sound a bit like a chore

timber tide
#

oh hmm

humble summit
#

i just can't wait till im done with this project

#

it's a class

#

where we have to do a solo project

timber tide
#

oh you're using y, should be z

humble summit
#

and i never do programming

humble summit
timber tide
#

im actually confused now that your original uses y

#

oh yeah ok you're applying the y offset in the y component, but you want to be using it in the z of the vector

timber tide
#

y is up, but your alg uses y to represent indexing

#

but you're populating on the x/z

humble summit
#

what should i do

#

fuck it i have bigger problems than this to focus on

humble summit
timber tide
#

you're setting the y value in the vector, but it should be the z value

humble summit
#

last time i properly coded was a year ago or more

timber tide
#

Yeah, grid stuff can be complicated, but it's not necessarily a unity thing, but more general coding. It's fun to learn though.

humble summit
humble summit
timber tide
#

Unity actually provides some grid class, but sometimes better to just make your own anyway

humble summit
#

im creating a prefab out of models

#

how do i set it a pivot

timber tide
#

So meshes you can't set pivots on in unity, but you can wrap them in another gameobject. This parent wrapper can now be to represent the pivot

#

So making some parent just for transform values

humble summit
#

then parent it

timber tide
#

Empty Parent -> Mesh Child

#

then you can move the mesh child freely and just reference the parent for the pivot

humble summit
#

and thats fine by me

#

thank you for your help

sour fulcrum
real thunder
#

that made me reflect for a moment
I am yeeting some code from github to reuse it while finding some bugs there and flaws and fixing it and it's like close to be a usual thing for me

#

that's not far from using AI's code is it

humble summit
#

it's a thin veil of morality

twin pivot
real thunder
#

more like typing question into google which did all the search
which is not that different from how AI spit it's code out, it's just less steps

woven scaffold
#

is there an easy way to make a wrapper class act as the value it contains for use in dictionaries?

essentially this:

Dictionary<wrapper, someOtherData> myDictionary = new()
Debug.Log(myDictionary[unwrappedData]) // prints someOtherData
real thunder
#

...scriptable object?

#

(I have no idea what am I talking about)

polar acorn
# real thunder that made me reflect for a moment I am yeeting some code from github to reuse it...

The difference is a human wrote that code. You can decide if you trust that human based off of their contributions and see if they're likely to know their stuff, and if there is a problem you can notify them and it could be fixed for whoever finds that in the future.

As opposed to an AI that will just lie to your face constantly because it's not actually an information source, it's a digital sycophant

polar acorn
swift crag
#

well, you appear to have it backwards here

#

it sounds like you want to be able to pass in a "wrapped" object and have it treated as the type it wraps

#

e.g.

#
Dictionary<int, float> whatever;
whatever[containsAnInt] = 1.0f;
wintry quarry
swift crag
#

where containsAnInt is a type like this:

public class IntWrapper {
  private int integer;

  public static implicit operator int(IntWrapper wrapper) => wrapper.integer;
}
#

the compiler will automatically try an implicit conversion operator

#

(as opposed to an explicit conversion operator, which would require you to do (int) containsAnInt)

woven scaffold
#

this is part to make it easier to debug from the inspector for other teammembers

wintry quarry
swift crag
#

so you need to index the dictionary with the unwrapped value?

woven scaffold
#

then just have #UNITY_EDITOR around the serialization

woven scaffold
wintry quarry
woven scaffold
#

im pretty sure ive done that before? thats not exactly what i mean, i would basically just make a duplicate field for the data and not another serialization format. then populate the duplicate field thats serialized with the same data. its just ugly as i gotta duplicate it

#

the runtime logic would never use it and it would be compiled out regardless, but i try my best to not mix editor and runtime code so if possible another solution would be great but idk how that would be or look like

long pasture
#

could you not just do a =>

#

or better just do an onvalidate function