#💻┃code-beginner

1 messages · Page 466 of 1

steep rose
#

you dont know what?

sleek gazelle
#

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

steep rose
#

how to look this up?

round mirage
#

this

steep rose
#

look up what issue means

languid spire
round mirage
sleek gazelle
polar acorn
#

What is the color of the image before the code runs?

languid spire
#

Anywhere else and just call it when it's needed

steep rose
# round mirage ohhh ok

also if you want us to help you in regards to your problem we would need to see your actual code

sleek gazelle
steep rose
#

not some mockup

polar acorn
verbal dome
polar acorn
#

If the animator state is Idle, you set it to what it is?

sleek gazelle
steep rose
#

that is a ton of things

#

for issue

polar acorn
verbal dome
steep rose
polar acorn
round mirage
# steep rose ok then what is your problem with your code?

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);
        }```
polar acorn
#

It's becoming solid instead of partially transparent

sleek gazelle
#

Thing is it doesn't

polar acorn
sleek gazelle
steep rose
sleek gazelle
#

but it doesn't

polar acorn
# sleek gazelle

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

round mirage
steep rose
#

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

polar acorn
# sleek gazelle

It looks like something else is setting this object's transparency back to 0.592 after this runs.

verbal dome
#

Could be an animator or another script

steep rose
round mirage
verbal dome
#

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

steep rose
sleek gazelle
polar acorn
round mirage
steep rose
verbal dome
#

Something like cs float camAngleY = cam.transform.eulerAngles.y; float camHorizontalRot = Quaternion.Euler(0, camAngleY, 0); Vector3 moveDir = camHorizontalRot * Vector3.forward * ...

sleek gazelle
steep rose
verbal dome
#

I've noticed that the orientation thing has become quite popular

steep rose
polar acorn
steep rose
#

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

round mirage
steep rose
#

ah then configure the drag then

round mirage
rocky canyon
#

drag is like air friction..
angular drag is like rotation friction

steep rose
#

thats what happens while you are in the air

round mirage
#

ok

rocky canyon
#

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

sleek gazelle
polar acorn
sleek gazelle
polar acorn
# sleek gazelle

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?

sleek gazelle
polar acorn
sleek gazelle
#

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

polar acorn
#

Yeah, I think that'd do it.

pastel mesa
#

how to edit a script?

polar acorn
#

I think it'd be best to modify the alpha through either animations or code, and not try to mix both

polar acorn
pastel mesa
#

i made my first script and it doesnt work

pastel mesa
#

it did nothing

upbeat snow
#

did you double click in the asset tab

pastel mesa
#

also i thing its stuff with my downloads

upbeat snow
#

well that's weird, you got visual studio installed?

pastel mesa
#

bc there r some stuff when i try it doesnt work bc its not downoaded

polar acorn
# pastel mesa it did nothing

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

sleek gazelle
upbeat snow
pastel mesa
#

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

polar acorn
#

How about send a screenshot of your whole unity window, show the thing you're trying to open

rocky canyon
#

nothing should cause it to not open a project..

pastel mesa
rocky canyon
#

might be the problem

polar acorn
pastel mesa
#

2.57 GB free of 87.3 GB

rocky canyon
#

oof

polar acorn
#

Yeah that's very not good

#

you're gonna need much more space

pastel mesa
#

;-;

rocky canyon
#

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

pastel mesa
#

ill get a better device but thats when i get college

rocky canyon
#

theres not much u can do besides try to delete unused programs

#

and try to push it up to like 12 - 20 gigs

pastel mesa
rocky canyon
#

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

pastel mesa
#

so i could use it

#

i see so i better not use unity until i get better pc

rocky canyon
#

well you cant lol

polar acorn
rocky canyon
#

you can still practice c# online

#

theres tons of online compilers and tutorials and stuff to get ready for when u do get unity

pastel mesa
#

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

rocky canyon
#

unity should be grateful for roblox

#

all kinda refugees spilling over once they want more lol

pastel mesa
#

tbh from what i saw in unity its almost same as roblox studio lol

rocky canyon
#

its a bit more complicated.. but thats. b/c its hella more powerful

#

if u can imagine it.. u can build it in unity

pastel mesa
#

i kinda make them in minecraft

rocky canyon
#

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

pastel mesa
#

bc minecraft commands r easier and not laggy

pastel mesa
rocky canyon
wild cargo
#

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.
vocal wharf
#

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

raw token
languid spire
wild cargo
#

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

languid spire
wild cargo
#

you mean i should delete PlayerData and remake it?

languid spire
#

not the script, just the SO asset

wild cargo
#

I guess i'm not sure what an SO asset is then

steep rose
#

scriptable object

languid spire
short hazel
#

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

wild cargo
raw token
# vocal wharf I'm trying to make an endless runner game (heavily based on google dino 🙂) but ...

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.

short hazel
short hazel
#

If you restart the Editor, your changes are lost

wild cargo
vocal wharf
rocky canyon
#

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

wild cargo
languid spire
wild cargo
#

Before/After

languid spire
languid spire
wild cargo
#

Its a prefab gameobject

languid spire
wild cargo
#

yes

languid spire
#

you cannot use an asset to store scene objects

raw token
# vocal wharf the last solution sounds good. What do you mean by "subscribe to the event" thou...

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;
}
vocal wharf
#

oh boi

#

this might take me a bit to comprehend hold on

raw token
#

I've gotta head out, but hopefully that provides some heading for further research :)

vocal wharf
#

thanks I'll try to implement this

wild cargo
wild cargo
#

I don't see how that will persist since it is an instance

languid spire
#

it will not persist but SO's dont persist at runtime however you use them

wild cargo
#

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?

languid spire
#

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?

fair temple
#

!ide

eternal falconBOT
wild cargo
#

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.

languid spire
#

just think of Unity as a render engine and design your data/code as if it didn't exist

wild cargo
#

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

vocal wharf
#

The first script you showed goes on the obstacle prefab and the second one goes on the obstacle spawner correct?

languid spire
vocal wharf
#

ok

languid spire
#

you really should look this stuff up in the docs

vocal wharf
#

I've tried

languid spire
#

really, google C# Action

hollow zenith
#

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.

cedar cove
#

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!

short hazel
hollow zenith
short hazel
#

Yeah use the RT

hollow zenith
#

Thanks, that works!

short hazel
#

It inherits Transform so you should be able to just cast it: rt = (RectTransform)transform

strong harness
#

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

cedar cove
#

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!

frosty hound
#

That is probably the most common of things people do. Have you looked online?

short hazel
#

We can help with existing code, creating a script from scratch so it fits your game is not something we do here!

cedar cove
#

oh, sorry

cedar cove
#

thank you so much!

proven mirage
#

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?

raw token
# vocal wharf The first script you showed goes on the obstacle prefab and the second one goes ...

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.

waxen adder
proven mirage
#

i mean ik we have acess to it

vocal wharf
waxen adder
# proven mirage i think so?

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.

raw token
proven mirage
#

so let me thnik

#

we have the player point

#

we have the grapple point

#

so thats the grapple point - the player postion rihght?

waxen adder
#

Those two yeah

proven mirage
#

like this right?

#

wrong wya

#

wrong way

waxen adder
#

I kinda struggle with vector math at times, but that looks reasonable 😛

proven mirage
#

ok now im kinda moving directly towrds the grapple point now

#

which is better than just falling

short hazel
#

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

proven mirage
#

however i sti;; want the player be affected by physics and stuff

#

so like hell swing around

proven mirage
waxen adder
#

Try different force modes

proven mirage
#

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

waxen adder
#

gotcha, could try multiplying the vector by a multiplier and mess with that

#

like a "forceStrength" multiplier

proven mirage
#

ok

waxen adder
#

Set it to different extremes to see if it does anything different

proven mirage
#

like that?

waxen adder
#

Yeah, could also turn that into a public variable for easier tuning

short hazel
waxen adder
#

Er wait

#

Hold

#

Put the vector subtraction in parantheses

proven mirage
#

why?

#

pemdas

waxen adder
#

PEMDAS

proven mirage
#

order of operation

#

same thing

#

it just moves me direcxtly to the grapple point

#

quicker

waxen adder
#

Make it a lower number, something like 0.5

proven mirage
#

alright

#

still doing the same thing

#

just slower

#

now that guy

#

reccomended we do aslepr

#

a slerp

#

which makes sense

waxen adder
#

Huh, is your character affected by gravity?

proven mirage
#

yeah i think so

#

yeah he is

#

he has rigidbody

#

we use physics to move him

waxen adder
#

Interesting, this just goes to show I still need to figure out unity physics

proven mirage
#

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

main quarry
#

'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)

waxen adder
#

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

proven mirage
#

yeah it should

#

thats what isaid in my head as well

raw token
# main quarry 'Non-invocable member 'Instaniate' cannot be used like a method.' `Instaniate(o...

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)

