#💻┃code-beginner
1 messages · Page 609 of 1
That seems like a pretty pretentious opinion tbh
a tad
Some people just really don't care honestly.
Improving the code of a fun game is far easier than Making some perfectly programmed yet boring experience enjoyable
I tend to rewrite entire systems 2-3 times
godot is actually a great engine if you don't care too much about your code and just want to make a game
development is highly iterative
python-type languages are top-tier when you just want to get crap done
you make it sound like you need to write shit code to make it fun
to do it efficently? Honestly a little yes
You prototype ideas as fast possible to test them out
maybe your definition of good code isn't that well defined
Unless its some highly game intensive thing that its doing
Committing time to developing a system that's going to get thrown out tomorrow is a massive waste of time
i get the feeling that "good code" is whatever fits the argument someone is trying to make
depends alot on the project you're working on too.. Who's gonna be spending tons of time doing every single SOLID by the T on a quick gamejam with other people ?
you're creating extra abstractions for someone else who might not know anything and waste time explaining everything
the idea of a prototype is that its not the final
it just kinda seems like you dislike the idea that bad code can be preferable to write in some contexts
you can hack together a prototype to test out an idea, but if you hack together an entire game ur gonna get fucked over by technical debt
you see, one guy is talking about prototying, the other about finishing a complicated factory game in a team of 20... how will they ever agree on whats good/bad by discussing abstract examples in a void?
I think there is a misunderstand, I'm mainly speaking during prototyping / getting some ideas out
the complicated factory game would have been prototyped homie
idk what yall talking about
Unity already forces bad coding practices on you by not allowing custom mono constructors so you've some funky accessors if not serialized from the editor
and by fucking up my generics 😠
custom mono constructors?
You don't new your components with parameters, do you? ;p
when do you new a component
thats the point no?
yeah but you can't define specific constructors for them which in theory would be nice
you mean in the inspector? when u hit add component?
no via code
They're saying that the fact that they can't use new on components enforces bad practices
Can't do proper Dependency Injection
I think ive only added a component at runtime like. once?
so ig I dont know the use case
if you want to initialize data you're doing it in awake/start or your own personal initializer, but that prevents having private accessors set by constructors, and making that readonly keyword pointless
im curious why one would want to do that
eg. if you want to spawn a person prefab and you have some scriptableperson template you need to provide them when spawning them. there isn't a built in way to offer some way to provide that on creation
DI alone is a major benefit
But you've almost certainly used Instantiate and then immediately set a variable on it
ohh you mean like that
that sounds more like you want a constructor for the gameobject, no?
I have wanted that
then no, I haven't instantiated a component if thats what you mean
Once you start messing with making your own classes that aren't inherited from anything you'll probably have a better understanding of the comparison people are making here
Then you're probably not using Instantiate properly. You shouldn't be passing GameObject to Instantiate, you should use the component you actually want
Which often times also means you set a variable on it right after
almost never a reason to use GameObject class directly
The semi-logic issue here is that while yes GameObjects hold components in 99% of cases there tends to be a primary component on the gameobject that is what people are spawning
the reality is that GameObject's have your primary component but how you actually use Unity tends to be more that your Primary Component has a GameObject
Animator.GetCurrentAnimatorStateInfo works for know info about the current animation state, but is there an equivalent that sees for an specific animator state independent if its the current or not?
I guess I'm doing things wrong then
GameObjects cant live without component and component cannot exist without GameObject
Calling Instantiate on a component still clones the whole object, but returns a reference to the component without needing a separate GetComponent
I think for the most part I dont do that bc
- a
public Gameobject prefabworks better than apublic Projectile projectilePrefab - my objectpooler I wrote years ago wouldn't like it
MyComponent myInstance = Instantiate(prefab, etc.)
myInstance.DoStuff```
In what way does that "work better"? It's the opposite of working better
I do know how it works yes
it works worse
I mean in the inspector
Again - in what way does it "work better"
its more GameObjectly typed
I don't have time to do an example
specifying the component that you use makes the editor ensure the component exists on the given object/prefab
so well just assume ur right
Using a component type for prefabs is pure upside. You assign it exactly the same way but now you don't have to do GetComponent
its not just them , its pretty much how its done properly universally
there is literally no lost functionality
but last time I checked u couldn't search thru prefabs with that sort of thing
like if u clicked on the little dot nothing showed up
probably something unlreated
I could be wrong
that is true, you would need to enable the more advanced searching feature
unity's default asset search rn struggles with that
Components have a direct reference to the game object its on, there is literally no code downside to using the component in instantiate
thats just unity inspector being weird. I just drag n drop it, never do i use that icon thing
And yea drag and drop is better for that
I use it maybe 90% of the time
if Projectile is a Component it will show a field just like Gameobject would
but thats just me
(in other contexts that search thing is a massive pain tho)
it works 50% of the time lol
Transform is also the cooler GameObject reference binding
it's simultaneously too broad and too narrow lmao
I also use Transform when I have no other components :p
Yeah absolutely
right? its either ALL or nothing..
the cooler search mode handles it way nicer
yeah the new search is goated
can't easily filter for a single package, gotta go through all of them 😭
luckily the new search has useful filters. Havent tried packages yet
Is there something specific you need this for? Last I recall you can do this in editor but not sure about at runtime. It sounds like a weird thing to need
i need a timer to have the exact lenght of a clip
and i felt like using the currentstate would make it more...unstable? i dont know how to explain it
Cant u reference the clip directly instead of trying to go through the animator states then? Even if using some #if editor to assign it to a value
how
thats my issue
for my own benifit, !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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://pastebin.com/GqtQctLX
Hi, why does the local variable isTriggered declared as false becomes true @line 47? I tried to place a print log on line 24 and 37 but it never got there to change it to true.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
use one of the sites above #💻┃code-beginner message
sorry, here it is https://scriptbin.xyz/qelutokaki.php
Use Scriptbin to share your code with others quickly and easily.
somewhere in that loop isTriggered is becoming true
how do you know for sure it never reached any of those two
Hello, I need a little bit of help on my project. There's an issue with my slots UI in my 2D game. For exmaple, I would have 5 same items in my inventory, I am able to drop them too. But the moment I drop them and close the inventory UI, the slots UI icon will revert back to its white box and not show the item icon despite having 4 left. I've tried everything :( nothing works
Did you try debugging?
I had a print earlier on those line, but I deleted it them. This is my console before i deleted them.
why delete them if you're still debugging
I would use debugger and put a break point on either of those
Thanks for this, I figured it out!
I just had to put the local variable in the for loop
I'm going to try that today, I'll come back if it doesn't work 
Hello I am a robotics student trying to code a field simulator, ive been using AI to help me debug but now i keep getting the same warning that is correlated with why my code isn't working
im trying to load a glb model into my simulator but as soon as i load the glb i get this error: glTF has no (main) scene defined. No scene will be instantiated.
UnityEngine.Debug:LogWarning (object)
GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__72:MoveNext () (at ./Library/PackageCache/com.unity.cloud.gltfast@8fc67a42c5f2/Runtime/Scripts/GltfImport.cs:680)
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<bool>:Start<GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__72> (GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__72&) GLTFast.GltfImportBase:InstantiateMainSceneAsync (GLTFast.IInstantiator,System.Threading.CancellationToken) GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__71:MoveNext () (at ./Library/PackageCache/com.unity.cloud.gltfast@8fc67a42c5f2/Runtime/Scripts/GltfImport.cs:657) System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<bool>:Start<GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__71> (GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__71&)
GLTFast.GltfImportBase:InstantiateMainSceneAsync (UnityEngine.Transform,System.Threading.CancellationToken)
FileUploader/<LoadGLBFile>d__4:MoveNext () (at Assets/FIleUploader.cs:80)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)
can you use guid in unity
you can use it but unity can't serialize it. If you need to see it in inspector for example, you can use string
Hello, when I click the help menu in a component window, it opens the local documentation file in a text editor instead of the default browser. Is it possible to either change the default program to open the doc or disable local documentation?
I can't find the documentation in built in package like google said to disable it
Running Unity 6
I don't see any option to select browser in the external tools like google said :/
Note that I DO want windows to open html files with my text editor. But I want Unity html doc to open with the browser obviously. So I can't change Windows default program for html files like google suggest either...
Or how to remove the doc I downloaded instead? :/
Ok, I deleted the documentation folder in the editor/data folder and modified the module.json file to set selected to false in the editor folder too. The documentation still shows as installed but links to open in the online doc now. Really buggy way to fix the issue. Modules should be toggable in the hub.
whats the correct way of handling dealing damages logic, do i set a damage variable on the weapon or the projectile, substract the other object health when weapon or projectile colide ?
WeaponStats in weapon sets damage amount, if its a projectile then set it on the projectile
health / damage receiver should not care who its from, just the amount to subtract void Damage(float amount)
thanks agree
but where should that void damage be? in the IEnemy? or the weapon or projectile if has projectile?
i feels like its the latter you saying but i seen the method TakeDamage very common in the IEnemy interface
weapon calls if its raycast, projectile calls if it directly hits.
Yeah TakeDamage is fine, a better interface would be IDamage or something, since enemies wouldnt probably be your only thing that damages
IDamage is new first time i seen this, thanks i'll try that
yeah I mean naming is up to you, just makes more sense to generalize it
you could also use a dedicated component approach too
i mean first time i seen damage class outside the player/enemy/weapon class
many objects for my world damage including random props in the world :p
yea makes more sense fr
hey mates, quick question:
is it possible to have an extra option in this manager in the context-menu (for example: new command), which then creates a scriptable object or whatever under it?
I only what to have it at this point.
I thought about something like
[CreateAssetMenu(fileName = "Command", menuName = "New Command")]
public class Command
but that would mean I already have that object created. I'd rather create a new "template", if you know what I mean
Hello, guys. Well, how can i disable this Debug Updater on my scene. It appears every time I start the scene...
it's in "Don't Destroy On Load" section in Hierarchy
looking online, it seems to be a URP thing
I've not seen it before, but is it causing any problems for you?
its for debugging so its not like the final built game would have it
it doesn't open on my pc idk why
put UnityEngine.Rendering.DebugManager.instance.enableRuntimeUI = false; in any script
no worries!
dunno what your asking for specifically but you might want a contextmenu attribute?
can i use
Input.GetKeyPressed()
or is it not recommended to?
considering that doesn't exist, i'd say it is not recommended to use that. perhaps you want to double check the documentation for the Input class
i meant GetKeyDown sorry
if that is what suits your needs best, then use it
Why would you think its not recommended to use it?
ah well.. i don't know
I suppose the best answer to this is no, it's not recommended, use the new input system instead.
as nice as sebastian lague's tutorial on procedural generation is just following him is not very helpful. Is there any good source to actually understand wtf im writing?
You can alway just do OpenGL tutorials and transfer that knowledge over
It's also very much not a beginner topic, but it's super interesting and there's a lot of engine-agnostic theories around it that you can find online, or in books. Essentially you should be able to use your understand of math and procedural generation -as its own topic- (not from some Unity specific context) and apply that to runtime mesh generation.
Lague's tutorial I feel already assumes quite a solid understanding of vector math.
oh yeah i'm a little cooked if that's the case. I understand the syntax, but the logic behind it is way out of my math level as of right now, considering I still have no clue what trigonometry even is. I should probably do procedural generation when I actually have a better understanding of math
Sebastian League's videos are not tutorials. They're more dev vlogs with the occasional summary of what was done to make it happen. I don't think it was ever supposed to be more than generally educational.
Oh oh, I love sharing this playlist from Freya Holmér. She does an absolutely brilliant job teaching this stuff.
https://youtube.com/playlist?list=PLImQaTpSAdsArRFFj8bIfqMk2X7Vlf3XF&feature=shared
ah, this seems really, really useful! Thank you so much.
Honestly dont even need to touch trig. Grab yourself the fastnoise library and sample that
Unless you're creating something more dynamic like ocean waves, it's not likely you're creating something structured purely on trig functions
Also, if it's enough for your needs, MapMagic is free on the assetstore and is incredible for generating procedural terrain
what does the ":" mean in this line of code?
It's basically the same as else in an if else block
That's called a ternary operation.
okay, so im following a tutorial, and i have an issue, and i dunno how to fix it.
Your script name is still 'NewBehaviourScript' - change it to PlayerController and you should be fine ^
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
o i see it
thanks
The script (file) name is PlayerController, the class name is currently set as NewBehaviourScript
i fixed it
Ah yep should have clarified it was the class name, not the file name ^
it works now
Still, setup your VS properly
what did i do wrong?
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
oh yeah i was wondering why it wasnt autocompleting like in the vid
Could someone help me figure out my variable isn't incrementing? It looks like it should to me, but it's not for some reason
!code also you're setting i to 0 in update
!ide
bot is down?
uh oh, did the bot die again
huh, is dyno taking the day off
It's online
#💻┃code-beginner message
message link on how to configure your IDE above
you dont have any highlighting which will point out errors and its a requirement to get help here
I think I have that on, since I installed it with Unity Hub
Is there a way to verify a dll plugin is loaded with the game launch, I dont mean using a if statement to check if the file is there. I mean a official way to verify it
your IDE is definitely not configured, you installed the IDE but follow the steps i linked above for it to provide you with syntax highlighting and more
I just checked and it looks like it's already configured to it
i am telling you that its not configured, which i can see directly from your screenshot
Which one? i?
follow the steps linked
That one, yes
just saying you were already given the answer here #💻┃code-beginner message
I did that, but it's still not working and I'm not sure why
do you think i should like just uninstall visual studio and reinstall it or something?
You moved the i = 0; out of update?
i think you should read and follow the instructions on that page, including the instructions for when you are experiencing issues.
Yeah, I put it in start
okay sorry
go through every step carefully. the instructions work.
theres no way in the minute you took between each response that you actually read through and followed every instruction
and also as a reminder to people
bit harsh, could just tell the answer (assuming its as simple as this one) and also give them the !ide command
that will just cause them to ignore the instructions to configure their ide so they just come back with further problems and unconfigured tools
Doesn't this mean it's configured..?
that is one step of the process
if you have a problem with the rules then take that up with the mods #1161868835423526933
but we've seen time and time again people just giving the correct answer, for the person to not configure their IDE cause their problem is solved.
Theres literally nothing to say other than fully read the instructions, which ive told you a few times already.
If you have problems with a specific step then thats fine to ask, but your question clearly shows you didnt even read the page
Apologizes. I just went through it all and everything says it's fully updated
Is there more that I'm missing..?
go through the troubleshooting steps at the bottom of this page: https://unity.huh.how/ide-configuration/visual-studio
No, it's not the correct place. This is a code channel, and that isn't code related. Delete it all and post in #📱┃mobile
and ideally post it as one message instead of 4
hello i have a problem with my movement script code, since it is my first time i copied a game from a youtube video and i did all the steps he did and my code is the exact same but i get errors when i try to start the game
share the relevant errors and !code
!code
right, bots down 
damn the bot is still dead. #854851968446365696 for code sharing guidelines
wait ill send it now
make that a vector2 and remove the z axis (the last part of it)
you're using a rigidbody2d. that's a 3 dimensional vector. cant have 3d velocity for a 2d object
I changed it and there are no errors but i still cant move the player
do i need to add something else?
have you configured visual studio yet
oh ill try it
is the script attached to the player?
that is not related to your issue, but it is a requirement for getting help here
not the problem, but it will massively help with debugging it
oh ok
which guide should i choose
i had visual studio installed before i even tried unity for school
installed manually
try turning off gravity on the object, temporarily. it could be moving slowly due to friction
This might be really stupid question, but I'm trying to get a square to lerp across four points infinitely. For some reason, it's teleporting from the last point to the first point. It's getting to the reset point I made, but it's not resetting itself so it doesn't teleport. Here's the code: (it's mainly the last if statement) https://paste.mod.gg/oobojukmsbyc/0
A tool for sharing your source code with the world!
you can set arrays in the inspector y'know. one, two, three and four can just be turned into a single array
it seems i have deleted my visual studio installer can i do these steps in the app as well
never mind
I might be very wrong, but I think I did that..? That's when you drag it in to fill the public variables, right?
im just stupid i found the other steps
you can do it for arrays too instead of allocating a new array every single frame you can just populate the array in the inspector instead of having numbered variables
also because the first parameter of Lerp is the starting point and when you reach the end of the array you reset so the starting point is the beginning of the array again you will always teleport back to that point and move to the next one.
Consider restructuring a bit, you could instead use MoveTowards rather than Lerp with a constant speed, and use the current position as the first parameter and the target from the array as the next, then when you reach the target change the target to be the next one in the array
My professor made this assignment to practice using Lerp or Slerp, so I have a good hunch he wouldn't like it if I used something else sadly
or just keep track of what the current point is and what the target is in separate variables instead of using a single int i since you are much more limited that way with your current setup
tbf MoveTowards is basically the same thing as lerp, just with a specific speed instead of a specific time
Is the rate for Lerp not its speed..?
no, it is the percentage from A to B (or normalized time)
https://unity.huh.how/lerp/overview
Lerp(a, b, t) will return a value that is t% of the way between a and b
Oh I see
yo i fixed the problem
as soon as i installed the extension it magically works
thanks for help
not too sure if you solved the problem above, but usually in this setup you'd want to keep track of how long you actually want it to take between objects. That "how long it takes" being used as the 3rd parameter in your lerp like T= (currentTime/totalDuration)
right now your rate would be 100 frames which is not a good thing. 100 frames could be 1 second for someone, or 5 seconds for someone else
I'm still trying and failing at fixing this, but how would you keep track of that sort of thing..? I don't think I've learned how to do that yet
add by Time.deltaTime and divide by how many seconds you want it to take
the total duration you define as a float, like you want it to take 1 second to go from A to B
you have another float used to keep track of the current time. it starts at 0 and you add to it every update
currentTime += Time.deltaTime
which is the time that it took between the last and current frame
then your 3rd lerp paramter is currentTime/totalDuration since its a normalized value, between 0 and 1
Quick other thing.. make this:
if (i > 4 || i + 1 > 4) //if it's at the final point, reset i
into this (it's easier to read and understand)
if (i > 3)
"why use many word when few work" is absolutely true when programming - the less code you have, the easier it'll be to find issues
I already change it to
if (i + 1 > 4)
even this is "non-idiomatic" and hard to read
if (i >= 4)
is much better
whenever you add something to a variable - you're usually indicating that you want to change that variable - conditional statements should have as little logic as possible in them so they read like english
we wouldn't say "if i plus one is more than 4" we would say "if i is more than 5"
not jordan, thats exactly why sharping says this is non-idiomatic. its not completely obvious at first glance
I figured since i + 1 is the end position, you'd add one to double check if it's at said end position, no?
yes, but it's a question of readability
you want to make your code as absolutely close to english as possible so bugs pop out
Would this do the same thing?
yes
paste your latest code and describe what's wrong again?
I would, but I have class in like 15 minutes so I've gotta run
I'll be back to ask question in a couple hours though
What code..?
oh, it's embedded
use a paste site
#💻┃code-beginner message (again)
Iam outside give me 10 min I will send it
ive attachted this script to a button but the MurderParent() method isnt showing up when i try adding it on the when clicked thing
do you perhaps see MonoScript in the menu when you go to select a method?
yes
oh my god im kicking myself
A tool for sharing your source code with the world!
after i delete the shopUI game object I can't get make another copy
its not setting the isShopSpawned to false for some reason
unless you changed it inspector, by default it will start as false. nothing in your code sets it to false during runtime though
look at the message i reacted to
i'm also getting a null reference error for line 18 here
the getScript gameObject does not have the popup script on it
so its null, and not assigning the value to false
you should deal with your errors first normally
thanks, turns out i had the child of the object in it instead
What is the point of having getScript here? Just drag the thing you want into script
When using a box collider for a ground check what is the best way to differentiate a wall from the ground so my player isn't being counted as grounded when jumping up against a wall?
use a physics query instead of relying on collision/trigger messages and make the query only just large enough to determine if the object is grounded and not so large that it would be considered grounded when just next to ground/wall
Like a boxcast?
yes, or really any shape cast you need. and if you don't need info like the normal of the surface you are on then a simple Overlap(Shape) will suffice
This is what my collider and ground check box looks like right now. Do you think a box cast would work best? and I know this is only slightly related but do you think I should use a secondary collider on the bottom that is the width of the feet?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider2D.Overlap.html
You can use that if you wanna do physic queries
And keep the setup you got there^
I don't mind the collision methods, but I like having it all in update/fixed so I can structure out the events orderly
Oh neat so this will allow me to determine the properties of the collision and use that information to decipher what the player is colliding with?
public int Overlap(Vector2 position, float angle, ContactFilter2D contactFilter, List<Collider2D> results); ```
Check that one
Actually one at the bottom:
public int Overlap(ContactFilter2D contactFilter, Collider2D[] results); ```
Can use a filter, or grab every object and cycle through it. Filters nice though if you only care about the floor and stuff like that
I am a bit confused haha. I am a newbie programmer.
So, you create a ContactFilter2D as well and then you set the LayerMask onto it using:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ContactFilter2D.SetLayerMask.html
I have the ground layer mask set.
public class Character : Monobehaviour
{
[SerializeField] private LayerMask groundLayersToDetect;
Collider2D[] groundResults = new Collider2D[10];
ContactFilter2D groundFilter = new ContactFilter2D();
private void Awake()
{
groundFilter.SetLayerMask(groundLayersToDetect);
}
private void FixedUpdate()
{
int count = Physics2D.OverlapCollider(groundFilter, groundResults);
for (int i = 0; i < count; i++)
{
if(groundResults[i].TryGetComponent(out Enemy enemy)
{
//Your feet hit an enemy
break;
}
if(groundResults[i].TryGetComponent(out Terrain terrain)
{
//Your feet hit terrain
break;
}
}
}
}
something like that
I think that's how the filter works. Been a minute
I'm trying to have a square lerp to four points infinitely in circle of sorts. At the moment, it goes to all the points, but when it goes from the last point back to the beginning the square teleports and I can't figure out why. Any assistance would be greatly appreciated, here's the code: https://paste.mod.gg/qpiqiashwfex/0
A tool for sharing your source code with the world!
I tried doing that and instead of moving smoothly, it teleported to all the points for some reason
show what you actually tried then
void Update()
{
Transform[] array = { One, Two, Three, Four };
rate += 0.01f;
if (rate < 1) //if it's not at the end yet
{
transform.position = Vector3.Lerp(array[start].position, array[end].position, rate);
}
else //it's at the end, so reset everything
{
start++;
end++;
rate = 0;
if (start > 3) //if it's at the final point, reset i
{
start = 0;
}
if (end > 3)
{
end = 0;
}
}
}
well you're still using the wrong t value. but what are the values of start and end
instead of adding 0.01f just add Time.deltaTime (assuming you want it to take about 1 second to reach each point)
and you didn't see that as a problem?
that would mean start and end are the same
How would you separate them, though..? Since they increase at the same time
That might be a really stupid question, I'm very tired
think about it for a second. how far apart (in terms of index) should they be?
A delay of one, right?
like if start is 0, what should end be in order to be the desired point
Would it be 4..? For the 4th position in the array..?
I feel like that's wrong though
Or would it be 1 already?
because it is wrong. if start is 0, meaning the first point in the array, what should end be? remember, end is not the end of the array, it is just named confusingly but is the desired target position of the lerp
right
so end should always be 1 greater than start (with the exception of when it loops back around to the beginning)
It's finally working, thank you
now as for this code:
if (start > 3) //if it's at the final point, reset i
{
start = 0;
}
if (end > 3)
{
end = 0;
}
because you are no longer needing to check if you are at the second to last position, this is incorrect. and can also be simplified (and made better).
so rather than hard coding the last number, you should instead use the length of the array so you don't have to change the number if you decide to add or remove elements of the array.
you can also use the % operator to properly loop it instead of hard coding the loop. so like start++; start %= array.Length; would correctly loop it once it reaches the end of the array
of course you can also extract that bit out as a method and use local variable instead of field and just return the new value, that would then allow you to use the method in place of a second variable
how would i go about creating something similar to this in script?
also not exactly sure where to post..
I see the BackInOut and kinda now think i could do it with some tweening libraries..
but im more interested in how its broken up.. are there two spheres? do u tween each one to get different "effects" .. you think its using any type of masking?
and would i use math and use the radius? or perhaps just rotate a GO w/ an offset instead?
any insight would be appreciated 🙏
so something like this:
private void Update()
{
t += Time.deltaTime;
if(rate > 1)
target = GetNextPoint(target);
transform.position = Vector3.Lerp(array[target].position, array[GetNextPoint(target)].position, t);
}
private int GetNextPoint(int point)
{
point++;
point%= array.Length;
return point;
}
So Time.deltaTime can replace the rate?
it would replace your hard coded 0.01f since that would vary the time it takes based on the framerate
using Time.deltaTime the way i am would make the lerp take exactly 1 second no matter what the framerate is
Apparently she also has a shader playlist. So goated
Oh I see
you could also divide deltaTime by the desired number of seconds you want it to take in order to change how fast the lerp happens
Good to know, thank you
You can do this with a mask and a circle image with a radial fill, though it won't have the rounded end caps. For animation, rotating the UI GameObject will mimic this effect. You can use a tween library for that . . .
thanks.. thats sorta the train of the thought i was aboard as well
What is thr code for walking and jumping and turning and running?
there are dozens, if not hundreds, of movement tutorials for unity. take your pick of the lot and follow it
Ok
there's also the built in premade controllers by unity themselves
u can use Rigidbody movement or
more arcade-y CharacterController movement..
you should probably consider that first.. theres pros and cons for both
https://github.com/Jan-Ott/CharacterMovementFundamentals as for pre-mades.. this is my favorite. Rigidody based with hella good documentation
iam new to unity coding and i encountered a problem but I couldnt find a solution, should i text here ?
indeed
like going from here to there and from there to there in the hospital
the problem is that when there are 2 people the scene does not change even though the game start button is clicked
what does that command do
if the bot were alive it would have posted the message i linked to
r.i.p then
yeah well click the link to see how to correctly post code in this server
Beeboop bee tzzz rs 😉
Posting code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
// Your code here
Add a comment with a line number if there is an error message.
Man.. Im stumped on my issue :/ Been trying to solve like 12 hours at this point
bro i just want fix my code not how to text code in discord
If you can't be bothered to send the code in a way that people in the server can properly read, then don't expect people to help 🤷♂️
just click expand button, if youre not smart enough to do that i guess you cant help anyway.
...he's got a point
no

Yeah let me get right on that.
Imagine asking for help then insult and make it a hassle for others to help..
We have code sharing guidelines for a reason. Follow them or don't get help 🤷♂️
smh what are they not paying you for
"i demand results right now in this channel for beginners!!!"
im kinda new to unity so sorry if this question is too obvious, but how do i actually make the character look like the preview from this? https://assetstore.unity.com/packages/3d/characters/humanoids/humans/protective-suit-man-158254 The character outline is in the prefab folder, but he is pink.
Not a code question. But that means its material is using a shader from a different render pipeline
I have a script for generating a mesh of a circle below an object. It currently is generating the mesh not below the object. it is either off to the side, below, or above the object depending on which object it is.
And on this episode of condescension now,
#854851968446365696 look at the top of the channel
What is it
Hey. Sorry I ended up just outsurcing the help on fiverr. I was getting frustrated with whats probably simple solution, but I'll find out I guess. I was trying a new concept with 4d movement in a 2d game with jumping so I could do air states off player state machines. But, I just couldnmt get terrain to work with the gravity scale being need on my player and colliders seeming wonky and my paperdoll was messed up too so I just got help that way. Ill see solvent and build and expand I suppose, but thanks anyway
Alrighty
Yeah
well first time ive heard someone do this
what?
need some help. Trying to reflect a raycast manually, but i'm running into some issues:
(ignore the errors, I had a stack overflow due to setting the raycast length too high initially)
for some reason, after it reflects, it still raycasts the original ray, so rather than move on to a new one it just keeps on hitting the floor over and over again and only reflecting that. (At least I think that's what happening). What is a simple way to stop this behavior?
relatively basic script attached
There's nothing in your code that would make more than 2 raycasts. Which is exactly what we're seeing in the screenshot
Didn't notice the recursion
is it not a recursive function?
https://paste.mod.gg/ here is the code he keep when i press the R button it get stuck when i press trigger in the animator its fine idk what to do i spent like 3 hrs idk what the problem
A tool for sharing your source code with the world!
It is, sorry. Let me have a look again.
ok so, very oddly enough:
after increasing the raycast length and letting bounces only happen a certain amount of times (to avoid stack overflow), it now registers a second bounce
my new issue here is that since draw gizmos happens every frame, i don't have a chance to see it
any clue on how I might overcome this?
Wdym by that?
basically, the bounce only appears for 7 frames before the OnGizmosDrawn() function is called again, which resets the bounce to default I believe?
but that doesn't really make sense
it would just stay at the end
i've got to be doing something wrong here
Can you share what it looks like now and the updated code? A video might be needed.
hyg
Can you upload the video as MP4?
sorry
(turns out it's only 1 frame)
- You still seem to have an error in the console.
- Collapsing the logs makes them basically useless, as we don't know what's happening during each frame.
alright, one moment, let me fix those rq:
Is it the clipping through the ground during jump that you're trying to fix?
when i press R its start to loop when i jump and start move in his place
Ah okay.
- You should be looking at the parameters tab in the animator when the issue happens.
- You should check the conditions of the transitions between the animator states.
- Log to the console whenever the parameters relevant to the conditions are set in the code.
- When you can confirm that your code keeps on setting parameters indefinitely, look at the relevant code and see why it runs when it shouldn't.
there you go, same code but just not collapsed
in the perameters when i hit trigger its works normaly but when i but an input it gose wild
More errors in the console this time.
Also, what I recommend is starting the game paused, then stepping one frame, so that we only have logs for one frame.
might be old because after clearing it's empty
ah but it's not the game, it's the editor with gizmos (which is why i can't efficiently debug it)
Follow the steps that I mentioned.
Okay, so unless we're missing some logs(because they move too quick), it seems like only the ground is hit.🤷♂️
you can see for a split second that the right is being hit
yeah this is a bit tricky, I'm probably just doing something wrong
Share the updated code.
I'd also recommend using Vector3.Reflect instead of whatever math you're doing currently.
Yeah, it's likely that your math is producing weird results. Trying to figure it to visualize what it does, make my head hurt.
But positions being mixed with directions in a dot product would usually mean you're doing something wrong.
yeah that's most likely it. Thank you anyways!
yeah that fixed it
the issue was with my math
fixed it was the animation event bruh
btw there's no other way for make the script wait/delay apart of using the timer, coroutines?
like a more simplier way?
or a way that uses animation clips maybe?
There's async
Coroutines and timers are already pretty simple
invoke when you just can't be bothered
yeah coroutines are nice. I do find them to feel bulky when you just wanna pause execution till next frame
ends up turning all my methods into enumerators
what the error iam confuised
Seems like an animator window/editor bug.
Try closing the window(removing the tab), clearing the console and reopening it again.
Can someone help me with VSCode?? I am using c# devkit and unity extension but it's acting weird...
On the first one, I pressed return/enter on the snippet I wanted
On the second one, i pressed SHIFT+9 (opening parentheses)
Anyone else experiencing this?
Interesting. Sounds usefull :3
Thx
Yeah u understand
How does that works?
I mean, timers are simple, but i dont want to fill up my code with values only everytime i want it to wait a sec
Did ya try a restart? Sometimes mine gets goofy until I restart it
Also one time I tried downloading codemaid and color semantics and had to disable them both in my VS or it wouldnt load older scripts. Wonky sometimes
Async will be much more complicated and definitely wasnt suggested as something for you to use. It's just something that exists
Just use a timer or coroutine
Then Invoke would do what you want. If you want a bit more sophisticated system, you could write a manager script that executes a delegate after the desired time. The script itself could use any of the mentioned solutions, but it would help simplify your code where you actually need a delay. You'd just need to TimedExecutionManager.RunAfterDelay(MethodToRun, 5f);.
Also, I'd disagree about async. While the way it works is indeed way more complicated than a timer and you need to know how it works to avoid exploding your project, once you know it, writing simple delays and other delayed/async logic becomes very simple:
async void MethodWithDelay()
{
await Task.Delay(delayTime);
//actual logic after the delay
}
I'm writing from memory, so some syntax or api might be slightly wrong.
I'm so confused. This has worked perfectly since I wrote it but all of a sudden it's doing whatever this is. I have not edited the object or the script. Last things I did on the project were completely unrelated. I will send some code.
void Update()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
if (transform.position.y <= 1)
{
transform.position = new Vector3(transform.position.x, transform.position.y + bounce, transform.position.z) ;
}
else
{
transform.position = new Vector3(transform.position.x, transform.position.y - bounce, transform.position.z);
}
}
so i did this
but the object bounces very fast
and if i multiply with delta time, it doesnt bounce anymore
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
A tool for sharing your source code with the world!
The weapon script.
Hierarchy setup if it matters.
hey, in a 2D game what's the easiest way to make that the enemy slighty moves to the contrary side it got hit by a missle or a melee?
Find the normal vector of the collision point and apply that force onto the enemy
Actually wait there’s a few ways to do it
Mostly depends on how ur games set up
For example, if the missile explodes, just make it find the vector from the center of the explosion to the enemy, then apply that vector onto the enemy, decreasing its force based on how far away the two points are from each other
https://paste.mod.gg/qxidohgddqzs/0 Made it easier to read.
A tool for sharing your source code with the world!
this will make it oscillate very fast around y=1
bouncing is a damped.. well, not really an oscillator
but yeah you usually don't add bounce
you multiply an existing speed by a bounce
why the <=1 check?
if the object goes below y = 1 i add some value to it
also have you considered using physics to handle it?
so it starts to go up
ok, but why exactly that value? hardcoding a specific height would make this code not very flexible
coins in a game which oscillate up and down as well as rotate
do you want them to oscillate or bounce
yes oscillate
as, say, a sine wave?
yes
private float bounce = 50f;
private float speed = 50f;
// Update is called once per frame
void Update()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
if (transform.position.y <= 1)
{
transform.position = new Vector3(transform.position.x, (Mathf.Sin(Time.time * speed))*bounce, transform.position.z) ;
}
else
{
transform.position = new Vector3(transform.position.x, (Mathf.Sin(Time.time * speed))*bounce, transform.position.z);
}
you wouldn't check for the y position
this worked
what if i want it to oscillate only for a certain height
although, that'll make all your coins oscillate in sync, which may not be the effect you want
that would be factored into the sin calculation
there's no condtional here
sin already goes from positive to negative and back
Sin gives a value in the range [-1, 1]
if you want to scale or move that range, you can multiply or add to it
*0.5 + 0.5
clamping wouldn't really work with sine
thanks for the help
i have a gameObject with 2 children that has a trigger, how can i check each trigger separately with a script in the parent?
hello, anyone know how to. Or are there any work around
Why not have the scripts on the children?
does anyone know if its possible to make a 2d movement input without any limits on speed (i dont know where to put it)
what do you mean?
i trying to make a 2d movement shooter
and i want an uncapped movement speed
like the speed keep increasing without limit when we press d for example?
yes
you know titanfall?
that kinda movement but instead in 2d
theres a capped movement speed with wasd BUT there are ways to gain speed and using those ways the speed isnt capped
AddForce?
probably best to atleast !learn the basics before you try recreating mechanics
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
its not recreating
but it was an example
but sure
are there any text heavy learning documents instead of videos
Hey currently my jump height in a 2d platformer I'm making seems to be dependant on framerate, with a lower framerate causing the player to not be able to jump as high
how can I correct this?
thankyou
I know I should use Time.deltaTime somewhere, but I'm not sure where to insert this
use LinearVelocity
my car is not moving what is wrong
public void Move(Vector2 velocity, Vector2 input, bool standingOnPlatform = false, bool dashing = false)
{
if (player == null)
player = GetComponent<Player>();
UpdateRaycastOrigins();
collisions.Reset();
collisions.velocityOld = velocity;
playerInput = input;
if (velocity.y < 0)
DescendSlope(ref velocity);
if (velocity.x != 0)
collisions.faceDirection = (int)Mathf.Sign(velocity.x);
HorizontalCollisions(ref velocity);
if (velocity.y != 0 || player.isRolling)
VerticalCollisions(ref velocity);
if (player.isDashing)
DashingVerticalCheck(ref velocity);
if (player.isRolling)
RollingEdgeCheck(ref velocity);
if (velocity.x != float.NaN)
transform.Translate(velocity);
else
Debug.Log("wtf went wrong");
if (standingOnPlatform)
collisions.below = true;
}
This is the bulk of my movement, which runs in update
(forgive my gross usage of if statements, this is one of the earliest working scripts I made)
if (!motionLocked)
controller2D.Move(velocity * Time.deltaTime, input);
noticed I am actually already doing this, but I still have the issue of jump height being frame dependant... any idea how to fix this?
i already copy the code from a youtube video but it will not work when i press W
not enough context. Share the full script
not enough context. Share your code and show the inspector for the Car Controller
I will not terrorize you with my awful player script, its kind of terrible and bloated, but I know what parts are invovled in movement
someday I will refactor
what context am I missing that would help?
the rest of the code
pls can youshow a pic of what you mean
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 AM NEW IN UNITY so i do not understand what you mean
- show your code
- show the inspector for the car controller which you cut off in your first screenshot
i already did
void Start()
{
mouseSensitivity = PlayerPrefs.GetFloat("currentSensitivity", 100);
slider.value = mouseSensitivity / 10;
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
PlayerPrefs.SetFloat("currentSensitivity", mouseSensitivity);
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
public void AdjustSpeed(float newSpeed)
{
mouseSensitivity = newSpeed * 10;
}
I know this question is asked a lot and I am pretty sure it has to do with delta time but when I play my game, the camera snaps to positions and if very glitchy.
Where?
what
You should not be multiplying mouse input by Time.deltaTime
where did you share the things I asked for?
Thats what I was guessing, but what would I multiply it by then?
nothing
just the sensitivity value, as you are already doing.
okay
where
ok that's the inspector, now show your code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 would I lower the sensitivity without it getting all glitchy looking?
the code is too long but ok
reduce your sensitivity variable
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
private float horizontalInput, verticalInput;
private float currentSteerAngle, currentbreakForce;
private bool isBreaking;
// Settings
[SerializeField] private float motorForce, breakForce, maxSteerAngle;
// Wheel Colliders
[SerializeField] private WheelCollider frontLeftWheelCollider, frontRightWheelCollider;
[SerializeField] private WheelCollider rearLeftWheelCollider, rearRightWheelCollider;
// Wheels
[SerializeField] private Transform frontLeftWheelTransform, frontRightWheelTransform;
[SerializeField] private Transform rearLeftWheelTransform, rearRightWheelTransform;
private void FixedUpdate()
{
GetInput();
HandleMotor();
HandleSteering();
UpdateWheels();
}
private void GetInput()
{
// Steering Input
horizontalInput = Input.GetAxis("Horizontal");
// Acceleration Input
verticalInput = Input.GetAxis("Vertical");
// Breaking Input
isBreaking = Input.GetKey(KeyCode.Space);
No
Use a paste site
As I linked above.
private void HandleMotor()
{
frontLeftWheelCollider.motorTorque = verticalInput * motorForce;
frontRightWheelCollider.motorTorque = verticalInput * motorForce;
currentbreakForce = isBreaking ? breakForce : 0f;
ApplyBreaking();
}
private void ApplyBreaking()
{
frontRightWheelCollider.brakeTorque = currentbreakForce;
frontLeftWheelCollider.brakeTorque = currentbreakForce;
rearLeftWheelCollider.brakeTorque = currentbreakForce;
rearRightWheelCollider.brakeTorque = currentbreakForce;
}
private void HandleSteering()
{
currentSteerAngle = maxSteerAngle * horizontalInput;
frontLeftWheelCollider.steerAngle = currentSteerAngle;
frontRightWheelCollider.steerAngle = currentSteerAngle;
}
private void UpdateWheels()
{
UpdateSingleWheel(frontLeftWheelCollider, frontLeftWheelTransform);
UpdateSingleWheel(frontRightWheelCollider, frontRightWheelTransform);
UpdateSingleWheel(rearRightWheelCollider, rearRightWheelTransform);
UpdateSingleWheel(rearLeftWheelCollider, rearLeftWheelTransform);
}
private void UpdateSingleWheel(WheelCollider wheelCollider, Transform wheelTransform)
{
Vector3 pos;
Quaternion rot;
wheelCollider.GetWorldPose(out pos, out rot);
wheelTransform.rotation = rot;
wheelTransform.position = pos;
}
}
share the link
how
copy and paste it?
I don't even know which site you're using so, hard to answer specifically
They will all have a way to share a link
i am in the BLazeBin site
i have press save the problem is sharing the link is it from file
here
did you download the site and then try to paste it in chat... how do you even do that 
when I change the variable, nothing changes
are you changing it in the inspector?
because that's where it matters
it should be around 1 or so
ohhhh why didnt you say so https://paste.mod.gg/
A tool for sharing your source code with the world!
I was changing it in both, but im doing it in just inspector
i did not
the inspector is the ojnly place that matters
how do i do that
with your mouse
where is the button located
ok
It didn't work, you have to sleep but this is just so people know what im talking about
can you screen shot it pls
just use another paste site, preferably one thats dyno mentions !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
here
it works
what did you change the sensitivity to
and what does your code look like
(i blocked the troll)
I tried 1 and .001
Which variable did you change
fair
and are you talking about in the inspector
The inspectors mouse sensitivity
mouseSensitivity = PlayerPrefs.GetFloat("currentSensitivity", 100);```
heres the controller2D script:
https://pastebin.com/rtdn8vSt
and the relevant parts of the player script:
https://pastebin.com/c4ZQSF1M
velocity is multiplied by Time.deltaTime just before its sent over to the controller2D script
and to recap, my problem is that my jump height is framerate dependent
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Your code is reading sensitivity from PlayerPrefs
so even changing it in the inspector won't help
here
you need to clear what you set in player prefs
or get rid of that line that loads it from there
i have sent it
read the bot command, no one is helping until you atleast do the bare minimum
That line is for the mouse sensitivity setting, where would I find player perfs?
Yes that's the setting we're discussing...
ok
I mean a slider in the game to change it
just comment out the line that reads it from playerprefs for now
so is the code correct
read the bot message
i have press the link already
a powerful website for storing and sharing text and code snippets. completely free and open source.
HERE IS THE CODE https://paste.myst.rs/u84n7htv/history/0
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
also a quick showcase of the issue
first I jump normally, then I throttle my framerate and try jumping, and I just can't go as high
a powerful website for storing and sharing text and code snippets. completely free and open source.
stop spamming links
i need someone to help see the code
yup, and we can see the code. no need to spam it
no no is my code correct to make a car move
a powerful website for storing and sharing text and code snippets. completely free and open source.
For one thing, you won't get a consistent jump height without using a fixed timestep. That's why the physics engine uses a fixed timestep.
I'm starting to think the issue may not be with my movement code, but with some of my timings... like, bcause of the lag, by the time it goes from one frame to another, I've been holding the button long enough that my code says, 'ok, thats enough going up, time to go down'
but because of the lag, I get less upward movement time
hmmm
There are a lot of branches in your code
but yes if you are basing it off how long the player holds the button down or something that can be an issue
yes, as I said, its a mess 😛
like velocity.y += maxJumpVelocity; is happening each frame?
In some circumstances
yea, because the jump height is variable, you can end the jump earlier by releasing the button early
umm hello
otherwise it will be framerate dependent
i steel need help i have the link
isn't that already being handled later in the code when I do velocity * Time.delaTime?
unless that's a one-off thing. Hard to tell with the logic.
that's for moving in one frame
but the rate at which you change velocity (accelerate) also needs that adjustment
assuming i'm reading this right that it's actually going to add that every frame
it seems weird you would add something called maxJumpVelocity each frame but I can't tell
HELLLOOO😟😟😟😟😟😟😟
hmm, I think I understand the concept
spamming isn't going to get you help faster...
i already told you. go read the docs on the wheel collider
sorry pls i need help
what do you mean
there's a full guide there on how to use it and the code is already written
where
^ ^ ^
what even is the issue, i can't find it lmao
I SAID I AM NEW IN UNITY I AM VERY CONFUSED
ooh what you're looking at is a special case for moving up slopes and jumping at the same time
else
{
Dust(controller2D.raycastOrigins.atFeet);
velocity.y = maxJumpVelocity;
source.PlayOneShot(jumpSound, GM.i.globalFlags.sfxVolume, 1);
}
This is the normal unconditional jump
stop trying to make a car then and go do the basics. you can find plenty of resources on sites like !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
that's not an issue, that's just your situation. i can't read your mind lol
OK 💥👍
you need to calm down
😡😡
you're setting y to the max velocity each frame then right?
Witha slower framerate you will:
- have potentially more error between when the button is released and the next frame comes - meaning it will move up higher
- more inter-frame error with longer frames that means more distance travelled.
Really there is a good reason the physics engine uses a fixed timestep - it's to avoid issues like this
have you considered not spamming?
🙄
this is a semi-professional space, please act civilly
ooooh well i thought discord will help me
we can't help you when you don't let us
but I'm using transform.Translate to move, not any physics, right?
jordan gave you resources already
spamming won't get you anywhere
help is a 2-way street
the gravity and all movement for my character goes through that controller2D script
I feed it velocity values, and it figures out where my player should be on the next frame
yes and I'm telling you why the physics engine uses a fixed timestep.
what else do you want me to do
there's nothing fundamentally different about what you're doing than what the physics engine does
That would be an easy way to get a fixed timestep
stop sending messages in chat and go check the resources that have been sent
you would then need to implement visual interpolation if you want the movement to appear buttery smooth though
alternatively - you switch to a Rigidbody which has built-in interpolation available
the problem is my inputs should stay in update right?
I dont know how to handle the timing between pressing the button in update and doing the movement in fixed update
- stop spamming here and go read the resources jordan mentioned (unity learn (at least unity essentials) & wheel colliders)
- if you still have problems, give the necessary info for us to help you (ie, what you're trying to do, what issue you're encountering, and relevant context and info, like code shared appropriately) without spamming.
same way anyone does it with Rigidbodies.
You store the player's intent to jump in a variable, and consume it in FixedUpdate
hmm, I guess I'm already doing that with the jumpBuffer
it is intent to jump, as long as the buffer is >0
so if my movement is in fixed update, should I still be multiplying the velocity by Time.deltaTime?
yes
although inside FixedUpdate, deltaTime takes on the value of fixedDeltaTime automatically
good to know
i have done all of that
aah i think I may have found the root of my problem
private void Start()
{
meleeAttacks = GetComponent<MeleeAttacks>();
dissolve = GetComponentInChildren<Dissolve>();
controller2D = GetComponent<Controller2D>();
playerSprite = GetComponent<SpriteRenderer>();
source = GetComponent<AudioSource>();
stats.currentHP = stats.maxHP;
stats.currentMP = stats.maxMP;
EventMaster.TriggerEvent("SetMaxHPMP");
//e_setMaxHPMP.Invoke();
coyoteTime = Time.unscaledDeltaTime * coyoteTimeFrames;
gravity = -(2 * maxJumpHeight) / Mathf.Pow(timeToJumpApex, 2); //g = -a2 / b^2
maxJumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
minJumpVelocity = Mathf.Sqrt(2 * Mathf.Abs(gravity) * minJumpHeight);
airborneTimer = 0;
airDashRemaining = stats.airDashMax;
manaRegen = stats.manaRegen;
playerState = PStates.idle;
}```
I'm defining a bunch of gravity variables in start, and then not adjusting them ever, even if the framerate changes
that's not an issue
but my timeToJumpApex I think is the issue specifically
cause that timing changes depending on the framerate, but my code doesn't account for that
i don't think that is either
you aren't counting frames, are you?
coyoteTime could have issues, but that's easily solvable by just defining it as time instead of frame count
well I think I have to call it a night for now
I'll probably try and tackle this some more tomorrow
its been a long standing issue that my jump height is weird at different framerates, and I realyl want to pin down a fix
hey guys I'm making a game and i have this problem where when i damage multiple enemies, the damage each one takes get multiplied by that amount, like when i hit 3 enemies, each one takes 3 damage instead of one, I'm using this code, I'd appreciate it if you told me what's the issue, this is the method I use for damaging:
public void DealDamage()
{
Collider2D[] enemies = Physics2D.OverlapCircleAll(attackPoint.position, weaponRange, enemyLayer);
if (enemies.Length > 0)
{
foreach (var enemy in enemies)
{
enemy.GetComponent<Enemy_Health>().ChangeHealth(-damage);
enemy.GetComponent<Enemy_Knockback>().Knockback(transform, knockbackForce, knockbackTime, stunTime);
}
}
}
you aren't factoring the amount of enemies hit, you'd need to multiply damage by enemies.Length
also you don't need that length>0 check. if the list is empty, the foreach will make 0 iterations
for some reason it's damaging them even more
wouldn't setting a coroutine on their health fix this problem?
no i want each of them to take only 1 damage
im such a dumbass
i read the problem as the goal lmao
okay scratch what i said to do
lol it's alr
how are you calling DealDamage?
i have the animation set on a specific frame and there i deal the damage
It's okay to use Input.GetKeyDown right?
why wouldn't it be
you're calling DealDamage from the animationclip?
yeah like an animation event
i always thought "legacy" means it's bad
that's not what legacy means, no
ok try adding a log to dealdamage to see how many times it's called when you perform an attack that hits multiple enemies
alright
yeah i figured
it's recommended to use the new input system, but there's not really anything wrong with using the old one
i find the old one much easier for me
i hit 3 enemies but i got 5 messages in the log
and you put the debug outside of the loop, right?
what happens if you hit some other number?
outside the loop it's only called once
so the problem is the damage
maybe some kind of collider problem?
because the hitboxes are bit messy right now
How is there an empty statement?
the ";" at the end of the if statement
this one
Yea, I thought it was that but for some reason before, when I deleted it, it said I was using improper syntax.
Now it doesn't
if it works it works ig
ah yeah that could be it, multiple colliders are getting hit and getting damage applied separately. try logging that in the loop with the collider as the context and see if that's the case
{
foreach (var p in m_StoreController.products.all)
{
Debug.Log($"Product: {p.definition.id}, Price: {p.metadata.localizedPriceString}");
}
if (m_StoreController == null) return "Price Unavailable";
var product = m_StoreController.products.WithID(productID);
if (product != null && product.hasReceipt) return product.metadata.localizedPriceString;
return "Price Unavailable";
}``` I am using this to fetch prices for my items from google play but its always showing Price Unavailable even though the purhcase is working fine does anyone have any idea how do i fix this ?
debug to figure out which of the 2 Price Unavailable results you're getting, then debug to find why the conditions aren't passing as expected
the thing is i am not able to debug in android its working fine in editor
ah.
well i guess at least do the first part by making the strings slightly different so you're able to differentiate
thats a good idea !
I did that and now the script doesn't work
can you share the entire script here ?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
using System.Collections.Generic;
using UnityEngine;
public class Restart : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
UnityEngine.SceneManagement.SceneManager.LoadScene(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name);
}
}
}```
when I remove the ;, it stops working
try this maybe
the script that doesnt work is the on you sent, it works if I put the ";" in but then there is an empty statement error
whats the error message in this script ?
Possible mistaken empty statement
There is none, but when I use that one the script doesn't cause the game to restart
for things like these, is it possible to see the specific loation it is talking about?
this is from inspect element on the Itch page
how does "getchild" work in this case? does it take only the surface level children, or nested children too? assuming FaceAccessory is the categoryParent
hm, weirdly enough, there's nothing on the docs about that. they usually have notes about edgecases like these
iirc, getchild doesn't return deep children, might be a good idea to double check though.
Pretty sure it only get the first later of children, and not the nested ones
Get child only returns immediate children. If it was going deeper, it would be named GetGrandchild or something
Also, it would be super confusing API if it was traversing the hierarchy deep.
i thought so but always good to double check, i think there might have been something similar like that
though GetComponentsInChildren gets the components in the parent your targeting so I can’t blame them for not trusting the names
but i could not tell you if i made it up in my head or not
If you use transform as a collection, it includes the parent as well iirc. That's about the only exception.
I just learned properties recently, and was experimenting a bit. I'm a little confused on why this doesn't work, could someone explain it to me please?
you need a backing field
stolen from the microsoft docs
private string? _lastName;
public string? LastName
{
get => _lastName;
set
{
_lastName = value;
_fullName = null;
}
}
basically, you need a variable above it for the property to refer to
Remove static.
seems to still throw an error with both solutions
I doubt this is at all a good use of properties anyway tbf
well, as long as it works 
Treat a property in a similar way you'd treat a Get/Set method, in most cases
First of all, for a static property you need a static backing field
whats the distinction between a property and getter/setter? i kind of assumed property includes that
And using Instance within Instance can cause an infinite loop
OH
right
i did do that
i managed to fix it by adding a 0.5 seconds cooldown to their health decreasing mechanic since the player's attack cooldown is 1 seconds, thanks for the help tho 🙏
seems visual studio might be having an issue
There won't be a backing field if you implement the getters and setters
Create an actual field and return/use that type in the getter/setter
ive got this now but it still has an issue, VS bug or actually unsupported?
oh bruh
idk why but i assumed get; automatically does return instance
no clue why
youre right that was it!
Treat it the same was as Get/Set methods, as I said
Doesn't matter what they do, they gotta do something
but yeah this works now 🙂 no more error
A property just looks like a field but is a bunch of methods under the hood, each method separate from each other, needing implementation
im making a level editor, but when moving objects, its not working normally, i can show video
The part of the code that calculates - https://pastebin.com/ERYEq9kV
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
ask if u have any questions about the variables, im here for solving the bug ;)
the 1st video shows the problem, its inverted when camera is down
You might want to provide a question to be focused on instead of making people try to interpret the unworking condition
i mean my question is why is my solution not working 😭 how can i make it not inverted
btw thats only for Z axis, the blue one, so its kinda weird
Given the direction from you to the target. Use the dot product with world direction-up to determine if you're above or below the target.
dont i already do this?
im sorry i think i dont understand cause english is not that good
lemme know if u know where the problem might be
i kinda dont understand what u meant but i think i am already doing that
Even though direction is only taken once at the beginning of the coroutine, it's still taking value from input every frame and makes the dash go shorter if the input is released and goes back to zero. What am i doing wrong? thanks
private IEnumerator Dash()
{
Vector2 direction = new Vector2(movement.x, movement.y).normalized;
yield return new WaitForSeconds(0.01f);
canDash = false;
isDashing = true;
stamina -= 25;
float duration = 0.6f;
float elapsed = 0.0f;
Invoke("StunTrigger", 0.6f);
while (elapsed < duration)
{
playerRb.AddForce(direction * _dashpower, ForceMode2D.Impulse);
elapsed += Time.deltaTime;
yield return null;
}
yield return new WaitForSeconds(1.1f);
isDashing = false;
canDash = true;
isStunned = false;
}
I've tried adding a bool flag but it also didn't work
Log the dot value and see if it's an acceptable value. If not, log the projected delta and drag delta
Acceptable as in, it's correct relative to what you'd expect
Place a log and see if you're not actually calling this multiple times to induce the input having an affect on the shortness of the dash
Hi, help please. Why it won't return false?
because your conditions aren't true?
it returned true. normal value is just 1 but my condition requires 2
the function returns true, the IF statement you made does not return true, therefore can never hit the false return of function
this is never true
dict2 has only 1 pair, (Normal, 1)
dict1 contains Normal, so that's true, negated to false
dict1[Normal] is 2, which is greater than 1, so that's also false
Thank you so much folks! ❤️
schizophrenia
For a csgo esque shooter, should i use rigidbody or a character controller for movement?
either works
do you want consistent movement or physics based movement?
both can achieve both though
technically yeah, thats how i tend to differentiate them though lol
Well im not sure if physics based is needed, as there is nothing else than running along a straight ground going on
i also folloowed and rb movement tutorial, and i cant seem to fix the fact that there is some sliding happening, but i assume thats my problem.
most likely yeah
fairs
character controller and rigidbody can achieve the same thing, just that charactercontroller gives you more control but also more to do yourself
oh okay, i think ill stick to rb then.
but on that note, could you help in fixing the sliding?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Did cinemachine's header change from "using Cinemachine;" in Unity 6?
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Movement")]
public float moveSpeed;
public float groundDrag;
[Header("GroundCheck")]
public float playerHeight;
public LayerMask whatIsGround;
bool grounded;
public Transform orientation;
float horizontalInput;
float verticalInput;
Vector3 moveDirection;
Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
private void Update()
{
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
MyInput();
SpeedControl();
if (grounded)
{
rb.linearDamping = groundDrag;
}
else
{
rb.linearDamping = 0;
}
}
private void FixedUpdate()
{
MovePlayer();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
}
private void MovePlayer()
{
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
}
private void SpeedControl()
{
Vector3 flatVel = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);
if(flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.linearVelocity = new Vector3(limitedVel.x, rb.linearVelocity.y, limitedVel.z);
}
}
}
i have speed at 5, and drag at 10.
Unity.Cinemachine, apparently
what's with the moveSpeed * 10f?
have you tried increasing the drag?
not exactly sure as i just followed a tutorial
you're using forces, so that's going to have some amount of slide
sounds like they did that just to avoid an extra acceleration variable lol
okay so essentially find some sweetspot of the drag value where you can move but dont slip and slide at all?
it's not an issue, just weird to me
is it possible to completely remove slide? like to the point where its completely unnoticable?
if you want an immediate stop, you could just hardcode that in
so like in update() i could add in an if statement that checks whether a key is pressed or not and just put velocity to 0?
or how?
something like that, might want to separate the axes
yh ill try
quick question though; do you want the acceleration? there is an alternative approach that gives direct control
i think direct control would be better
you can set the linearVelocity directly to the axes (multiplied by the speed of course)
how?
similar to how you did in SpeedControl
rb.linearVelocity = new Vector3(speed * horizontalInput * orientation.right, ....)
actually you'd need to normalize that
or rather clamp the magnitude
one sec
Thank you!
moveDirection = Vector3.ClampMagnitude(orientation.forward * verticalInput + orientation.right * horizontalInput, 1);
rb.linearVelocity = new Vector3(moveDirection.x * moveSpeed, rb.linearVelocity.y, moveDirection.z * moveSpeed);
```does this make sense to you?
you can move stuff around of course
yeah i think so
you could do like, new Vector3(horizontalInput, 0, verticalInput) * orientation.forward * moveSpeed for example
this is exactly what i was looking for thanks
it works really well
and i understand it
thank you so much
i have another question though, when im moving around there is some camerabobbing happening, and i have no clue why
this may be due to the map or something but idk
if you want i can do a screenrecording
Sure
how do i send a video if its above 10mb
compressing it made it bigger for some reason
Windows trim sometime makes the file size larger. Use a site to compress it
im on mac but yeah ill try that
A 6 second vid shouldnt also be that large of a file size, you can probably adjust the recording output. At least I know u can in OBS
Projecting the mouse delta onto a camera-aligned axis doesn't really make sense.
I would probably do this all with screen space coordinates
Think about it. In the "Z" mode, you are projecting a mouse coordinate onto the camera's forward (or back) axis. Those are completely perpendicular, doesn't make sense
yeah i havent downloaded obs yet so i just used native mac screenrecording
Converting the world X/Y/Z axis to screen space and then doing the dot checks in screen space is probably easier
I recently did a similiar thing for a 3D editor tool
did you record the entire screen or just the game view?