#💻┃code-beginner
1 messages · Page 826 of 1
How do I ignore specific LayerMasks when Raycasting.
It would have something to do with that parameter
huh? Sorry, I'm not understanding what you mean by that
You'd best elaborate on your specific issue else https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.Raycast.html
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
Show what you've tried
do you want rc only detect colliders on a specific layer?
because i am assuming you phrased you question not correctly
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?
if i understood correctly you want this https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Vector2.MoveTowards.html
but you´d also want to go back to the initial position, so you need to save that position before the movetowards
We're not certain without knowing more about what they're doing (physics base, animation etc)
Oh thank you that's what I needed
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
you need to instantiate it first
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
then you can do some kind of injection and let the object that instantiats your prefab, assign your prefab to the field
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
why do you need to do that before, any reason?
Could anyone help answer a few questions I have about a 2d game I am trying to start creating?
we dont know if we can answer them but we will try
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
show your code , it seems like you are using the old Input class
sorry had to go, here it is
!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.
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);
}
}
}
you should consider looking at the stack trace for the error so you can see where it actually originates from
already tried this
screenshot your entire visual studio window with the solution explorer visible
click the error error in the console to see the entire message, including the following lines
with the solution explorer visible
i dont use vs that much how do you do that?
"vs solution explorer"
View > Solution Explorer
the error you posted is actually the opposite of what you posted. it says you are using the old input system. are you sure it is this script that gives this error
so you didn't follow the instructions in the link i sent
i just did it again now
nothing
did what specifically? there are several different steps
If an assembly in the Solution Explorer is marked as (unloaded), right-click it and select reload project.
Restart your computer.
then you've missed something else in the steps. or you lied 🤷♂️
On unity when i tried running the game it said that was the error. When i checked I was on the new input system. is the problem something else?
did you look at the stack trace yet
idk what that is
not you
okay
yes the error is coming from another script. not the one you posted
double click on the message
oh okay i fixed it
for whatever reason .net wasnt installed apparently
or we can make it easier, change the input system to both for now #💻┃code-beginner message
Are you responding to me when you said change it to both
yep
This project uses Input Manager, which is marked for deprecation. To manage input in your project, use the <a href="https://docs.unity3d.com/Packages/com.unity.inputsystem@latest">Input System package</a> instead.
This came up when I changed it to both. What do I do?
just look at the fucking stack trace so we can actually find out where this error is coming from
who are you talking to
you. the person i have told to look at the stack trace several times now.
I thouoght you were talking to vincordian. What is the stack trace?
i already answered that the first time you asked before you deleted that message
Im still not sure what the stack trace is.
the error is in if (Keyboard.current.rightArrowKey.wasPressedThisFrame)
prove it. show the stack trace
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
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
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
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
tbf i have no clue. i learned unity coding from modding so that might be something to look into
okay then what specifically are you trying to do with "il2cpp things"
Thats because you had to work with processed c# IL in cpp. None of that is relevant to using unity normally
alright so what would an Il2cppReferenceArray be in normal unity?
gotcha
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
If you mean you want new enum values to exist that cant be done without modifying its definition
What is a "state" in this case?
like if enum enemyState has 3 values idle follow and recover those would be 3 states
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
ok so how should i approach this if i want default enemy states
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)
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 🙁
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?
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)
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
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
(definitely not a beginner topic)
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 :) )
well start with the moving bool
also you should def be configuring your code editor properly
unfortunaltey i dont know how to do either of those things 😅
well the bool is simple you try to associate it to something, instead of hitting it with true everyframe. it should only be isMoving = true when the agent speed is above a certain threshold number
the editor . follow these instructions 👇
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i see, i tried to set up something similar but i dont think i set the concept of speed correctly
show what have you tried
is there anywhere i can find a guide with visual scripting for an inventory system
i couldnt find any on youtube elol
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
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
Yes, you can move the camera's parent with the player
In a multiplayer game, have the camera as a child of a gameobject. Make a script for the gameobject to follow the player.
yeah that was what i assumed what i would do, thanks
I recommend using Cinemachine for all Unity games.
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
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
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
Very popular explanation on mvps
Yeah makes sense
Where would I start if I want to take this approach
is there a way to apply post processing to UI without it being worldspace?
Well or Screen Space - Camera
!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**
{
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
and you dont have any errors? because it has to be && instead &
OOH THANKS
& works, it just doesn't short-circuit (though yeah, it should be &&)
probably just didn't save & recompile
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
there is also Quaternion.Lerp
the difference between Lerp and RotateTowards is that you have an ease while with the other you dont
ok
you're thinking of smoothdamp
and transform.euleranlges is just the rotation itself
oh you're talking about wronglerp?
should I be using Quaternion.Slerp or Quaternion.RotateTowards
depends on what behavior you want and what the inputs are - there's also 2 ways to use lerp, the correct way of actually interpolating, or wrong-lerp, which gets inconsistent smoothing
And is there any reason to ever touch transform.eulerAngles
not to read them, no
okay, thanks
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); }
}```
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
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
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
that would work be it would be less readable i want smth clean and commonly used for enemy bases
But the current design is flawed if it only uses 1 enum type and you have realised this
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?
yeah exactly i want to drop enums from base
for smth maybe more flexible and commonly used for enemy bases
public enum StateType { Default, Custom }
public struct StateKey
{
public StateType stateType;
public int stateId;
}
Can be used with a Dictionary for example
ok that would work
like a dictionary for the specific enemy?
wouldn't a map be better?
Anyone know how to walking animation in unity?
Is there any script I need to write?
how do i start learning c#?
this is quite a vague question
you need to get quite a bit more specific than that
eg, 2d or 3d? frames or tweening? what perspective? etc
there's a crap ton of resources and i'm a bit overwhelmed
there are resources pinned in this channel
most of the resources are alternatives, not steps
choose one and go with it, if it isn't working out, try a different one
how'd you learn
2D like frame
i read the resources
to be completely honest with you at some point reading is just neccasary for learning a language
especially programming
i'd really recommend article resources, much easier to skim or search through
reading i understand will be nesesecary at SOME point but for now while i'm getting started i'd prefer a video series
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
reading is visual learning though?
you still have to read the code someone else writes in a video lol
well yeah a programming language is written
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
I try to make sense of it
Good evening
Video resources are great
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
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
do you have an event system in the scene?
Send the code screenshot and the canvas screenshot too
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?

typically one big script for everything is a bad idea though
I think someone asked something similar a a bit ago #💻┃code-beginner message
if its completely different mechanics then its a bad idea to put them in the same script
its just for the prototype but I get your point of view
How do I make hitboxes for combat?
Most tutorials last 30 minutes
Using colliders?
if learning for 30 minutes is too much for you, then you should consider something besides game dev as a hobby/career path
You aint here just to judge people
This is a help channel
yeah, this is a help channel not a spoon feeding channel
Some people learn differently
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
here's a hint: tutorials typically tell you what to use
They do that bruh
But 30 minutes is too long
For just some words
then game dev isn't for you. 30 minutes of learning is nothing
Just tell me what yall use for combat
15 learning, 15 watching a guy talk
nah, i am just gonna block you instead. i won't help people who don't want to put in any actual effort
Yet I can talk on this channel
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?
You usually don't instantiate hit boxes, Unity has overlap box that can give you a list of collisions
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.OverlapBox.html
I found it out
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
esc will always unlock and show the mouse cursor inside the editor
If its a build then its up to you to add this functionality
Its not a build, Unity is about to crash
I cant unlock it 
If esc does nothing then the editor may not be responding. then you are probably screwed unless it works again
I forgot to put one line 
poor logic such as infinite loops will cause such issues

Ima alt F4
Guys if Alt F4 doesnt work
then what is the next step
It worked thanks
A backup thing appeared on unity
cool i dont need a running commentary anymore thanks
Can I like override the previous version
or I can just save the backup?
ok nvm
thanks
I love spending 5 minutes figuring out how to re-open the inspector, I feel like a grandma 💔
When I launch my game with this program, my character jumps about one time out of ten. Are there problems with the script?
also 👇
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Don't read input in FixedUpdate
is isJumping set in the inspector? (it shouldnt be serialized to begin with, really, same for isGrounded)
I'm still new to Unity but Is this how a lot of games are designed or is my information incorrect/lacking?
- 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.
- Other singletons are also created with it for core systems (like audio and stuff).
- 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)
- Game menu, garage/shop/etc, and each individual level each exist in its own scene.
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
what are the majority/common ways to handle player data and actions and core systems?
you're basically asking "what's the main way to make a game"
there's not going to be a singular answer for that
^^ depends on your games needs
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)
yeah no this is not really a proper foundation lol
In the inspector, there are boxes that are checked or unchecked for isJumping and isGrounded.
it's like you're trying to learn every tiny rule of world league football before you figure out how to kick the ball
figure out the small stuff first
none of the big stuff will make sense unless you understand the small stuff
and are they checked or unchecked
isGrounded is checked by default and is Jumping is not checked
that part shouldn't be an issue then. might just be the input reading in fixed update 🤷
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
Maybe, because the game I'm playing comes from a tutorial that's 6 years old.
but not because
that stuff typically comes with experience, identifying stuff that's perhaps not as good as it could be and finding ways to improve.
if you have specific instances of code you want to ask about, feel free to (perhaps start a thread in #1390346827005431951)
Does this also apply to learning about game structure?
yeah
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
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
Yo can someone tell me how to make a multiplayer main menu screen
kinda like 1996 main menu doom feel
why does the main menu need to be multiplayer
- servers 2. create server
that's just UI, that's not it being multiplayer. do you not know how to make UI?
oh thats what i meant
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
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
Thank you thats gonna be a big help
note that adjacent fields can also help, like math (especially vector math) and physics (especially kinematics)
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;
}`
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
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).
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.
yeah you wouldn't want to do that every frame but why do you need to ?
you only need to grab it once then cache it
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
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.
either options work , do whatever is easier for you to keep track
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
Just profile in the future to check if this causes performance issues
I've actually never messed around with shaders. My graphics are made with clay sculptures, so in this case, I've got "chunky" grass, so I'm not sure if that would fit with what you're describing.
I guess doing a tag check before GetComponent is probably more efficient, eh?
I don't typically fuss over performance because my projects are small, but this has been an issue in the past, so I'm trying to get ahead of it, if I can.
Definitely better than get component
it is more advanced as the shader needs to be able to dynamically react/deform based on some world position
Once I've confirmed the tag, I'll still need GetComponent to check their velocity.
But the prior technique of just using 2d physics should be fine if you restrict how many can happen at once in a frame
use TryGetComponent instead and ditch tags
I believe on trigger stay has a collider sent which you can just do collider.attachedrigidbody no?
So then collider.attachedrigidbody.linearvelocity? Idk I haven't used 2D in a while but that's a thing in 3d for sure.
I'm using a custom movement controller that uses raycast for collision detection instead of rigidbodies.
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.
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
Perhaps an interface hmm? 🤔
I was just about to suggest an interface. Interfaces my beloved
So the grass would have the interface? And players/enemies/etc would pass their movement controllers to be cached and queried (for velocity)?
up to you how you want to approach it, I would not pass them the whole controller just the speed from their movement
does grass needs to be really caring about where the speed comes from player ? enemy ? animal ?
My thinking was that passing the whole controller would allow me to check the velocity each frame instead of just the velocity of the entity when it entered the grass. It might help to know that the ground blocks are 2x1, so the grass is also wide.
No, not at all. Anything that has a MovementController will probably be suitable to rustle the grass.
one thing you mentioned you may have 2 players. Which one should grass 'follow' ?
I'm picturing a very simple animation of the grass wiggling back and forth, so it shouldn't matter which direction the player/actor is moving.
just saying if one player is in there then stops moving, then another player enters it should then track both or
Oh, I see. It would be both (any) object that moves while touching the grass.
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
Maybe, but then that component would have to constantly check for overlapping grass.
Maybe that's a better way, though.
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
That's true. I think I'll try something like that.
Thanks for the input, everyone.
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?
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
Oh yeah I can just put multiple points along the route and animate in a sort of way that looks like its curving
*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?
the PlayerInput component handles enabling/disabling actions so that isn't something you need to worry about when using it
also #🖱️┃input-system
okayokaythanks
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
gotta show where your field is defined too
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)
I'm not seeing "Data loaded" in your logs at all
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
It's not clear what logs we're actually looking at here
or what data you're saving
here's a better snapshot of the console (without the Update loop)
i'm pretty sure the first two 13's correspond to the Debug.Logs before "Data loaded"
label your logs better so you don't have to guess
Debug.Log($"Data loaded with {currentSave.levels.Count} levels");```
for example^
yeah that's what i did in the update loop above
ok well can you show us the SaveFile class?
[System.Serializable]
public class SaveFile
{
public List<LevelSaveDictionaryEntry> levels;
}
honestly the simplest explanation for this is you're just looking at the inspector for a different object than the one that's printing that it has data
oh yeah i'll check that
Can I ask you a question about developing the MetaQuest 3 app here?
oh oof the inspector was displaying the prefab for some reason
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 ?
If I have 30 entities, it would be logical to make script which controls all of them?
yea of course if they all follow the same rules, it's common to have a manager that updates/commands them
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
how can i solve this jiterring?
inputaction is set up normally
collider on obj is disabled
this is the rigidbody
linear damping set to 0 makes no change
try setting interpolation
and make sure your camera following is on LateUpdate
It's using cinemachine atm, and previously I was using lateupdate to no avail
and have you set interpolation
and as mentioned previously, make sure you aren't touching transform anywhere else
yes, interpolation does seem to fix it
i set it to interpolate
any idea what the problem could be?
the lack of interpolation
i've already checked that nothing is calling transform
shouldnt that be on by default?
i recall it being set by default, but ive seen a lot of people asking without that set, so 🤷
is the problem not fixed?
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"
alr ty
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\
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
the speed is okay the rotation is just instant
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
ah yes rotate toward thanks
My character moves forward and backward with walking animation. But how can I rotate it left and right.
transform.forward,
dir.normalized,
rotationSpeed * Mathf.Deg2Rad * Time.deltaTime,
0f
);
rb.linearVelocity = transform.forward * playerStats.sprintSpeed;```
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)
What is it for? Following a target?
its for like the playback system
like i record the player's current interaction and they can replay it in the future. think of it as a ghost like this:
Why does it need to be 100% accurate and what does that even mean?
And if the map changes then how is it a replay if they take a different route
no like if the map changes, for example theres a new wall and if the ghost get to that wall, it crashes instead of going pass it.
because im doing a parkour game and its very accuracy-sensitive
I don't understand what you want to happen. Should it or should it not go through the wall? If it shouldn't, how does that make any sense in terms of the replay?
I use the term "replay" to explain my current problem im facing bc its similar to the problem im having. Im not really sure what they call it since my english sucks, but what im trying to achieve here is the ghost should not go through the newly appeared wall.
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?
maybe try record the rigidbody velocity rather than apply position then it should work with physic
I wouldn't suggest that
I tried that but its not really accurate as said
Its gonna stuck there except in the past the player moves the character else where
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
fr miss that is it the same with other api too? like .moveposition and such
Think of it as a key logger that tracks w a s d keys
could do that then
Well tried but its not accurate
Make it accurate then
Thats why i choose to record something else in the first place
Thats the problem
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
yup
if it's frame times that are the issue, you could probably just use the fixed time step
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
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.
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
What does "moving points" mean and how does that relate to " preset rooms"?
If you would use an interface here, it makes more sense the other way around.
Characters have the interface (IGrassRustler or whatever lol). Grass tries to get the interface from the character on trigger enter, and the interface also has a velocity getter if you need.
Doesn't need to be just characters obviously, could be any medium-large object
for creating the individual rooms, I'm trying to make a script that allows you to move points in the editor to resize the rooms automatically
IE based on 4 coordinates make a room
I don't understand what that means. What do those coordinates represent?
Can you draw a picture? I.e.:
- Here's the points
- Here's the room it generates
Is it always a quadrilateral? Is it a polygon? What shape should it be? Is 4 points always enough?
your problem is currently underspecified
please help i dont know how to fis that
looks like you probably have a duplicated script
ok and how do i remove the duplicated script?=
find it and delete it from the filesystem
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
yea i fixed it. there duplticated script was right undder tutorial info. i prob clicked a button do duplicate it by accident
Quick question for beginner programming theres not anything different between unity 2019 and 6.3 right?
Right, over 7 years they haven't done anything other than changed the version number 
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)
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?
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/GameObject.GetComponent.html
I have no idea why it tells you to just not include the type argument. As far as I know that was never valid in Unity's C#. Maybe it can infer it in the later C# versions that aren't available yet?
But you need to include the type in angle brackets for GetComponent so it knows what type to return.
I have another theory
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
That's not how things work here. You'll need to actually ask the question here, there aren't any voice channels
ah I see, where do I ask?
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.
Show the code and check for errors in the console when playing
do u want me to send the code here?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
And the gameoobject that has the script, is it active?
Thank you! That fixed the error and lets the game load in!
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();
yes
I cant move around in game but I'll see if I can fix that myself first :)
oh shit now that i check it in error pause it does say that the program woke and also called show E, idk why I never got the debug message then
Idk how error pause would fix that but good 😅
lol idk either, so apparently the program is running but not doing anything
So the ShowPress methods are called but the UI objects are not being set active?
yes exactly
If so, the null check fails (or something else is disabling them)
Assign the UI objects that are null I presume
they are all assigned tho?
Then the null checks don't fail and the objects are being set active 👍
Make sure you don't accidentally have more than one of these things in the scene
and add logging around the behavior that isn't working as expected
Debug.Log("Show E called, UI exists: " + (pressEUI != null));```
ok lemme try
It's likely that you have a duplicate of this component yeah
okay i got: Show E called, UI exists: True
but i didn't see the text so now idek what's going on
like a duplicate of pressEUI?
also idk if this means anything but if I stood within range the message kept sending over and over again
Yeah, but if you only see one log from Awake then you only have one of them
Then it is setting the UI active. How did you confirm that it isn't setting it active?
Maybe it's actually outside the view, or it is being disabled by something else, or its parent is inactive or something
i opened hierarchy while running the game and checked to see if the ui is being set active
if i get rid of LateUpdate() then the UI stays active from the very beginning ...
yh there was only one
Wait... I didn't even read the LateUpdate part
Why are you deactivating everything in LateUpdate?
i need to deactivate them at the start no?
LateUpdate runs every frame!
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
sounds like a hands-on lesson about why errors are nice to have lol
mistakes will happen - errors are explicit, bugs are silent
Got it!
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
Are you getting the "Stopped attacking" log when the animation stops?
yeah the logs are working as they should, while mouse1 is being held it prints attacking and as soon as i let go it prints stopped attacking
its just while im holding mouse1 it just stays on the first frame of the animation
So it's not printing early, but it is ending the animation early?
Ah, that's what you mean
yeah like the animations not even playing
Any State means any state
The condition is still true. So it transitions to itself again
Yes
can anyone help me understand scale in unity?
is there any way to have like a universal measure of size for an object
1 unit = 1 meter
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
Can you explain what you mean by this? Like a tool in the editor, or what?
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
that seems like a good way to do it tbh.
(putting it in the scene)
you could make an editor tool perhaps
but the "size" of a 3D object can be vague
is this a model or a sprite?
like.. how "big" is a cat
You can always use the renderer bounds: https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Renderer-bounds.html
For models, you should make sure all of your meshes have a consistent scale
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
but if im doing something where size needs to match, like I want the width of a wall to exactly match the floor, is there a way to do that without just putting them next to eachother?
create all of your models with a consistent scale and everything will work out correctly
how are you making the objects?
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.
right now im importing assets from the unity store, but I will be making them in blender
Blender tells you the size
got it
Just make sure you import/export at a consistent scale and you're good
It may be helpful to create prefabs with consistent scales
e.g. you prefab everything to fit onto a 4-by-4 meter grid
so the size from blender will be transferred if I load in the 3d model
yes although there may be a conversion factor
which can be addressed in the unity import settings or the blender output settings
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
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
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)
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);
}
}
what?
thats really not something you should share here. if you have a specific question about this then just ask
yeh, the comments
"drag the parent player object here" yeah bro pack it up
yeh lmao
its okay tho
can use ai to get started
i just dont see the point
The classic incorrect use of Time.deltaTime...
lmao i didnt even notice it
it feels similar to the vid brackeys made, considering the xrotation variable
They also fumbled the deltaTime
dont really feel like looking at that huge wall of text tbh lol
thats what happens when you train LLMs on incorrect info engrained on the internet
it literally is the exact same apart from the comments
the "first person movement" video
its not AI generated, it's just taken from Brackey's and reposted here
the comments look suspicious of "AI"
It's AI generated and the AI generated it from the thousands of brackeys clones on github
That deltaTime bug is never going away 😭
too bad Brackeys does Godot tutorials now
Now he's their problem
I've always wondered why the "mouse sensitivity" was so high
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
Before what update
!learn 👇 instead of finding something to just copy from, consider learning what you are doing so you can make it yourself
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
but also yeah, movement hasn't really changed in a long time
Any movement script from the last 15 years will basically work the same now as ever
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
What? everything is crashes, I used to add velocity to objects and it never broke, now it does and nothing from videos goes with minimal errors
Wdym "everything is crashes"?
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
This was in the video that i used
that's because you copied it wrong
this is a simple coding or copying error on your part
this would not have worked 15 years ago either
you also need to get your Visual Studio configured properly so it shows errors
I tried, i have the unity extetions and idk why
!vscode
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
why?
Because you messed up. Not sure how to anwer "why"
You copied incorrectly from the tutorial
(whatever tutorial you're using)
But i retyped it, whats wrong? it's late and i need to make it in a day or so
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.
now compare that to your own code because it is, in fact, not the same
Where do you define _playerInputController in your PlayerController class?
and digi is here just in time to tick the counter
"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
And no, it is not "pretty same", it's actually almost completely different
There isn't a single thing the same between your PlayerInputController and theirs but the name
Is that a genuine statistic or made up for effect?
It is every time I've seen this exact notion repeated by someone with my own eyes in this server
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
Yea, coding sucks
it's much easier if you actually pay attention to the information provided to you
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.
I am made for farm work, i dont know why i went to cs, it suckss, i could have a ranching job rn
yea, i keep learning every day
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
spelling is important. get vs code configured like you were instructed to before
and this with extra troubleshooting steps for configuring it: https://unity.huh.how/ide-configuration/visual-studio-code
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
that looks confiugred to me
there's also no errors in that code, is there?
Why is my inspector not creating a sprite list?
Do you have any compile errors
thank you
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?
reference the component and replace the sprite property of it
eg mything.sprite = newSprite
how do i reference an image
getcomponent<image>() doesnt work
why not
yes its telling you you're missing the namespace
Probably using UnityEngine.UI or something
what is a namespace
how do i make it work
Basically a folder for code
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
oh like an import
when in doubt also check the docs
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.Image.html
there are a ton of Image classes, so you have to make sure to get the right one, too 😉
after putting in using UnityEngine.UI i get this error
thats just unity editor bugging out its not your code
you can just clear it, restart unity if it appears again
ty
ineteresting how even the docs has example code of changing a sprite
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.Image.html#UnityEngine_UI_Image_sprite
granted its old input system but the concept is there
General rule of thumb, if the line number is some long hex address in <> you can probably ignore it
Check the stack trace and see if any of those lines are in code you wrote
also usually coming from UnityEditor instead of UnityEngine
it aint waking up 😢
*cues the RATM track - Wake up *
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
You can have custom editor ui to quickly use presets perhaps to set value or you can have other scriptable objects to assign preset values
Make a class or struct
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
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?
Classes until later c# versioning
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
}
?
That and for most cases you want to pass stuff around as a reference
this feels like inheritance + specifically interfaces
I kinda just scrapped my entire codebase because I was making things over reliant on each other
abstraction!
yes - though you can set the stuff in the inspector. (if you want)
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.
}```
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)
why do you need to override it?
you don't need that override
don't make it abstract
You can make it virtual which allows for optional but not required overloading
Hmm yea I think you miss understood something. I thought you were making say loads of item type classes and duplicating fields/properties.
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
you definitely misunderstand
you're confusing types and instances here
learning time! https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/inheritance
it makes every type that derives from the parent have the same fields, but it doesn't make every instance use a shared dataset
(statics would do this behaviour)
Every vehicle has wheels. But that doesn's mean they're all sharing the same pair of wheels
Not super new to unity, but can someone help me import an FBX? I can get the model in, just cant get the textures
Import textures separately
I learned about static variables years ago
I'm just stupid and I haven't seriously coded in a long time so I'm forgetting basic things .-.
ive tried that lol
Overengineering cause I went down the rabbit hole of scriptable objects too
Itd be helpful if someone could guide me through it
Gltf better if you want full asset import
Nothing wrong with re learning this stuff! Then you will be in a stronger place to program again.
yeah I read through this now I just feel stupid xD
this is a unity server
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
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
is there a way i could basically just do like a for loop that runs through the hierarchy and sets the velocity and animation speed of everything else except my character to 0
use an event instead
how do events work
it pauses things that rely on scaled time. there also exists unscaled time
I am using UGS for leaderboards. Whats the recommended way to implement some sort of profantiy or hate speech filter on names?
ultimately you have to have a system for extra checks because someone who wants to be vile will always find a way. You could at least begin with running the name through some sort of list/file of known profanity words
a library specifically made for this is probably your best bet cause they might contain even variants using numbers as letters n all that
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
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
Yeah I guess I am asking where do people usually put the profanity check, at input, at display, in unity, in cloud code, etc
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
hi
did you read the info in the link?
btw is this site real
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
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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.
Something with that script on it was destroyed. It does not mean that there are none in the scene, it means something was referencing one that no longer exists
So, probably your GameOverScreen. Which CollectAndDestroy is that referencing?
do people usually create test suites for games, or is everything done manually ?
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!
The one you're looking at in the inspector and the one that's logging the number are two different XpBars
sorry for the late reply but it is referencing the mole's (the cylinders) collect and destroy script
Are you sure? If you click on it, does it highlight the one in the scene? Does it stay assigned in play mode?
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.
Just wanted to check back in and say thanks, I read this and am investigating
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?
Then most likely the thing it's assigned to isnt in the scene. Drag the scene object in again
Probably means the one you're reading from and the one you're colliding with are two different instances
Are either of these objects prefabs
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
What do you mean by this?
And the object with the script is in the scene for the script
I double checked and dragget it again
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
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
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?
To debug log
You can log the one that's changing its bool, and the one GameOverScreen is referencing, and see if they're the same ones
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
coolmethod(param1, param2, etc.)
time to refresh on basic c#
That's why I'm in code beginner
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??
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
more or less
is this the chat for understanding unity coding?
Okay so i can ask question for doing things like first person movement and camera controlls?
Be sure to checkout tutorials on Unity Learn first. All of that can be found there.
Start with Pathways courses.
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
Beginning with https://learn.unity.com/pathway/unity-essentials
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'
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
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.
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; }
}
hm alright, i see, interesting enough approach for me to see and gives a bit more insight in it, thanks for the input.
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
what's the best technical way to make a npc move in 2d top-down?
As with all other "what's the best" questions, the answer is "there is no best" and "it depends"
makes sense
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
You're positioning it with Instantiate so probably get an idea what the offset is doing
so should i delete the offset?
i don't understand
0.5f would imply that it's trying to center it, but your prefab pivot not represent that
Well, assuming in units of 1
so what do i have to do
mess with the offset or pivot of the prefab
the pivot is pretty much at the center of the prefab
so thats fine
so i think
offset i need to change
i don't know what i need to change in the offset then
usually it's more like x * tilesize to get to the cell pivot, then to center you'd do tilesize / 2
just remove the whole vector3?
so (x+tilesize) /2
not the same
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
(x * tilesize) -> cell pivot
tilesize / 2 -> half length
so (x*tilesize) + (tilesize/2)
the extra offset could be a negative offset though depending how the grid pivot is setup
sure
I guess there can be 4 different offset variations, (x, y), (-x, y), (-x, -y), (x, -y)
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
oh hmm
thanks for helping anyways
i just can't wait till im done with this project
it's a class
where we have to do a solo project
oh you're using y, should be z
and i never do programming
i'll try
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
so i delete y and put in z
thanks so much anyways
you're setting the y value in the vector, but it should be the z value
i really have no idea how to code so i can't change this a lot other than with chatgpt
last time i properly coded was a year ago or more
Yeah, grid stuff can be complicated, but it's not necessarily a unity thing, but more general coding. It's fun to learn though.
it would be fun if this wasnt on a deadline
i'm basically using procedural generation to create dungeon levels
Unity actually provides some grid class, but sometimes better to just make your own anyway
one more question
im creating a prefab out of models
how do i set it a pivot
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
so i make a little nothing burger object and then place it where i want to be
then parent it
Empty Parent -> Mesh Child
then you can move the mesh child freely and just reference the parent for the pivot
what i've came up with now sort of almost looks like i want it too
and thats fine by me
thank you for your help
please be clear when you use chatgpt, lot of people uncomfortable helping that kind of stuff
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
no
it's a thin veil of morality
Nah thats called using your brain to find what code would be useful in that situation
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
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
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
Yes, actually!
I'm not sure what you mean? What you've posted would work assuming unwrappedData exists in the dictionary
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;
Write an implicit type conversion operator. (Fen just wrote you an example!)
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)
yes, though it kinda needs to be like that as the wrapper is what serializes the data. but when i actually use it i dont really care about the serialization class
this is part to make it easier to debug from the inspector for other teammembers
Are you sure you want to put the wrapper itself in the dict instead of the unwrapped type though?
so you need to index the dictionary with the unwrapped value?
i mean i could just do both, and have one be serialized as its literally only to be able to see it and be able to manually confirm it is what it should be
then just have #UNITY_EDITOR around the serialization
yea pretty much, if not id just do a dumb workarounnd like i said above
This won't work - Unity gets very upset if you have different serialization formats for a type in a build vs in the editor
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
can you elaborate on this?