#💻┃code-beginner
1 messages · Page 360 of 1
There are many reasons that could happen. Show something helpful so we can figure it out.
Are you animating the model to move, but the parent is not moving?
what to show you more exactly
How the animator is set up would be the first thing that comes to mind
Looks like you have root motion enabled, not sure if the problem is really about the code
The object moves, but the animator moves it again, and with root motion enabled it snaps back when the animation clip loops
where would I ask for help, cause im struggling?
How would you go about making a pokemon style movement system? Would you create a grid for the player to move to square to square?
and how I could solve it
Read the message I sent
yes, that's pretty much exactly what pokemon did. and you can use tilemaps for your map which means you have a grid right there. Just lerp the player's position to the next cell center each time it needs to move and voila you've copied pokemon's movement
The animation you made is not at a fixed state so it happens. Simple.
No, I won't be connecting to your computer and fix it for you
There are quite a few tutorials on this subject... do you think as a beginner it's best to avoid these and try to make my own system?
use the tutorials to help understand how you do certain things so that you have the knowledge to make your own system if the tutorials don't do exactly what you want
So when you're learning do you just watch the video without trying to copy?
I've been stuck in tutorial hell for quite some time and I'm really trying to claw my way out of it
there's really no one way to learn and everyone learns a bit differently. you just gotta figure out what works best for you
Anything useful. The video didn't show much.
Show the code, the animator settings, the inspector for the player, anything
can someone answer my question here please https://discordapp.com/channels/489222168727519232/497874004401586176/1244706234637090917
For sure, thank you
It's not with the animator settings or the code it's the animation itself.
Who knows? Way too few details were shown
or if you don't send a video from yt where I can see
That person does not seem to understand what we're trying to say
I'm asking YOU to send something useful
what does ref mean? im using this package i found
!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.
Pass-by-reference. It's as if a pointer to the value was passed instead of the value itself.
In this case, the method will recieve the original quaternion, not a copy
(since Quaternion is a struct, a value type, it's by default copied when you pass it around)
awesome thaks
Can someone help me with my air resistance code? Im trying to make it so my bomb goes all over the place and rotates and sways then stabilizes at 90* pointing down heres my code
https://hastebin.com/share/eqaluwomug.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@rich adder fixed that stupid rotation issue i had by passing rotation in the update rotation method in the KCC
its ok now
In this very specific case, that method could modify the quaternion, and you'd still get the changes from outside that method
Quaternion q = transform.rotation; // copy
UpdateRotation(ref q); // reference, modified inside
Debug.Log(q); // modified
Or should I post this in #archived-code-general / #archived-code-advanced
How can i set my fps characters direction to go to the direction it is looking? (My camera script turns the character already in Vector3.up)
currentInputVector = Vector2.SmoothDamp(currentInputVector, input, ref smoothInputVelocity, .1f);
Vector3 move = new Vector3(currentInputVector.x, 0, currentInputVector.y);
controller.Move(playerSpeed * Time.deltaTime * move);```
transform your input direction (after turning it into a vector3) using transform.TransformDirection
transform.forward / transform.right
All over what place?
Yea i tried that too but it says "cant convert vector3 to float"
They are both Vector3s
i feel like the fading goes too quickly, but i cant use standard delta time if im making the timescale 0. how can i fix this issue?
Multiply them by the value if needed
You didn't show much of what I asked for at all.
The child is definitely moving on its own, and the parent is much slower. That's about all I can say
Oh, it's a long video...
Well, video is perhaps the worst way you could possibly share that information, but give me a minute to watch it
What code editor are you using looks very colorful oooo
.forward looks okay but .right...
deltaTime / duration
That's already right, using unscaled one
jetbrains rider with the nightfall theme
Is it different from Visual Stuido
Or nah
Rider is paid
yea,
Ohhh yea nvm
What's wrong with transform.right?
Your animation itself is moving moving the transform, right? I don't see that in the video, but it's hard to follow along the way it is recorded, especially on my phone
idk
guys do i need to learn about the .NET to develop games?
Changing a single word is enough to make it work with right too
Just all over randomized
Right is a vector
oh great tysm
And you are trying to assign it to a float
Not necessarily
But forward not?
i learned the basics of C# upto OOP what should i learn next?
check dm
It is. Simply check them out. And read what I've written you.
Hmm, interesting. That should cause an error too
Just play around with unity lol
💀 oh
That's how I learnt to code
ohhhh
Played a lot any idea that came to mind tried to make it
What's the problem in continuing it here?
Quite fun, your game wont be polished but gotta learn things here
we dont have to learn about the codes and syntax at all?
it says i cant convert vector3 to float
when I say play around with unity as in make very random things in unity
yes
So you're learning unity and coding
oh.
Why?
Does it also say not to continue here?
Is the a POSSIBLE way to make it look like that
themes for syntax highlighting?
Why are you trying to plug forward and right into a vector at all?
They are already vectors
I'll show you the code
Possible
Just set move to forward * your multiplier (or right if that's what you want)
Visual Studio allows you to change the colors
Sorry english isn't my main language so i cant explain myself so good. In this line Vector3 move = new Vector3(transform.right * currentInputVector.x, 0, transform.forward * currentInputVector.y); I am trying to move my character through to looking direction. The last argument, transform.forward * currentInputVector.y is okay. But in the first argument, its saying you cant transform vector3 to float. Please say if you didnt understand anything..
There are themes yes
"Tokyo Night" would look close to what you saw
Wiat no
Maybe tokyo night is a better choice?
Neither of them are floats
You cannot do that
I don't know why the error is NOT showing for forward, but what you are attempting to do is not right
Wait mb
So you assign the x axis to (currentInputVector.x, 0, 0)
this is a much easier option with no extra math involved #💻┃code-beginner message
can I smooth out after that?
what do you even mean by that
Yeah I ment tokyo night
In here, i am smoothDamping the value for much smoother movement.
Search the extensions for "theme"
To smoothly interpolate between the colors, the 3rd parameter time should be constant, and, in your case, correspond to Time.unscaledDeltaTime
Can you use the vector in smoothdamp? Of course... why not?
Yes sir!
all what i suggested does it transforms the direction to be the world space direction based on your object's rotation. it has nothing to do with changing the length of the vector at all
um okay i will try it
This is wrong, by the way
Make sure to change the Time parameter according to the fade duration
Setting the parameter to unscaledDeltaTime makes it only work when the duration is 1 real-time second
So simply multiply em
So i add that "move = transform.TransformDirection(move);" line and now its working. Idk am i do it right but at the end its working. Tysm!
{
// Smooth movement codes.
Vector2 input = moveAction.ReadValue<Vector2>();
currentInputVector = Vector2.SmoothDamp(currentInputVector, input, ref smoothInputVelocity, .1f);
Vector3 move = new Vector3(currentInputVector.x, 0, currentInputVector.y);
// Transform the move direction relative to the object's rotation
move = transform.TransformDirection(move);
controller.Move(playerSpeed * Time.deltaTime * move);
}```
yes, that is how you use that
I'm getting an error in unity for the 1st line of code in this function and I don't really understand why. The error is "object reference not set to an instance of an object. ```cs public void Movement(bool move)
{
//Extra gravity
rb.AddForce(Vector3.down * Time.deltaTime * 10);
//Find actual velocity relative to where player is looking
Vector2 mag = FindVelRelativeToLook();
float xMag = mag.x, yMag = mag.y;
//Counteract sliding and sloppy movement
FrictionForce(InputManager.x, InputManager.y, mag);
//If speed is larger than maxspeed, cancel out the input so you don't go over max speed
if (InputManager.x > 0 && xMag > currentSpeed || InputManager.x < 0 && xMag < -currentSpeed) InputManager.x = 0;
if (InputManager.y > 0 && yMag > currentSpeed || InputManager.y < 0 && yMag < -currentSpeed) InputManager.y = 0;
float multiplier = (!grounded) ? controlAirborne : 1;
float multiplierV = (!grounded) ? controlAirborne : 1;
float multiplier2 = (weaponController.weapon != null) ? weaponController.weapon.weightMultiplier : 1;
if (rb.velocity.sqrMagnitude < .02f) rb.velocity = Vector3.zero;
if (move)
{
rb.AddForce(orientation.transform.forward * InputManager.y * acceleration * Time.deltaTime * multiplier * multiplierV / multiplier2);
rb.AddForce(orientation.transform.right * InputManager.x * acceleration * Time.deltaTime * multiplier / multiplier2);
}
else
{
if (grounded) rb.velocity = Vector3.zero;
return;
}```
Also the error is only showing up in the unity console and not in the code
runtime exceptions will not show up in the code. go through this: https://unity.huh.how/runtime-exceptions/nullreferenceexception
thanks
The error "object reference not set to an instance of an object" indicates that the variable rb is referencing a null object, likely due to a missing Rigidbody component or the script being attached to the wrong GameObject.
ohhhhh okay thank you
Yeaa
How do I parse a json that uses the following naming convention: example_property
Having exampleProperty field in the target class does not work. Can I somehow give custom names to fields?
fyi: I am using JsonUtility.FromJson<T>() method
Not with JsonUtility. With more potent serializers like Newtonsoft.Json there are attributes you can put on the fields/properties in case the names differ, but not with the basic JsonUtility
You'll either need to switch to another serialization library, or rename your fields so they have the same name as in the JSON objects
how do I install Newtonsoft Json package? Couldn't find any installation guide here https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@2.0/manual/index.html
am i doing this right? it doesnt feel like its lerping between the two curves correctly.
switch (damageMultiplier)
{
case > 3:
MoveVector = MoveVector.normalized * (launchSpeed * heavyCurve.Evaluate(progress));
break;
case > 2:
MoveVector = MoveVector.normalized * (launchSpeed * Mathf.Lerp(mediumCurve.Evaluate(progress), heavyCurve.Evaluate(progress), damage / 3));
break;
default:
MoveVector = MoveVector.normalized * (launchSpeed * Mathf.Lerp(lightCurve.Evaluate(progress), mediumCurve.Evaluate(progress), damage / 2));
break;
}
could anyone help me? i have 2 main problems with visual studio when working in unity. I dont have autocomplete pop up when i type code and I dont see any errors until i save and go back into Unity. It is wasting a lot of my time and none of the solutions online are helping me
Add by URL from the Package Manager: com.unity.nuget.newtonsoft-json@3.2
!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
• Other/None
What values are you expecting to be getting for damage
oh waitttt
its meant to be damage multiplier
thanks
When I go to external script editor and change it from file extension to Unity 2022 it doesnt show any code whatsoever
That still doesn't make much sense
i cant find a solution
im trying to lerp damagemultiplier between itself and the next tier if that makes sense
If damageMultiplier is greater than 2, it's entirely possible that damage / 3 is greater than or equal to 1
why would you change to 'Unity 2022'? That is not even an option offered
but then it goes to the next one doesnt it?
sorry, visual studio 2022
!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.
mistyped, my brain turns to mush quickly
Ah, right, it'd always be somewhat less than 1. But it's odd to want to lerp approximately 90% of the way to the end every frame
Why isn't the room list function being called back?
https://gdl.space/boyumokiwo.cpp
Di you change it and press regenerate project files?
yep. visual studio pops up but no code appears
screenshot your VS window
for my use case, it doesnt have to be super precise
as the value usually jumps over these thresholds anyway
Why cant i see the Gizmos+
I'm just wondering what you're actually trying to do here. You're trying to set MoveVector to some value that is roughly 90% of the way between a specific point on two curves?
with a script from your project open
What function are those in
when i changed it to visual studio from file extension thats all it gives me
whenever i try to go into my code
im trying to do balloon knockback with my characters.
obviously the video is an extremely exaggerated version of what i want to do
but thats basically it
wait a minute
no this looks right
Huu?
What function is the code in
its spelt wrong
Okay, and are you calling OndrawGizmoos anywhere?
no...
Window->Reset Window Layout
@polar acorn
while (stunRemaining > 0)
{
yield return null;
stunRemaining -= Time.deltaTime;
if (decay)
{
launched = true;
float progress = (length - stunRemaining) / length;
switch (damageMultiplier)
{
case > 3:
MoveVector = MoveVector.normalized * (launchSpeed * heavyCurve.Evaluate(progress));
break;
case > 2:
MoveVector = MoveVector.normalized * (launchSpeed * Mathf.Lerp(mediumCurve.Evaluate(progress), heavyCurve.Evaluate(progress), damageMultiplier / 3));
break;
default:
MoveVector = MoveVector.normalized * (launchSpeed * Mathf.Lerp(lightCurve.Evaluate(progress), mediumCurve.Evaluate(progress), damageMultiplier / 2));
break;
}
MoveVector = FightPhysics.ApplyGravity(MoveVector);
MoveVector = FightPhysics.CalcEnv(MoveVector);
}
}
this is the full thing, am i doing it wrong possibly?
This is the code
Gizmos can only be drawn inside of a specific function
it doesnt feel like its following the curve
That function is not OndrawGizmoos
Okay, so, you want it to follow the curve, I'm wondering what the point of lerping between two curves is?
now i get that
Try looking it up. Let this be a test of your ability to find and read the documentation
just to try and do like a smooth transition between three discrete curves i've made
click that install button
make it feel better in the game
RightClick On Solution-> Reload Project with Dependencies
man.... okay i JUST got home from an 5hour test but ig the point is to learn XD
Why would you be changing between curves? Wouldn't you just be progressing through a single curve?
Figured it out
❤️
i want the movement curve to be different depending on what the players health is
i thought it would be okay to lerp based on the difference between health
Okay, but is their health going to be changing during this coroutine? Seems like this would run once all the way through an animation curve, unless you restart it, in which case it would run all the way through a different curve
And absolutely nothing here has anything to do with health
no it wont be changing
health is called damagemultiplier
its not health per se
its more like smash bros
where ur damage goes up
bad naming on my part
Okay, so then it seems like that damage should be deciding which curve you use, rather than getting some value between two curves
so should i just remove the lerp, then?
I think so, yes
will try this, thanks
hey i also have a question, does anybody know how i can make something fly along a predetermined path in a natural way? ( i have this fireghost that is looking for shelter from the rain in a forest, he searches for a few seconds and then stops under a tree)
Use the spline package
ahh that looks promising, is that like a curve i can draw in the world?
i have something that makes 0 sense.
i have a pick up script, with an assignable layerMask variable, call it allowedLayers.
the player object is under the Player layer (i checked) and the allowedLayers is assigned to the Player layer.
i then do an OnTriggerEnter, and something illogical happens.
i have
if (other.gameObject.layer != allowedLayers)
return;
and when the PLAYER enters the trigger, it returns (i checked with debug.log). however... when i do
if (other.gameObject.layer == allowedLayers)
return;
it DOESNT return.
idk why
How can I load the unique GUID's of my objects when entering a new runtime? All the old ones are gone on startup (new ones get assigned) and I have them saved but theres no way for me to find which objects had which ids, currently I have it working except I am using FindObjectsOfType so it keeps loading the objects in a different order and thus not mapping to them correctly how can I accomplish this? Having a hard time trying to figure this out
to be explicit my enemies spawn coins if its the players first time defeating it, so i am saving the guid of all the enemies that were defeated, and then loading them to determine which enemies should drop coins (since the enemies will be back the next runtime) - essentially the incorrect mapping results in the wrong enemy not spawning coins when it should
because allowedLayers is a layer mask, but gameObject.layer is not
https://unity.huh.how/bitmasks
what? isnt gameObject.layer the layermask of the game object?
no, it's the layer index
but the manual says "the layer the gameobject is part of"
yes, it is the layer's index. it is not a layer mask. read through the link i sent
no. Layer Id is not LayerMask of that id
then how do i check for the layermask of a gameobject
did you bother reading the information on the link i shared?
Create a mask from the layer index
convert the Layer id to a LayerMask
there's a convenient side bar that has some options for things like exactly what you are trying to do
can i ask a basic question about why unity cant find a gameobject i made?
im not smart enough for binary lol it scares me
i wrote it bad
!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.
how carful should i be with the data i need to save? do i need to write to the file every time there is a change incase it crush or can i just save when the game closes?
yea i know i miss clicked the enter without the shift
also why are you even checking if it is in a mask manually? just filter the collision from the layer matrix
if (partita != null) { partita.SetActive(false); }
how can you set it to inactive if you dont have a reference to it?
damn im a dumbass how did i not think of that lol thank you
its strange because that part works well, its just the FinePartita one that doesn't get setted active
wait nvm i read != as ==
my brain refuses to function today
void HandlePlayerCollision(GameObject player)
{
// Disable the player
player.SetActive(false);
// Determine the winner
string winner = player.name == "Player1" ? "Player 2" : "Player 1";
// Disable the game object called "Partita"
GameObject partita = GameObject.Find("Partita");
if (partita != null)
{
partita.SetActive(false);
}
else
{
Debug.LogWarning("Partita GameObject not found");
}
// Enable the game object called "FinePartita"
GameObject finePartita = GameObject.Find("FinePartita");
if (finePartita != null)
{
finePartita.SetActive(true);
// Update the text of the "WinnerText" object
Text textComponent = finePartita.GetComponentInChildren<Text>();
if (textComponent != null)
{
textComponent.text = "complimenti al " + winner + " per aver vinto il round! \n \n \n \n \n Premi la X per tornare al menù";
}
else
{
Debug.LogWarning("Text component not found in FinePartita");
}
}
else
{
Debug.LogWarning("FinePartita GameObject not found");
}
}
i get the debug warning Debug.LogWarning("FinePartita GameObject not found");
i checked the name alredy and its the same
Then there's no active objects in the scene named "FinePartita"
this
GameObject partita = GameObject.Find("Partita");
will only find an active gameobject. Is it active?
you should use a better way to get a reference to that object
Is there a reason you can't just use a public or serialized variable and dragging it in?
idk i can try
@languid spireI think i got it fixed thanks to you, i appreciate it ❤️
Any advice on this? I cant seem to find any tutorials on how to do this
are you talking about InstanceIDs?
No
I am giving them unique guids at runtime and saving the ones that have been killed, then loading those guids the next runtime my problem comes when I cant map the objects to the ids they were given the first time
I've tried using a dictionary but if anything it just made it worse
ideally you would assign the GUID at edit time, not runtime. the problem with doing it at runtime, is how do you know what GUID maps to which object without a deterministic way to remap them. and it's not like you'd be able to just generate a new GUID, because that would be kind of pointless.
so assign the GUID at edit time, then it will never change and you will just not have the problem you are currently trying to solve
wdym would it work in a build? if you have already assigned the GUIDs and they are serialized in some way then it will just be there in a build already
Can someone recommend me a good free unity course for developing 2d games using Unity ? Thank you
Get a GUID, assign it to the field you want it to be. The same way you assign any other value
So you mean manually go add a guid to all of my objects? That is the easiest way?
i mean you could write a script to do it automatically, but otherwise yeah
You can have an editor script do it for you
yo my block cooldown method is not working
the BlockCooldown is not startinf
idk why
do you actually use those bools you assign to?
the code is probably not running in the first place
Use more logs
I use the canBlock and canParry
Can even just:
// example
public string Id => _id;
[SerializeField] private string _id = Guid.NewGuid().ToString();
And just serialize the string. I do this for my dialogue graph nodes.
the canblock and canparry are sucesffully equaling to false but its just the startcouroutine not working
how do you know
show logs
my player is taking damage
show your console
oka
very simple question that i never quite understood even when explained a few times. when would i use public and private? what exactly is the difference?
encapsulation
class Foo {
public int A;
private int B;
}
var foo = new Foo();
foo.A = 1; // no error, public is accessable to anything if it has an instance to Foo
foo.B = 2; // error! private cannot be accessed outside of the type
public is accessable outside of the class, private is only accessable inside the class / reference itself
before block cooldown
and after blockcooldown
it looks like it prints blockcooldown has started
which is in the couritine
Looks like your code is running just fine
but does not reset the blockcount
See how it says "Block cooldown started"
ya
So the problem is not what you said
the BlockCooldown is not startinf
This is not correct
and yes that would have been preferable to these cropped screenshots
ya now I think the problem is that the playerhealth.blockcount=0 is not happening
yeah... this is definitely smarter, I got to remove like 300 lines of code and it works exactly how I want. I guess manual is better sometimes, thanks!
Maybe your coroutine is not coming back from the yield which can happen for several reasons:
- You have a really long cooldown
- Time scale has been slowed or set to 0
- The object running the coroutine was deactivated or destroyed
Most of the time it's the third one
ohhh that makes sense
That's unfortunate
Why are you needing to assign a guid manually 🤔
Does your coroutine get started several times as you wait for some seconds on the beginning before setting the block back to 0? So its overwriting itself?
basically this code is attatched to an projectile object and when it hits something, it gets destroyed
alr tnx man
well yeah then that's obviously the issue
because of this issue I was having read up if you are interested, assigning at runtime was not working out
Is there any store in unity on some mock projects to start with?
for free
I wanna try a few things
here or separate website?
there are a lot of threads here
google unity learn
kk
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
also which one is more useful youtube tutorials or unity learn?
learn
#💻┃unity-talk for general questions like this also
ye that was my next question XD
there are 100 threads here XDD
thanks y'all
I don't get the issue though from your description of it in relation to what you are trying to do. There isn't any code to show off the problem either from your original message, so it's mainly guesswork on what you were originally doing. That's why I'm asking.
the original issue was that I was assigning guids at runtime, saving and loading them, and then attempting to correlate them back to their original objects with some sort of mapping, but as some others pointed out it seems to be more efficient to just assign them at edit time so that that whole mapping issue goes away
but in that case why not just use public for everything and only access it if you need it. why lock it to only a specific class?
yeah -- if you can assign GUIDs reliably at runtime, then you already have a way to correctly identify which item is which: their order!
In software systems, encapsulation refers to the bundling of data with the mechanisms or methods that operate on the data. It may also refer to the limiting of direct access to some of that data, such as an object's components. Essentially, encapsulation prevents external code from being concerned with the internal workings of an object.
Encaps...
The more public everything is, the more issues you will end up having when everything touches everything else all over the place. Encapsulation makes code easier to manage.
To have clean code, to be able to avoid unwanted changes of variables, that should only be handled by the class itself. Same question would go for, why not write ALL code in one csharp file?
Think of it this way:
When designing a car, why don't they just expose the engine components to the passenger cabin? Wouldn't that make it easier to work on the engine when necessary? You could just ignore it otherwise.
yeah... my code was a mess trying to map them back as if its somehow more efficient doing all that extra work just so i didnt have to enter them manually
I have 2 sprites for my player jumping animation. One for when the player jumps up and one when they fall back down. Anyone have any idea how I could detect when the player is moving up and down in script?
that does make sense, thanks guys
I know how to detect when the player is moving along the Y axis, but not up or down seperately
by the way, this might be handy for giving the coins their IDs:
void Reset() {
myId = GenerateRandomID();
}
What is your movement based on? rigidbody, transform.position, kinematic or physics gravity based?
Reset runs when a component is attached, or when you hit Reset in its context menu
you still don't have to enter in anything manually, just generate the GUID automatically when the object is created/reset
Rigidbody
I do this in my game, actually!
I assign GUIDs to some things so I can identify them when I save and load config data
Check if velocity is going up or down and if its jumping might do the trick
that works on monobehaviour?
That's what this example was for
But you do create those items before runtime anyway, right?
Right.
If you create the items at runtime, then you can at least keep track of the order you created the objects in
maybe keep a running counter
Checking the velocity would just give me a float, right? How could I differentiate the up and down movement?
velocity is a Vector3
velocity is a directon vector
speed would be a single float
Oookay, I think I get ya
incredible!!! thank you ❤️
me when I didnt even know that method existed
Serialize it all to an ecs and store the world to disk 
dump the game's memory to disk
Not sure why you want create a guid for runtime created objects anyway
It worked, thanks
That would be "fine" if you didn't save the object state to disk, as that is an instance id. So it will change every time.
the original goal was to remember which items got collected
if you know the order you generate coins in, you can just write down the indices of the coins
instance IDs are not consistent, so they are not useful here
Yeah, this is only for runtime obejcts that only live in that runtime scope. If you wanna store those values across game starts, you need to save them anyway.
well, if the objects aren't going away, you just store references to the objects themselves :p
Thats why I was so confused when the discussino began about tracking the order of the generation of coins for example 😄
Guids are nice too if you need cross-object communication across game state deserialization. Since then you can load them back up where they were, with their same id, and use that guid as an id into a lookup map. Dunno what that would end up being needed for but it is a useful thing nevertheless. Maybe if an enemy has to follow another enemy around, that could be a use-case for it 
I use GUIDs in two places:
- I copy asset GUIDs into my ScriptableObject assets, then look them up in a big dictionary. That lets me write GUIDs and then read them to look up the correct asset
- I generate GUIDs in some MonoBehaviour instances, so that I can identify them in serialized data
I do the same for asset guids yeah. I have a custom AssetRef<T> that I serialize to its guid generated from its asset path relative to a root folder (we don't change the paths after we make it). Then that is converted to a guid when saved to disk. And is converted back when loaded up. Super nifty. I do need to rewrite this at some point once we get funding, but for our latest demo it works great.
velocity.y -= gravity * Time.deltaTime;
if (velocity.y < maxSpeed)
{
velocity.y = maxSpeed;
}
is this a good way to clamp if i only want to clamp a maximum?
you have that backwards, I think
it sets the Y component to maxSpeed if it's less than maxSpeed
otherwise, yes, that's reasonable
maxspeed is meant to be like the fastest you can fall
so like
if its less than -30 for example
sets it to -30
ah, okay
-30 being the vector y component
Could also be written like this I guess
float maxSpeed = -30;
velocity.y = Mathf.Max(velocity.y - Time.deltaTime, maxSpeed);
an alternatve that's more general:
Vector3 down = Vector3.down;
Vector3 fallingPart = Vector3.Project(velocity, down);
Vector3 otherPart = Vector3.ProjectOnPlane(velocity, down);
if (Vector3.Dot(fallingPart, down) > 0)
fallingPart = Vector3.ClampMagnitude(fallingPart, 30);
velocity = fallingPart + otherPart;
Not so useful here, but it would be if gravity was going all over the place!
split your velocity into two pieces:
- the part that's aligned with "down"
- the part that isn't
if the first part points in the same direction as "down", clamp its length
put them back together
velocity.y -= gravity * Time.deltaTime;
velocity.y = Mathf.Min(velocity.y,maxSpeed);
i did it like this
But min will return anything below maxSpeed, if I am not wrong
this is for falling
i guess i could max and the absolute value of velocity.y
you want Mathf.Max for falling
so that you get your currently Y velocity as long as it's more than -30
See my one liner
i see
velocity.y -= gravity * Time.deltaTime;
velocity.y = Mathf.Max(velocity.y,maxSpeed);
so like this?
yes
I would call that variable "max fall speed" to make it more obvious than it's going to be negative
i suppose for bidirectional movement i'd use clamp?
Yes, you could use clamp there
Hello.
I have a player controller script that's a bit buggy, can someone help?
Courtesy of Udemy.
you need to be more descriptive and show more information
what script? !code
whats buggy about it
📃 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.
https://gdl.space/midesawero.cs it has a few red lines
okay, and what are the actual errors?
😂 screenshot the console in Unity to explain "the red lines"
ok one moment
following a multiplayer course, not good...
Enemy enemy = hit.collider.GetComponent().< Enemy > ();
These are basic C# syntax errors. If you're struggling with these it's really not a good idea to be trying to make a multiplayer game.
this is A line with an error
is there a way to link one TMPro text box with another in a scene so that it copies what ever is written in the other one WITHOUT using Update() ?
the get component stays underlined in red
events
Make a function that updates both
is there a spacing error
which even is triggered when the text changes?
or is it a missing brace?
no you make your own function that updates one and fires the event
the syntax is completely wrong
or a property, which is basically just a function.
the generic type parameter has migrated past the function call, and then you're trying to call it again
i concur with this
yes make a property that invokes event onchange or use regular method as suggested
i'm trying to do text shadow, and only way i found was to create another text, place it under and update it. Is there a better way?
how long have you been using Unity and C# and have you done any previous tutorials?
TMP has a built in text shadow thing
yeah I mean I get it
ive been using Unity a couple months, and c# for about a couple months, I have done other tutorials
If you must do it with two objects, just make a component that handles it all
its asking for an identifier
Unity also has a Shadow component for ui
TMP has it as build in material ?
You should know how to write GetComponent properly by now if it's been a few months
right, with Underlay?
whats wrong with the shadow built in TMP shader?
these are basic errors you should be able to solve then, is your !ide configured?
and if you cant then you shouldnt really be doing multiplayer
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
• Other/None
Just compare your code:
GetComponent().< Enemy > ();```
With literally any GetComponent example on the internet
couple of month is not even remotely close for doing multiplayer
when i try doing that, it creates these bugged lines
Does that have to do with my font settings?
Count these braces. Seems like an issue. See it?
yeah
you've been coding these few months without a configured ide ?
a lot of people do that who dont come to the server
if a video doesnt say it how else would you know it needs to be configured
ive been with a ide that's at Csharp
By wondering why the video's code looks different and autocompletes, then researching it.
At least that was my path to it
one moment ill brb
I have a question about exporting from blender into unity. I have this animation, mesh, and rig that's in blender and it loops well, uses root motion, and doesn't have any obvious errors while it's in blender. I store the animation in a NLA editor strip. However, when I export the thing into unity, the root motion seems to change and instead of working like it should, the animation moves the character back every 22 frames, which I know doesn't exist in the original blender animation. Does anyone know why this could be happening?
ok, I'm going to go over it again, much more thoroughly
thank you guys for your time and support
Use a field initializer?
Or have the constructors call each other.
Also make sure you're not using a constructor on a MonoBehaviour
Optional parameters are a potential alternative too
structs are not classes, no
they are types
can i edit a font's generation settings after it's been generated? Trying to change the padding
unclear what you mean by "use them as classes"
in c# they are difference between reference types and value types
In C# the difference is that structs are value typed and classes are reference-typed
C# has proper access modifiers
pretty big in my opinion
in c++ structs just hold data
nothing at all to do with being a "private version" of a class
if you dont specify access modifier its also private in c#
wdym it's defaulted to private? like the members? because c++'s struct members are public by default iirc
Any ideas on why my player is refusing to move?
private void Update()
{
if (isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
if (input != Vector2.zero )
{
var targetPos = transform.position;
targetPos.x = input.x;
targetPos.y = input.y;
StartCoroutine(Move(targetPos));
}
}
}
/*
coroutine to move player from current position to target position
used to do something over a period of time, in this case moving the player from current position to next position
checks difference between target position and current position is greater than some value
yield return null stops coroutine and begins it again
*/
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
}
you're only processing movement... if you're already moving?
Should if (isMoving) be if (!isMoving) ?
or maybe even better:
if (isMoving) return;
// the rest of the code```
Also, you never set isMoving = false
also this code will only ever allow you to move within 1 grid space unit of 0,0
consider adding to the target position instead of assigning each axis to the input
Well first off best practice would be to store the current grid position with int variables or a Vector2Int
because right now if your user is using a joystick / gamepad, sadness is going to happen
Can you show me an example?
it's literally just += instead of =
Or a = a + b; instead of a = b;
Works great, thank you all
So i copied this code from a tutorial video, what steps do you recommend I take so that I understand it further?
Vector2 inputDir = value.ReadValue<Vector2>();
Vector3 movementDir = new (inputDir.x, 0, inputDir.y);
rb.velocity = movementDir * speed;```
Why isnt this working?
It says:
'InputValue' does not contain a definition for 'ReadValue'
bool does not have an implicit cast to integer in c#, nor does the inverse exist either
Ctrl c ctrlv or wrote it?
It always saddens me that I cannot if (myInt)
Well I hand wrote it of course
Make him look at the cursor
int isTrue = myBool ? 1 : 0 ;
But I still "copied it" from a video
Make him look at the cursor.
Wdym make him look at a the cursor? Like point the animation towards it?
Make the player look at the mouse cursor
How do I go about doing that?
bro wtf is happening bro why is my console not outputting everything
just a second ago it was outputing everything
now nothign
Clicked hide logs?
How would I go about changing the underlay color of my text based on the color of the text?
we wont even need code just inject our ideas into the machine
🙏 🙏 you deserve nirvana
What position does transform.position refer to? Is it always self-referential? So in my case the player object?
transform.position is self world position
transform.localPosition is position from parent, if no parent its world pos
What is world position?
the position in the world
Position in the world of the object? Isn't that transform.position?
Transform's position property would be that of the world position
The local position would be what you'd see in the inspector
Can you provide an example of when you would use the world position?
If I understand it correctly transform.position would be used for something like movement, but what would world be used for?
They are both simply positions
Either can be used for movement
The local position would simply be the position of the object without accounting for the parental offset.
Hmm I think i kind of understand it
if (!collision.gameObject.CompareTag("Boss") && !collision.gameObject.CompareTag("shooter") && !collision.gameObject.CompareTag("Projectile"))
{
Destroy(gameObject); // Destroy projectile if it hits anything else
}
bascially there is one boss object, one shoooter object and there are multiple projectile objecters everywhere, and the projectile objects sometims hit each other and just get stuck in the air, how would I fix this
I dont want the projectile objects to destroy each otehr when they touch
but I also don't want the projectile objects to collide and just float in the air
this is an "oncollisionenter" method btw
Maybe have them on a layer that would ignore each other
How can i make it so the Text Underlay (aka shadow) is based on the text color (like example on the right) rather than a fixed color for every piece of text (like on the left example)?
it seems impossible
i just typed a big ass thing and resolved my problem just by typing it out bye
also if you want collision, you typically don't move transforms directly but thats another topic 😛
like if I have projectiles all in the same layer, they wont collide or do anything with each other?
this is a code channel
Root @ (1, 0, 0) // local position
- Child @ (10, 1, 0) // local position
Root world position -> (1, 0, 0)
// this is effectively each transform's local position added up
// in its parent tree
// so (1, 0, 0) + (10, 1, 0) = (11, 1, 0)
Child world position -> (11, 1, 0)
// local positions allow you to position relative to a parent.
// such as an item that bobs up and down on a moving platform.
// the platform would want the item to move along with it
// while the bobbing effect would want to only apply to the local position
// so it still follows the platform, but moves up and down.
Have that layer ignore objects on the same layer 🤷♂️
If your projectiles don't need collision data, i.e. they never bounce off walls or anything like that you might want to change the collider to a trigger collider and use OnTriggerEnter() instead.
oh, where am i supposed to post this, then?
oh i see the thing you sent me, i can cahnge it in settings
i tried on trigger enter before but the object never destroyed itself when the method was callled, im going to try the layer method first
hello, I did a little looking. I know its a bit of a meme to say I followed a tutorial verbatim but I checked it out and set { doesnt need a ; before it but... again super new here just trying out.
I kinda understand that most parameters or whatever the term is need ; but thats usually within the brackets
are you serious? you didnt join the server today...
I think I get it, thank you so much for that
remove the ; on those. They aren't fields anymore, they are properties.
you might have to write your own script that handles that.
that worked. not sure how or why but thank you
You don't need the semicolons after the property name. I'm sure that's not how it is in the tutorial
you should configure your !ide 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
• Other/None
it isnt. youre correct
good news: it ignores objects
bad news: though minimal, it is randomly getting stuck on something which I do not know of
Hello, im having trouble on something im sure is simple. I made a script to shoot a ray cast and if it hits the object tagged with candrag, I want to move it up and down on the y axis while its still on the line of my raycast. How should I approach this?
here is my script https://gdl.space/toxiciwopo.cs
move it up and down as in animation? use dotween or coroutine
would this be me manually moving it since thats what Im going for. Not something I click on and it automatically moves up or down
you did not specify that
sorry
how do you want to move it up and down?
you could probably raycast on a plane
set plane center where the object center is
maybe explain the mechanic of what you want to do
If you got code from a tutorial, what process do you do to understand how it works and ensure you can replicate it later?
this is called learning
I hate just watching a video, writing the code and not retaining the information/concepts
look up the functions you are using, use them in different usecases over and over
repetition is key to retaining info
you need to experiment with it, change values, see what outcome it does. Try to understand what most functions actually do
A lot of tutorials really are just shit though, so be wary
simply put
The redcircle game object is a target. I click, hold down mouse to drag down redcircle on the Y axis to hit a greencube. The player has to keep the crosshair on the redcircle in order to keep pulling it down and hit the greencube. I need the redcirlce to follow the crosshair going down on the Y axis as long as the crosshair is on the redcirlce.
I hope this makes sense, bad at explaining things
how do you prevent 2 bools from being active at one time in the inspector? like if there is bool lamborgini and benz, you cant have 2 favorite cars.
I still think raycast on plane is way to go and just only have the obj you casted on only use y pos. I'm still confused on what you're going for fully
use enums
Use enums or have a setter where when you set one true you set the other false
Enum is better
bools aren't active, but either true or false. when one is set to true, set the other to false . . .
though, an enum is definitely better for this . . .
can an enum run without play mode? i want to make a big selection of bools for the inspector and if any of these bools are set to true, this other bool will be set to false if it was true and if the one bool is set to true, sets the other bools to false
you need a custom inspector, or possibly, OnValidate for that . . .
Enums do not run. Nor do bools.
Selecting an enum will make that the current value only though
darn it my mind switched meanings again, i was thinking of ienumerator when u said enum
lmao
an enum displays a drop-down. only one value can be selected . . .
i should probably stop trying today
public enum MyValues {
X,
Y,
Z
}
public MyValues currentValue;
currentValue can only be x, y, or z (as written, there is a way around this, but that is not what you want)
well
flags
think Layermask
i didn't mention flags or using bitmasks though. that's a different story . . .
for sure, just pointing out its an option for selecting multiple in inspector
i know the way to just correct the bool at runtime, i was wondering if there is a way to run my if statements out of runtime
Item perhaps? I'm really skeptical about subclassing a dictionary though
you loop by accessing the value of each kvp (key-value pair) of the dictionary . . .
then you can access the bool field of each extVals struct . . .
i saw this on stackoverflow but theres only an example void of how to add a value to the dictionary
Just fyi, those are called methods, not voids.
Void is something a method can return (meaning it returns nothing)
You would do:
foreach (KeyValuePair<int, extVals> pair in this) {
int key = pair.Key;
extVals value = pair.Value;
bool myBool = value.fileBool;
}```
It's pretty unusual to be deriving from Dictionary in practice though
instead of just, for example having a Dictionary field
Also it's C# convention for type names to use PascalCase, not camelCase (extVals -> ExtVals)
honestly, i missed (skimmed over) the derivation from Dictionary. that's wild . . .
Maybe share the stack overflow page that you're referring to and provide some more context on the issue.
isnt it funny this is how i just discovered what a struct is
you could even go a step further and implement your own dictionary class that will handle any special operations that you would need. for example if you wanted to have an Add method that accepted an int, object, and double
Is there a reason you chose that?
Hey guys I wanna learn code is there a full course where I can learn all the basics I know most of the theory behind coding just not the actual words lol
Microsoft has a guide
And !learn, which is obviously specific to unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
All are free
awesome ty
my intention was to hard code the values, somehow serialize the bools, and then use OnValidate to make sure that one specific bool is false when any of the others are true, and when that one bool is true, sets the other bools to false
And remind me why you don't just go with enums?
Which would not need all that extra work
i wanted to make it so that with any of the other bools, any amount of them can be set to true
So, you can use the [Flags] attribute on an enum
But then you need to deal with setting flags false. Certainly a lot easier and cleaner than with bools though
hey all I have no programming knowledge but I have to make a unity game for my scholarship that could grant full ride and it's due in about 3 weeks
I'm trying to adjust the center of mass of my car. How can I do so if the boxes are greyed out? (I used a script from a tutorial on youtube)
Those are read-only values. You can't edit them
So there's no way to change them? I heard lowering the COM helped keep the car from flipping over
From code
how to change tiling of a material again? I remember there's a specific code for this
if() = true; is wrong
oh
and the other one
what would I use instead of if ("potato") = true then?
should just be if(x) and if(!x)
do I just replace the "com" in the script with the value? public class `ExampleClass : MonoBehaviour
{
public Vector3 com;
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.centerOfMass = com;
}
}`
I don't fully understand sorry do you mind explaining
Thank you I'm reading it now 🙂
Why are you trying to set an if statement to a boolean
Honestly not sure just learning code since 5 minutes ago haha
new dev that skipped basics
I know, I'm asking leading questions to let them realize why the code makes no sense
Just curios how they interact with each other
Well to me it makes sense
idk
If applesauce is true say this and if its not true say that
I don't know coding but that's just how I saw it
anyways, the () is important to look out for, it controls who can intereact with another
Why did you put an entire second class inside this script
im more worried with that semicolon tho lol 😆
hey man, keep it up! you'll get this sorted out in no time. once you get to applying these skills, it'll all help over time.
my best advice is when you see an example/tutorial, retype all of it without copy/pasting.
I see in the link you sent is it not refering to an int instead of a booleen can I not use the true and false instead of a numerical value?
I got no idea how this works tbh, I'm trying to make a game for a scholarship project so I can go INTO game development
lemme try something rq
I appreciate it man its honestly really interesting but hard lol
Then you should take some time to actually learn the basics of how code works. There are links in the pins, or on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
do you have two classes in this file? What's going on there?
That' looks super weird
You can do whatever you want
as long as whatever's in the if condition evaluates to a boolean
I don't have time unfortunately or else I would
won't it evaluate it based on what I set it as for exmaple I said it was true so if I said if its true say this why didn't that work
I thought the code was copy and paste my neurons didn't connect LOL
Then you very very do not have time to just make shit up and hope it works
I got an idea tho
It will evaluate to what it is
if() only accepts bools, the docs I sent used numbers with < > and == to convert numbers to bools
you don't have a week?
I got a job
okay so does nearly everyone here
Once I'm done with fixing the center of mass I'm just making levels and stuff
I can model all night
bools are true and false statements right?
I guess what I read was wrong in the tutorial rip
CHAT I DID IT
yes
YIPPEE
hey man, good on you. good luck with your project - try to keep the scope of it small and simple! (i say this as someone who did modeling and art first and foremost)
thanks! It's just a simple racing game
one last thing though, my car is jittery now when I drive. How can I fix that
what is the geometry of the ground like? is it terrain or something you'd modeled?
Your issue is that = is not checking if it is true, it SETS it to true. == is a comparison
Also, the whole thing needs to be INSIDE the parentheses
Doesn't the if statement check if its true or is there more code involved in that?
We confirmed I set it to true then if see's if its true no?
An if statement evaluates a bool
You set it to true incorrectly,
dang
THAT
an if statement runs the code inside it if the condition evaluates to true
makes so much more sense
because
the condtion
should be in the if statement
not outside
Dumb mistake ty ❤️
it's flat terrain however here's the vid
ignore the colors that's just bc i'm bad at OBS lol
embed fail moment lemme convert it
I could be wrong but doesnt the code end with a } usually
What do all those underlined lines say
like the last line
sorry
I'm no programmer though so dont take my advice lol
I'll check again
hovering over those will tell you -- if you have C# and intellisense working in your IDE
Yeah it added another {}
but it didn't fix it
The braces are not the issue
Did you hover over all of the errors and see what they are saying the problems are
Yep
they just said preview and add {}
I don't see a problem with the last letter
Character, not letter
Does it need a condtion but I thought I set the condtion above
I don't think it needs caps and the spaces look right
I'm not ending the code there either so idrk
Look at the format of an if statement and compare it to yours
You're ending the code whenever you hit a semicolon
Especially what comes between the ending ) and beginning {
Hint: nothing should go there
Yeah
Yeah google tells me to set condtion2 but that doesn't make sense
oop now my car is buttery smooth I just changed the interpolate value from "none" to "interpolate"
Not relevant at all to the issue
oop
put ```cs on the same line
if (something)
{
// do something
}
else if (something else)
{
}
ohhh
U would put the something else in the ()
So It would be console.writeline(") in the else if
What condition are you checking in the else if?
That is part of the issue. Also, as was explicitly said, remove the semicolon after the if condition
I'm not checking to see if applesauce is greater than or equal to 5 and if not write you suck
So why use else if
instead of else
Because it kept auto filling whenever I tried to use else
You don't HAVE to use what it suggests
Also, have you gone through the entire https://www.w3schools.com/cs/index.php yet? Seems like it would be pretty quick to be finished since I said it
have you tried asking chatgpt or smth to evaluate your code? it can help break down the basic concepts n stuff so that you can ask it direct questions. tell it to elaborate and everything
i second w3schools
yes! I'm currently going through that one right now as we speak haha
Just got confused about how the statements worked
If i want a 3d healthbar to be in my game above my player at all times, Just always facing the camera no matter what orientation the camera is in, how do i do this? Do i use a canvas
I tried chatgpt but I got the wrong answer from it
= is assignment
== is comparison . . .
ignore that so sorry I set applesauce to a nubmer I meant to put potato in there
There is no need to even do == for a bool.
Just If (boolVar)
Ah, it is not a bool. Ignore that then
How would that be comparing thoo am I not checking if its true
ohh okay thanks
Do not use gpt. It lies most of the time and will make things much harder
if statements can only check if something is true
You need to give it a condition that evaluates to true or false
ah okay thank you
Agree, if you're experienced, you can utilize it, but for the most part, it is wrong
awesome thanks
no. using = assigns the left-hand side (field) to the right-hand side (value). you need == to compare the left-hand side to the right-hand side . . .
within the Canvas component on the GameObject, change the "Render Mode" to World Space . . .
Okay that works
How do i make it always just face the camera, like theirs an option in particle system to always face camera
place a script on it, with code that allows it to always face the camera . . .
I can do Transform.LookAt, but my characters rotation is very sharp and it bugs,
oh, so you already have the code. have it face what ever GameObject you want, and that's it . . .
healthSlider.transform.LookAt(mainCamera);
I have that in Update, But my players rotation is instant ant sharp, w rotates it 90, s rotates -90 and it bugs a little bit
if the camera remains in this position, there is no reason to have it in 3d or rotate with the player . . .
just have it face the current view and move along with the player. i don't see a need to rotate it at all . . .
I'm not rotating the camera i'm rotating the player
you don't have a camera assigned for the "Event Camera." just watch a video for 3d ui and it'll give you all the details . . .
also, the glitchyness is because the canvas is a child of the player. it should follow/track the player's position instead of being a child . . .
I dont know why thats necessary
This was my only concern
So in a seperate script, it shouldnt be a child, and ill just manually set it to follow the player in Update?
it's part of using 3d ui; that's why there is a warning. the warning give you further details. i'd read it . . .
that's how i type . . .
You were directed to the vfx channel. Why did you decide to cross post off topic here as well?
sorry, this doesn't seem like a coding issue . . .
I have this code for movement on a 2d sprite:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movemnt : MonoBehaviour
{
public float jumpForce = 5;
public float speed = 5; // Added speed variable
private Rigidbody2D rb; // Declared rb as a class member
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
rb.velocity = new Vector2 (moveHorizontal*speed, rb.velocity.y);
if(Input.GetButtonDown("Jump")){
rb.AddForce(new Vector2(rb.velocity.x, jumpForce));
}
}
}
(ignore jump)
When you go 1 direction for too long, it starts jumping a little. I'm unsure of why or how to disable it.
When you press both keys, it stops, as expected, but several things happen. When you release both and you press the key you pressed first, it doesn't move until you go backwards. It also gets buggy.
there was noone there and this seemed more like a simple issue that vfx issue
but now I know
from pin
so its alright
This channel is not for random simple issues. It's for code issues.
Doesn't look like the issue is related to this code. Do you have other scripts on the object?
Also, you should probably move the velocity and add force to fixed update.
And (I know you said ignore jump, but...) consider using ForceMode.Impulse for a jump
No other scripts. The collider has an offset because the player was floating before it. There are no bumps on the surface it is moving.
Show the inspector for the rigidbody
This could be relevant.
Typically you'd offset the visuals, not the colliders/rbs.
Well the colliders aren't touching and it's floating. I don't know why but it fixed it.
Avoid the "I don't know how, but it fixed it" solutions. Figure out what's happening first and why. This kind of solutions are a sure way to get more issues.
These are the colliders. An offset of 0.1 on the y of the collider of the player fixed it.
The collider of the floor is at the bottom of the orange line, behind it.
This is in pause after it fully hit the bottom.
- You should probably use a simpler collider, like a capsule or sphere. Colliders with corners can get stuck/stumble on a surface where 2 colliders meet.
- You can offset your visuals(sprite renderer) instead of the collider.
- It's likely that you are working with small scales judging from the size of the gap. I'd recommend not scaling your objects down too much. A character should be somewhere between 1 and 2 units ideally.
ill change it to capsule and change it back if i need it.
imma try doing that and come back if issues presist
uh the cell size of the grid is 1, and the player's size is 0.2
idk how to scale it up properly
This doesn't look like .2
Can I hire someone to help me with some coding for games, guidance with manuals I get, give me a tell and I can add you?
It's.2 times whatever the actual size of the sprite is to start with
oh then it should be inbetween 1 and 2 right?
- This is scale. Not the actual size of your character. Which means that your sprite is just huge originally. You should modify the units per pixel property of your sprite.
- You should avoid scaling rbs.
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
📃 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.
I need help with this code... https://paste.ofcode.org/32suhgRqiZG3gUT7vWL7ivE
I was coding the whole thing over, and then this 1 error in the compiler had appeared to be a bit difficult, I want to finale it with you all hopefully.
your brackets are all messed up. Look at the method Die() and past that.
Did you write this code yourself? You really shouldnt be doing multiplayer if you arent decently good with coding
Is it just brackets?
No, I'm taking a tutorial.
To improve and get a certificate.
I seem to be getting into a multiplayer, that's basic and just leave it as experience made.
Theres 2 (die)'s.
both have no error
for the error you have, yes. One thing which points this out is the weird indentation on it, which your IDE likely did
why would this crash my game private IEnumerator HealthRegenerationCoroutine() { while (health < maxHealth) { health += (0.1f * regenSpeed); UpdateHealthSlider(); } health = maxHealth; UpdateHealthSlider(); yield return null; } 😭
In my take damage function i call it here HealthRegeneration = StartCoroutine(HealthRegenerationCoroutine());
what do you mean? there is one method named Die. And is your !ide configured
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
• Other/None
i'll check the IDE, brb
its likely not crashing your game, just infinitely running (for whatever reason). your coroutine also does nothing here that a regular method wouldnt do.
In a loop it will instantly keep increasing the health by 0.1f * regenSpeed then call UpdateHealthSlider();.
If this loop ever finishes, it will set the health to max, then call UpdateHealthSlider();
THEN it finally waits for 1 frame before doing nothing
IDE updated... probably needs more tuning, brb
I feel dumb
regenSpeed was set to 0
I am alsi using yield return new WaitForSeconds(regenSpeed); now
ok it's updated
What's the difference between Lerp and MoveTowards? Are they similar in principle?
i would add a sanity check in that while loop as well to do nothing if regen speed is 0 or negative. Also this doesnt fully make sense that you are using regenSpeed in the WaitForSeconds. If your regen speed is 1, you heal 0.1 every 1 second. if its 0.5, you heal 0.5 every 0.5 seconds... same thing (assuming we ignore the imprecisions here)
your ide now should point out the errors, but in this case really just go through your brackets because you have extras. Errors will be near the brackets because theres code where there shouldnt be, according to the IDE
{
while (health < maxHealth)
{
health += 0.1f;
UpdateHealthSlider();
yield return new WaitForSeconds(regenSpeed);
}
health = maxHealth;
UpdateHealthSlider();
yield return null;
}```
have u read the docs for them? they both do different things
ah i see you arent multiplying by regenSpeed in health now. I guess this is fine depending on what you want
They both smooth out two points, right?
well do you want to heal by regenSpeed every 0.1 seconds, or heal by 0.1 every (regenSpeed) seconds?
Pretty big difference there
there is nothing smoothing about either, a lerp is a linear interpolation. Meaning some point between A and B at percentage T.
MoveTowards goes from A to B by some amount C.
What is creating the smoothing in MoveTowards?
Nothing, what smoothing?
Smoothing would be done entirely separately from both methods
Also with this coroutine, In the beginning, Its delayed with the WaitForSeconds. If the player gets hit, I want it to cancel that coroutine, and start it again, how come this doesnt work? HealthRegeneration = null; HealthRegeneration = StartCoroutine(HealthRegenerationCoroutine());
In the TakeDamage() function
Setting the reference to null does not affect the actual coroutine
Hmml,
There is a StopCoroutine method
I believe yes. Not sure. Try it
Looks like this worked, Thank you! ``` if (HealthRegeneration != null)
StopCoroutine(HealthRegeneration);
HealthRegeneration = StartCoroutine(HealthRegenerationCoroutine());
i forgot you were storing the coroutine also, you will want to set it to null at the end of the actual coroutine too
after the yield return null?
i'm dumb
well that specific line doesnt need to exist, but yes at the very end
MoveTowards doesn't do any smoothing?
By updating an object’s position each frame using the position calculated by this function, you can move it towards the target smoothly.
Theres a difference between smoothing, and something moving smoothly. The docs are just telling you that MoveTowards can be used to make something move towards another object in a way that doesnt look its teleporting or stuttering
there is no smoothing
Oh okay lol
its always useful to just make a test script and debug what the values are, like print the result you get from MoveTowards if you give it a 0 vector, and try to move towards (1, 0, 0) for example. Change the max distance around.
Its not like the method will magically give you a different value than what you asked for because it thinks itll look better
yeah i'll go ahead and try that
Hey Everyone,
I have a certain functionality that a lane can get removed out of the scene by scrolling downwards out of the scene. As you can see the items which are on the lane fully are no issue, as they leave the scene exactly when the lane leaves. But there are other items:
I want to handle these 2 situations such that the items which arent on the lane get destroyed immediately. The item partially on lane should be handled such that it doesnt look that its lying on the ground and lane as well. Its all about it shouldn't look absurd to the player
When trying to build my project as a WebGL I kept running into errors and while trying to close an error message I accidentally closed the unity editor. When I reopened it I had a bunch of nullreferenceexception errors that dont make sense and I can't figure out how to fix, does anyone know what might have caused this? I'm not even able to move around in my game anymore.
Debug the errors as you would any normal NRE error
Probably just something wasn't saved
Sorry this is my first project how would you debug any normal NRE error
Figure out what's null and make it not null
thanks
[CreateAssetMenu(fileName = "New Gun", menuName = "Gun Data")]
public class GunData : ScriptableObject
{
public string gunName;
public int damage;
public float fireRate;
public enum FiringMode {SemiAuto, Auto }
}
``` This is my scriptable Object class, But their is no option for it in my Create Menu?
Do you have any errors in your console?
None
Show your asset menu?
should not matter
you sure you saved/compiled ? Try triggering a recompile, right click inside project window do Reimport
woo!
Noob question: How come I need to AddComponent CharacterController?
controller = gameObject.AddComponent<CharacterController>();
https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
You do not need to
you can add it via the inspector as well 🤷♂️
Ah, I see. The code is like that just so they don't have to explain that you need to add the component in SOME way.
You can do it via inspector, or in code. It doesn't matter. The example code simply chose to do it via code with addcomponent
They could have also done [RequireComponent(typeof(CharacterController))] and then getcomponent
That example code is not great honestly. It is preferable to combine all the vectors and only do ONE Move() call per update
Makes sense, thank you
void Start()
{
controller = gameObject.AddComponent<CharacterController>();
}
void Update()
{
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
}
What am I doing wrong here I am trying to move the player left and right, top to bottom but it disappears into the void then reappears when I hit a key
i am having problem with vs code agan
does anyone know how to turn back the red wavy line again
idk what i did yesterday
!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
• Other/None
Yeah you gotta enable it
Checkout the link above
So the character is moving just fine but the sprite disapppears... any thoughts?
can someone explain to me why i can't drag my GameObject into mt component
You are trying to assign a Scene Object, which will only exist on runtime to a prefab in your assets folder
what can i do then?
You cant do that. If you want your player to be assigned to the bullet, either have a player singleton in your script or assign your player as soon as you instantiate it
can you assigne in code?
Seems like you should go through the starter tutorials on unity learn, to understand what you actually doing 🙂
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You assign the player to the singleton when they wake https://unity.huh.how/references/singletons
Or spawn the player from the singleton directly, for example
There are multiple ways, mostly depends on your needs
You do not even need the player. Just rotate the bullet to the correct rotation when instantiating already and let it fly its own forward vector
it's my second time making a game so i'm bad
oh true i didn't think about that
Not bad, unexperienced probably. Just keep learning and digging into the unity docs while using their functions. The extra step will help you understand the whole thing better in the long run
true the unity docs are so good
void Start()
{
controller = gameObject.AddComponent<CharacterController>();
}
void Update()
{
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
}
I'm trying to move the character along both the X and Y axis top down style yet it just moves left and right, where did I go wrong?
you are putting vertical on the z axis
Tysm
don't forget to normalize your vector or your character will move faster diagonally
How do I do that?
you just type . normalized at the end of your vector
Hi, I am currently having an issue with the "Loader" field getting removed when I press play. I have included parts of the scripts that might have made the problem.
why line 16 (GetComponent) when the value is set in the inspector?
also the inspector value is set from the Transitions game object NOT the game object containing this script
Sorry, once I removed the (GetComponent) line and it immediately fixed itself. Thank you very much!