waxen adder
#

What does the grapple look like right now? In video?

proven mirage
#

see this what unity docs says

#

about the spring compoennt values im modifying

waxen adder
#

Oh is that on the grapple?

proven mirage
#

the spring compoennt

#

here are the values in the insepctor i set it to

waxen adder
#

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

proven mirage
#

bc i checked ik im not grounded whn i am grappling

waxen adder
#

You could increase your spring amount or force or whatever over time while being grappled

main quarry
waxen adder
#

Instead of just applying a seperate, external force

proven mirage
#

imma try incressing the sprin force

waxen adder
#

Make sure to comment out that external force you have

raw token
main quarry
#

(i did look up IDE but im not super tech savvy so it didnt really help)

proven mirage
#

i check it

#

im sure it something to do with gravity

raw token
# main quarry I have no clue what an IDE so technically no? (i am very new to this, before uni...

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 👇

eternal falconBOT
main quarry
final kestrel
cosmic dagger
raw token
# final kestrel https://discord.com/channels/489222168727519232/497872424281440267/1275921881459...

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

final kestrel
#

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 😄

deft grail
raw token
final kestrel
#

Yeah I know thats why I'm making the other objects prefab too

polar acorn
#

What's the issue?

final kestrel
#

This is my InventoryManager. I made this a prefab. To hold the items inside, I need to make the items prefabs right?

