#💻┃code-beginner
1 messages · Page 547 of 1
This guy has a lot of resources about making AI btw
https://www.youtube.com/@IainTheIndie
I worked on Medieval II: Total War, The Bureau and Bioshock: Infinite.
in my game, everyone is an Entity
Entities experience perceptions that can be attributed to other Entities
Entities make decisions based on these perceptions and their memories (e.g. they can be friendly or unfriendly to one another based on prior events)
do you recommend git-ammend on youtube?
So there's no special "Player" class at all
One thing I don't really get about the whole "blackboard" idea is how it's not just a Dictionary<string, object>
git-ammend is good youtuber
Keeping your keys and values in order sounds very annoying
I have separate dicts for int, float, vector3 etc
Then methods Get/SetInt/Float/Vector3
And a dictionary for object for when it is absolutely needed
Idk how I'm going to serialize that yet tho..
what are some things you store in these dictionaries?
Not really familiar with that youtuber but seems decent
Not many youtubers touch intermediate subjects like this
I can't actually remember if I'm even using it yet
I think I just futureproofed
But it could be any data that doesnt fit into the other types
I may have just constructed a "blackboard" in a slightly roundabout way, with things like:
- Perceptions (I experienced a strong visual stimulus that I associated with Bob)
- Relationships (I am afraid of Bob)
- Motives (I am fearful right now)
- Traits (I really hate being fearful)
what did Bob do 😭
well that's down to the Inclinations!
those provide default relationship values based on qualities of the other entity
I'm running out of nouns, help
I don't actually store everything in the blackboard, I do have data types like TargetInfo which stores the detection state, aggression, observed actions etc. per each NPC's target
I've just struggled to imagine how I'd enjoy using a "blackboard", since it's this giant bag of completely random values with no structure
It makes sense for the entity to have a pool of knowledge
I mostly use the blackboard for evaluating Utility AI
hence all of this crap information
okay so i've break my code into more modular pieces, i've created ITarget IDamageable etc. So for example if i have Player: Character, ITarget, IDamageable, and then if i store ITarget currentTarget in my Enemy, can i do if currentTarget.GetComponent<IDamageable> (...)?
would that work?
you cannot GetComponent on an interface
its not a Component

