#💻┃code-beginner
1 messages · Page 466 of 1
Why? I want my fade out animation for multiple gameobjects but I want only some to be setactive false. That way I can just attach the script if I want it to be setactive false
how to look this up?
this
look up what issue means
Because there is nothing there which changes frame by frame
ohhh ok
So where should I put it?
What is the color of the image before the code runs?
Anywhere else and just call it when it's needed
also if you want us to help you in regards to your problem we would need to see your actual code
(1,1,1,1)
not some mockup
Okay, so, you're changing it to 1,1,1,1. What are you expecting to change?
Tbh, google translate gives me 37 different translations for "Issue" so maybe we should just point out that in this context it means "Problem"
If the animator state is Idle, you set it to what it is?
I thought you meant before the animation, sorry
LOL i didnt even notice 😂
that is a ton of things
for issue
How about instead of just logging "1" which tells you nothing, try logging $"Original color: {image.color}, new color: {visible}"
Yeah I was surprised too lol
ok then what is your problem with your code?
I get this:
Okay, so it does appear to be changing
1- my player must jump for move
2- when my player have an high speed with rigidbody he slide on the ground
3- if i use transform.translate (my old program) my player can noclip in the wall
old code : void FixedUpdate() { if (CanMove && loading.gameReady) { verticalInput = Input.GetAxis("Vertical"); horizontalInput = Input.GetAxis("Horizontal"); transform.Translate(Vector3.forward * verticalInput * speed * Time.deltaTime); transform.Translate(Vector3.right * horizontalInput * speed * Time.deltaTime); } }
new code :
{
rb.AddForce(Vector3.forward * speed);
}
else if (Input.GetKey(KeyCode.S))
{
rb.AddForce(Vector3.back * speed);
}```
It's becoming solid instead of partially transparent
That's what is should be doing yeah
Thing is it doesn't
Then the thing you're looking at isn't image
well when working with rigidbodies if you have no friction, at high speeds they will slide, so you need to clamp the speed of your rigidbody.
secondly you want to move only when you jump?
If it changed, it would log 1,1,1,1 for the original color on the second log
but it doesn't
Debug.Log($"{gameObject.name} is setting the color of {image.gameObject.name}'s image from {image.color} to {visible}");
Try that
Let's get more info about what is changing which
no my player actually move only when i jump and i dont want this and if i rotate my cam my player will not go forward (forward for the camera)
does turning up the speed help you move?
when on ground?
also the reason why your rigidbody isnt going in camera direction is because you are using Vector3.forward/back/left/right which is global
It looks like something else is setting this object's transparency back to 0.592 after this runs.
Could be an animator or another script
you need to either use a orientation object on your character or use your characters transform
yes but he slide on the ground 😢
Instead of Vector3.forward you should rotate the vector with the camera instead
Usually you only use the camera's Y euler angle to rotate it
what does your drag variable say on your rigidbody
The only other things changing object's transparency are the fade in/out animations but they aren't running rn
What about the actual Idle animation clip itself
it say 0
scratch that, do you have a physics material?
Something like cs float camAngleY = cam.transform.eulerAngles.y; float camHorizontalRot = Quaternion.Euler(0, camAngleY, 0); Vector3 moveDir = camHorizontalRot * Vector3.forward * ...
There's no animation clip attached to it
you could just use a orientation object on your character
Either works
I've noticed that the orientation thing has become quite popular
do you have a physics material on your collider?
Something in your code is changing the image's transparency
no
change drag to 1.5
or whatever stop your character
but it sounds like you have a physics material on your collider
if at fast speeds it slides
he dont slide but he is fast when he jump
ah then configure the drag then
ok
drag is like air friction..
angular drag is like rotation friction
thats what happens while you are in the air
ok
its a tuning process
just gotta find those good values
u can / and might have to configure the drag values dynamically in script
say ur grounded then theres 1 drag value.. if ur airbourne u change it to another drag value, etc
If I disable animator component, it instantly changes the color so you're right. But it's weird cause I don't have any animation clip attached to the idle state
Show the inspector for the idle state
And are you sure that this is the animator controller attached to TextLogo?
And that you're not changing to one of the other states in code?
Yes
IF there's a blue moving bar under the idle state, it's that it's the current animation right? If yes, then my logo is semi transparent while in Idle state
Right, but if it switches to another state that does modify the transparency and back to Idle in the same frame, you wouldn't see that other state in the window but it would still affect the alpha
Ohhh
I didn't know that
So yeah, looks like I have another animation, stopped in the middle of it but modifying the alpha
The fade out one
Yeah, I think that'd do it.
how to edit a script?
I think it'd be best to modify the alpha through either animations or code, and not try to mix both
double click it
i made my first script and it doesnt work
did you double click in the asset tab
yes
also i thing its stuff with my downloads
well that's weird, you got visual studio installed?
bc there r some stuff when i try it doesnt work bc its not downoaded
no
Then either:
A) You already have it open
B) You have nothing that can open a .cs file on your entire computer
C) You aren't clicking fast enough
D) The thing you're double clicking on isn't actually the script file
The thing is that my fade out animation is stopped (cause gameobject's set to false) and it looks like it freezes the animation when I do that, but the animation still modify the alpha value
best explanation i've ever seen in my life
is there a place in unityhub to download anything missing?
bc i also cant make a 3D project i make it and it says project failed to open
How about send a screenshot of your whole unity window, show the thing you're trying to open
how much storage space do u have on ur c drive?
nothing should cause it to not open a project..
idk i use crappy old laptop
might be the problem
so go check
2.57 GB free of 87.3 GB
oof
;-;
yup not a unity issue
its a storage space issue
unity caches alot of stuff on the c drive in order to run. the editor and the c# stuff
ill get a better device but thats when i get college
theres not much u can do besides try to delete unused programs
and try to push it up to like 12 - 20 gigs
cant do bc this isnt my laptop its my sisters but she alrady graduated
even if u had an external drive it wouldnt work b/c its cached on the boot drive.. u'd need to move most of ur stuff from ur c: drive to the external drive
well you cant lol
Then you're probably not going to be using Unity on this
you can still practice c# online
theres tons of online compilers and tutorials and stuff to get ready for when u do get unity
im still learning everything else
other than the C#
how i do it is look what every thing does then get to the coding
thats how i got to roblox studio
unity should be grateful for roblox
all kinda refugees spilling over once they want more lol
tbh from what i saw in unity its almost same as roblox studio lol
its a bit more complicated.. but thats. b/c its hella more powerful
if u can imagine it.. u can build it in unity
yeah i have alot of games i would make if i had enough experience
i kinda make them in minecraft
you'll get there.. keep ur sights on unity and developing and when u get a new device w/ the storage to handle it you'll have a head-start
bc minecraft commands r easier and not laggy
whats the avrage storage for unity users?
anyway.. this is turning into general unity talk #💻┃unity-talk
ok
Working on my first real unity project, some code is not going quite as expected.
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "PlayerData", menuName = "Persistance")]
public class PlayerData : ScriptableObject
{
public GameObject[] equippedItems;
}```
inside the PlayerScript:
```C#
public GameObject[] equippedItems;
[SerializeField]
public PlayerData playerData;
public void UpdateEquipment(Transform[] items)
{
for(int i = 0; i < equippedItems.Length; i++)
{
equippedItems[i] = items[i].gameObject;
playerData.equippedItems[i] = items[i].gameObject;
}
}```
I'm using PlayerData to have certain data persist through scenes. The items are being correctly assigned to the PlayerScript.equippedItems[]. However, when I try to assign values to playerData.equippedItems[], each element shows as 'type mismatch' instead of the expected gameObject. I want them to be the same.
I'm trying to make an endless runner game (heavily based on google dino 🙂) but I can't figure out the score system. I'm planning on adding a trigger collider to each of the 3 obstacle prefabs and detecting when the player enters the trigger and add 1 point to the score UI. The only problem is that to detect if the player enters the trigger, I have to have the points script attached to each of the 3 obstacle prefabs. However because they are prefabs that get spawned in, I cannot assign my text UI to the script in the inspector. Does anyone have any ideas to do this differently?
I also have to detect when the player dies on the obstacle (or use the existing death detection in the player movement script) to change the high score on death somehow
What does the type mismatch message say?
Im a bit concerned that you do not initialize the PlayerData array, how are you setting a size for it?
its not an error message, but here is a ss of the inspector after trying to update it
I'm setting the size for it in the inspector
delete the SO asset and create a new one
you mean i should delete PlayerData and remake it?
not the script, just the SO asset
I guess i'm not sure what an SO asset is then
scriptable object
what did you think this was doing then?
[CreateAssetMenu(fileName = "PlayerData", menuName = "Persistance")]
Side note that if you're using this to "save" player data, you will need some code to write it to somewhere actually persistent, because changes made to ScriptableObject instances are not saved between play sessions
it has been saving for me between sessions
Whatever instantiates the prefab can pass or set whatever references to in-scene objects which the scripts on the prefab need, e.g.
public GameObject Prefab;
public FooScript Foo;
// ...
GameObject newClone = Instantiate(Prefab);
MyScript myScriptOnClone = newClone.GetComponent<MyScript>();
myScriptOnClone.FooReference = Foo;
Or the same as above, just more succinct:
public MyScript MyScriptOnPrefab;
public FooScript Foo;
// ...
MyScript myScriptOnClone = Instantiate(MyScriptOnPrefab);
myScriptOnClone.FooReference = Foo;
A more robust solution would be to have the obstacles invoke an event in OnTriggerEnter(), and whatever instantiates them subscribe to the event with a method which changes the the score text. This way the obstacles are completely decoupled from the score manager or score text or whatever.
In the Editor, but on a standalone executable that won't be the case
ah ok good to know
If you restart the Editor, your changes are lost
tbh this is my first time learning about scriptable objects so my understanding isn't great but I think i get what you mean and I'll try it
the last solution sounds good. What do you mean by "subscribe to the event" though? Sorry I'm still learning
say "hey, event when u fire off imma know about it.. so i can do my own things"
u subscribe to the event when the script runs.. (in awake start or w/e) .. and u need to unsubscribe to it.. if the script gets destroyed or disabled
else its just working harder listening for that event for no reason
Alright I deleted, created a new one, but its doing the same things.
show the inspector
Before/After
I know what it is, you are trying to set scene objects into an asset, you cannot do that. You will need to use ScriptableObject.CreateInstance to make a runtime instance of your SO
Why does that say EmptyItem not GameObject? What is EmptyItem?
Its a prefab gameobject
ok, so you set those in the inspector
yes
ok, then my comment above stands
you cannot use an asset to store scene objects
I have to run momentarily, but for a quick example, I could have something like this in my ObstacleController script:
public int Score = 1;
public event Action<int> OnScored;
public event Action<ObstacleController> OnDisabled;
private void OnTriggerEnter() {
OnScored?.Invoke(Score);
}
private void OnDisable() {
OnDisabled?.Invoke(this);
}
If anything is subscribed/listening to the OnScore event, this will invoke all of the subscribed methods and pass them one int argument - the configured score for the object. It also invoked an event for when it's disabled, passing along a reference to itself.
Then my ObstacleManager script (or whatever it's called) can then subscribe to these events when it spawns the obstacle with logic that interacts with the rest of the scene:
void SpawnObstacle() {
ObstacleController obstacle = Instantiate(ObstacleControllerOnPrefab);
obstacle.OnScored += HandleObstacleScored; // Subscribe HandleObstacleScored to the new object's OnScored event.
obstacle.OnDisabled += HandleObstacleDisabled;
}
void HandleObstacleScored(int score) {
// TODO: Do something with the obstacle's score - maybe call something on the ScoreManager or change the score text.
}
void HandleObstacleDisabled(ObstacleController obstacle) {
// When an obstacle is disabled, unsubscribe from the events to prevent memory leaks.
obstacle.OnScored -= HandleObstacleScored;
obstacle.OnDisabled -= HandleObstacleDisabled;
}
I've gotta head out, but hopefully that provides some heading for further research :)
thanks I'll try to implement this
first off, thank you for your help, and second, if I understand correctly, I create an instance of PlayerData in my playerscript instead of referencing the PlayerData asset in my playerscript.
correct
I don't see how that will persist since it is an instance
it will not persist but SO's dont persist at runtime however you use them
so would it be better to store the gameobject data as non gameobject variables and then reproduce them from those variables on a scene change?
the data will persist across scene changes just not across play sessions
but will the gameobjects you are putting in there persist across scene changes?
!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
hmm thinking about it, not necessarily. Some scenes won't display your equipment, but I still want the PlayerData to persist through all scenes. I'm wondering if I'm confusing gameobjects with regular objects now. if this wasn't in unity, I'd have an item class and have each type of item inherit from it, and the player would have an array of items for their equipment.
so do that, nothing stopping you
just think of Unity as a render engine and design your data/code as if it didn't exist
definitely have not been doing that so it should be fun to redo everything lol. I think i can figure it out now though. thank you so much
It gives me an error when I try to type that
The first script you showed goes on the obstacle prefab and the second one goes on the obstacle spawner correct?
using System;
ok
you really should look this stuff up in the docs
I've tried
really, google C# Action
How do I position a prefab image after instantiating it with a proper pivot?
My issue: I set pivot on y axis to 0 + anchor to bottom center in a prefab.
When I instantiate prefab with an image and position it at 0,0 it is instead positioned at 0, 190(190 being 50% of 380 which is the container height) which is what you'd expect if I change pivot to 0.5
It seems like after Instantiating, the image is not properly set?
In the inspector after instantiating pivot is properly at 0.
anyone have a script for w a s d movement? I need it for a game i want to make and if i study it maybe i’ll learn some of the code!
Make sure you change the position by using the anchoredPosition property of the Rect Transform, otherwise with position it'll be relative to the center of the screen
I used this: imageInstance.transform.localPosition = new Vector3(x, y, 0);
That might be the case, I guess that for UI elements I always have to use RectTransform?
Yeah use the RT
Thanks, that works!
It inherits Transform so you should be able to just cast it: rt = (RectTransform)transform
Hey, can we use virtual camera (cinemachine) with one camera while each virtual camera renders different layers?
or I have to define several cameras for each layer
My problem is that I want some layers to be affected by post processing effects. Also, all these cameras should move together and update ortho size
anyone have a script for w a s d movement? I need it for a game i want to make and if i study it maybe i’ll learn some of the code!
That is probably the most common of things people do. Have you looked online?
We can help with existing code, creating a script from scratch so it fits your game is not something we do here!
oh, sorry
If the goal is to learn code, then here
https://www.w3schools.com/cs/index.php
And then
https://learn.unity.com/pathways
thank you so much!
hey guys i was trying to make a grapple hook for my fps game in unity so im using a spring component and i realized when i grapple hook on to something im kinda just falling down because i need to modify my players velocity to actually get the player moveing so i was just wonderg how could i do that?i move the player by adding aforce in its facing direction.then i have this grapple function.heres a video example.bascially how coul i modify my players velicty i know i have lerp it to a max velocity.i was just wondering how should i go about modifying my players velocity based on input?
You've probably sorted it by now, but yeah, that's correct.
I find I often use that sort of two-script pattern where a "controller script" is responsible for just the specific behaviors of a single object or prefab, and a "manager script" is responsible for managing any number of those objects/controllers - maintaining a collection of references to them, interfacing them with other game systems, iterating over them for whatever reason, etc.
Is it possible to capture the point that the grapple connects to? Could use that as a point of reference for direction for velocities/forces/etc
i think so?
i mean ik we have acess to it
I tried to implement your solution but it was too complicated for me so I'm trying to figure out my own way 🥲 thank you for your help though
This is going to be a bit of a general brainstorm, but what you can do is capture the point the grapple lands and then apply forces on the player in the direction of the grapple landing point. You might need to toy with the actual power of the force to get a good effect though.
oh ok
Fair enough 😁
Events are a little tricky to get a handle on at first, for sure. But they're not too bad once you've fiddled with them for a bit, and definitely a tool you'll want have in your toolbox at some point. If and when you revisit them, I found this video to be a nice succinct overview 👍
so let me thnik
we have the player point
we have the grapple point
so thats the grapple point - the player postion rihght?
Those two yeah
I kinda struggle with vector math at times, but that looks reasonable 😛
ok now im kinda moving directly towrds the grapple point now
which is better than just falling
Possible improvement: also account where the player is looking at in the direction calculation, so you can nudge the player in a direction that will allow them to "curve around" the grapple point - if you played Apex Legends or Titanfall 2, you might have seen how to do it
however i sti;; want the player be affected by physics and stuff
so like hell swing around
oh ok so we add aforce to the way were looking at?
Try different force modes
yeah it defintly stays the same
so its not aforce mode
so we know we should add a force to where the players looking
thats easy
gotcha, could try multiplying the vector by a multiplier and mess with that
like a "forceStrength" multiplier
ok
Set it to different extremes to see if it does anything different
Yeah, could also turn that into a public variable for easier tuning
Yeah you can do that, or combine both directions with a Vector3.Slerp once at the start of the grappling and apply that continuously until you release the grapple.
But that's a possible improvement as I said, you're definitely free to not do that at all
done
illt ry in asex
PEMDAS
order of operation
same thing
it just moves me direcxtly to the grapple point
quicker
Make it a lower number, something like 0.5
alright
still doing the same thing
just slower
now that guy
reccomended we do aslepr
a slerp
which makes sense
Huh, is your character affected by gravity?
Interesting, this just goes to show I still need to figure out unity physics
its because im using im spring compoennt
which makes it easier
so he said we should add a force
where were looking
however thats only at the srat
'Non-invocable member 'Instaniate' cannot be used like a method.'
Instaniate(objectToSpawn, spawnPoint.position, Quaternion.identity);
Im still doing the learning tutorial but im getting this error? im using the exact same code as in the tutotorial letter for letter i have quadruple checked the spelling and i cant figure out whats wrong (i also dont know what the error means)
I'm gonna be honest, thought that the multiplier was going to work. Trying to think of general physics in my head, gravity would be applying on you the whole time you're grappling towards the point, so unless you're y component velocity up overpowers gravity, you don't go up
And instead would go down
You've misspelled "Instantiate"
But for some reason the error is saying that the object which you're calling Instaniate() on (or the current class, if you're not directly calling it on anything) has a member field (or property) named Instaniate which is not a method or delegate, e.g.
public int Instaniate;
void Foobar() {
Instaniate();
}
Should throw that exception (trying to invoke a variable like it was a method)
What does the grapple look like right now? In video?
Oh is that on the grapple?
yeah
the spring compoennt
here are the values in the insepctor i set it to
Hmmmm. I'm not familiar with that component, but now I think everything you might need is in that component
In terms of getting closer to the point
You could increase your spring amount or force or whatever over time while being grappled
... i dont know HOW i misspelled it, i literally have no clue i spent like an hour going over the video and the code trying to figure out if i misspelled something, i retyped it multiple times everything! how did i miss that T?! i literally dont know!
Instead of just applying a seperate, external force
imma try incressing the sprin force
Make sure to comment out that external force you have
Just to be sure, have you configured your IDE to work with Unity?
alright
I have no clue what an IDE so technically no? (i am very new to this, before unity the only coding i did was on renpy and well thats renpy)
(i did look up IDE but im not super tech savvy so it didnt really help)
Integrated Development Environment - fancy text editor with a bunch of bells and whistles to assist in writing code.
For Unity you should be using Visual Studio, Visual Studio Code, or Jetbrains Rider. When configured to work with Unity, they'll provide syntax highlighting and autocomplete, among other invaluable features.
If you haven't already, follow the guide below appropriate for your !ide in order to get it set up 👇
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
OHHHH yeah im using visual studio code, that's the thing it didn't highlight that it was wrong then.. becuase it was going off of public class Instaniate : MonoBehaviour from the top of the screen it had filled in that for me and i didn't realize, thats where i went wrong
#💻┃unity-talk message
Uh can I do it like this
That would do it. Why do you have a class named Instantiate?
I'm not entirely sure what you're asking...
Usually any reference pre-assigned in a prefab script is just used as a default value, and if the game logic in some scene or prefab needs different values on the spawned instances, the spawning script within that scene/prefab can set the necessary value on the spawned instance. Whether that's a float, string, prefab reference, instance of a prefab, or whatever.
A prefab will generally only need a reference to another prefab if it is responsible for spawning instances of the other...
I don't think there's a name for a prefab referencing some other prefab - it's just a script with a reference to a prefab, which itself happens to be used within a prefab
Hm I have objects that hold references to other prefabs. Like lots of them. I try making a prefab of one gameobject. It is dependent on other gameobjects to work. So I go and make the other gameObject a prefab then the dang object needs another reference etc 😄
a prefab CANNOT reference a scene object
I think you might be confusing prefabs with their instances there... It sounds like your prefabs need references to other objects which already exist in the scene rather than other prefabs...
Those sorts of relationships should be set on the new instance of the prefab after it is instantiated into the scene, because neither the prefab nor the other objects exist outside of the scene at runtime.
Yeah I know thats why I'm making the other objects prefab too
So, you're spawning an object that spawns more objects?
What's the issue?
This is my InventoryManager. I made this a prefab. To hold the items inside, I need to make the items prefabs right?
Are you intending to spawn instances of them on this InventoryManager script?
I spent like 5 minutes trying to figure out why. it's becuase its the name of the script and i couldn't be bothered to name the script correctly as it's just a tutorial thing. i forgot i did that
If your items have a "physical" representation, yes, if they are just data no
Not really. My main concern is that I want to just drag my inventory manager inside the hieararchy then I want it to hold the items and such so i do not have to drag and drop them every single time when I set up InventoryManager
They are gameobjects
Prefabs are templates. If I make a UI prefab which needs a reference to the player in order to get and render the player's health, making the player a prefab and referencing that doesn't make any sense - that player template is not the player in the game. It's health will never change, because it's not a part of the game. It's a template describing what a player looks like, not any specific player.
Instead, when I instantiate my UI prefab into the scene, I now have a copy of my template which is actually in the game. I give that copy a reference to the player instance within the game. Now the copy of the UI template which is being used within the game is referring to the player which is in the game, and will appropriately reflect the player's health and such
So, if you're not going to spawn instances of these prefabs in InventoryManager, why would it need to have references to prefabs?
There's no point in referencing a prefab for any purposes other than instantiating it
But an inventory can for example just store what item-id is in which slot and how many of them instead of holding the prefab, and you just spawn the gameobjects if you want to show them somewhere
I have a serializable non-monobehaviour class "cellgrid" contained on a monobehaviour class and is being serialized.
I set the values of cellgrid's variables in the inspector, just numbers, but when I start the scene, the variables are all 0 after printing them out, even though the inspector says otherwise
You are right. Damn I realized I do not want to do it when trying to explain myself.
show your code
You are probably printing a different instance of cellgrid than you're looking at in the inspector
I remember there was a convenient place to dump some code to easily link it, I've seen others do it, do yall know what the website is?
!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.
thanks
so, in my testing, unity is calling the default constructor and thus calling my initializegrid method, but the variable values like maxheight and maxwidth are all 0
can you call the function on cell manually in start instead of in the constructor of the cell?
i am not sure how unity handles creating referenced instances of classes
maxHeight and minHeight have no initial value, so they default to 0. If you are setting those values in the inspector, then by definition you're setting it on an instance that already exists, and therefore won't have any effect on any new instances of CellGrid
So, in the event that the default constructor is called, the height and width must therefore be 0
And if InitializeGrid is only ever called by the constructors, it will never be called on an instance of the CellGrid that has maxHeight and minHeight set.
the default constructor seems to be called as soon as I click play. does this mean unity is creating a new instance of cellgrid and replacing the instance that the inspector is referring to?
It has the following order:
- Start game
- SpriteGenerator gets created
- SpriteGenerator creates CellGrid
- CellGrid constructor runs
- SpriteGenerator sets values to CellGrid from inspector
Whenever the GameObject holding the reference is created, it's making a new instance of the class on it and reading the data from disk. That's what "Serializable" means, it tells the engine to load the data from the scene file
So, the constructor is called, then the values are loaded.
It can't have any data set until it exists, and the constructor is the very first thing an instance will ever be able to do
this is incredibly helpful to know
Like i said above, just call the initialize function on CellGrid in the start function of SpriteGenerator
should solve your problem 😄
I have a big problem when using sprites + multi cameras (one base + multi overlay cameras). The rendering is urp
Clear depth is unchecked in Overlay cameras.
The sprites rendered by overlay cameras are always behind other sprites
When I change ZWrite off to ZWrite on, these sprites are rendered on top of others!
I want standard sprite ordering based on sort order
how can i make it so smth ignores the collisions of smth thru code
wait that is worded like booty cheeks
Physics.IgnoreCollision
ye but like in the oncollisionsenter method
you can check if you collide with a collider then do physics.ignorecollision
what do you mean ?
you do the exact same thing, why would it be different
basically im adding a blocking system so im just making it that if u click, a empty gameobject with a collider is activated the issue is its parented to another gameobject with a script that if it collides with an ememy it does damage and if the enemy collides with the blocking collider i still get damaged
well its more of a trigger collider so ye
idk about anyone else, but that sentence makes no sense to me.
yes
That is sent AFTER the collision occured. You can make your logic ignore it, but the physics engine would already have acted at that point
That's not possible. Sprites are transparent and rely on the draw call order for depth sorting as opposed to z writing and depth map. I don't see how it's possible for the overlay camera sprites to render behind the base camera sprites, it should be the opposite.
think thats the same idea everytime this guy sends any sort of question, always everyone is confused 🧠
why do you need it parented?
this is my Player, The game object named player has a script on it that tells it that if it collides with an enemy then it would reduce ur hp by 1 and the parrycollider is a gameobject with a collider on it once i activate it if an enemy touches that collider too i still lose damage
which is normal cause oncollisionenter also affects the children of the gameobject with the scipt, that is why im asking if i could make it so it would not register hits on the parrycollider
you can put parry collider on a different layer/tag and check if you are hitting it, if so do nothing
if not do damage
because when u pary an attack u want the attack to not rlly do dmg if i would have it not parented it would just chill in the middle of no where i would like it for the gameobject with that collider to follow the player
oh yeah i can make it so the collider of the enemy ignores a specifc layer
since it isnt the enemy touching the player that damages it, its the thing that the enemy is holding
Hi, I have an excel sheet with 30.000 city names and I need a way to search through these names to see if the player typed a city that is on the list. How can I search the file through code in unity, in an efficient way?
are you trying to search through names that are matched exactly? or similar to like an autocomplete?
in the first case, if the list is sorted you could easily do this fast with a binary sort.
in the 2nd case you should probably look at spell checking algorithms.
and you'd also ideally want to keep a copy of this data in some collection rather than reading from the file everytime
No i am looking for a simple exact match
So you are saying it is best to like copy them in an array?
then yea best way, sort the values once then binary search on it. O(log n) time should be around 14 searches max in the worst case through your 30000 elements
yes
That initial sort wont be pretty though you can do this once when the game loads.
I will have to search how to do a binary search, as it is the first time I will have to do something like that
I was thinking of splitting then in 26 arrays based on their first letter
so i will have approximately 1k-2k names each time
its very easy. Requires a sorted collection which is why i say to sort it first. Im sure there are even videos online explaining it and going through examples so you can see why it works so quickly
i assume that they want the index in the original file, to see other data in the same row of the excel sheet
There are probably many ways to go about with little difference in performance
what i said would be the simplest imo for a beginner to get the index and all the data of that row. A hashset wouldnt have an index so you'd need like a dictionary to get the other data they actually need
ah, ty
Yep, thats right
though I could have a dictionary and an index
and then search for the rest of the data with that index
A dictionary so large would probably be slow as well tbh though you could profile and try it. I'd personally just go with the binary search. It really is 14-15 searches MAX
All right, I will do tha t
And when I say slow it's relatively slow. All this is instant anyways
This will vary depending on hardware, the type of key and whatnot, but according to this simple case with int keys, Dictionary starts beating binary search at around 75 elements.
https://gamedev.center/array-vs-dictionary-lookup-in-net/
Of course, a dictionary will always take the same amount of time to search, regardless of size.
What is easier to do for now, so I can get it started?
List.Find maybe
Based on your description, I would use a HashSet. You only need to find an exact match and don't need an index.
I'm trying to use coroutines to make an extremely expensive function not make my program hang, but I don't think I am understanding it probably. This is what I have so far but it doesnt make it any faster:
bool terrainLoaded = false;
private void GenerateTerrain()
{
StartCoroutine(GenerateNavMesh());
}
IEnumerator GenerateNavMesh()
{
while (!terrainLoaded)
{
MakeNavMesh();
yield return null;
}
}
public void MakeNavMesh()
{
navMeshSurface.BuildNavMesh();
terrainLoaded = true;
}```
I want to get an index, or a way to access the rest of the data for that city
Yep. The point of using a coroutine is to spread the execution over several frames, but you're not spreading anything in your code.
In fact you're now executing the expensive thing once per frame 👀
Oh and that too
I thought that the yield return null means that it drops out of the function and returns to it next frame?
It does, yes - Unity will resume the coroutine from that point next frame. But it still has to wait for MakeNavMesh(); to return before it gets there
Which I guess, thinking about it, means that the coroutine will also exit after one iteration 🤔
My end goal is to not have the frames hit 1 fps in the loading screen
i thought this IEnumerator GenerateNavMesh() { MakeNavMesh(); yield return null; }
Means that it wont work
like without the while loop
No. It just waits in the coroutine instead
In not sure if buildnavmesh is sync or async, it seems to be sync.
For starters, profile that timing to find the culprit
I comment out the navMeshSurface.BuildNavMesh(); and there is no hang at all, I'm fairly certain that it is the slow function.
its slow even when you click on it in the editor and dont do it in code
Do. Profile. The game.
You want to have some solid profiling data to back up your assumptions.
Yeah there is an almost 8000 ms call in the monobehaviour's start function where my failed coroutine implementation suffers
so coroutines wont work for this I assume?
In order to benefit from a coroutine here, you'd need to find a way to split up the work - some way to incrementally build a portion of the navmesh data instead of all at once.
I know nothing about nav meshes, but the NavMeshBuilder class has some interesting methods which make me think it might be possible
Share the data
So if I can chop up the terrain into may 9 or more slices and then runn a navmesh surface build on all of the like build1() yield return null build2() yield return null etc, that will work? but I have to space the functions out?
do I need to use the deep profiler?
No, but a hierarchy view would've been better. You can see that it's waiting for a job there, meaning that the navmesh build is probably running on the background thread.
the documentation I found for the NavMesh stuff is pretty sparse
Navmesh surface has some other methods, like add data and update that is async. Might want to try use that instead.
how can i use player prefs without frying my ssd?
like i currently have this as my thing
{
PlayerPrefs.SetFloat("Highscore", WaveCounter);
Highscore++;
}
}
private float Highscore;```
the if statement is located in an Update Method
are you looking for an answer other than yes? you should use the profiler to see why you have issues. something like that looks like you might be using player prefs every frame which of course would be bad
and if that runs every frame then i got myself a nice little homemade ssd fryer but that isnt what im looking for
Wait till the end of the match to record the score?
theres absolutely 0 reason that you would need to compare those 2 values every single frame
even just checking when they are changed should be enough
i dont know how to do it once
like once the game is finished
i already have a bool for that
WaveFinished
but idk how to make it run once
use a public method or property for the values like highscore, wavecounter, or this wave finished bool. Whenever its changed through the method or property, call a method to save the score
Why can't you call a method to check after the wave is over?
i can but i need it to run once to avoid frying the storage
Why would the method run more than once? When the wave ends, you call the method (in-between waves), then the next wave starts . . .
yeah but how do u want me to check if the wave is finished wont i need to put it in an update function to do so
but the thing is i would also want the highscore to only update when the wave counter is higher then the highscore
A wave is completed when all enemies are defeated . . .
I'd assume the enemies are in a collection . . .
When that collection is empty — 0 — the wave is complete . . .
{
ChangeHighscore();
}
}
private void ChangeHighscore()
{
if (PlayerPrefs.GetFloat("Highscore") < WaveCounter)
{
PlayerPrefs.SetFloat("Highscore", WaveCounter);
}
}``` i wrote this
the if wavefinished is called everyframe when the wave finished thing is true
idk i just have a variable that increases with each kill then i get the ammount of enemies i spawn and once the kill count is the same as the enemy spawn count then the next wave beggings
So, when an enemy is defeated, you check if there are any more. If so, do nothing. If empty, handle your end of wave stuff . . .
You shouldnt really be reading from player prefs often too. Ideally read it once at the start and only set it when needed.
by my thinking this would only run when the wave is finished which is clear then it checks everyframe to see if the PlayerPrefs is smaller then the wave counter then it updates
oh i think i have an idea
I'm not sure also how to make it more clear that you shouldnt need to check in update or if wavefinished. Something is setting that to true. At the same time just record the score
{
Highscore = PlayerPrefs.GetFloat("Highscore");
}
private void Update()
{
if (WaveFinished == true)
{
ChangeHighscore();
}
}
private float Highscore;
private void ChangeHighscore()
{
if (Highscore < WaveCounter)
{
PlayerPrefs.SetFloat("Highscore", WaveCounter);
Highscore++;
}
}```
What's the issue? I could help out
This is still checking in update..
i dont need to record the save i just need 1 number
ye
if i put the if wave finished statement ting in the ChangeHighscore Method it would just never be called therefor never run
im tryna figure out how to not fry ssds with playerprefs
lol. And the script is above? The entire script right?
not even close
the spawner script is a lil bit longer
its like 100 lines of code
Store the player prefs variable at the beginning of the wave, then check that variable instead . . .
No need to access player prefs every frame . . .
but im not
its only accessing player prefs when the highscore variable is smaller then the wavecounter
then it runs until the highscore variable reaches the same size as wave counter
therefor it runs only once?
I have an excel sheet with some city data and I want each column of the excel sheet to be stored in an array in unity. How can I do that?
Here is an example from my file:
Ahmedabad 23.0225 72.5714 8009000 India
Ankara 39.93 32.85 5503985 Turkey
Atlanta 33.7628 -84.422 5180179 United States
@strong wren How the hell does that fry your SSD
And i want for example a Name array that stores all the names
I mean, checking in update, sure, but I cant see how
it isnt that the thing. it was a little bit worst where instead of having a variable i just checked the player prefs but at the beggining i had it like that
this was the original code which is rlly just the same thing
i just wanted to make sure since knowing my expired brain i just had to double check
CSV files are typically easy to read once you define the reading structure
take a look at some example code for reading CSV files in C#
Alright alright
so its good?
are csv prefered over tcv?
Not necessarily, I prefer them however
Then fine by me
Cant say for sure, but I do believe so, would you mind showing the entire code or is this the only relevant part?
Have you identified via the profiler that this is the worrysome part?
i mean the code has rlly nothing to do with it only those lines
not rlly
i never even tested it
If you comment this part out, things are alright?
lol, you should
i dont know how
wait, what?
wdmy by profiler
So you're saying it fries your SSD without actually checking if it fried your SSD?
the profiler gives you statistics when running your game, and via this tool you can identify parts that are taxing
never said that i asked if it is bad for the ssd first
before even trying it out
commonly used for memoryleaks for example, or just when games are running badly, it's a superb tool
I highly doubt it would be bad for your SSD
oh my game has like 3 verticies so its good 🗣️ 🔥
im checking for stuff in the sdd everyframe
i dont think it would be damaging if im running it at 60 since i did make a FPS capper but it coujld run up to 600 fps and having ur ssd being used 600 times a sec is kinda not rlly recomended
I mean, if you had a old brick of an HDD and used PlayerPrefs then sure, depending on the amount it could be bad, but any SSD will be fine
Then prevent it
I'm just saying, it makes sense to try it out first before assuming or asking anything. There may be no problem at all . . .
yeah thats why i came to check as i would rather ask then risk my own computer parts
i already did
SATA SSD: Approximately 128,000 writes per second.
NVMe SSD: Approximately 768,000 writes per second.
You'd have to change your code structure, but using an FSM to control the waves would be easier . . .
think you're good buddy
its my 3rd game i think i should still be learning C# lol
Let me know if things work out
I dont know if this is the right channel to ask but yeah. I took an asset from assets store that has a door on it but the door its just there, not working. When I putted mine that works, my door opens but that piece of mesh remains there according to the asset. Is there any way I can delete it? Here s an image
The old door that its just the mesh remains there and when my door opens, that mesh hasnt a collider and I simply can go through it
wtf lol, so you only have one door in the game currently?
not the old AND the new?
I'm not sure I understand what the issue is
So I took an asset from the store. That asset already has a door in it but u can go trought it since it doesnt have any colliders. When I putted mine so its a collider door with open function over the old one its good. When I open it, my door opens but the old mesh that was behind my door remains there according to the asset. Can I somehow remove it? Can I somehow work with what the prefab has and switch some things up?
Well, if its a mesh that you want removed you can toss the .FBX into blender and take it out, otherwise its just a bad asset IMO. And as @polar acorn said, this is not a code question, and would likely be asked elsewhere
sorry cause I asked here and thank you with the blender option
and I cant do that
since its one piece
its the entire house in only one piece
then Blender is for the best, plenty of tutorials online where you can cut out vertices of a mesh, give it a shot, you might learn something about 3D modeling along the way
So I can remove that door in blender right?
If it's a mesh, yes
then you'll need to edit it in a 3D modeling software
Don't worry; you'll be learning C# for the rest of your days . . .
Ok, Ill download blender and Ill see what I can do
I won't work on it any longer today
But I will reply to your message when I finish it tomorrow
Alright, best of luck!
How can I quickly search through filenames of an asset I know without importing it first?
Hi, im new to coding and trying to get a basic code for my jump button, it does work but if you just hold the space bar it makes you fly and im just trying to make a sqaure (player) jump. Please help 😄
hi, anyone know how to "loop" a coroutine? I'm trying to make it so that the mom GameObject would attack every few seconds randomly but it only runs once per activation and im wondering whether there's a way to repeat the coroutine after it has completed the lines of code inside. thx!
{
public float speed;
public finalRandomRange = Random.Range(5, 10);
void Start()
{
StartCoroutine("momCoroutine");
}
IEnumerator momCoroutine()
{
finalRandomRange = Random.Range(5, 10);
yield return new WaitForSeconds(finalRandomRange);
Debug.Log("attack");
}
}```
Input.GetKey() returns true for every frame during which the key is down. Input.GetKeyDown()/Input.GetKeyUp() only return true for the single frame after the key is pressed or released, respectively.
AddForce() has another optional parameter - the ForceMode. By default it's ForceMode.Force, which means that the arguments are interpreted as "force per second" - so they get multiplied by Time.deltaTime (and essentially scaled down). When you're applying forces constantly like this using AddForce(), you should do so in FixedUpdate(); otherwise, because physics updates generally occur less frequently than frames, you may end up seeing strange effects when the force is applied multiple times in one physics update.
But in this case, where you want to apply a whole bunch of force at once, you might instead use ForceMode.Impulse for which the entire force value will be applied to the rigidbody instantaneously, and time is ignored. Applying impulse forces within Update() is fine, since it is only occurring once such that the framerate/physics update disparity is not an issue.
If you combine an impulse force with one of the input methods which will only return true for a single frame, you get a big force applied for the one frame in which the jump key is pressed :)
Presently it rolls a random number, waits for that many seconds, logs the attack, and exits. Throw an actual loop in there so it repeats instead of exiting 🙃
public int Seconds = 0;
// Count up seconds forever - or until something external terminates the coroutine.
IEnumerator CountSeconds() {
while (true) {
yield return new WaitForSeconds(1f);
Seconds++;
}
}
(Edit: don't actually count time like this - the results will be inaccurate as yield instructions like WaitForSeconds() will only be evaluated once per frame. Use Time's members instead)
To avoid headaches and heartache, always make sure your loops within a coroutine have a yield statement somewhere... It's a very common mistake to neglect to and turn it into an infinite loop trying to execute within one frame 👀
will make sure that doesnt happen, ty again :)
Thanks, anyway you could show me what that code would look like, I think im understanding what your talking about, though since im new i dont exxactly know what word and symbols to put in. if you dont have time its okay 😄
Check out AddForce()'s docs - the second example at the bottom of the page shows how to call AddForce() with three floats and specifying that it should be an impulse.
Then it's just a matter of changing your Input.GetKey() out for one of the other options.
Give it a run, and chime back if you get stuck somewhere 👍
alright thanks!
i got 3 errors in my code and im pretty confused about this. If anyone could help then it would be much appreciated.
You're checking if clearCounter is null but then use this.clearCounter instead
thanks
I usually name the parameter something like newClearCounter or clearCounterReplacement or similar to avoid confusion
alright, thank you for the help.
Do not cross post. Also this is not a code question
I want some sprites to be affected by post processing and some of them not
!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 do I get positions of the Sprites in a Sprite Atlas?
What exactly are you trying to do?
do u need to understand code, what it does and why/when to use it in order to program a game urself?
absolutely, if you cannot do that you either need to learn how to or do something else
I have a gameobject with 1 or 2 colliders i want to destroy. Before the destruction an animation is played. While the animation is played i want to disable all collisions. The problem is i dont know how many colliders the thing i want to destroy has and making a list seems excessive. Destroying the rb doesnt work, since the colliders still detect collisions
I want to get the Sprite from Atlas coordinates
making a list seems excessive
in what way? Just make a list
if you want a list of colliders that something has, make a list of colliders.
use GetComponents (in children) in start or awake to get an array
fair, just thought there would be a simple way to disable physics
i have the rigidbody, i should be able to get the colliders from there
no
well setting the RB to kinematic does ignore it from the physics system. The other colliders still exist alone and can be hit by other rigidbodies but wont move
Collider2D[] cols = rb.transform.GetComponents<Collider2D>();
why do you need the rb.transform in that?
you right, i dont
Hi there! good morning guys, i just found this script and i want to ask what do you think is better in performance, using overlapsphere or raycast in only the layer of my interactable items?
They aren't comparable. OverlapSphere detects colliders in a given radius at a certain point. Raycast detects a single collider along a specific line (position + direction * distance)
tbh the Physics calls are the least of your problems, the 2 nested foreaches are horrible
also use the non alloc version https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.html
yes, in performance for its better than foreach i remember that you are right
what mean Like Physics.OverlapSphere, but generates no garbage, i have readed this long time ago, im not using nonalloc but i dont understand very well why
I would be more concerned about the nested GetComponents, you need to investigate a better way to do this
right now, im using raycast, my performance i think is good, but when i do raycast only check gameobjects in interactable layer, but after this i must access to his component to check some params, how can i investigate a bbetter way to do it?
i usually check alot of tutorials and read docuemntation, im using addressable, scriptable, etc.. but how can i access his component after doing raycast w/o using getcomponent and his parameters?
it does not create a new array everytime you use it, it just fills the array you provide it. if you look at the docs, it shows you how to use it even.
what does this part even mean?
when i do raycast only check gameobjects in interactable layer
The overlap functions also let you specify the layer
it checks whatever layer you tell it to
think about what you are trying to achieve, you are asking one object to find other objects and then asking those objects to supply you with information (i.e the interactable objects)
Maybe switch it around, use the observer pattern so the target objects can subscribe/unsubscribe to an event on the origin object
hello i have found a script for rigidbody movement and i have set my speed to 170 but when i fall my player fall very slow so i have put an if statement if the player have jump or not but i have 2 problem if my player fall and he didnt jump he fall very slowy and if he jump and move while he jump my player will become very fast```void FixedUpdate()
{
if (loading.gameReady && CanMove)
{
if (isOnGround)
{
rb.velocity *= rb.drag * Time.deltaTime;
rb.velocity *= (1 - rb.drag * Time.deltaTime);
}
rb.AddForce(oriantation.forward * speed * verticalInput, ForceMode.Force);
rb.AddForce(oriantation.right * speed * horizontalInput, ForceMode.Force);
}
}
void Update()
{
if (loading.gameReady)
{
if(CanMove)
{
if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
{
isOnGround = false;
playerAnim.SetBool("isJumping", true);
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
rb.AddForce(oriantation.forward * speed * verticalInput, ForceMode.Force);
rb.AddForce(oriantation.right * speed * horizontalInput, ForceMode.Force);
}```
The code in FixedUpdate is weird. The velocity manipulation with multiplying the drag (twice) is probably what's causing it, and you're already applying movement force in Update, so the last two instructions of FixedUpdate are unnecessary
its a Physics drag formula https://discussions.unity.com/t/physics-drag-formula/541279/6
Drag is applied by the physics engine, you don't need to do it yourself
if i dont use this my player slide and i have made a speed potion so the value change
Increase the drag in the Rigidbody's Inspector so you don't slide forever. For jumping, while you're not grounded, set the drag to a lower value so you fall down faster
Or add a constant supplementary downwards force
Why does it says it's not MonoBehaviour?
but i dont find the good drag because if the drag is too high i must press my key for a long time for move and if the drag is too low my player slide
It worked fine before and suddenly it stopped working
Then you can adjust the drag based on your own velocity. Low velocity = low drag so you pick up speed faster - High velocity = high drag so you reach terminal velocity at some point
nvm, I added an empty line and it solved it
so rb.drag = rb.velocity ?
That won't compile, but that's the idea. Drag would be a function of the velocity in your case. You can do it with a Math.Lerp(), a curve you can modify in the Inspector of your script, etc.
ok
i will have to do this ? Mathf.Lerp(rb.drag, rb.velocity, rb.drag);
That does not compile
Lerp takes three float, you gave it a float, a Vector2, a float
oh
uh so i was following a tutorial on a top-down shooter game and somehow the character is rotating 90 degrees to the wrong angle?
private void FixedUpdate()
{
_smoothedMovementInput = Vector2.SmoothDamp(
_smoothedMovementInput,
_movementInput,
ref _movementInputSmoothVelocity,
0.1f);
_rigidbody.velocity = _smoothedMovementInput * _speed;
RotateInDirectionOfInput();
}
private void RotateInDirectionOfInput()
{
if (_movementInput != Vector2.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(transform.forward, _smoothedMovementInput);
Quaternion rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);
_rigidbody.MoveRotation(rotation);
}
}
private void OnMove (InputValue inputValue)
{
_movementInput = inputValue.Get<Vector2>();
}
}
i dont understand how i can change the drag with Mathf.Lerp()
Lerp is a method that, given a minimum value, a maximum value, and a "percentage" (value between 0.0 and 1.0), returns a value between minimum and maximum corresponding to said percentage
ok
Eg. Lerp(2, 3, 0.5f) gives 2.5f because 2.5 is halfway (0.5 - 50%) between 2 and 3
ok
You can use that to scale the drag depending on the velocity
I have to go, someone else will take the lead
but if rb.velocity is a vector2 then how can i put velocity in Mathf.Lerp ?
When using line renderer with points with tight angles, I get this funky early curlves, and inconsistent widths.
Is there a way to to make it display EXACTLY the points and widths without this strange lerping at the corners? If not is there another easy alternative that does this?
uh so i was following a tutorial on a top-down shooter game and somehow the character is rotating 90 degrees to the wrong angle?
private void FixedUpdate()
{
_smoothedMovementInput = Vector2.SmoothDamp(
_smoothedMovementInput,
_movementInput,
ref _movementInputSmoothVelocity,
0.1f);
_rigidbody.velocity = _smoothedMovementInput * _speed;
RotateInDirectionOfInput();
}
private void RotateInDirectionOfInput()
{
if (_movementInput != Vector2.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(transform.forward, _smoothedMovementInput);
Quaternion rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);
_rigidbody.MoveRotation(rotation);
}
}
private void OnMove (InputValue inputValue)
{
_movementInput = inputValue.Get<Vector2>();
}
}
Is the character's forward pointing to the right direction?
good point, let me cehck
it works, thanks 
i have tried this but it dont work 🥲
rb.drag = Mathf.Lerp(rb.velocity.x, rb.velocity.z, 0.5f);
In your own words, how do you think Lerp works?
In fact, you will need 4 values in total
Your min drag and max drag, at what velocity the drag will be minimal and at what velocity the drag will be maximal
These are all going to be values set by you
Then you can use your min velocity, max velocity and current velocity to find the percentage you are at
I would recommend setting minimum velocity as 0
That greatly simplifies it to simply currentVelocity/maxVelocity
Following so far?
rb.drag = Mathf.Lerp((minDrag, MaxDrag),(currentVelocity, maxVelocity), 0.5f);
im really new to unity. The UI isn't looking like how it was in the engine. Can someone help me with this?
Nope
oh
Have you understood the idea as I described it so far?
not really
Where did you get lost
You've zoomed out the game view in Unity. Set the scale back to 1x
i dont understand wich value i have to put in Mathf.Lerp()
I will get there
ok
But first I need you to understand the first part
i will need to set the min and the max drag and min , current, max velocity
Where exactly it is located
Lerp takes in 3 variables - the first one is the minimum value, maximum value and the percentage you are at
this scale? but this doesnt let me see the full screen
That is the full screen
It you give it (0,1,0) it will return 0, if you give it (0,1,0.5f), it will return 0.5f
that's why it looks wrong in build
Makes sense?
so Mathf.Lerp(3, 3 ,0.5f) = 3
That does not make much sense, since your min and max values are the same
2+ 4 = 6 6/2 = 3
No
2 + (4-2)*0.5
why 2+ ?
ok
It's easily shown in ms paint but I'm on my phone rn
oh ok
start + ((end - start) * t);
rb.velocity = Mathf.Lerp(minVelocity, MaxVelocity, CurrentVelocity); ??
Almost there
The result you are looking for is
float xDrag = Mathf.Lerp(minDrag, maxDrag, (currentVelocity-minVelocity)/(maxVelocity-minVelocity))
Having minVelocity 0 greatly simplifies the 3rd number to just currentVelocity/maxVelocity
ok
quick question: is there a function similar to OnDrawGizmoSelected which gets also called when I select one of child objects of the script that has OnDrawGizmoSelected in it?
I currently want to visualize the path of a bezier curve and DrawLine is visable as long as I select the object, but when I select one of the child object handles which manage the path of the Curve, it disappears because the main script GO is no longer selected?
(I know that I could also use OnDrawGizmo but that one is always drawn and thats not what I want)
xDrag = rb.drag ?
No
xDrag is drag in the X direction
You need to find X and Y directions separately
ok
All of these velocities are floats, not vectors btw
Probably should've marked that, sorry
ok
They are the part X values in a Vector2
And you need to do the exact same thing with the Y values
ok
Then you get dragX and dragY and combine them into the final rb.drag vector
float YDrag = Mathf.Lerp(minDrag, maxDrag, (currentVelocity-minVelocity)/(maxVelocity-minVelocity))
rb.drag = Mathf.Lerp(Xdrag, Ydrag, 1);
No
rb.drag = Mathf.Lerp(Xdrag, Ydrag, 0.5f);
If you want to understand what lerp is
but drag is not a vector ??
Google linear interpolation
Is drag a scalar?
Mb the
Then
In that case you only need to do it once
Forget the X and y values, just take single velocities
oh ok
rb.drag = Mathf.Lerp(minDrag, maxDrag, (currentVelocity-minVelocity)/(maxVelocity-minVelocity));
Yes
CurrentVelocity being RB.velocity and the rest being your arbitrary values
I would highly recommend setting minDrag and minVelocity as 0
ty
😄
maxVelocity and maxDrag you need to find out via experimentation
Just set something and change those values until it feels good
dont work with this (rb.velocity is a vector2 but not drag)
float Dragy = Mathf.Lerp(0, maxDrag, (rb.velocity.y - 0)/(maxVelocity-0));
rb.drag = Mathf.Lerp(Dragx, Dragy, 1);```i slide on the ground and if i change the value it dont seem to stop slidding
I'm guessing math is not your strong point, but what are you expecting - 0 to do here?
rb.velocity.y - 0)/(maxVelocity-0
😭

I told him to do that, albeit I'd expect him to drop it from the equation completely
You don't need to calculate the X and Y at all, that was my fault, you can just use this
but rb.velocity is a vector2
Also this
rb.drag = Mathf.Lerp(Dragx, Dragy, 1);
is nonsense. its exactly the same as
rb.drag = Dragy;
i did this for rb.velocity.y and rb.velocity.x
I am not 100% sure if there's a value you can get for the speed of the object as a float, not a vector
sure, the magnitude of a direction vector will give you speed
If not you can calculate it with a^2 + b^2 = c^2
Or that, yeah
Basically what I suggested, just tried to write it out to make him understand where the value came from
But yeah, code wise the easiest way is what Steve suggested, use the magnitude of the RB.velocity vector @round mirage
rb.velocity.magnitude ?
That should be it yeah
Also, if you don't see a difference, you could have either a low max drag or a high max speed
and then current velocity become rb.velocity.magnitude
ok
Yes
it work perfectly thank you 😊
Sweet
is there a way to make something happen for only one frame in code, similar to the trigger system for the animator
Sure, do it in an if block in update, then set the condition to false.
oh that makes sense actually, thank you
Hey everyone, i'm not sure where to put this but are there users here that are skilled in both Unity and Godot C#?
any programming questions you have for Unity are answered here . . .
If you have a Unity related programming question, you can just ask it.
Just so I understand the API correctly:
- Update is Frame depending, (So for convenience I say the game runs at 20 fps, I have 20 Updates)
- Time.deltaTime is the amount of time passed since the last frame (at 20 FPS this means time since the last frame is 0.05)
So if I have a:
lerp(x,y,t) and t = t * Time.deltaTime
that means t will increase each Update by 0.05 and therefore it will always take t 1 sec to interpolate the lerp from 0 to 1?
no, lerping is a separate topic
t += Time.deltaTime;
a = Mathf.Lerp(x, y, t / totalTime); // correct
Yes, that's right
Perfect now i have one yes and one no ^^'
😆
var unitsPerSecond = speed;
a = Mathf.MoveTowards(x, y, unitsPerSecond * Time.deltaTime); // also correct
Your statement is entirely correct if you replace * by + in here:
t * Time.deltaTime
Pretty sure this was a typo
Since t is 0 from the beginning, multiplying it by deltaTime of any frame rate results in constant t and, in your case, x always returned
this is wrong because you are not adding 0.05 but multiplying . . .
we'll never know . . . 🤷♀️
oh! it was a typo
Ha, you see!
Ignore that she was writing that for an eternity
this is my t
you can just do += instead . . .
+=
I... could do that yes 🙈
and remove the () . . .
This is irrelevant, since everybody has their own style
yup! but you should just be calling it lerpT or smthT to avoid confusions :p
You should not
interpolate amount already describes it nicely, but it should differ for different methods
tho clean code wasnt my question^^
I just wanted to be sure that "if I add Time.deltaTime" to "something" that it will (as long as it is written in Update) always add a total of 1 per second
That's right
or in my case: run through the whole lerp in 1 sec
Yes
Ok. thanks ❤️
also thanks to Lyrcaxis and RandomUnityInvader. you were right that * would not have done what I wanted ❤️
we must put a stop to this, at once!
!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.
so now that I know that the lerp will finish in 1 sec. I dont want that. I want it to have a consistent speed.
If we say the distance between a and b in the lerp is 45m. I have to:
float distance = 45f;
float speed= 6f; //speed = m/s
interpolateAmount += (Time.deltaTime / distance * speed);
so that it will take 45s and therefore reduce the speed to 1m/s and then I can easily increase it to whatever I want (6 in this example) ?
you're also right about the framerate-independent logic though!
check my responses above: #💻┃code-beginner message
lerp is best done when you're dealing with TIME only as a parameter
lerp is best used for duration, not speed . . .
if you have UNITS involved, you're better off using a MoveTowards variant (e.g.: Mathf.MoveTowards(..)
this code should work, but you're confusing yourself for no reason
I am confusing myself because I only knew lerp and had no clue that MoveTowards exists ^^'
first of all by not ordering the operations correctly -- it should be Time.deltaTime / (distance / speed),
coming from the equation X = U*T => T = X/U (U = speed, X = distance, T = totalTime)
Originally I had this as:
t += Time.deltaTime / totalTime;
a = Mathf.Lerp(x, y, t); // correct
-- which is correct, but changed it so it'll be less confusing universally
a = Mathf.Lerp(x, y, t / totalTime); should be the only proper way to do lerp -- then you just have deal with totalTime since t is a simple timer (+= Time.deltaTime)
and this is just to avoid overcomplicating the meaning of t -- since, if you're following this convenience, it's a plain timer that tracks raw time
LMK if overcomplicating things or actually helping xD
I currently try to understand how Vector3.MoveTowards works
basically it's slightly different: a = Vector3.MoveTowards(a, b, maxOffset); // Call every frame
where maxOffset is usually speed * Time.deltaTime
so you offset a and update it on the same frame, then use the updated a on the next frame
and the code will keep updating a until a == b
ooooh so the "maxDistanceDelta" is the distance it moves with each Update, and to change it from "distance per update" to "distance per sec" we * by Time.deltaTIme
the opposite 😄
from distance per sec --> distance per update: We * Time.deltaTime // common practice
from distance per update --> distance per sec: We / Time.deltaTime // inverse also works
but yeah you got the maxDistanceDelta part down!
To understand this better:
- Imagine we have
Speed = 6(units/s) - Assuming there are ~20
Update()calls within a second- =>
Time.deltaTimewill be a constant0.05
- =>
- If we want to emulate movement for a single frame, we move the object by
6 * 0.05 = 0.3units - ..which is what
Speed * Time.deltaTimewill return
Yes and thats what I mean: by default MoveTowards(x,y,t) will move my object every update 6m, unless we multiply by time.deltaTime. Which lets us switch from "6m per update" to "6m per sec" ?
yes!
I'll point out just in case that t is a wrong variable name in the MoveTowards scope 😛 a = MoveTowards(a, b, u) would be the way to type it
It creates a vector that is some distance from a to b that is not further than maxOffset. It's basically value = a + (direction * Mathf.Min(Vector3.Distance(a,b), maxOffset))
yeah makes sense since we talk about units and not time
yeah I slowly understand it now ^.^
Now I just need to figure out how to correct b 🙈
btw I advise you re-read the above just in case you missed any parts about why t is better off named as just t when lerping 😛
yeah makes sense to call it t now since it's harder to put t into u than to put some other random name into u
what? 😆 alright if it makes sense to you that way it's all good xD
my main selling point for it would be this ^ (keeping t as a raw timer)
If I call it t-Something then I know that it is timer related and that I shouldnt put it into a function that requires x,y,u etc. which I would have done if I call it interpolateAmount. That's what I meant^^
Now I need to figure out how to change b ...
can someone explain what happened? public variables wouldn't appear on my script i made only the part that says what the script was, i deleted stuff in my script seeing if that would work and it did, i then repasted it going to fix the code but suddenly the variables where there? it's all working normally now but i still dont know what happened and might be good to know for the future if this is just a unity bug or something or something related to the coding and my script
sounds like you either had compilation errors you fixed or your code was not previously saved/compiled
you probably had a compile error. Did you look in the console
everything mentioned above . . .
it was a compile error but the only error i was getting was 'Random' does not contain a definition for 'range'
and that's becuase I couldn't interact with the public numbers in the script as they wouldn't show up. thats all it was telling me
Yeah that's a compile error
you have to fix that
or literally nothing in the codebase can change
yes, but ANY compile error in ANY script will block everything
oh i thought the error was becuase i didn't put anything in the public script when i couldn't as it wouldn't appear. well i have no issues what's wrong then ill take a minute to try and figure it out before i ask
well Random does not contain a method range. It does contain one called Range though
to specify i'm doing a tutorital on learning unity so im just copying this guys code one for one at the moment to get first hand experince with it, as far as i can tell i didn't make any typo's but it's still the error
show the error and the line of code
Show code, show tutorial
How can I quickly search through files in an asset I bought before I import it?
I see through the asset store I can look through files, but this is a lot of manual work opening each folder one by one.
I'm looking for a specific filename
The unitypackage format is just a fancy zip file, you could try extracting them all somewhere on your file system and searching that way
But that's debatable whether it's faster than just importing them through the package manager and searching the project
Vector3 randomPosition = new Vector3(Random.range(minX, maxX), Random.Range(minY, maxY), 0);
that's the error code in question specfiacly the first part starting at the first Random.Range based on the error
'Random' does not contain a definition for 'range'
the error. and the tutorital requires making an account should i send a screenshot?
Send a screenshot yes
you spelled something wrong
so, as I said, range should be Range
Is there much risk with importing where it could break my project?
That's why I don't want to start importing a bunch of assets
If you're that worried, commit it to version control first and revert if it breaks
provided you are using some sort of version control, there is never a risk because you can always revert
but typically, simply importing an asset wouldn't break a project
then import it into a blank project
Maybe creating a separate Unity project just for importing would be better
OH MY GOSH! why does this keep happening? why do i keep misspelling things?! every time ive had an issue ive spent like 15 minutes to an hour trying to fix it only for it to be a minor typo!
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 176
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-08-22
if you are that paranoid, then don't import anything ever because what if there's some error you don't understand 5 years down the road due to an asset you import today?
This would be better to do instead of unzipping the unitypackage?
because your !ide is not configured
is there a way to copy messages in the Console without copying the stack trace for every message?
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Hello i need help who can come private pls?
make sure that your IDE is configured so you have intellisense preventing you from making silly mistakes
no. !ask 👇
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Unfortunately, no. You have to grab the whole thing
in fact, ALWAYS commit to version control before importing a new library/asset
up to you, the result is the same
so i lookde at the VS code part and set unity to pick VS code as it's regular thing (despite it already chosing it) and idk what exactly this is supposed to help with, nothing changed
oh NOW it changed after i reset it mulitple times it finally brought up a 'would you like to install a unity what ever thing' and now its doing what i think its supposed to do
which is why we generally advise to use Visual Studio Community rather than Visual Studio Code
what's the difference?
VS is a proper fully fledged ide, VS Code is a jumped up text editor
they both can do the job.. but VS Community is normally the better option esp for newcomers
i prefer vscode. b/c i can modify almost every aspect of it
tbf I do do a great deal more with VS other than Unity C#
Do they use different programming languages or anything different like that?
nope
Well I'll go ahead and finish up yhe tutorial in code and see how that goes or if I keep having issues when i start to do thing's on my own with it, if so then ill I'll try out community
Thanks for the recommendation though as I didn't even know about community
it really should be your first choice, although the functionality is similar the integration with Unity is far superior in VS Community
if ur a general programmer vscode is pretty good.. i use it for programming hardware
but if ur only using it for unity.. vs studio is probably better
interesting, I generally use Eclipse when I'm doing real low level stuff
I mostly just use VIM for that
-# Maybe someday I'll figure out how to close it
how do i make objects have collisions?????
Put colliders on them and don't crosspost
huh?
That was an answer, and also a statement
Answer: Put colliders on them
Statement: Don't crosspost
how do i do that?
What have you tried?
The same way you've put any component on any object
ok lemme try
Because, if you bothered to google your exact question with the same number of ? marks, you would have found this.
im dependent on platformIO
what do i click
Are you trying to change any of these values
@cedar cove ^ collider = collision
if ur not understanding what each component does check into Unity Collisions via google / youtube/ or the !learn resources
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
So i did some research and i read that community can only be used for open source products?
nonsense
and im getting a lot of back and forth anwsers now going deeper... some say they take roaylties, some say they don't
Visual Studio does not take royalties. You can use it for production as well.
okay i guess ill go ahead and use community then as suggested
don't junx it lol
microsoft got plenty of other methods of revenue.. and vs community been around for a while..
doubt you'll ever have to worry about that
who is saying they take royalties?
-# inb4 chatgpt
nope its smart enough to know better
I honestly do not know where people come up with such crap, it would be like MS Word taking royalties for every document I write
Adobe, they get it from Adobe
Not my favourite people, mind you I dont like MS very much. Come to that I don't like anyone very much, go figure
it was just stuff i found people saying online maybe they were confusing it with the paid versions or something idk at all now
okay question how do i get { } to automatcily move down into the correct postion below what im coding? (liek if i add new { } how do i get it to move i mean as hes doing it with a single button click in my tutorial)
start by making sure that your !IDE is configured. then it's just a matter of setting up your desired styling settings (though that would be the default for c# so you shouldn't have to change anything in the settings once it is 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
• :question: Other/None
its called auto-formatting just google it w/ whatever program ur using
mines set up to format on line breaks.. and when i paste
I have an empty object and inside that a player body (capsule) and a cube to see which way Im facing
I did try adding gravity to it, adding rigidbody and capsule collider but everytime it goes through the ground and falls into the void
can I add gravity to it how
Does your ground have a collider
box cllider
Can you show the inspectors of the ground and the object with the rigidbody?
- ur capsule starts clipped into the ground
- its collider is marked as trigger
- ur applying gravity by just changin the transform.position <-- this wont respect physics and collisions
- for some reason u have those set to layers that ignore each other (doubtful)
thats the only reason why it'd go thru the ground ^
do I add capsule collider to the empty or the capsule in it
it wont matter.. any collider beneath the rigidbody will count as the body of it
You'd have the collider on the thing with the rigidbody usually
but ya its good practice to keep them together
But as spawn said, a rigidbody will also contain the colliders of its children
my capsule dont starts clipped to the ground, actually its flying
yeah i can't find it oh well i guess
in vscode thers settings to do it automatically.. in vs studio u probably have to use the hotkeys
have a little stairs as well
i tried doesn't do anything
u have to have the code selected
it just gives me an error sound
Expand and show both colliders as well
is it
it is.
ok
Wait is it a Character Controller or a Rigidbody
u can use gizmo's in the scene view to see the collider