polar acorn
main quarry
silk night
final kestrel
raw token
# final kestrel Yeah I know thats why I'm making the other objects prefab too

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

polar acorn
#

There's no point in referencing a prefab for any purposes other than instantiating it

silk night
# final kestrel They are gameobjects

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

grave bluff
#

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

final kestrel
#

You are right. Damn I realized I do not want to do it when trying to explain myself.

polar acorn
grave bluff
#

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?

silk night
#

!code

eternal falconBOT
grave bluff
#

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

silk night
#

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

polar acorn
#

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.

grave bluff
silk night
#

It has the following order:

  • Start game
  • SpriteGenerator gets created
  • SpriteGenerator creates CellGrid
  • CellGrid constructor runs
  • SpriteGenerator sets values to CellGrid from inspector
polar acorn
#

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

grave bluff
silk night
#

Like i said above, just call the initialize function on CellGrid in the start function of SpriteGenerator

#

should solve your problem 😄

grave bluff
#

👍

#

thanks for the help

strong harness
#

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

strong wren
#

how can i make it so smth ignores the collisions of smth thru code

#

wait that is worded like booty cheeks

rich adder
strong wren
steep rose
#

you can check if you collide with a collider then do physics.ignorecollision

rich adder
deft grail
strong wren
#

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

eternal needle
#

idk about anyone else, but that sentence makes no sense to me.

steep rose
#

yes

strong wren
#

😮‍💨

#

let me think of a better way to explain this

summer stump
brave compass
deft grail
strong wren
#

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

steep rose
#

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

strong wren
# steep rose why do you need it parented?

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

strong wren
#

since it isnt the enemy touching the player that damages it, its the thing that the enemy is holding

bold swallow
#

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?

eternal needle
#

and you'd also ideally want to keep a copy of this data in some collection rather than reading from the file everytime