You can!
oh rly?
Sure
(well, if you cast it)
Ooh, I just realized that you could add members to the interface that match what MonoBehaviour already has
using UnityEngine;
public interface ITarget
{
GameObject gameObject { get ; }
}
IComponentLike
can I just do it like that?
Cast to what?
for things that are shaped like a Component
yep, exactly what i was about to suggest. can just throw the getcomponent declaration on the interface
and then if (gameObject.GetComponent<IDamageable>)
presumablpy a Component
after adding the relevant members to the interface, yeah
my first thought did not involve changing the interface
(bad)
because you can't call GetComponent on the interface without it either being declared as part of the interface or being cast to an object that has the method on it. you can call GetComponent to get an interface which might be what you were thinking of
Ohh, on the interface yeah i misread
yeah I think there was confusion, you can GetCompeont <interface> you cannot interface.GetComponent
Nevermind me 🤦♂️
using UnityEngine;
public interface ITarget
{
GameObject gameObject { get ; }
}
if (gameObject.GetComponent<IDamageable>)
that works?
yes
use proper capitlization for props
it will get any component that implements that interface
i think it has to be lower case @rich adder
I would not recommend using the name .gameObject though, since all components already have a property of that name
I think the idea is to match gameObject so it is just automatically implemented
When added to a monobehaviour
yes
Indeed.
Thats the whole point
I somehow never thought of that
oh had no idea it autoimplemented
got it from stackoverflow, is this like outdated?
I've really wanted to be able to make an interface that demands an object be...Component-shaped
I wasted my time doing GameObject Object => gameObject 🥲
I used to make interfaces with GetGameObject() methods before I realized I can just add a gameObject property, which is already implemented in a MB
lol glad i could help you think of something 😄
Ah, I get it, you want your interface to have access to the MonoBehaviour's gameObject property! That's actually brilliant
hehe look at us learning new things every day
I must have thought "but I couldn't implement the member myself..."
I've never thought of doing that either...
exactly
But you don't have to! Your type just has to have the member
Hence why you don't use override when implementing an interface
game changer 😎
I have always just passed it in as a parameter, or made a new member
you aren't overriding an abstract member. you're just meeting the criteria of the interface.
Now, this does still leave you with the bugbear of not being able to serialize interface types
But there are some workarounds..
you just made me go blind with that light
so that way i can store ITarget and just check if that ITarget also implements IDamageable interface etc, just by doing if(currentTarget.gameObject.GetComponent<IDamageable>), or TryGetComponent right? no need to initialize that gameObject anywhere?
Bingo
im using odin inspector i think they are already serializing interfaces
target.gameObject is accessing the gameObject member of whatever MonoBehaviour-derived type of yours implements the ITarget interface
that's sexy lol
And, if you decide you need some kind of "abstract target" that isn't actually a component, you just need to implement the gameObject property yourself
That might get icky if you decide you have to just return null
But I dunno if that would even happen in practice
Something I've learned over time: You have to draw lines in the sand about abstraction
"Yes, every target IS associated with a game object"
right
When you get more abstract, you're giving up on some capabiliities in exchange for being able to work with more kinds of things
if you go too far it decomposes into doing nothing to everything
very cool
public void PlayGame() {
return;
}
i guess this answers my question " is there a specified case to use interfaces over just using the class"?
interfaces yeah
Yeah, that's the idea.
that's also confusing atleast for me at the stary of my journey
when to use abstract classes instead of interfaces
You assert that you only need a few capabilities.
Now you can operate on anything with those capabilities.
is it just preference most likely
But you can't do anything else!
you cannot use multiple classes for 1 class , interfaces you can use as many as you want
Abstract classes are used when there's actual concrete behavior you need to inherit
right, although the classic animal hierarchy falls apart really quickly
Do you people use default interface implementations?
Just realized I have still not used those
Not really
They're mostly useful for inserting new members into an interface without breaking anything
there is so much to learn about proper approch/patterns and this is terrying me 😄
when to use factory pattern, when to use this when that etc
i am spending more time designing my systems instead of coding them and learning
thinking im doing it "the wrong way"
at some point you have to Make The Damn Game
you will create paralysis by analysis don't
this is so true. time to restructure my class hieararchy 
Most of my larger systems I have rewritten from scratch about 2-3 times before I got enough experience to do it right from the get go
its a trail and error thing, see what works best for your projects eventually
you learn by making your mistakes and correcting them on the next iteration
hopefully not on production
indeed
going from game to game, gradually refining the idea
My settings system is the result of like...four different projects
I like it now
I do not like what I had originally
Enum hell
You learn more from failure than you do from success.
and you learn more from doing something than from doing nothing :p
What did you move to?
could you recommend any good learnign sources?
for intermediate level?
if any
Each setting is now an asset.
Oh yeah, that thing
i've been watching git-ammend on youtube but i barely understand his videos and the level of compelxity he's doing
The doohickey
I have script like this:
public class GameManager : MonoBehaviour
{
public GameObject fallingObject;
public float maxX;
public Transform spawnPoint;
public float spawnRate;
bool gameStarted = false;
void SpawnObject(){
Vector3 spawnPosition = spawnPoint.position;
spawnPosition.x = Random.Range(-maxX,maxX);
Instantiate(fallingObject, spawnPosition, Quaternion.identity);
}
void StartSpawning(){
InvokeRepeating("SpawnObject", 0.5f, spawnRate);
}
void Update()
{
if(Input.GetMouseButtonDown(0) && !gameStarted){
gameStarted = true;
StartSpawning();
}
}
}
And I try to put a prefab as a fallingObject but nothing falls when prefab is disabled, but when I enable it it falls and prefab gets destroyed so nothing can referance it anymore, why is that?
"the prefab is disabled"?
is fallingObject in your scene? it shouldn't be
that should be a reference to a prefab asset
you're probably touching the fallingObject prefab instead of the spawned instance
I should delete it after I already made it into prefab?
Do you have a way of loading a setting from script? By GUID or something? Or do you need a direct reference to the asset
Don't reference the object that's in your scene
Exactly
I store references to them. I can fetch all of my settings assets to construct the settings menu
But I never load them by name
thats because he covers advanced topics for experts, start with someone more beginner friendly, like codemonkey or something
Instantiate returns you the copy of the cloned object
That's just an instance of the prefab
Which is no different from any other object at runtime
@lyric rapids you need to save the return of instantiate to a variable
That does the trick, mb, thanks a lot once again
The problem is that they're referencing a scene object instead of the actual prefab asset.
yeag
just reminder, if you plan on destroying the spwned item do so on the Instance not the prefab
I also never serialize them by name. The only strings I serialize are user-provided labels and a couple of niche settings, like screen resolution.
It is a bit of a nuisance to not be able to just write Settings.quality or something like that
I do have a few singleton assets that store commonly-used settings assets so I can refer to them without assigning a reference every time
Will " yield return new WaitForSeconds(0f) " still wait one frame or will it execute the rest of the code on the same frame?
I would expect it to wait for at least one frame (probably not more than one frame)
any yield will wait a frame
The core idea is to keep as much out of the game's code as possible. It's like how you wouldn't make a class for each kind of enemy in your game.
What you would/should do is:
float timeToWait = whatever;
if (timeToWait > 0) {
yield return new WaitForSeconds(timeToWait);
}```
Thank you ^^
anyone know how to use raycasts to tell where the player is looking
cast a ray from the main camera's transform.forward?
ok yeah but im in the code-beginner for a reason
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.Raycast.html use this and put the player's camera's transform.forward into the direction parameter
What do you mean by tell where the player is looking
do you mean find out what the player is looking at?
You answered that in your question - use a raycast.
like how far the point is from the camera
and i asked becuase i dont know how to use raycasts
do a raycast and check the distance in the RaycastHit
You can see example code in https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.Raycast.html
RaycastHit has a distance property from you can get the distance https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RaycastHit.html
Has anyone ever tried, where the console says null reference error, but you have referenced field assigned, with the correct type ? In this case it's a gameObject with an image component
Perhaps you're looking at the wrong object.
Click once on the log message during play mode and Unity will select the offending object
since when is that possible? 😮
but i have all the fields assigned
it shows you the object that is null?
Again: You could be looking at the wrong object
doesn't mean you couldn't have a null inside one of them
It's also possible that you have a valid reference, but then you access a null reference from it
foo.bar.baz
if foo is null OR if foo.bar is null, you'll get an error
maybe show the line that's given in the stacktrace
It shows you the "context" of the log message. You can provide one yourself:
Debug.Log("Hi!", gameObject);
oh, i thought it automatically points you towards the object that is null
Ah, no, it just selects a unity object
It's not telling you where in an expression the exception came from
I tried putting some Debug logs in to spot where null error arose from. Now i get this error, even though they literally are on the same prefab. Anyone got any ideas ?
great that you dont show the line numbers of the code
the Plus signs indicate you are not looking at the prefab itself.
You're looking at an instance of the prefab in the scene
You still haven't proven that you're looking at the correct object
well, it could be a prefab variant, i suppose
or that
but yes, I'd like to confirm that the actual prefab has these components
add GetInstanceID to the debug and the gameobject as the second parameter
There exists a DoorController that does not also have a Door. Since the one you've shown has both, then that object is not the one this error is talking about
it can also be that you are destroying door component somewhere in your code
highly unlikely between Awake and Start
true just pointing out the possibilities
I tried this, and console confirms they are indeed on the same
my friend, that's a prefab not a scene object
...how is Start even running?
Okay, but what about the error message? Add the instance ID to that message
Instantiated objects get a negative instanceID (although persistent objects can have a negative ID, too)
But Start shouldn't be running on the actual prefab object
Im so fking stupid. Very new to Unity. There was just an old gameObject that i had forgotten to remove the DoorController script from. Adding the GetInstanceID helped. Was a good trick, thank you!
That'll do it (:
hence why I suggested doing this!
Pretty common mistake
someone can help me correct my code, I can't find the error, it's a 2d game
the error appears to be that the “groudCheckLeft” and “groudCheckRight” functions are not defined in the “PlayerMovement” function.
:
Where is the actual error?
I don't see any errors indicated in the screenshot
if your code editor isn't showing errors and providing completions, see !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
make sure you read the entire error message
PlayerMovement is a class and your groudCheck's are fields none of them are functions
this is the first code I've done, so I don't know where the error is....
did you read the entire error message? because it tells you what you forgot to do
the stacktrace will tell you
it will literally say "You probably need to assign the groudCheckLeft variable of the PlayerMovement script in the inspector" which is what you've forgotten to do
sorry to ask this, but how do we do it? (I told you, I'm not really good at coding, considering it's my first).
ignore the code and drag the desired object into the slot on the object's inspector
surely whatever tutorial or course you are following would have shown you how to do that
no unfortunately 😅 🫠
then it's a shit course/tutorial or it is beyond your skill level. start by learning the basics. there are beginner c# courses pinned in this channel and the unity essentials then junior programmer pathways on the unity !learn site will teach you how to actually use unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ok..
the error appears to be that the “groudCheckLeft” and “groudCheckRight” functions are not defined in the “PlayerMovement” function
Make sure to actually read the error, because that's not what it says at all.
also they are not functions
anyone know how to make the hand of this rig rotate so that the palm is against the object
looks like you've already done it
hold on
yes i know
but hold on
the palm is just keeping the same rotation as when its created
You need to do a raycast and project the cast direction on the surface to get the tangent along which you want your hand to align
is there any other way to do that
idk how
learn
you certainly don't know some other unknown way either
Physics.Raycast
Vector3.ProjectOnPlane
You can also use RaycastHit.normal to get surface normal.
https://docs.unity3d.com/ScriptReference/RaycastHit-normal.html
You'd probably have a script that has LateUpdate, which runs after animations have completed.
In LateUpdate you raycast (red) along the arm towards the hand, and if it hits something then you get the normal of the hit(yellow) and use that to create a rotation for the hand
create a rotation for the hand
This part is more complex
Indeed.
This is a very common situation
It's often easy to find one direction
But you need second direction to figure out a rotation
Cross products likely come in handy here
Hence the "tangent"
im just using an IK script on the hand and set the target to where the player is looking
Actually yeah probably should just project the arm's direction onto the surface with ProjectOnPlane like praetor is suggesting I think
This way you get the "forward" direction of the hand resting on the surface
You can use the normal as the "up" direction
And from the forward&up you can construct a rotation
Vector3.Project tells you how much of a vector lines up with a second vector
Vector3.ProjectOnPlane tells you how much doesn't line up
that doesnt really help me understand what im suppoused to do
my idea was just point the front of the palm away from the camera but obviously that wouldnt work
Maybe this is a bit over your skill level then
Need to be fairly familiar with vector maths to do this kinda thing
i just thought it would be funny for the player to touch things
well i give up
i will fix this when i have more time
bye
Now that I think of it, it could be as simple as cs transform.forward = armForward; transform.up = hit.normal;
Orcs transform.rotation = Quaternion.LookRotation(armForward, hit.normal);
Yep
Might be some weird edge cases that need to be handled
But that should get one started
If I have a really low framerate, and have say something that moves all the ways to the right, and then back to the left based on Time.time
Is it possible that the frame hithces or pauses could be perfectly so that you never see it move?
;-;
How to avoid that, or should I even care?
bc Time.time is not capped
Sure -- if the object's position is entirely a function of the time, it could stay in the same spot forever given the appropriate framerate
(although, I'm pretty sure Time.time can't increment by more than the maximum delta time of 1/3 of a second)
i have an animation that is a function of the time
oh i see
i didnt know it actually was capped
Hopefully your game isn't running at under 3 FPS
oterhwise?
well if your game runs at less than 3 fps then you have some serious problems
and at that point, it's more a slideshow than a game
it does not
It's a setting in the Time settings
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Time-maximumDeltaTime.html
Why are you concerned about this? Does the object need to collide with things, perhaps?
I really wish these docs would show the default value
no its purely visual
https://hatebin.com/acjnhwjbti
so i have this basic movement script for my game, but when i walk into objects my character just keeps moving forward and its getting like teleported back, its looking very bad and when i walk into an object mid air, it also keeps me in air for few more seconds, what can i do to avoid it?
who told you to use transform.Translate
the biggest issue is you're using translation to directly move ur character..
tranlsation doesn't consider collisions
if u want to continue to use transform.position/translate to move the player you'll have to end up doing a few work-a-rounds to get it to behave correctly
well, i watched unity junior programmer lessons and they used it there so i thought its a good idea
if u swap over to rigidbodies u could use playerRB.velocity = or playerRB.linearVelocity considering which version of unity ur using..
and for the platforms u could use playerRB.MovePosition
should i use rigidbody?
if not then i'd def use a CharacterController and its Move() function
you mean the lessons in learn.unity.com? 😱
yea
Was it the one with a car?
Rigidbody-based movement ensures the player collides properly with objects and doesn’t "teleport" or clip through them.
the one with car, and that dude throwing pizza and some more, idk i watched a lot of it
rb will almost certainly improve the feeling and collisions
so i should rewrite the whole thing to use rigidbody and that's the best solution?
I've seen the car tutorial that moves a rigidbody with Translate. It's a bit embarassing
imo yes..
actually i prefer Kinematic Rigidbody solutions.. (kinda best of both worlds) but thats a bit more complex
it shouldnt be hard, just replace the transform.Translate and transform.Rotate with its rigidbody equivalents, for example instead of transform.Translate use rb.velocity/linearVelocity like Spawn recommended
okie dokie
Hi, I'm currently working on 2d fighting game for 2 players, I finished coding of the character that fights, but now i'm struggling with doing the 2 players system, how can I make it so I have 2 characters, each work dependently of each others?
I would appreciate any help, my project deadline is so close 🙂
You mean independently of each other?
Ideally both characters would use the same scripts
Just different instances of those script components of course
start panicking. multi-player even local needs to be designed in from the start not added as an afterthought
Local or online?
local
well
am i stupid? i've red the unity documentation about lienarvelocity and came up with
playerRb.linearVelocity = new Vector3(0, 0, vertical);
playerRb.linearVelocity = new Vector3(horizotal, 0, 0);
(also tested a lot of different solutions)
none of them works as i want, whyyyyy?
i'm cooked, I guess?
playerRb.linearVelocity = new Vector3(0, 0, vertical);
playerRb.linearVelocity = new Vector3(horizotal, 0, 0);```
setting velocity wont keep the velocity it already has
ur effectively re-writing it on ur very next line
for example if u wanted to keep the X and Y on the first and just adjust the Z
it'd be more like
playerRb.linearVelocity = new Vector3(playerRb.linearVelocity.x, playerRb.linearVelocity.y, vertical);
you'd pass in its own velocity it already has to the X and Y if u dont want to mess w/ those
otherwise ur setting them to 0 killin off any velocity
if (Input.GetKey(KeyCode.Space) && isGrounded)
{
playerRb.velocity = new Vector3(playerRb.velocity.x, jumpHeight, playerRb.velocity.z);
isGrounded = false;
}``` for example this would be a jump
but i used Vector3(transform.position.x, transform.position.y [...]
and it did not work
ok so after a long time i understood why my socket messages are being sent from unity editor but not from iOS
Failed to send event my-event: Operation is not supported on this platform. The unsupported member type is located on type 'System.Object[]'. Path: $.
how do i go around it?
this is the lib im using
https://github.com/itisnajim/SocketIOUnity.git
and here is my event emitting:
public void EmitEvent<T>(string eventName, T data) { string jsonData = JsonConvert.SerializeObject(data); Socket.EmitAsync(eventName, jsonData); }
For velocity?
i usually construct my vector like FinalVector during the update after i get my inputs.. and then after everything is added together i'll pass the final vector
yeah i used it cuz i didnt knew i have to put rigidbody instead of transform
Currently this is what i'm working with, but they are using the same controls, so yeah, I don't really know how to fix it, I was thinking of making a constructor that takes the controls from the PlayerManager, but I don't know if this is the right approach
You need to understand the difference of a position vector (like transform.position) and a directional vector (like a velocity)
Wouldn't make sense to plug a position into a velocity
That would just yeet you outwards from (0, 0, 0)
You could give each player diffrent controls example. Player 1 uses WSAD Player 2 uses arrows
ect.
public float speed = 5f;
private Rigidbody rb;
private Vector3 moveInput;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Read inputs in Update
float horiz = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");
moveInput = new Vector3(horiz, 0f, vert).normalized; // Normalize for consistent speed
}
void FixedUpdate()
{
// Apply movement in FixedUpdate
rb.velocity = new Vector3((moveInput.x * speed), rb.velocity.y, (moveInput.z * speed));
}```
heres just the most basic of RB controllers..
Well let's say I'm so Negative now after what @languid spire said, and I feel like i will do all of it for nothing ...
How much time do you have?
should I make a new class for controls or the Player Manager could handle all of that?
ummmmmm 5 days
That's manageable, as long as you put in enough effort
And depending on how complex the game already is and how it is designed
the thing is I'm so lost, I don't know where to start from
Search for local multiplayer tutorials for unity?
I did, some of them are so complex to the point I don't understand how to implement the idea to my project, and some of them are stupidly simple, couldn't find anything in the middle, I even tried Udemy
well, that does work but it creates a huge weird input delay....
damnn
i didnt know making player move is so hardd
The "delay" is probably because input axes have some smoothing to them by default
You can use GetAxisRaw to ignore that smoothing
You can also change the smoothing in the input manager
okiee that does work now
whoopwhoop
but still its kinda weird for me
even w/ that little change u should have much better colllisions w/ walls now
why do i have to put movement in fixedupdate and make it complicated instead of just using
playerRb.linearVelocity = new Vector3(horizotal * speed, playerRb.linearVelocity.y, vertical * speed);
in update?
Because then your movement speed would fluctuate based on framerate
Because it needs to reside on the physics step, unless of course you want framerate dependent movement
oh yeah right
This doesnt affect anything until the next fixed update anyway
you can assign velocity in Update. it won't run until FixedUpdate . . .
then just keep it in FixedUpdate
I'd keep it in FixedUpdate for clarity's sake
yup
Also fixedupdate runs just before update...
i used transform.rotate to rotate my character before, now when the character rotates its still moving along the normal xyz axis
So update would introduce one frame of delay, right?
probably not, as if it does run only until the next FixedUpdate call it shouldn't provide any delay and even if it did it probably would be minuscule and unrecognizable
ive always still used transform to rotate.. never really an issue in my projects..
using torque and stuff was a bit complicated
now if my character had to turn and rotate real-world objects. then yea i probably woulda figured out how to do it with Torque
but my player rotation has nothing to do w/ collisions
it feels like the mesh is rotating but not the rigidbody or something idk
The order is:
FixedUpdate -> Physics update -> Update
So if you set the velocity in Update, it will have effect in the second Physics Update
If you set it in FixedUpdate, it will have effect immediately in the first Physics Update
ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
if the object the rigidbody is attached to rotates.. the rb rotates w/ it
waitttttt
i think i set my rigidbody to have fixed rotation so it wont spin in air in radom directions
(sorry for flood)
unless u have code rotating the rigidbody too.. then there would be conflicts
fun fact.. my rigidbody controller doesn't actually rotate.. i rotate a gameobject and the rigidbody just moves (in that objects forward direction)
well even so, it would be a minuscule difference of delay
cool fact
I can't believe that people don't care about a whole frame of delay in the input
When it can be easily mitigated
i shot him first I swear!
dollarstore wifi Ftw!
dollar store wifi playing on a virtual machine hooked up to a server
COD becomes a prediction shooter 😉 lol
I'm not saying to ever put it in update, I would keep it in fixedupdate either way
HELP 🤣
ya, u could technically get away with putting it in either.. since changing the velocity in update wont take affect until fixedupdate..
It can be slight but it also scales with your framerate
the only thing i dislike is when input is done in fixedupdate
feels soo janky and disconnected
But I just explained why it's sometimes better to do it in FixedUpdate
Do you want to start moving this frame or the next frame?
true true.. im moving to the new input system either way.. soo my input code is irrelevant as of now
When you press a button
well of course it does
im guessing a full refactor is in order
are we bikeshedding? i like bikeshedding
my game runs at 400 fps at the moment..
my body doesn't and couldn't ever discern 1 frame of input lag
What if your game is performance intensive and runs at ~60FPS
I'd rather not have an extra 16ms delay on the input
oh wait.. i use a CC.. soo doesn't matter to me either way heheh
I should probably continue working on my project 😅
as should I, lets do it 👊
I would not say these things run "before" or "after" each other at all
nevermind i totally would lmao
I'm not sure exactly when the input state gets updated, though
If it's updated when the input events happen, then we are doomed
i have that pinned up on my wall ^
It'd be worth testing that
i still need it for OnMouse stuff
I mean this is what i see
good point, so then there is no reason to keep rb.velocity in update
excellent
try it both ways and see for urself
which would be an accurate assessment
The extra 16ms of input lag makes the game more cinematic.
yeah true
If you have time please test it also so I can get some confirmation lol
i doubt you'll see anything.. but just maybe
Was this with the input manager or the new input system?
well if I cap my framerate to 60 sure I'll notice something (or even lower)
ya, you'll feelit more than see it i imagine...
builds are typically faster than editors i think..
my game might peak at 600 fps.. 👀 that just means im lacking content
it's worth testing your game at like
5 FPS
this can make execution order problems very obvious
@swift crag Pretty recent test I did: #💻┃code-beginner message
you could feel it and see if done right (i.e recording while looking at a wall with markings and see if there is any or not)
and expect it to work thru the entire game-loop?
thats very high expectations lmao
I spent a while getting the order exactly right (through a mixture of script execution order and by adding explicit ordering to my code)
I had issues like the eyes of entities looking at a position from one frame behind
which was really obvious during fast movement
I gave up on relying on excecution order too much
ive only did that for my game-manager to initalize things.. im more than certain i'd break something if i played with the execution order too much
and my cameras were off by one frame, causing clipping through tight spaces
I like manually calling things from a centralized script
you could still cap framerate in builds with Application.targetFrameRate right?
I reserve it for third-party assets I don't want to fuss with too much
as far as i know yea
My own code just gets run in an explicit order
Also helps with quickly placing profiler markers on different systems
I admit it was Fen who got me to use those
Less deep profiling
I'm slowly filling my game with profiler markers
they're really nice for getting a quick overview of hot spots
Is there any part of this script that would need to be adjusted to have frame rate independence? The game works perfectly in Unity but as soon as I try and build the character doesn't move the way I want it to, which I think is an error with the frame rate difference. Thanks!
what does "doesn't move the way I want it to" mean?
It slightly overshoots the target position
There's some really weird stuff happening with "slimetype". It seems like that should be an enum or an int. Why is it a float?
And yes using a coroutine like that with WaitForSeconds with MoveTime is sensitive to framerate differences
This script overall seems overcomplicated for what I think it's doing
Hello! Someone can explain why I get this error "NullReferenceException: Object reference not set to an instance of an object"
I don't understand here is my entire script ^^
Look at the line the error says it is on. Something on that line is null but you're trying to do something with it anyway
Your Rigibody2d is null you need to tell your script what rigibody you are setting it to something like this:
Rigidbody2D rigidbody2d;
private void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}
Thx guys! This works now :3
hey hey quick question, does anyone have a good tutorial/resource about loading, main menu, start game?
Before i try to go and find myself, maybe someone has a good resource on hand
brackeys has a pretty basic one
anyone know if the OnTriggerEnter Function work?
alrighty thanks
https://www.youtube.com/watch?app=desktop&v=iXWFTgFNRdM&t=0s
this one is a really good one
Learn how to design and implement a loading screen in Unity!
Making Progress Bars: https://www.youtube.com/watch?v=J1ng1zA3-Pk
Custom Playables In Unity: https://www.youtube.com/watch?v=12bfRIvqLW4
Strategy Game Camera Controller: https://www.youtube.com/watch?v=rnqF6S7PfFA
----------------------------------------------------------------------...
it basically tells me it doesnt exist
ohh nice, thanks again 🙏
may have to combine the two.. b/c this one doesnt go into the Menu and buttons and stuff
know how would i add that delay?
just moer about the loading screen and progress bars
np, best o luck 🍀
You need a coroutine
Coroutines.. and WaitForSeconds(
it depends what you mean by "does it work"
need more context
are you making a 2D game by chance?
basically doesnt even think it exists
within 2D pipeline?
alright so what does that mean
no im making a 3d game
it depends on if it has a collider
- set to trigger
- and theres a rigidbody in the mix
be more specific
can you send a screenshot of how it's saying that?
you need to finish writing it
doesnt auto complete, and doesnt work when finished
i tried
is it within the monobehaviour ?
what do you mean by that
public Class : Monobehaviour
{
// inside these brackets
}
oh yes it is inside it but it doesnt seem to be working
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
gimmie a sec
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
easy to check.. at the top it should say AssemblyCSharp
in the left top corner above the text area
it's possible but it's showing the DetectCollision.OnTriggerEnter when you were hovering over it
when its not configured w/ unity it'll still do stuff within the class and stuff..
it just wont know any Unity specific stuff
Time to do some learning!
https://docs.unity3d.com/6000.0/Documentation/Manual/coroutines.html
it seems its already set up properly
hover Monobehaviour <-- at the top of ur class
if it refers to Unity it should be good
yep it refers to unity
do all my game objects have to have rigid body for it to work?
remove the private and just type OnTriggerEnter
just one of the objects involved w/ the trigger interaction
onTriggerEnter
alright so im fine
Ohhh ok my bad
Yes it does appear
yea, just dont type private or public before it
it get confused
it thinks ur wanting to create ur own function
private/public is ok, my ontrigger works fine with it
You can put the accessor before it, that shouldn't affect anything . . .
think about how u want it to work...
if the trigger is on an object ur player needs to cross into to pick up.. it'd make sense to have the OnTriggerEnter on the player to detect when it crosses into that trigger
or.. u can put it on the object.. and check if hte player crosses into it
its just whichever
public class Bullet : MonoBehaviour
{
private float topBound = 5f;
// Update is called once per frame
void Update()
{
if (transform.position.y > topBound)
{
gameObject.SetActive(false);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
collision.gameObject.GetComponent<EnemyHealth>().TakeDamage(1);
gameObject.SetActive(false);
}
}
}
I have my bullet projectile set up like this for an example
in this example the Bullet is a the trigger.. and its detecting when an Enemy tagged object crosses into it
I meant if i put it on void Update() or void Start()
u should use TryGets they're more optimized than GetComponent
oh what's those?
thats exactly what im trying to do but it just doesnt allow me
Show a screenshot of where you're putting it
like a full script screenshot?
if (collision.gameObject.CompareTag("Enemy"))
{
EnemyHealth enemyHealth;
if (collision.gameObject.TryGetComponent<EnemyHealth>(out enemyHealth))
{
enemyHealth.TakeDamage(1);
}
gameObject.SetActive(false);
}```
Type it up, let it be underlined, then send a screenshot of your IDE window with that script open
Yes, full IDE window
if it doesnt have an EnemyHealth.. theres no need using GetComponent<EnemyHealth> when its gonnna be null anyway
Okay, finish declaring the function and it'll work
if ur using VSCode u may want to install the UnitySnippets plugin
if u havent already
when i do it creates a seperate function
if it finds that component it automatically assigns it to the enemyHealth Variable
i will try that
right above it
Yes that's how it's supposed to work
It is a separate function
i meant a custom function thats not OnTriggerEnter But one named it
Now you're getting it
yeah its weird
No, I mean what are you talking about
You want to make a function named OnTriggerEnter
when he types private before OnTrigger...
it's not autocompleting the function for him basically
it doesnt autocomplete
even without private
Why doesn't he just say that lol
soo OnTrigg wont autocomlpete it?
VSCode doesn't really do autocomplete very well
yea, install that UnitySnippet plugin for better results 👍
i will install that
im genuinely so sorry yall
dont be.. its how u learn
plus there may be 4 or 5 lurkers that didn't know that either
just helped them too lol ¯_(ツ)_/¯
the extension actually did it
heck ya.. its almost required if u wanna use VSCode for unity
fun fact.. u can create ur own snippets in vscode
probably other ide's too but i know for sure in vscode
huh that interesting
lol i was basically forced off of vscode by my teacher
for what? vs studio?
yep
had our first unity class so I was using vscode, was thinking "hmm why doesn't anything autocomplete and where are the funny colours"
the ole
vs
fued..
he comes over "oh you're using vs code, i don't know how to use that lol"
will continue til the end of days
i use it b/c i develope for microcontrollers..
my only reason for being on vscode is that my pc cant handle rider or vs2022
sad.. imo
even if he didn't use it for his class you'd think he'd still have some familiarity with it
before a code review.. just open ur solution in vscommunity and delete the .vscode folder
ezpz ;D
everyone is lurking
out of 18k+ users there has to be atleast 1
us and the others where they are waiting to help someone, just like a velociraptor
does anybody knows how to fix sticking to walls while mid air and holding direction key towards that wall? like on screenshot
slippy material (Physic materials)
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
remove the sticky goop on the cubes
learned how to coroutine btw, ty
np! you're now more powerful than ever 💪
just a tip i wish i woulda known at first.. sometimes you'll need to Stop a coroutine..
just cache it when u start it.. and then u can use that variable to stop it
thank you a lot ❤️
is there a way to find an inactive GameObject?
If it being inactive is the only criteria, it might be difficult
what are you trying to do?
Was trying to set some objects active when starting the game game with them inactive.
if you know the transform to look under, then you can check the child gameobjects - gameObject.activeSelf indicates if it's active or not
is vs2022 too different from vscode?
i stopped liking vscode
its way too basic
(without extentions) for my taste
VS is an IDE, VSCODE is more of a text editor on steroids. both will work (editin C# for Unity). VSCODE is more lightweight.
i was actually wrong, it seems it wont work in practice actually ( i just used a test script to figure it out )
i cant really find an issue with it though
do they have the same feel, like they look similar or their layouts are similar?
Reference it in the inspector.
would it be fine to post the attacking script?
They are different yes with different use cases, VSC can be an IDE via extensions
alright, do i need the c++ workloads for vs2022? or just the unity one
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
yes and no. they're both free (VS community) so download both and try them.
just unity and .net
does anybody knows how to remove glitch that allows someone to double jump when they stick to a wall?
got it
.net desktop (workload)
you would have to show your setup and code
most likely an issue related to how you determine 'is grounded' or you're not checking if you're grounded before jumping
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
that's basically my player movement script
i use capsule as a player and i think that this might be the issue
i use colliders set like this
you are allowing your jump if you have collided with anything
well...
you would probably want a ground check for that
and.. how to do that? is there a premade function that i can use?
Raycast/spherecast would be good, overlapsphere would also suffice
Raycasts do return a boolean, so you could just assign an isgrounded boolean to it
ok real quick does anyone know how to make an object not inherit its parent's scale
because my movement scales the player and that messes with other things and causes shearing
this just feels yucky to look at
no. either change parenting or change the scale.
well im not rewriting the entire fucking player code
There is no magic setting to toggle.
this engine can make some of the best indie games in human history and cant individually scale child objects
a gameobject's scale is based on its parent (if it has one)
it does
and i dont know how to make it face the way it does without parenting it to the player
like how do i make it have the same rotation and position as the camera without parneting it to it
Easy, use a position and a rotation constraint component . . .
code
yes
I think there's a parent constraint as well. Type "constraint" when adding a component to see what pops up (away from the computer, ATM), or check Google. They have a bunch of constraint components . . .
what does "my movement scales the player" mean?
but code what
well the player is naturally 1.5 in hieght and hets shrunk down to 0.5 when crouching
literally just set object A to object B using .position and the equivalent code after, the same applies to rotation
I dont understand what it wants from me, the variable is already set in the inspector prior to PlayMode, after setting it Active.False it just forgets about it I guess.
ah. you should be changing the collider height, not the gameobject scale
Check for a duplicate script. Also, we can't tell if that is the correct script or not bcuz the image is cut-off . . .
well i didnt write the code
it was a tutorial
Only a single object with that script
how have you confirmed that?
Is this a prefab from the project folder or the GameObject in the scene?
In the scene
first, you need to search by type, not by name. use t:UIManager and second, you also need to ensure you do this search during play mode when the error appears
is there any more to the stack trace?
Nope, nothing new
what the ...
It started working
how t*
Aint changed nothing... and it starts working.. (unity just wants to emberass me)
{
Flip(currentVelocity);
if (Mathf.Abs(_rb.velocity.x) < maxSpeed)
{
_rb.AddForce(Vector2.right * currentVelocity * walkForce);
}
else if (Mathf.Abs(_rb.velocity.x) > maxSpeed)
{
_rb.velocity = new Vector2(Mathf.Sign(_rb.velocity.x) * maxSpeed, _rb.velocity.y);
}
}
else
{
_rb.velocity = Vector2.Lerp(_rb.velocity, Vector2.zero, 0.5f);
};```
Is this a good way to make 2D movement?
I tried making the deceleration process by adding counter forces but it was giving some weird results
Most likely me being bad at coding, but yeah
I decided to "cheat" by Lerping the velocity for deceleration
i do that for my CC for momentum damping
i use MoveTowards tho.. when lerping, passing it the variable ur actively lerping as one of the parameters isn't a good way to lerp.. (you'll never reach the target that way)
That was how the Documentation showed it I think
im very skeptical of that.. but its possible.. its a super common mistake.. and theres entire web-dev logs devoted to it
ah
Thank you
https://gamedevbeginner.com/wp-content/uploads/Trick-Lerp.gif
bout here is where it shows exactly what ur doing
just note.. it probably isnt gonna be "game breaking" or anything
So when reading it, I mentally replace the transform.position with _rb.velocity?
yea.. all the other example you'll notice the variable they're setting
is not included in the lerp
I see
They added a local variable for taking the current position
Maybe doing the same with the currently velocity will avoid that
public float targetValue;
void Start()
{
StartCoroutine(LerpFunction(targetValue, 5));
}
IEnumerator LerpFunction(float endValue, float duration)
{
float time = 0;
float startValue = valueToChange;
while (time < duration)
{
valueToChange = Mathf.Lerp(startValue, endValue, time / duration);
time += Time.deltaTime;
yield return null;
}
valueToChange = endValue;
}```
is there a way to make vs2022 not so laggy or is it just like that
yup, but theres also alternatives..
like MoveTowards()
SmoothDamp etc
smoothstep rather
🤔 no lag here
its just my crappy laptop
Isn't that a bit overkill?
The only way i'm using Lerp is for decelerating a rigidbody, so it doesn't feel as unnatural as just outright setting the velocity back to zero
ya, i know what u mean.. my momentum stuff does the same thing
airVector = Vector3.Lerp(airVector, airVector + airControlVector, characterSettings.airControlStrength * Time.deltaTime);
groundVector = Vector3.Lerp(groundVector, Vector3.zero, characterSettings.airDamp * Time.deltaTime);``` this is at the end of my update loop
just two vectors i constantly feed to my CC's Move() function.. when its not being actively updated by the input it slowly fades to zero
ohh lookie, lookie.. those are worng
😄
those should be MoveTowards()
they are in my updated version
yea, it keeps cutting the result in half
and it keeps getting incremently smaller and smaller and smaller
Nice to know :D
yea, just a weird thing most ppl learn after they use lerp a few times
It's probably best to just add a condition in case the value reaches a certain threshold
thats a solution as well 👍
Maybe a While loop?
Idk I've been avoiding while loops since every time I tried them, the editor would freeze
i think its simpler than a while loop hold on
valueWeChange = Mathf.Lerp(valueWeChange, 0, Time.deltaTime * 5f);
if (valueWeChange < 0.1f) valueWeChange = 0;```
You can make an if without the {}?
That's cool
as long as its a single line
Yes, but that doesn't mean you should.
I couldn't directly change the rb.velocity through this way for some reason
Vector2 rbCurrentVelocity = _rb.velocity;
if (Mathf.Abs(rbCurrentVelocity.x) < 0.01f)
{
rbCurrentVelocity.x = 0f;
}
_rb.velocity = rbCurrentVelocity;```
So I had to create a local variable to hold it`
does it work?
Due to readability?
Ayup
ya, basically that'd be the only legitimate reason
that and scaleability.. if u had to add more than 1 line.. u'd have to add the brackets back..
lord forbid
Yeah. Making it easy to read should be the most important.
Now I wonder, with my current movement code
Would I be able to add movement hazards?
Like strong wind or moving platforms, stuff like that
if (Mathf.Abs(rbCurrentVelocity.x) < 0.01f)
rbCurrentVelocity.x = 0f;
_rb.velocity = rbCurrentVelocity;```
is pretty readible to me..
but, i get it
Since I am using forces
you'd just add them into ur vector u use..
u can always break up ur vectors and add them together before u send them to rb.velocity
normalMovementVector + outsideForcesVector; and then just lerp the normalMovementVector part
instaed of the entire rb.vel
finalVector =
(groundVector * finalSpeed) +
(airVector * characterSettings.airSpeed) +
(Vector3.up * gravitySim);
characterController.Move(finalVector * Time.deltaTime);```
i'll only lerp my ground and air vectors
no reason to lerp the gravitySim
Yeah just I've heard that setting the rigidbody's velocity outright make adding stuff like moving platforms and strong winds significantly harder than by just using forces
u just gotta keep up w/ what ur doing 🤪
but yea.. it does make it a bit more involved.. when ur adjusting ur velocity directly
a player controller is the most important part of ur game (most times)
u wanna make sure u have a solid understanding of it anyway
but by breaking up ur forces and stuff into different variables instead of just bunching them all into one.. u can help mitigate that a bit..
say something goes wrong w/ my groundVector i'll have alot easier of a time debugging it.. b/c all the other things wouldn't be involved at all
can someone check out why the AttackDouble coroutine doesnt work?
all the things which affect it are kind of all over the script so i just pasted the whole thing
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
okay, https://paste.ofcode.org/Kg6CXWUkRL9L5ZYP67YJ2q
does that work
How can I get the name of a button i pressed? I want this for something like 50 buttons, so i need something efficient.
a ui button?
what do you mean?
Yes UI button
WHy do you want the name
dealing with object names is usually not efficient
What do you actually want to do?
Is it for a hotbar system for example?
It is for a quick project, i need it to make a pair between a button and a 3d object. (when i press the button the 3d part changes)
You can directly provide a reference to the object as a parameter to the function in the button inspector when you assign a listener function
wouldnt that mean i have to go through each of my 50-ish buttons individually?
Wouldn't the thing you're asking about mean you would need to individually write code for 50ish different button names?
I mean, I already had a list of stuff I wanted to model, so when I made the buttons/3d models i made sure for the names to match.
So if I could do the match name-wise I could do it with a single function, my guess
ideally the buttons would all have been prefab instances calling a listener on themselves that just grabs their own .name
barring that - you can write a loop that adds a runtime listener to each one that takes the button object's name and passes it into some function
I also found this EventSystem.current.currentSelectedGameObject.name. It returns the name of the button (CURRENTLY PRESSED*) as it is written in the hierarchy, so I think I can use this.
No it returns the name of the currently selected GameObject in the event system. Which... I mean I guess it would be the button you clicked on usually... kinda hacky
The other thing to do would be to implement IPointerClickHandler on your button
or add an event trigger to it with the PointerClick event
That would give you access to https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.PointerEventData.html
Ill take a look, thanks for the guidance
(oh boy)
Hey, i have a... Jittery raycast point??
No clue why, but this is what's happening:
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The small cube has it's position set to spawnCast_Hit
The big one's using the same code i'm using for drawing those rays
Still, i have no clue why it's so. damn. jittery
What exactly is jittery? I can't spot an issue in the video.
The smaller wirecube should be at the same point at the bigger one
but it's just jumping around
What is it even? How is it related to the raycast?
Ah, ok. So it's repositioned to the hit point?
how do i make it so that after an action i have to wait a certain amount of time to do that action again?
I'd add a check whether the raycast hit anything before drawing the gizmos.
like a cooldown?
yeah just like that, i was thinking making the action itself a method and then using invoke with a key press with a delay
is that correct?
you could use a coroutine, time.time timer or invoking a function
if you already have a function you made, invoking it may suffice
else you could use a coroutine or time.time timer
i havent learned what coroutines are at the moment so ill try the other two and see how it goes
thanks again
If I move a game component's position outside of the update function without lerp it is jarring, but I cannot get Lerp to work outside the update function. Is there a work around function.
Example:
What lerp?
And where is "outside of the update"??
I am doing that
canSpawnObjectHereRay is the bool "If this ray hit something"
spawnCast_Hit is the out from that ray
i'm only ever drawing the cube if it's hitting something
I don't see you checking it before //Shakey Cube
oh, yeah, it's acter the other one, hold on
Sorry Vector3.Lerp for transform.position.
Currently:
- on update check for button down.
- on button down call function that takes a list of game objects and adjusted their transform positons.
Continue
just did that, and it's still inconsistent as shit
Example of the Lerp in terms of the camera:
void Update()
{
transform.position = Vector3.Lerp(transform.position, new Vector3(player.transform.position.x, transform.position.y, transform.position.z), speed * Time.deltaTime);
}
This creates a smooth movement from a to b, but it takes place in the update().
If I do
:
void Update()
{
CameraFunction(camera.transform);
}
....
public void CameraFunction(Transform t)
{
transform.position = Vector3.Lerp(transform.position, new Vector3(player.transform.position.x, transform.position.y, transform.position.z), speed * Time.deltaTime);
}
It does not update smoothly, instead it only moves one frame worth of the distance, before attempting again from where it was.
Draw a debug ray following the box cast right after it.
This is not actual code, but an example
- This is not a correct way to lerp(the third param). Check the docs.
- Extracting the same code into a method wouldn't change anything about it's behavior. Double check that you didn't miss anything when extracting it. Seeing the actual code might be helpful.
I deleted the lerp attempt, but I can show you the code i'm using to move all the game objects.
Warning its bad:
public void AdjustTerrainVerticalityDown(int tSpeed, GameObject cliff)
{
cliff.transform.position = new Vector3(
cliff.transform.position.x,
cliff.transform.position.y - .4f,
cliff.transform.position.z
);
foreach(GroundPiece gP in currentTerrain){
gP.groundPiece.transform.position = new Vector3(
gP.groundPiece.transform.position.x,
gP.groundPiece.transform.position.y - .4f,
gP.groundPiece.transform.position.z);
}
}
So in place the current pos = pos. I was doing pos = new vec3.lerp(current,new,rate);
Let me rewrite it and attempt again
I'm not sure I understand the purpose of this code. Are you implementing a floating origin or something?
In the gif posted with the question, you can see the layers of the world adjust on y axis.
That is what this code is doing. I want it to adjust, but I want it to be smooth and not instant.
This adjusts all the elements in the current terrain down, another function moves them up.
Multiply whatever changes you apply on frame basis by delta time. That would smoothen it up.
Let me attempt now.
It did not work as expected, Since the function is only called once, when the button is pressed down, does it only modify 1 frames worth of movement?
Indeed. You'd need to call it from update or a coroutine for as long as you want it to move smoothly over time.
So I only want it to adjust once, when the button is pressed down. Would a coroutine be able to accomplish that? I have not looked into that yet, but it would be my next stop.
A simple example would be I have one game object. I press button it smoothly goes down and stops untilk I let go and press again.
Both a coroutine and some logic with a flag/bool check in update would work.
And while we're at that, I'd suggest you go over the beginner pathways on unity !learn before working on your own project.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i found the problem, i was being a dumdum and using a boxcast isntead of a simple raycast
Okay, I've started working with Unity Built-In UI Builder and UI ToolKit got all my ui set up for my intended issue but if I re-scale the game to anything but 1920 x 1080 the UI just stays exactly to what I've set it as. is there a way to make it automatically rescale?
Tried to look it up on youtube. didn't find anything on this rescaling issues. although a lot point to Position being Relative and Match the Game view that literally did nothing. should I apply a script to my UI Document that allows it to use a Canvas Scaler. I don't really have a viesable approach or anything to go off.
It's a pain cause I think it's my last piece to my puzzle on UI Builder
Hey everyone!
I am trying to make a simple collision script where I update the speed variable when the boxcollider is triggered. Here, PlayerController is a script of my player gameobject. I understand this is wrong, would someone know how I should thinkin
g of this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUps : MonoBehaviour
{
public GameObject powerUp_Prefab;
public GameObject player;
void Update()
{
BoxCollider2D boxCollider2D = powerUp_Prefab.GetComponent<BoxCollider2D>();
playerController = player.GetComponent<PlayerController>();
if (boxCollider2D.isTrigger)
{
playerController.speed = playerController.speed + 0.5f;
}
}
}
Also please excuse my syntax errors!
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Look into ontriggerenter2d
how would i differentiate between materials for adaptive hit noises or footsteps
thank you! I saw to use that as a solution, I am curious as to why it would not work the way I have it. My thinking is if the script is a component of my game object why can't I use get component and update the variable that way
The code you have makes no sense. It's doing this:
- Each frame, check if the box collider on the prefab is a trigger.
- if the box collider on the prefab is a trigger, increase the player's speed
it is doing absolutely nothing to detect collisions between the box and the player
As for the use of GetComponent, that part looks correct assuming you have actually referenced the correct objects in the inspector
However - it's completely unnecessary
You could have just referenced the components directly in the inspector
saving yourself the GetComponent call
e.g.
public Collider powerUpCollider;
public PlayerController player;```
You might also be a little confused about what a prefab is.
A prefab is a thing in your project folder. Prefabs do not exist in scenes.
The things in the scene that are made from the prefab are instances of the prefab, not the prefab itself.
Tag is probably easiest
@wintry quarry That makes sense! Thank you for the explanation 🙂
how would i reference those in the script
Put a script on the surfaces with an enum for surface type, or even just have that script directly reference the audio clips.
Tbh I think it depends somewhat on the layout of your ground colliders
I think the most elegant way would be to ontriggerenter with a collider that collides with ground layer and cache the ground material you want
But if you have overlapping colliders and whatnot it might be better to just raycast down from ur feet
what about for hit sounds? is there a stand in thing i could put for that comment
im not above just repeating the if statement for 6 materials
i actually havent made those yet, im on the gridded test area stage
ill keep that in mind
Use a dict or something you don’t want to have to write a new if statement every time you add a sound
And try to avoid instantiating and destroying a lot, if you gonna reuse the effects anyway. You can look into objectpooling for that case. Just another tip
Hello community 🙂 I have an issue with my animation on my 2D character.... it doesnt stop... even with no input from the keyboard... can anyone help me? I'm trying to solve this since 3 days....
You can and will be helped if you share the context of the issue. !Code specifically and an indication where people might have to look.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
This is my PlayerController Script:
test
this is my script and i did a clean up because i had in every line a Debug.Log
i dont know why my animation is still ongoing even if i dont move
or is it better to post in the networking channel because it's multiplayer?
Either or, you should put some logs in there to know, who is calling your stuff. guessing, that your server might be updating your player with its last state it received
when i move it works and when i dont move in the console it says:
No movement detected, deltaPosition is zero.
UnityEngine.Debug:Log (object)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:62)
so the scripts detects that there is no movement, but why does my player still has the animation going?^^
please post your script on a script page, so we actually got line numbers and stuff
how? i posted my script as a message, because it's too big
!code as already mentioned 🙂
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
As far as I can see, you never reset to false
animator.SetBool("isRunning", true);
ok? so i expand the if statement with an else and set the boolean to false?
Thats something for you to test and figure out. But the reason your animation is going is, that this is set to true and never reset
nice now it works on the host and on the client! but one more issue^^ when i watch on the host screen the client animation dont stop but on the client screen it stops
any idea?^^
hmm... yeah but i dont know where to but the code... 😦 sorry
in the update i put:
private void Update()
{
if (!IsOwner) return;
// Eingaben des Spielers abfragen
float moveHorizontal = Input.GetAxisRaw("Horizontal");
float moveVertical = Input.GetAxisRaw("Vertical");
// Bewegung basierend auf Input berechnen
Vector2 deltaPosition = new Vector2(moveHorizontal, moveVertical) * moveSpeed;
if (deltaPosition != Vector2.zero)
{
// Sende Bewegungsanfrage an den Server
SendMoveRequest(deltaPosition);
// Optional: Direkte Anwendung beim Eigentümer zur Reduzierung wahrgenommener Latenz
if (isOwnerPrioritized)
{
RespondToMoveRequest(deltaPosition);
}
}
else
{
Debug.Log("No movement detected, deltaPosition is zero.");
animator.SetBool("isRunning", false);
}
}
now it works on the host
but i think i have to set the bool in the ServerRpc
right?
No clue, sorry
ok, no problem thank you 🙂
Hi friends, I want to change the sprite position and scale as we do in the editor using a corner point and dragging it but in runtime with points showing in-game view
i got it! created a ServerRpc and a ClientRpc that sets the boolean to false gg wp
you could also rely on your rb velocity to make him run or not dynamically
can you detect the exact point where raycast hit a certain object?
you have a RaycastHit or RaycastHit2D
so it would use hit.point
ty
very amazing indeed