bold swallow
bold swallow
eternal needle
#

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

eternal needle
#

That initial sort wont be pretty though you can do this once when the game loads.

bold swallow
bold swallow
#

so i will have approximately 1k-2k names each time

eternal needle
rich adder
#

couldnt you just use a Hashset

#

iirc has fast lookup

eternal needle
#

i assume that they want the index in the original file, to see other data in the same row of the excel sheet

teal viper
#

There are probably many ways to go about with little difference in performance

eternal needle
#

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

rich adder
#

makes sense, thought they just wanted to populate the names in a collection

static vine
#

ah, ty

bold swallow
#

and then search for the rest of the data with that index

eternal needle
#

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

bold swallow
#

All right, I will do tha t

eternal needle
#

And when I say slow it's relatively slow. All this is instant anyways

brave compass
#

Of course, a dictionary will always take the same amount of time to search, regardless of size.

bold swallow
#

What is easier to do for now, so I can get it started?

teal viper
#

List.Find maybe

brave compass
#

Based on your description, I would use a HashSet. You only need to find an exact match and don't need an index.

ember tangle
#

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;
}```
bold swallow
teal viper
raw token
#

In fact you're now executing the expensive thing once per frame 👀

teal viper
#

Oh and that too

ember tangle
#

I thought that the yield return null means that it drops out of the function and returns to it next frame?

raw token
#

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 🤔

ember tangle
#

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

teal viper
#

No. It just waits in the coroutine instead

#

In not sure if buildnavmesh is sync or async, it seems to be sync.

teal viper
ember tangle
#

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

teal viper
#

Do. Profile. The game.

#

You want to have some solid profiling data to back up your assumptions.

ember tangle
#

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?

raw token
#

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

ember tangle
#

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?

ember tangle
teal viper
ember tangle
#

the documentation I found for the NavMesh stuff is pretty sparse

teal viper
#

Navmesh surface has some other methods, like add data and update that is async. Might want to try use that instead.

strong wren
#

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

eternal needle
#

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

strong wren
#

and if that runs every frame then i got myself a nice little homemade ssd fryer but that isnt what im looking for

raw token
eternal needle
#

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

strong wren
#

like once the game is finished

#

i already have a bool for that

#

WaveFinished

#

but idk how to make it run once

eternal needle
#

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

cosmic dagger
#

Why can't you call a method to check after the wave is over?

strong wren
cosmic dagger
#

Why would the method run more than once? When the wave ends, you call the method (in-between waves), then the next wave starts . . .

strong wren
#

but the thing is i would also want the highscore to only update when the wave counter is higher then the highscore

cosmic dagger
#

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 . . .

strong wren
#
        {
            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

strong wren
cosmic dagger
#

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 . . .

eternal needle
strong wren
eternal needle
#

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

strong wren
#
    {
        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++;
        }
    }```
wispy finch
#

What's the issue? I could help out

eternal needle
#

This is still checking in update..

strong wren
strong wren
#

if i put the if wave finished statement ting in the ChangeHighscore Method it would just never be called therefor never run

strong wren
wispy finch
strong wren
#

the spawner script is a lil bit longer

#

its like 100 lines of code

cosmic dagger
#

No need to access player prefs every frame . . .

strong wren
#

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?

bold swallow
#

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
wispy finch
bold swallow
wispy finch
#

I mean, checking in update, sure, but I cant see how

strong wren
strong wren
#

i just wanted to make sure since knowing my expired brain i just had to double check

wispy finch
#

take a look at some example code for reading CSV files in C#

strong wren
bold swallow
wispy finch
bold swallow
#

Then fine by me

wispy finch
# strong wren so its good?

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?

strong wren
strong wren
#

i never even tested it

wispy finch
#

lol, you should

strong wren
#

i dont know how

wispy finch
#

wait, what?

strong wren
#

wdmy by profiler

cosmic dagger
#

So you're saying it fries your SSD without actually checking if it fried your SSD?

wispy finch
#

the profiler gives you statistics when running your game, and via this tool you can identify parts that are taxing

strong wren
#

before even trying it out

wispy finch
#

commonly used for memoryleaks for example, or just when games are running badly, it's a superb tool

wispy finch
strong wren
#

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

wispy finch
#

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

cosmic dagger
strong wren
strong wren
wispy finch
#

SATA SSD: Approximately 128,000 writes per second.
NVMe SSD: Approximately 768,000 writes per second.

cosmic dagger
#

You'd have to change your code structure, but using an FSM to control the waves would be easier . . .

wispy finch
#

think you're good buddy

strong wren
wispy finch
full kite
#

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

wispy finch
#

not the old AND the new?

full kite
#

no bro, i was asking if I can somehow remove it

#

what?

wispy finch
full kite
#

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?

polar acorn
#

Click on it and press delete

#

Also, not a code question

wispy finch
full kite
#

sorry cause I asked here and thank you with the blender option

full kite
#

since its one piece

#

its the entire house in only one piece

wispy finch
#

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

full kite
#

So I can remove that door in blender right?

wispy finch
polar acorn
cosmic dagger
full kite
#

Ok, Ill download blender and Ill see what I can do

bold swallow
#

But I will reply to your message when I finish it tomorrow

wispy finch
tiny hawk
#

How can I quickly search through filenames of an asset I know without importing it first?

hollow dawn
#

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 😄

upbeat snow
#

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");

    }
}```
raw token
# hollow dawn Hi, im new to coding and trying to get a basic code for my jump button, it does ...

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 :)

raw token
#
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)

upbeat snow
#

oh alright, was dumb for me to not think of that lol

#

tysm!

raw token
# upbeat snow tysm!

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 👀

upbeat snow
#

will make sure that doesnt happen, ty again :)

hollow dawn
raw token
hollow dawn
#

alright thanks!

lean anvil
#

i got 3 errors in my code and im pretty confused about this. If anyone could help then it would be much appreciated.

keen dew
#

You're checking if clearCounter is null but then use this.clearCounter instead

keen dew
#

I usually name the parameter something like newClearCounter or clearCounterReplacement or similar to avoid confusion

lean anvil
#

alright, thank you for the help.

languid spire
#

Do not cross post. Also this is not a code question

strong harness
topaz mortar
#

!code

eternal falconBOT
shut finch
#

How do I get positions of the Sprites in a Sprite Atlas?

ivory bobcat
umbral rock
#

do u need to understand code, what it does and why/when to use it in order to program a game urself?

languid spire
proper cloud
#

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

shut finch
eternal needle
#

if you want a list of colliders that something has, make a list of colliders.

languid spire
proper cloud
proper cloud
eternal needle
proper cloud
languid spire
proper cloud
#

you right, i dont

atomic bison
#

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?

short hazel
languid spire
eternal needle
atomic bison
atomic bison
languid spire
atomic bison
#

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?

eternal needle
eternal needle
#

it checks whatever layer you tell it to

languid spire
round mirage
#

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);
    }```
short hazel
short hazel
#

Drag is applied by the physics engine, you don't need to do it yourself

round mirage
#

if i dont use this my player slide and i have made a speed potion so the value change

short hazel
#

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

sleek gazelle
#

Why does it says it's not MonoBehaviour?

round mirage
sleek gazelle
#

It worked fine before and suddenly it stopped working

short hazel
sleek gazelle
#

nvm, I added an empty line and it solved it

short hazel
#

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.

round mirage
#

ok

round mirage
short hazel
#

That does not compile

#

Lerp takes three float, you gave it a float, a Vector2, a float

round mirage
#

oh

silver plaza
#

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>();
    }
}
round mirage
short hazel
#

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

round mirage
#

ok

short hazel
#

Eg. Lerp(2, 3, 0.5f) gives 2.5f because 2.5 is halfway (0.5 - 50%) between 2 and 3

round mirage
#

ok

short hazel
#

You can use that to scale the drag depending on the velocity

#

I have to go, someone else will take the lead

round mirage
#

but if rb.velocity is a vector2 then how can i put velocity in Mathf.Lerp ?

distant ocean
#

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?

silver plaza
#

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>();
    }
}
keen dew
#

Is the character's forward pointing to the right direction?

silver plaza
silver plaza
round mirage
sullen rock
round mirage
#

its a percentage of 2 value

#

ohhhhhhhh

#

ok

#

but then what can i do for this

sullen rock
#

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?

round mirage
#

rb.drag = Mathf.Lerp((minDrag, MaxDrag),(currentVelocity, maxVelocity), 0.5f);

alpine spade
#

im really new to unity. The UI isn't looking like how it was in the engine. Can someone help me with this?

round mirage
#

oh

sullen rock
#

Have you understood the idea as I described it so far?

round mirage
#

not really

sullen rock
#

Where did you get lost

keen dew
round mirage
#

i dont understand wich value i have to put in Mathf.Lerp()

sullen rock
round mirage
#

ok

sullen rock
#

But first I need you to understand the first part

round mirage
#

i will need to set the min and the max drag and min , current, max velocity

alpine spade
sullen rock
#

Lerp takes in 3 variables - the first one is the minimum value, maximum value and the percentage you are at

alpine spade
#

this scale? but this doesnt let me see the full screen

keen dew
#

That is the full screen

sullen rock
#

It you give it (0,1,0) it will return 0, if you give it (0,1,0.5f), it will return 0.5f

keen dew
#

that's why it looks wrong in build

sullen rock
#

Makes sense?

round mirage
sullen rock
#

That does not make much sense, since your min and max values are the same

round mirage
#

oh

#

Mathf.Lerp(2, 3 ,0.5f) = 2.5f

sullen rock
#

Correct

#

(2,4,0.5f) would be 3

round mirage
#

2+ 4 = 6 6/2 = 3

sullen rock
#

No

round mirage
#

oh

#

x0.5 ?

sullen rock
#

2 + (4-2)*0.5

round mirage
#

why 2+ ?

sullen rock
#

It's the base value

#

It's the minimal value you can get

round mirage
#

ok

sullen rock
#

It's easily shown in ms paint but I'm on my phone rn

round mirage
#

oh ok

languid spire
#

start + ((end - start) * t);

round mirage
#

rb.velocity = Mathf.Lerp(minVelocity, MaxVelocity, CurrentVelocity); ??

sullen rock
#

Almost there

round mirage
#

oh

#

rb.drag = Mathf.Lerp(minVelocity, MaxVelocity, CurrentVelocity);

sullen rock
#

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

round mirage
#

ok

left dawn
#

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)

sullen rock
#

No

#

xDrag is drag in the X direction

#

You need to find X and Y directions separately

round mirage
#

ok

sullen rock
#

All of these velocities are floats, not vectors btw

#

Probably should've marked that, sorry

round mirage
#

ok

sullen rock
#

They are the part X values in a Vector2

#

And you need to do the exact same thing with the Y values

round mirage
#

ok

sullen rock
#

Then you get dragX and dragY and combine them into the final rb.drag vector

round mirage
#

float YDrag = Mathf.Lerp(minDrag, maxDrag, (currentVelocity-minVelocity)/(maxVelocity-minVelocity))

sullen rock
#

Yes, keep in mind this is pseudocode

#

Kinda

round mirage
#

rb.drag = Mathf.Lerp(Xdrag, Ydrag, 1);

sullen rock
#

No

round mirage
#

rb.drag = Mathf.Lerp(Xdrag, Ydrag, 0.5f);

sullen rock
#

rb.drag = new Vector2(xDrag, yDrag)

#

You are very confused my man

round mirage
#

ohhhhh ok

#

ye 🙂

#

🥲

sullen rock
#

If you want to understand what lerp is

round mirage
#

but drag is not a vector ??

sullen rock
#

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

round mirage
#

oh ok

#

rb.drag = Mathf.Lerp(minDrag, maxDrag, (currentVelocity-minVelocity)/(maxVelocity-minVelocity));

sullen rock
#

Yes

#

CurrentVelocity being RB.velocity and the rest being your arbitrary values

#

I would highly recommend setting minDrag and minVelocity as 0

round mirage
#

ty UnityChanThumbsUp 😄

sullen rock
#

maxVelocity and maxDrag you need to find out via experimentation

sullen rock
#

Just set something and change those values until it feels good

round mirage
languid spire
#

I'm guessing math is not your strong point, but what are you expecting - 0 to do here?
rb.velocity.y - 0)/(maxVelocity-0

sullen rock
sullen rock
round mirage
languid spire
#

Also this
rb.drag = Mathf.Lerp(Dragx, Dragy, 1);
is nonsense. its exactly the same as
rb.drag = Dragy;

round mirage
sullen rock
#

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

languid spire
sullen rock
#

If not you can calculate it with a^2 + b^2 = c^2

sullen rock
#

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

round mirage
#

rb.velocity.magnitude ?

sullen rock
#

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

round mirage
#

and then current velocity become rb.velocity.magnitude

sullen rock
#

Yes

round mirage
#

it work perfectly thank you 😊

sullen rock
#

Sweet

knotty gust
#

is there a way to make something happen for only one frame in code, similar to the trigger system for the animator

teal viper
knotty gust
#

oh that makes sense actually, thank you

buoyant violet
#

Hey everyone, i'm not sure where to put this but are there users here that are skilled in both Unity and Godot C#?

cosmic dagger
frosty hound
#

If you have a Unity related programming question, you can just ask it.

left dawn
#

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?

grand badger
#
t += Time.deltaTime;
a = Mathf.Lerp(x, y, t / totalTime); // correct
left dawn
#

Perfect now i have one yes and one no ^^'

cosmic dagger
#

😆

grand badger
#
var unitsPerSecond = speed;
a = Mathf.MoveTowards(x, y, unitsPerSecond * Time.deltaTime); // also correct
willow scroll
#

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

cosmic dagger
willow scroll
cosmic dagger
#

we'll never know . . . 🤷‍♀️

left dawn
#

oh! it was a typo

willow scroll
#

Ignore that she was writing that for an eternity

left dawn
#

this is my t

cosmic dagger
#

you can just do += instead . . .

willow scroll
left dawn
#

I... could do that yes 🙈

cosmic dagger
#

and remove the () . . .

left dawn
willow scroll
grand badger
# left dawn

yup! but you should just be calling it lerpT or smthT to avoid confusions :p

willow scroll
#

You should not

#

interpolate amount already describes it nicely, but it should differ for different methods

left dawn
#

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

left dawn
#

or in my case: run through the whole lerp in 1 sec

willow scroll
#

Yes

left dawn
#

Ok. thanks ❤️

#

also thanks to Lyrcaxis and RandomUnityInvader. you were right that * would not have done what I wanted ❤️

cosmic dagger
wanton hare
#

!code

eternal falconBOT
left dawn
#

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) ?

grand badger
grand badger
#

lerp is best done when you're dealing with TIME only as a parameter

cosmic dagger
grand badger
#

if you have UNITS involved, you're better off using a MoveTowards variant (e.g.: Mathf.MoveTowards(..)

grand badger
left dawn
grand badger
#

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)

grand badger
#

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)

grand badger
#

LMK if overcomplicating things or actually helping xD

left dawn
#

I currently try to understand how Vector3.MoveTowards works

grand badger
#

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

left dawn
#

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

grand badger
#

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!

grand badger
left dawn
grand badger
#

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

polar acorn
left dawn
left dawn
#

Now I just need to figure out how to correct b 🙈

grand badger
#

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 😛

left dawn
grand badger
#

what? 😆 alright if it makes sense to you that way it's all good xD

grand badger
left dawn
#

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 ...

main quarry
#

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

slender nymph
#

sounds like you either had compilation errors you fixed or your code was not previously saved/compiled

languid spire
cosmic dagger
#

everything mentioned above . . .

main quarry
polar acorn
#

you have to fix that

#

or literally nothing in the codebase can change

languid spire
main quarry
languid spire
main quarry
#

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

languid spire
#

show the error and the line of code

tiny hawk
#

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

polar acorn
#

But that's debatable whether it's faster than just importing them through the package manager and searching the project

main quarry
#

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?

languid spire
tiny hawk
#

That's why I don't want to start importing a bunch of assets

polar acorn
slender nymph
#

but typically, simply importing an asset wouldn't break a project

tiny hawk
#

But if I don't know until down the road

#

Ok thanks

languid spire
tiny hawk
#

Maybe creating a separate Unity project just for importing would be better

main quarry
#

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!

polar acorn
slender nymph
tiny hawk
languid spire
mint remnant
#

is there a way to copy messages in the Console without copying the stack trace for every message?

eternal falconBOT
lusty quarry
#

Hello i need help who can come private pls?

slender nymph
slender nymph
eternal falconBOT
polar acorn
grand badger
languid spire
main quarry
#

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

languid spire
languid spire
#

VS is a proper fully fledged ide, VS Code is a jumped up text editor

rocky canyon
#

i prefer vscode. b/c i can modify almost every aspect of it

languid spire
#

tbf I do do a great deal more with VS other than Unity C#

main quarry
#

Do they use different programming languages or anything different like that?

main quarry
#

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

languid spire
rocky canyon
#

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

languid spire
polar acorn
#

I mostly just use VIM for that

-# Maybe someday I'll figure out how to close it

cedar cove
#

how do i make objects have collisions?????

polar acorn
cedar cove
#

huh?

polar acorn
#

Answer: Put colliders on them
Statement: Don't crosspost

cedar cove
#

how do i do that?

frosty hound
#

What have you tried?

polar acorn
cedar cove
#

ok lemme try

frosty hound
#

Because, if you bothered to google your exact question with the same number of ? marks, you would have found this.

rocky canyon
cedar cove
polar acorn
#

Are you trying to change any of these values

cedar cove
#

idk

#

i dont understand 😦

rocky canyon
#

@cedar cove ^ collider = collision

#

if ur not understanding what each component does check into Unity Collisions via google / youtube/ or the !learn resources

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

main quarry
main quarry
# languid spire nonsense

and im getting a lot of back and forth anwsers now going deeper... some say they take roaylties, some say they don't

frosty hound
#

Visual Studio does not take royalties. You can use it for production as well.

main quarry
#

okay i guess ill go ahead and use community then as suggested

rocky canyon
#

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

polar acorn
#

-# inb4 chatgpt

rocky canyon
#

nope its smart enough to know better

languid spire
rocky canyon
#

adobe can kick rocks

#

making me use old ass tools to avoid subscriptions 👿

languid spire
main quarry
main quarry
#

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)

slender nymph
#

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)

eternal falconBOT
rocky canyon
#

mines set up to format on line breaks.. and when i paste

terse spindle
#

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

polar acorn
terse spindle
polar acorn
rocky canyon
#
  • 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 ^

terse spindle
#

do I add capsule collider to the empty or the capsule in it

rocky canyon
#

it wont matter.. any collider beneath the rigidbody will count as the body of it

polar acorn
#

You'd have the collider on the thing with the rigidbody usually

rocky canyon
#

but ya its good practice to keep them together

polar acorn
#

But as spawn said, a rigidbody will also contain the colliders of its children

terse spindle
#

my capsule dont starts clipped to the ground, actually its flying

polar acorn
#

Show the inspectors of both objects

#

the rigidbody and the floor

terse spindle
#

its the normal

main quarry
terse spindle
rocky canyon
terse spindle
#

my empty can climb stairs but just flies in the y dont fall back

rocky canyon
#

in vscode thers settings to do it automatically.. in vs studio u probably have to use the hotkeys

terse spindle
#

have a little stairs as well

rocky canyon
#

u have to have the code selected

main quarry
#

it just gives me an error sound

polar acorn
terse spindle
#

thats the empty

#

no layer overrides

rocky canyon
#

u dont need the capsule collider

#

Character Controller IS a collider

terse spindle
#

is it

rocky canyon
#

it is.

terse spindle
#

ok

rocky canyon
polar acorn
rocky canyon
#

u can use gizmo's in the scene view to see the collider