#💻┃code-beginner

1 messages · Page 609 of 1

ripe shard
#

i think this "make it fun" argument is used too often as an excuse by people who can't even make it fun independent of any code quality

sour fulcrum
#

That seems like a pretty pretentious opinion tbh

rich adder
#

a tad

glass lynx
#

Some people just really don't care honestly.

sour fulcrum
#

Improving the code of a fun game is far easier than Making some perfectly programmed yet boring experience enjoyable

glass lynx
#

I tend to rewrite entire systems 2-3 times

timber tide
#

godot is actually a great engine if you don't care too much about your code and just want to make a game

sour fulcrum
#

development is highly iterative

timber tide
#

python-type languages are top-tier when you just want to get crap done

ripe shard
sour fulcrum
#

to do it efficently? Honestly a little yes

#

You prototype ideas as fast possible to test them out

ripe shard
#

maybe your definition of good code isn't that well defined

rich adder
#

good code is code that works tbh

#

if it does what you want it to do, its good code

glass lynx
#

Unless its some highly game intensive thing that its doing

sour fulcrum
#

Committing time to developing a system that's going to get thrown out tomorrow is a massive waste of time

ripe shard
#

i get the feeling that "good code" is whatever fits the argument someone is trying to make

rich adder
#

depends alot on the project you're working on too.. Who's gonna be spending tons of time doing every single SOLID by the T on a quick gamejam with other people ?
you're creating extra abstractions for someone else who might not know anything and waste time explaining everything

dense wind
#

the idea of a prototype is that its not the final

sour fulcrum
dense wind
#

you can hack together a prototype to test out an idea, but if you hack together an entire game ur gonna get fucked over by technical debt

ripe shard
#

you see, one guy is talking about prototying, the other about finishing a complicated factory game in a team of 20... how will they ever agree on whats good/bad by discussing abstract examples in a void?

rich adder
#

I think there is a misunderstand, I'm mainly speaking during prototyping / getting some ideas out

sour fulcrum
#

the complicated factory game would have been prototyped homie

rich adder
#

idk what yall talking about

timber tide
#

Unity already forces bad coding practices on you by not allowing custom mono constructors so you've some funky accessors if not serialized from the editor

sour fulcrum
#

and by fucking up my generics 😠

timber tide
#

You don't new your components with parameters, do you? ;p

dense wind
#

when do you new a component

rich adder
#

thats the point no?

sour fulcrum
#

yeah but you can't define specific constructors for them which in theory would be nice

dense wind
#

you mean in the inspector? when u hit add component?

sour fulcrum
#

no via code

polar acorn
#

Can't do proper Dependency Injection

dense wind
#

I think ive only added a component at runtime like. once?

#

so ig I dont know the use case

rich adder
#

AddComponent isnt related

#

like
MyComponent comp = new(injectSomethingHere)

timber tide
#

if you want to initialize data you're doing it in awake/start or your own personal initializer, but that prevents having private accessors set by constructors, and making that readonly keyword pointless

dense wind
#

im curious why one would want to do that

sour fulcrum
#

eg. if you want to spawn a person prefab and you have some scriptableperson template you need to provide them when spawning them. there isn't a built in way to offer some way to provide that on creation

rich adder
#

DI alone is a major benefit

polar acorn
dense wind
#

ohh you mean like that

#

that sounds more like you want a constructor for the gameobject, no?

rich adder
#

gameobject has a constructor

#

we're talking about components

dense wind
#

I have wanted that

dense wind
sour fulcrum
#

Once you start messing with making your own classes that aren't inherited from anything you'll probably have a better understanding of the comparison people are making here

polar acorn
#

Which often times also means you set a variable on it right after

rich adder
#

almost never a reason to use GameObject class directly

sour fulcrum
#

The semi-logic issue here is that while yes GameObjects hold components in 99% of cases there tends to be a primary component on the gameobject that is what people are spawning

#

the reality is that GameObject's have your primary component but how you actually use Unity tends to be more that your Primary Component has a GameObject

acoustic belfry
#

Animator.GetCurrentAnimatorStateInfo works for know info about the current animation state, but is there an equivalent that sees for an specific animator state independent if its the current or not?

dense wind
rich adder
#

GameObjects cant live without component and component cannot exist without GameObject

polar acorn
dense wind
#

I think for the most part I dont do that bc

  • a public Gameobject prefab works better than a public Projectile projectilePrefab
  • my objectpooler I wrote years ago wouldn't like it
rich adder
#
MyComponent myInstance = Instantiate(prefab, etc.)
myInstance.DoStuff```
polar acorn
dense wind
#

I do know how it works yes

polar acorn
#

it works worse

dense wind
polar acorn
ripe shard
dense wind
#

I don't have time to do an example

naive pawn
dense wind
#

so well just assume ur right

polar acorn
#

Using a component type for prefabs is pure upside. You assign it exactly the same way but now you don't have to do GetComponent

rich adder
#

its not just them , its pretty much how its done properly universally

polar acorn
#

there is literally no lost functionality

dense wind
#

but last time I checked u couldn't search thru prefabs with that sort of thing

#

like if u clicked on the little dot nothing showed up

rich adder
#

probably something unlreated

dense wind
#

I could be wrong

sour fulcrum
#

that is true, you would need to enable the more advanced searching feature

#

unity's default asset search rn struggles with that

eternal needle
#

Components have a direct reference to the game object its on, there is literally no code downside to using the component in instantiate

rich adder
eternal needle
#

And yea drag and drop is better for that

dense wind
#

I use it maybe 90% of the time

rich adder
#

if Projectile is a Component it will show a field just like Gameobject would

dense wind
#

but thats just me

sour fulcrum
#

(in other contexts that search thing is a massive pain tho)

rich adder
#

it works 50% of the time lol

timber tide
#

Transform is also the cooler GameObject reference binding

naive pawn
rich adder
timber tide
#

Yeah absolutely

rich adder
sour fulcrum
#

the cooler search mode handles it way nicer

rich adder
#

yeah the new search is goated

naive pawn
rich adder
#

luckily the new search has useful filters. Havent tried packages yet

eternal needle
acoustic belfry
#

and i felt like using the currentstate would make it more...unstable? i dont know how to explain it

eternal needle
humble marsh
#

for my own benifit, !code

eternal falconBOT
hearty glade
hearty glade
rich adder
#

how do you know for sure it never reached any of those two

hallow tangle
#

Hello, I need a little bit of help on my project. There's an issue with my slots UI in my 2D game. For exmaple, I would have 5 same items in my inventory, I am able to drop them too. But the moment I drop them and close the inventory UI, the slots UI icon will revert back to its white box and not show the item icon despite having 4 left. I've tried everything :( nothing works

https://github.com/YourLocalOriginalSnowy/unity_proj

GitHub

Contribute to YourLocalOriginalSnowy/unity_proj development by creating an account on GitHub.

hearty glade
rich adder
#

I would use debugger and put a break point on either of those

hearty glade
#

I just had to put the local variable in the for loop

hallow tangle
late oxide
#

Hello I am a robotics student trying to code a field simulator, ive been using AI to help me debug but now i keep getting the same warning that is correlated with why my code isn't working

im trying to load a glb model into my simulator but as soon as i load the glb i get this error: glTF has no (main) scene defined. No scene will be instantiated.
UnityEngine.Debug:LogWarning (object)
GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__72:MoveNext () (at ./Library/PackageCache/com.unity.cloud.gltfast@8fc67a42c5f2/Runtime/Scripts/GltfImport.cs:680)
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<bool>:Start<GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__72> (GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__72&) GLTFast.GltfImportBase:InstantiateMainSceneAsync (GLTFast.IInstantiator,System.Threading.CancellationToken) GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__71:MoveNext () (at ./Library/PackageCache/com.unity.cloud.gltfast@8fc67a42c5f2/Runtime/Scripts/GltfImport.cs:657) System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<bool>:Start<GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__71> (GLTFast.GltfImportBase/<InstantiateMainSceneAsync>d__71&)
GLTFast.GltfImportBase:InstantiateMainSceneAsync (UnityEngine.Transform,System.Threading.CancellationToken)
FileUploader/<LoadGLBFile>d__4:MoveNext () (at Assets/FIleUploader.cs:80)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)

drifting cosmos
#

can you use guid in unity

rich adder
silent vault
#

Hello, when I click the help menu in a component window, it opens the local documentation file in a text editor instead of the default browser. Is it possible to either change the default program to open the doc or disable local documentation?

#

I can't find the documentation in built in package like google said to disable it

#

Running Unity 6

#

I don't see any option to select browser in the external tools like google said :/

#

Note that I DO want windows to open html files with my text editor. But I want Unity html doc to open with the browser obviously. So I can't change Windows default program for html files like google suggest either...

#

Or how to remove the doc I downloaded instead? :/

#

Ok, I deleted the documentation folder in the editor/data folder and modified the module.json file to set selected to false in the editor folder too. The documentation still shows as installed but links to open in the online doc now. Really buggy way to fix the issue. Modules should be toggable in the hub.

rugged beacon
#

whats the correct way of handling dealing damages logic, do i set a damage variable on the weapon or the projectile, substract the other object health when weapon or projectile colide ?

rich adder
#

health / damage receiver should not care who its from, just the amount to subtract void Damage(float amount)

rugged beacon
#

thanks agree
but where should that void damage be? in the IEnemy? or the weapon or projectile if has projectile?

#

i feels like its the latter you saying but i seen the method TakeDamage very common in the IEnemy interface

rich adder
rugged beacon
#

IDamage is new first time i seen this, thanks i'll try that

rich adder
#

yeah I mean naming is up to you, just makes more sense to generalize it

#

you could also use a dedicated component approach too

rugged beacon
#

i mean first time i seen damage class outside the player/enemy/weapon class

rich adder
#

many objects for my world damage including random props in the world :p

rugged beacon
#

yea makes more sense fr

civic cradle
#

hey mates, quick question:
is it possible to have an extra option in this manager in the context-menu (for example: new command), which then creates a scriptable object or whatever under it?
I only what to have it at this point.

I thought about something like

[CreateAssetMenu(fileName = "Command", menuName = "New Command")]
public class Command

but that would mean I already have that object created. I'd rather create a new "template", if you know what I mean

echo copper
#

Hello, guys. Well, how can i disable this Debug Updater on my scene. It appears every time I start the scene...

#

it's in "Don't Destroy On Load" section in Hierarchy

west radish
#

looking online, it seems to be a URP thing

#

I've not seen it before, but is it causing any problems for you?

#

its for debugging so its not like the final built game would have it

echo copper
west radish
#

put UnityEngine.Rendering.DebugManager.instance.enableRuntimeUI = false; in any script

echo copper
#

okay

#

just put it in the debug script, it worked, thanks

west radish
#

no worries!

sour fulcrum
vital helm
#

can i use
Input.GetKeyPressed()
or is it not recommended to?

slender nymph
#

considering that doesn't exist, i'd say it is not recommended to use that. perhaps you want to double check the documentation for the Input class

vital helm
#

i meant GetKeyDown sorry

slender nymph
#

if that is what suits your needs best, then use it

west radish
#

Why would you think its not recommended to use it?

vital helm
#

ah well.. i don't know

burnt vapor
gleaming kraken
#

as nice as sebastian lague's tutorial on procedural generation is just following him is not very helpful. Is there any good source to actually understand wtf im writing?

timber tide
#

You can alway just do OpenGL tutorials and transfer that knowledge over

visual linden
#

It's also very much not a beginner topic, but it's super interesting and there's a lot of engine-agnostic theories around it that you can find online, or in books. Essentially you should be able to use your understand of math and procedural generation -as its own topic- (not from some Unity specific context) and apply that to runtime mesh generation.
Lague's tutorial I feel already assumes quite a solid understanding of vector math.

gleaming kraken
burnt vapor
#

Sebastian League's videos are not tutorials. They're more dev vlogs with the occasional summary of what was done to make it happen. I don't think it was ever supposed to be more than generally educational.

timber tide
#

it's really just throwing waves at the vertex shader

#

or noise

visual linden
gleaming kraken
timber tide
#

Honestly dont even need to touch trig. Grab yourself the fastnoise library and sample that

#

Unless you're creating something more dynamic like ocean waves, it's not likely you're creating something structured purely on trig functions

visual linden
#

Also, if it's enough for your needs, MapMagic is free on the assetstore and is incredible for generating procedural terrain

rigid swallow
#

what does the ":" mean in this line of code?

teal viper
rigid swallow
#

oh ok

#

thanks

queen adder
frosty cargo
#

okay, so im following a tutorial, and i have an issue, and i dunno how to fix it.

dusty nimbus
#

Your script name is still 'NewBehaviourScript' - change it to PlayerController and you should be fine ^

hexed terrace
#

Your visual studio isn't setup correctly either

#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

hexed terrace
frosty cargo
#

i fixed it

dusty nimbus
frosty cargo
#

it works now

hexed terrace
#

Still, setup your VS properly

frosty cargo
#

what did i do wrong?

hexed terrace
#

you didn't do what is needed

#

see bot msg

#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

frosty cargo
#

oh yeah i was wondering why it wasnt autocompleting like in the vid

stark ingot
#

Could someone help me figure out my variable isn't incrementing? It looks like it should to me, but it's not for some reason

rich ice
#

!code also you're setting i to 0 in update

slender nymph
#

uh oh, did the bot die again

rich ice
#

huh, is dyno taking the day off

queen adder
#

It's online

eternal needle
stark ingot
#

I think I have that on, since I installed it with Unity Hub

wicked cairn
#

Is there a way to verify a dll plugin is loaded with the game launch, I dont mean using a if statement to check if the file is there. I mean a official way to verify it

eternal needle
frosty cargo
#

uuh i think i still did visual studio wrong

#

pretty sure its supposed to be helpful

stark ingot
eternal needle
eternal needle
#

follow the steps linked

stark ingot
eternal needle
stark ingot
#

I did that, but it's still not working and I'm not sure why

frosty cargo
echo ruin
#

You moved the i = 0; out of update?

slender nymph
stark ingot
frosty cargo
#

okay sorry

eternal needle
#

and also as a reminder to people

rich ice
slender nymph
#

that will just cause them to ignore the instructions to configure their ide so they just come back with further problems and unconfigured tools

stark ingot
#

Doesn't this mean it's configured..?

slender nymph
#

that is one step of the process

eternal needle
eternal needle
#

If you have problems with a specific step then thats fine to ask, but your question clearly shows you didnt even read the page

stark ingot
#

Apologizes. I just went through it all and everything says it's fully updated

#

Is there more that I'm missing..?

slender nymph
hexed terrace
#

No, it's not the correct place. This is a code channel, and that isn't code related. Delete it all and post in #📱┃mobile

slender nymph
#

and ideally post it as one message instead of 4

ebon marsh
#

hello i have a problem with my movement script code, since it is my first time i copied a game from a youtube video and i did all the steps he did and my code is the exact same but i get errors when i try to start the game

slender nymph
#

share the relevant errors and !code

slender nymph
ebon marsh
#

wait ill send it now

rich ice
ebon marsh
rich ice
rich ice
# ebon marsh

make that a vector2 and remove the z axis (the last part of it)

#

you're using a rigidbody2d. that's a 3 dimensional vector. cant have 3d velocity for a 2d object

ebon marsh
#

I changed it and there are no errors but i still cant move the player

#

do i need to add something else?

slender nymph
#

have you configured visual studio yet

ebon marsh
#

oh ill try it

rich ice
ebon marsh
#

yup

#

im trying to configure it i think thats the problem

slender nymph
#

that is not related to your issue, but it is a requirement for getting help here

rich ice
ebon marsh
#

oh ok

#

which guide should i choose

#

i had visual studio installed before i even tried unity for school

rich ice
#

installed manually

rich ice
# ebon marsh yup

try turning off gravity on the object, temporarily. it could be moving slowly due to friction

stark ingot
#

This might be really stupid question, but I'm trying to get a square to lerp across four points infinitely. For some reason, it's teleporting from the last point to the first point. It's getting to the reset point I made, but it's not resetting itself so it doesn't teleport. Here's the code: (it's mainly the last if statement) https://paste.mod.gg/oobojukmsbyc/0

rich ice
ebon marsh
#

it seems i have deleted my visual studio installer can i do these steps in the app as well

#

never mind

stark ingot
ebon marsh
#

im just stupid i found the other steps

slender nymph
rich ice
slender nymph
#

also because the first parameter of Lerp is the starting point and when you reach the end of the array you reset so the starting point is the beginning of the array again you will always teleport back to that point and move to the next one.
Consider restructuring a bit, you could instead use MoveTowards rather than Lerp with a constant speed, and use the current position as the first parameter and the target from the array as the next, then when you reach the target change the target to be the next one in the array

stark ingot
#

My professor made this assignment to practice using Lerp or Slerp, so I have a good hunch he wouldn't like it if I used something else sadly

slender nymph
#

or just keep track of what the current point is and what the target is in separate variables instead of using a single int i since you are much more limited that way with your current setup

slender nymph
stark ingot
#

Is the rate for Lerp not its speed..?

slender nymph
polar acorn
stark ingot
#

Oh I see

ebon marsh
#

yo i fixed the problem

#

as soon as i installed the extension it magically works

#

thanks for help

eternal needle
# stark ingot Is the rate for Lerp not its speed..?

not too sure if you solved the problem above, but usually in this setup you'd want to keep track of how long you actually want it to take between objects. That "how long it takes" being used as the 3rd parameter in your lerp like T= (currentTime/totalDuration)
right now your rate would be 100 frames which is not a good thing. 100 frames could be 1 second for someone, or 5 seconds for someone else

stark ingot
#

I'm still trying and failing at fixing this, but how would you keep track of that sort of thing..? I don't think I've learned how to do that yet

rich ice
eternal needle
#

then your 3rd lerp paramter is currentTime/totalDuration since its a normalized value, between 0 and 1

dark laurel
#

"why use many word when few work" is absolutely true when programming - the less code you have, the easier it'll be to find issues

stark ingot
#

I already change it to

if (i + 1 > 4)
dark laurel
#

even this is "non-idiomatic" and hard to read

#
if (i >= 4)

is much better

#

whenever you add something to a variable - you're usually indicating that you want to change that variable - conditional statements should have as little logic as possible in them so they read like english

#

we wouldn't say "if i plus one is more than 4" we would say "if i is more than 5"

eternal needle
#

not jordan, thats exactly why sharping says this is non-idiomatic. its not completely obvious at first glance

stark ingot
#

I figured since i + 1 is the end position, you'd add one to double check if it's at said end position, no?

dark laurel
#

yes, but it's a question of readability

#

you want to make your code as absolutely close to english as possible so bugs pop out

stark ingot
dark laurel
#

yes

stark ingot
#

Got it

#

Sorry, I'm very tired

winter echo
dark laurel
stark ingot
#

I would, but I have class in like 15 minutes so I've gotta run

#

I'll be back to ask question in a couple hours though

dark laurel
winter echo
dark laurel
#

oh, it's embedded

rich ice
slender nymph
winter echo
twin pivot
#

ive attachted this script to a button but the MurderParent() method isnt showing up when i try adding it on the when clicked thing

slender nymph
#

do you perhaps see MonoScript in the menu when you go to select a method?

twin pivot
#

yes

slender nymph
twin pivot
#

oh my god im kicking myself

winter echo
twin pivot
#

its not setting the isShopSpawned to false for some reason

eternal needle
twin pivot
rich ice
#

the getScript gameObject does not have the popup script on it

eternal needle
#

you should deal with your errors first normally

twin pivot
polar acorn
eternal aspen
#

When using a box collider for a ground check what is the best way to differentiate a wall from the ground so my player isn't being counted as grounded when jumping up against a wall?

slender nymph
#

use a physics query instead of relying on collision/trigger messages and make the query only just large enough to determine if the object is grounded and not so large that it would be considered grounded when just next to ground/wall

slender nymph
#

yes, or really any shape cast you need. and if you don't need info like the normal of the surface you are on then a simple Overlap(Shape) will suffice

eternal aspen
timber tide
#

And keep the setup you got there^

#

I don't mind the collision methods, but I like having it all in update/fixed so I can structure out the events orderly

eternal aspen
timber tide
#
public int Overlap(Vector2 position, float angle, ContactFilter2D contactFilter, List<Collider2D> results); ```
Check that one
#

Actually one at the bottom:

public int Overlap(ContactFilter2D contactFilter, Collider2D[] results); ```
#

Can use a filter, or grab every object and cycle through it. Filters nice though if you only care about the floor and stuff like that

eternal aspen
#

I am a bit confused haha. I am a newbie programmer.

timber tide
eternal aspen
#

I have the ground layer mask set.

timber tide
#

public class Character : Monobehaviour
{
  [SerializeField] private LayerMask groundLayersToDetect;
  Collider2D[] groundResults = new Collider2D[10];
  ContactFilter2D groundFilter = new ContactFilter2D();

  private void Awake()
  {
    groundFilter.SetLayerMask(groundLayersToDetect);
  }

  private void FixedUpdate()
  {
    int count = Physics2D.OverlapCollider(groundFilter, groundResults);

    for (int i = 0; i < count; i++)
    {
      if(groundResults[i].TryGetComponent(out Enemy enemy)
      {
        //Your feet hit an enemy
        break;
      }

      if(groundResults[i].TryGetComponent(out Terrain terrain)
      {
        //Your feet hit terrain
        break;
      }
    }
  }
}
#

something like that

#

I think that's how the filter works. Been a minute

stark ingot
#

I'm trying to have a square lerp to four points infinitely in circle of sorts. At the moment, it goes to all the points, but when it goes from the last point back to the beginning the square teleports and I can't figure out why. Any assistance would be greatly appreciated, here's the code: https://paste.mod.gg/qpiqiashwfex/0

slender nymph
stark ingot
#

I tried doing that and instead of moving smoothly, it teleported to all the points for some reason

slender nymph
#

show what you actually tried then

stark ingot
#
void Update()
{
    Transform[] array = { One, Two, Three, Four };

    rate += 0.01f;

    if (rate < 1) //if it's not at the end yet
    {
        transform.position = Vector3.Lerp(array[start].position, array[end].position, rate);
    }
    else //it's at the end, so reset everything
    {
        start++;
        end++;
        rate = 0;
        if (start > 3) //if it's at the final point, reset i
        {
            start = 0;
        }
        if (end > 3)
        {
            end = 0;
        }
    }
}
slender nymph
#

well you're still using the wrong t value. but what are the values of start and end

stark ingot
#

The time is confusing me slightly

#

Start and end both start at zero

slender nymph
#

instead of adding 0.01f just add Time.deltaTime (assuming you want it to take about 1 second to reach each point)

slender nymph
#

that would mean start and end are the same

stark ingot
#

How would you separate them, though..? Since they increase at the same time

#

That might be a really stupid question, I'm very tired

slender nymph
#

think about it for a second. how far apart (in terms of index) should they be?

stark ingot
#

A delay of one, right?

slender nymph
#

like if start is 0, what should end be in order to be the desired point

stark ingot
#

Would it be 4..? For the 4th position in the array..?

#

I feel like that's wrong though

#

Or would it be 1 already?

slender nymph
#

because it is wrong. if start is 0, meaning the first point in the array, what should end be? remember, end is not the end of the array, it is just named confusingly but is the desired target position of the lerp

stark ingot
#

Then it'd be 1, right? Since 1 is the second point in the array

#

I think..?

slender nymph
#

right

#

so end should always be 1 greater than start (with the exception of when it loops back around to the beginning)

stark ingot
#

It's finally working, thank you

slender nymph
#

now as for this code:

if (start > 3) //if it's at the final point, reset i
{
    start = 0;
}
if (end > 3)
{
    end = 0;
}

because you are no longer needing to check if you are at the second to last position, this is incorrect. and can also be simplified (and made better).
so rather than hard coding the last number, you should instead use the length of the array so you don't have to change the number if you decide to add or remove elements of the array.
you can also use the % operator to properly loop it instead of hard coding the loop. so like start++; start %= array.Length; would correctly loop it once it reaches the end of the array

#

of course you can also extract that bit out as a method and use local variable instead of field and just return the new value, that would then allow you to use the method in place of a second variable

rocky canyon
#

how would i go about creating something similar to this in script?
also not exactly sure where to post..
I see the BackInOut and kinda now think i could do it with some tweening libraries..
but im more interested in how its broken up.. are there two spheres? do u tween each one to get different "effects" .. you think its using any type of masking?
and would i use math and use the radius? or perhaps just rotate a GO w/ an offset instead?

#

any insight would be appreciated 🙏

slender nymph
stark ingot
#

So Time.deltaTime can replace the rate?

slender nymph
#

it would replace your hard coded 0.01f since that would vary the time it takes based on the framerate

#

using Time.deltaTime the way i am would make the lerp take exactly 1 second no matter what the framerate is

gleaming kraken
slender nymph
#

you could also divide deltaTime by the desired number of seconds you want it to take in order to change how fast the lerp happens

stark ingot
#

Good to know, thank you

cosmic dagger
rocky canyon
woven kraken
#

What is thr code for walking and jumping and turning and running?

slender nymph
#

there are dozens, if not hundreds, of movement tutorials for unity. take your pick of the lot and follow it

woven kraken
#

Ok

gleaming kraken
rocky canyon
idle cove
#

iam new to unity coding and i encountered a problem but I couldnt find a solution, should i text here ?

rocky canyon
#

indeed

idle cove
#

like going from here to there and from there to there in the hospital

#

the problem is that when there are 2 people the scene does not change even though the game start button is clicked

slender nymph
#

!code

idle cove
slender nymph
#

if the bot were alive it would have posted the message i linked to

idle cove
#

r.i.p then

slender nymph
#

yeah well click the link to see how to correctly post code in this server

astral falcon
true olive
#

Man.. Im stumped on my issue :/ Been trying to solve like 12 hours at this point

idle cove
#

bro i just want fix my code not how to text code in discord

slender nymph
idle cove
#

just click expand button, if youre not smart enough to do that i guess you cant help anyway.

lethal smelt
#

...he's got a point

sour fulcrum
#

no

lethal smelt
slender nymph
rich adder
#

Imagine asking for help then insult and make it a hassle for others to help..

slender nymph
#

We have code sharing guidelines for a reason. Follow them or don't get help 🤷‍♂️

sour fulcrum
#

smh what are they not paying you for

grand snow
#

"i demand results right now in this channel for beginners!!!"

last radish
slender nymph
last radish
#

oh my bad used the wrong channel

#

what do i do in that case?

#

im using urp

spare mountain
last radish
#

okie dokie will send my message there

#

thanks

robust willow
#

I have a script for generating a mesh of a circle below an object. It currently is generating the mesh not below the object. it is either off to the side, below, or above the object depending on which object it is.

twin pivot
true olive
# thorn holly What is it

Hey. Sorry I ended up just outsurcing the help on fiverr. I was getting frustrated with whats probably simple solution, but I'll find out I guess. I was trying a new concept with 4d movement in a 2d game with jumping so I could do air states off player state machines. But, I just couldnmt get terrain to work with the gravity scale being need on my player and colliders seeming wonky and my paperdoll was messed up too so I just got help that way. Ill see solvent and build and expand I suppose, but thanks anyway

thorn holly
#

Alrighty

true olive
#

I spent so many hours trying lmao

#

Thankyou though!

thorn holly
#

Yeah

grand snow
#

well first time ive heard someone do this

robust willow
gleaming kraken
#

need some help. Trying to reflect a raycast manually, but i'm running into some issues:

(ignore the errors, I had a stack overflow due to setting the raycast length too high initially)

for some reason, after it reflects, it still raycasts the original ray, so rather than move on to a new one it just keeps on hitting the floor over and over again and only reflecting that. (At least I think that's what happening). What is a simple way to stop this behavior?

relatively basic script attached

teal viper
gleaming kraken
winter echo
#

https://paste.mod.gg/ here is the code he keep when i press the R button it get stuck when i press trigger in the animator its fine idk what to do i spent like 3 hrs idk what the problem

teal viper
gleaming kraken
#

my new issue here is that since draw gizmos happens every frame, i don't have a chance to see it

#

any clue on how I might overcome this?

gleaming kraken
# teal viper Wdym by that?

basically, the bounce only appears for 7 frames before the OnGizmosDrawn() function is called again, which resets the bounce to default I believe?

#

but that doesn't really make sense

#

it would just stay at the end

#

i've got to be doing something wrong here

teal viper
teal viper
winter echo
#

sorry

gleaming kraken
winter echo
#

give me a sec

teal viper
# gleaming kraken hyg
  1. You still seem to have an error in the console.
  2. Collapsing the logs makes them basically useless, as we don't know what's happening during each frame.
gleaming kraken
teal viper
winter echo
#

when i press R its start to loop when i jump and start move in his place

teal viper
# winter echo

Ah okay.

  1. You should be looking at the parameters tab in the animator when the issue happens.
  2. You should check the conditions of the transitions between the animator states.
  3. Log to the console whenever the parameters relevant to the conditions are set in the code.
  4. When you can confirm that your code keeps on setting parameters indefinitely, look at the relevant code and see why it runs when it shouldn't.
gleaming kraken
#

there you go, same code but just not collapsed

winter echo
#

in the perameters when i hit trigger its works normaly but when i but an input it gose wild

teal viper
winter echo
#

the console is clean af

teal viper
# gleaming kraken

Also, what I recommend is starting the game paused, then stepping one frame, so that we only have logs for one frame.

gleaming kraken
gleaming kraken
teal viper
teal viper
# gleaming kraken

Okay, so unless we're missing some logs(because they move too quick), it seems like only the ground is hit.🤷‍♂️

gleaming kraken
#

yeah this is a bit tricky, I'm probably just doing something wrong

teal viper
#

Share the updated code.

teal viper
#

Yeah, it's likely that your math is producing weird results. Trying to figure it to visualize what it does, make my head hurt.

#

But positions being mixed with directions in a dot product would usually mean you're doing something wrong.

gleaming kraken
gleaming kraken
#

the issue was with my math

winter echo
acoustic belfry
#

btw there's no other way for make the script wait/delay apart of using the timer, coroutines?

#

like a more simplier way?

#

or a way that uses animation clips maybe?

teal viper
timber tide
#

invoke when you just can't be bothered

#

yeah coroutines are nice. I do find them to feel bulky when you just wanna pause execution till next frame

#

ends up turning all my methods into enumerators

winter echo
#

what the error iam confuised

teal viper
celest jay
#

Anyone else experiencing this?

acoustic belfry
acoustic belfry
# teal viper There's async

How does that works?
I mean, timers are simple, but i dont want to fill up my code with values only everytime i want it to wait a sec

true olive
#

Also one time I tried downloading codemaid and color semantics and had to disable them both in my VS or it wouldnt load older scripts. Wonky sometimes

eternal needle
teal viper
# acoustic belfry How does that works? I mean, timers are simple, but i dont want to fill up my co...

Then Invoke would do what you want. If you want a bit more sophisticated system, you could write a manager script that executes a delegate after the desired time. The script itself could use any of the mentioned solutions, but it would help simplify your code where you actually need a delay. You'd just need to TimedExecutionManager.RunAfterDelay(MethodToRun, 5f);.

Also, I'd disagree about async. While the way it works is indeed way more complicated than a timer and you need to know how it works to avoid exploding your project, once you know it, writing simple delays and other delayed/async logic becomes very simple:

async void MethodWithDelay()
{
  await Task.Delay(delayTime);
  //actual logic after the delay
}

I'm writing from memory, so some syntax or api might be slightly wrong.

mystic ferry
#

I'm so confused. This has worked perfectly since I wrote it but all of a sudden it's doing whatever this is. I have not edited the object or the script. Last things I did on the project were completely unrelated. I will send some code.

fair crane
#
void Update()
{
    transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
    if (transform.position.y <= 1)
    {
        transform.position = new Vector3(transform.position.x, transform.position.y + bounce, transform.position.z) ;
    }
    else
    {
        transform.position = new Vector3(transform.position.x, transform.position.y - bounce, transform.position.z);
    }
}
#

so i did this
but the object bounces very fast
and if i multiply with delta time, it doesnt bounce anymore

eternal falconBOT
mystic ferry
#

The weapon script.

#

Hierarchy setup if it matters.

acoustic belfry
#

hey, in a 2D game what's the easiest way to make that the enemy slighty moves to the contrary side it got hit by a missle or a melee?

thorn holly
thorn holly
#

Mostly depends on how ur games set up

#

For example, if the missile explodes, just make it find the vector from the center of the explosion to the enemy, then apply that vector onto the enemy, decreasing its force based on how far away the two points are from each other

mystic ferry
naive pawn
fair crane
#

yes. thats the problem

#

i want it to oscillate slowly

#

like coins

naive pawn
#

bouncing is a damped.. well, not really an oscillator

#

but yeah you usually don't add bounce

#

you multiply an existing speed by a bounce

#

why the <=1 check?

fair crane
#

if the object goes below y = 1 i add some value to it

naive pawn
#

also have you considered using physics to handle it?

fair crane
#

so it starts to go up

naive pawn
fair crane
#

okay

#

so what changes should i make

naive pawn
#

first off, what exactly are you trying to achieve

#

and how does y=1 relate to it

fair crane
#

coins in a game which oscillate up and down as well as rotate

naive pawn
#

do you want them to oscillate or bounce

fair crane
#

yes oscillate

naive pawn
#

as, say, a sine wave?

fair crane
#

yes

naive pawn
#

then use that

#

Mathf.Sin(Time.time * frequency * 2 * Mathf.PI), perhaps

fair crane
#

 private float bounce = 50f;
 private float speed = 50f;
 // Update is called once per frame
 void Update()
 {
     transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
     if (transform.position.y <= 1)
     {
         transform.position = new Vector3(transform.position.x, (Mathf.Sin(Time.time * speed))*bounce, transform.position.z) ;
     }
     else
     {
         transform.position = new Vector3(transform.position.x, (Mathf.Sin(Time.time * speed))*bounce, transform.position.z);
     }
naive pawn
#

you wouldn't check for the y position

fair crane
naive pawn
#

although, that'll make all your coins oscillate in sync, which may not be the effect you want

naive pawn
#

there's no condtional here

#

sin already goes from positive to negative and back

#

Sin gives a value in the range [-1, 1]
if you want to scale or move that range, you can multiply or add to it

fair crane
#

can i oscillate the object in the range [0,1]

#

how would i do this

rich ice
#

absolute or clamp the value

#

probably absolute if you're trying to make it bounce

fair crane
#

okay

#

thank you very much

naive pawn
naive pawn
fair crane
vital helm
#

i have a gameObject with 2 children that has a trigger, how can i check each trigger separately with a script in the parent?

vital helm
#

hello, anyone know how to. Or are there any work around

ivory bobcat
#

Why not have the scripts on the children?

vital helm
#

because

#

wait your right

#

god how did i not think of that at all

lofty kelp
#

does anyone know if its possible to make a 2d movement input without any limits on speed (i dont know where to put it)

lofty kelp
#

and i want an uncapped movement speed

vital helm
lofty kelp
#

yes

#

you know titanfall?

#

that kinda movement but instead in 2d

#

theres a capped movement speed with wasd BUT there are ways to gain speed and using those ways the speed isnt capped

vital helm
#

AddForce?

lofty kelp
#

ion know

#

im really new

#

its kinda like gernade jumping in titanfall 2

rich ice
#

probably best to atleast !learn the basics before you try recreating mechanics

eternal falconBOT
#

:teacher: Unity Learn ↗

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

lofty kelp
#

but it was an example

#

but sure

lofty kelp
slate roost
#

Hey currently my jump height in a 2d platformer I'm making seems to be dependant on framerate, with a lower framerate causing the player to not be able to jump as high
how can I correct this?

lofty kelp
#

thankyou

slate roost
#

I know I should use Time.deltaTime somewhere, but I'm not sure where to insert this

vital helm
#

use LinearVelocity

brazen cedar
#

my car is not moving what is wrong

slate roost
#
    public void Move(Vector2 velocity, Vector2 input, bool standingOnPlatform = false, bool dashing = false)
    {
        if (player == null)
            player = GetComponent<Player>();
        UpdateRaycastOrigins();
        collisions.Reset();
        collisions.velocityOld = velocity;
        playerInput = input;
        if (velocity.y < 0)
            DescendSlope(ref velocity);
        if (velocity.x != 0)
            collisions.faceDirection = (int)Mathf.Sign(velocity.x);
        HorizontalCollisions(ref velocity);
        if (velocity.y != 0 || player.isRolling)
            VerticalCollisions(ref velocity);
        if (player.isDashing)
            DashingVerticalCheck(ref velocity);
        if (player.isRolling)
            RollingEdgeCheck(ref velocity);
        if (velocity.x != float.NaN)
            transform.Translate(velocity);
        else
            Debug.Log("wtf went wrong");
        if (standingOnPlatform)
            collisions.below = true;
    }

This is the bulk of my movement, which runs in update
(forgive my gross usage of if statements, this is one of the earliest working scripts I made)

        if (!motionLocked)
                controller2D.Move(velocity * Time.deltaTime, input);

noticed I am actually already doing this, but I still have the issue of jump height being frame dependant... any idea how to fix this?

brazen cedar
#

i already copy the code from a youtube video but it will not work when i press W

wintry quarry
wintry quarry
slate roost
#

I will not terrorize you with my awful player script, its kind of terrible and bloated, but I know what parts are invovled in movement

someday I will refactor

#

what context am I missing that would help?

wintry quarry
#

the rest of the code

brazen cedar
eternal falconBOT
brazen cedar
wintry quarry
novel nymph
#
    void Start()
    {
        mouseSensitivity = PlayerPrefs.GetFloat("currentSensitivity", 100);
        slider.value = mouseSensitivity / 10;
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        PlayerPrefs.SetFloat("currentSensitivity", mouseSensitivity);
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }

    public void AdjustSpeed(float newSpeed)
    {
        mouseSensitivity = newSpeed * 10;
    }

I know this question is asked a lot and I am pretty sure it has to do with delta time but when I play my game, the camera snaps to positions and if very glitchy.

wintry quarry
brazen cedar
#

what

wintry quarry
wintry quarry
novel nymph
wintry quarry
#

just the sensitivity value, as you are already doing.

brazen cedar
wintry quarry
brazen cedar
#

ok

#

here the first side

wintry quarry
#

!code

eternal falconBOT
novel nymph
brazen cedar
wintry quarry
wintry quarry
#

Use a paste site

brazen cedar
#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CarController : MonoBehaviour
{
private float horizontalInput, verticalInput;
private float currentSteerAngle, currentbreakForce;
private bool isBreaking;

// Settings
[SerializeField] private float motorForce, breakForce, maxSteerAngle;

// Wheel Colliders
[SerializeField] private WheelCollider frontLeftWheelCollider, frontRightWheelCollider;
[SerializeField] private WheelCollider rearLeftWheelCollider, rearRightWheelCollider;

// Wheels
[SerializeField] private Transform frontLeftWheelTransform, frontRightWheelTransform;
[SerializeField] private Transform rearLeftWheelTransform, rearRightWheelTransform;

private void FixedUpdate()
{
    GetInput();
    HandleMotor();
    HandleSteering();
    UpdateWheels();
}

private void GetInput()
{
    // Steering Input
    horizontalInput = Input.GetAxis("Horizontal");

    // Acceleration Input
    verticalInput = Input.GetAxis("Vertical");

    // Breaking Input
    isBreaking = Input.GetKey(KeyCode.Space);
wintry quarry
#

Use a paste site

#

As I linked above.

brazen cedar
#

private void HandleMotor()
{
frontLeftWheelCollider.motorTorque = verticalInput * motorForce;
frontRightWheelCollider.motorTorque = verticalInput * motorForce;
currentbreakForce = isBreaking ? breakForce : 0f;
ApplyBreaking();
}

private void ApplyBreaking()
{
    frontRightWheelCollider.brakeTorque = currentbreakForce;
    frontLeftWheelCollider.brakeTorque = currentbreakForce;
    rearLeftWheelCollider.brakeTorque = currentbreakForce;
    rearRightWheelCollider.brakeTorque = currentbreakForce;
}

private void HandleSteering()
{
    currentSteerAngle = maxSteerAngle * horizontalInput;
    frontLeftWheelCollider.steerAngle = currentSteerAngle;
    frontRightWheelCollider.steerAngle = currentSteerAngle;
}

private void UpdateWheels()
{
    UpdateSingleWheel(frontLeftWheelCollider, frontLeftWheelTransform);
    UpdateSingleWheel(frontRightWheelCollider, frontRightWheelTransform);
    UpdateSingleWheel(rearRightWheelCollider, rearRightWheelTransform);
    UpdateSingleWheel(rearLeftWheelCollider, rearLeftWheelTransform);
}

private void UpdateSingleWheel(WheelCollider wheelCollider, Transform wheelTransform)
{
    Vector3 pos;
    Quaternion rot;
    wheelCollider.GetWorldPose(out pos, out rot);
    wheelTransform.rotation = rot;
    wheelTransform.position = pos;
}

}

wintry quarry
#

buddy

#

please read

brazen cedar
#

ok

#

from there how do i bring the code here

wintry quarry
#

share the link

brazen cedar
#

how

wintry quarry
#

copy and paste it?

#

I don't even know which site you're using so, hard to answer specifically

#

They will all have a way to share a link

brazen cedar
#

i am in the BLazeBin site

wintry quarry
#

press save

#

and share the link

brazen cedar
#

i have press save the problem is sharing the link is it from file

wintry quarry
#

Copy and paste the link

#

from your browser

#

from the address bar...

brazen cedar
wintry quarry
#

lol wtf

#

JUST SHARE THE LINK

rich ice
#

did you download the site and then try to paste it in chat... how do you even do that HUH

novel nymph
wintry quarry
#

because that's where it matters

#

it should be around 1 or so

brazen cedar
wintry quarry
#

this has to be a troll

#

you just linked the empty site

novel nymph
brazen cedar
#

i did not

wintry quarry
brazen cedar
#

what

#

you said i should copy it

wintry quarry
#

Yes

#

press save

#

then copy it

brazen cedar
#

how do i do that

wintry quarry
#

with your mouse

brazen cedar
#

where is the button located

wintry quarry
#

I'm sure you can ffind it

#

it's not hidden

#

anyway I need to sleep soon

brazen cedar
#

ok

novel nymph
brazen cedar
#

can you screen shot it pls

rich ice
eternal falconBOT
brazen cedar
#

here

wintry quarry
#

what did you change the sensitivity to

#

and what does your code look like

#

(i blocked the troll)

novel nymph
#

I tried 1 and .001

wintry quarry
#

Which variable did you change

rich ice
wintry quarry
#

and are you talking about in the inspector

novel nymph
#

The inspectors mouse sensitivity

wintry quarry
slate roost
# wintry quarry the rest of the code

heres the controller2D script:
https://pastebin.com/rtdn8vSt

and the relevant parts of the player script:
https://pastebin.com/c4ZQSF1M

velocity is multiplied by Time.deltaTime just before its sent over to the controller2D script
and to recap, my problem is that my jump height is framerate dependent

wintry quarry
#

Your code is reading sensitivity from PlayerPrefs

#

so even changing it in the inspector won't help

brazen cedar
wintry quarry
#

you need to clear what you set in player prefs

#

or get rid of that line that loads it from there

brazen cedar
#

i have sent it

rich ice
novel nymph
wintry quarry
brazen cedar
#

ok

novel nymph
wintry quarry
#

just comment out the line that reads it from playerprefs for now

brazen cedar
#

so is the code correct

rich ice
brazen cedar
slate roost
#

also a quick showcase of the issue
first I jump normally, then I throttle my framerate and try jumping, and I just can't go as high

brazen cedar
rich ice
#

stop spamming links

brazen cedar
rich ice
brazen cedar
#

no no is my code correct to make a car move

wintry quarry
rich ice
#

ok im too tired for this. just read this

slate roost
wintry quarry
#

but yes if you are basing it off how long the player holds the button down or something that can be an issue

slate roost
#

yes, as I said, its a mess 😛

wintry quarry
#

like velocity.y += maxJumpVelocity; is happening each frame?

#

In some circumstances

slate roost
#

yea, because the jump height is variable, you can end the jump earlier by releasing the button early

wintry quarry
#

but if you're adding a value each frame

#

you need to moderate that with deltaTime

brazen cedar
#

umm hello

wintry quarry
#

otherwise it will be framerate dependent

brazen cedar
#

i steel need help i have the link

slate roost
#

isn't that already being handled later in the code when I do velocity * Time.delaTime?

wintry quarry
#

unless that's a one-off thing. Hard to tell with the logic.

wintry quarry
#

but the rate at which you change velocity (accelerate) also needs that adjustment

#

assuming i'm reading this right that it's actually going to add that every frame

#

it seems weird you would add something called maxJumpVelocity each frame but I can't tell

brazen cedar
#

HELLLOOO😟😟😟😟😟😟😟

slate roost
#

hmm, I think I understand the concept

naive pawn
rich ice
brazen cedar
brazen cedar
rich ice
#

there's a full guide there on how to use it and the code is already written

naive pawn
brazen cedar
slate roost
rich ice
eternal falconBOT
#

:teacher: Unity Learn ↗

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

naive pawn
naive pawn
#

you need to calm down

wintry quarry
# slate roost ooh what you're looking at is a special case for moving up slopes and jumping at...

you're setting y to the max velocity each frame then right?
Witha slower framerate you will:

  • have potentially more error between when the button is released and the next frame comes - meaning it will move up higher
  • more inter-frame error with longer frames that means more distance travelled.

Really there is a good reason the physics engine uses a fixed timestep - it's to avoid issues like this

naive pawn
brazen cedar
#

🙄

naive pawn
#

this is a semi-professional space, please act civilly

brazen cedar
#

ooooh well i thought discord will help me

naive pawn
#

we can't help you when you don't let us

slate roost
naive pawn
#

jordan gave you resources already

#

spamming won't get you anywhere

#

help is a 2-way street

slate roost
#

the gravity and all movement for my character goes through that controller2D script
I feed it velocity values, and it figures out where my player should be on the next frame

wintry quarry
brazen cedar
wintry quarry
#

there's nothing fundamentally different about what you're doing than what the physics engine does

slate roost
#

oh I get what you mean

#

should my movement also be in fixed update then?

wintry quarry
#

That would be an easy way to get a fixed timestep

rich ice
wintry quarry
#

you would then need to implement visual interpolation if you want the movement to appear buttery smooth though

#

alternatively - you switch to a Rigidbody which has built-in interpolation available

slate roost
#

the problem is my inputs should stay in update right?
I dont know how to handle the timing between pressing the button in update and doing the movement in fixed update

naive pawn
# brazen cedar what else do you want me to do
  1. stop spamming here and go read the resources jordan mentioned (unity learn (at least unity essentials) & wheel colliders)
  2. if you still have problems, give the necessary info for us to help you (ie, what you're trying to do, what issue you're encountering, and relevant context and info, like code shared appropriately) without spamming.
wintry quarry
slate roost
#

hmm, I guess I'm already doing that with the jumpBuffer

#

it is intent to jump, as long as the buffer is >0

#

so if my movement is in fixed update, should I still be multiplying the velocity by Time.deltaTime?

wintry quarry
#

yes

#

although inside FixedUpdate, deltaTime takes on the value of fixedDeltaTime automatically

slate roost
#

good to know

slate roost
#

aah i think I may have found the root of my problem

    private void Start()
    {
        meleeAttacks = GetComponent<MeleeAttacks>();
        dissolve = GetComponentInChildren<Dissolve>();
        controller2D = GetComponent<Controller2D>();
        playerSprite = GetComponent<SpriteRenderer>();
        source = GetComponent<AudioSource>();
        stats.currentHP = stats.maxHP;
        stats.currentMP = stats.maxMP;
        EventMaster.TriggerEvent("SetMaxHPMP");
        //e_setMaxHPMP.Invoke();
        coyoteTime = Time.unscaledDeltaTime * coyoteTimeFrames;
        gravity = -(2 * maxJumpHeight) / Mathf.Pow(timeToJumpApex, 2); //g = -a2 / b^2
        maxJumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
        minJumpVelocity = Mathf.Sqrt(2 * Mathf.Abs(gravity) * minJumpHeight);
        airborneTimer = 0;
        airDashRemaining = stats.airDashMax;
        manaRegen = stats.manaRegen;
        playerState = PStates.idle;
    }```

I'm defining a bunch of gravity variables in start, and then not adjusting them ever, even if the framerate changes
naive pawn
#

that's not an issue

slate roost
#

but my timeToJumpApex I think is the issue specifically

#

cause that timing changes depending on the framerate, but my code doesn't account for that

naive pawn
naive pawn
#

coyoteTime could have issues, but that's easily solvable by just defining it as time instead of frame count

slate roost
#

well I think I have to call it a night for now
I'll probably try and tackle this some more tomorrow
its been a long standing issue that my jump height is weird at different framerates, and I realyl want to pin down a fix

quasi hinge
#

hey guys I'm making a game and i have this problem where when i damage multiple enemies, the damage each one takes get multiplied by that amount, like when i hit 3 enemies, each one takes 3 damage instead of one, I'm using this code, I'd appreciate it if you told me what's the issue, this is the method I use for damaging:

public void DealDamage()
{
Collider2D[] enemies = Physics2D.OverlapCircleAll(attackPoint.position, weaponRange, enemyLayer);

    if (enemies.Length > 0)
    {
        foreach (var enemy in enemies)
        {
            enemy.GetComponent<Enemy_Health>().ChangeHealth(-damage);
            enemy.GetComponent<Enemy_Knockback>().Knockback(transform, knockbackForce, knockbackTime, stunTime);
        }
    }
}
naive pawn
#

you aren't factoring the amount of enemies hit, you'd need to multiply damage by enemies.Length

#

also you don't need that length>0 check. if the list is empty, the foreach will make 0 iterations

quasi hinge
#

wouldn't setting a coroutine on their health fix this problem?

naive pawn
#

that's what you said you wanted though?

#

oh shit wait

quasi hinge
naive pawn
#

im such a dumbass

#

i read the problem as the goal lmao

#

okay scratch what i said to do

quasi hinge
#

lol it's alr

naive pawn
#

how are you calling DealDamage?

quasi hinge
#

i have the animation set on a specific frame and there i deal the damage

vital helm
#

It's okay to use Input.GetKeyDown right?

naive pawn
naive pawn
quasi hinge
#

yeah like an animation event

vital helm
naive pawn
#

that's not what legacy means, no

naive pawn
quasi hinge
#

alright

vital helm
naive pawn
vital helm
#

i find the old one much easier for me

quasi hinge
naive pawn
#

and you put the debug outside of the loop, right?

quasi hinge
#

uh... oops

#

let me try again

naive pawn
#

what happens if you hit some other number?

quasi hinge
#

outside the loop it's only called once

#

so the problem is the damage

#

maybe some kind of collider problem?

#

because the hitboxes are bit messy right now

novel nymph
#

How is there an empty statement?

vital helm
#

this one

novel nymph
#

Yea, I thought it was that but for some reason before, when I deleted it, it said I was using improper syntax.

#

Now it doesn't

vital helm
#

if it works it works ig

naive pawn
blazing prairie
#
    {   
        foreach (var p in m_StoreController.products.all)
        {
            Debug.Log($"Product: {p.definition.id}, Price: {p.metadata.localizedPriceString}");
        }
        if (m_StoreController == null) return "Price Unavailable";
        var product = m_StoreController.products.WithID(productID);
        if (product != null && product.hasReceipt) return product.metadata.localizedPriceString;
        return "Price Unavailable";
    }```  I am using this to fetch prices for my items from google play but its always showing Price Unavailable even though the purhcase is working fine does anyone have any idea how do i fix this ?
naive pawn
#

debug to figure out which of the 2 Price Unavailable results you're getting, then debug to find why the conditions aren't passing as expected

blazing prairie
#

the thing is i am not able to debug in android its working fine in editor

naive pawn
#

ah.

#

well i guess at least do the first part by making the strings slightly different so you're able to differentiate

blazing prairie
#

thats a good idea !

novel nymph
blazing prairie
novel nymph
blazing prairie
#
using System.Collections.Generic;
using UnityEngine;
 
public class Restart : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player")) 
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name);
        }
    }
}```
novel nymph
#

when I remove the ;, it stops working

blazing prairie
#

try this maybe

novel nymph
#

the script that doesnt work is the on you sent, it works if I put the ";" in but then there is an empty statement error

blazing prairie
#

whats the error message in this script ?

novel nymph
#

Possible mistaken empty statement

blazing prairie
#

no in the one withtout ;

#

that i sent

novel nymph
#

There is none, but when I use that one the script doesn't cause the game to restart

blazing prairie
#

adding ; only causes syntax error

#

now we have a logical error i guess

novel nymph
#

for things like these, is it possible to see the specific loation it is talking about?

#

this is from inspect element on the Itch page

rancid tinsel
#

how does "getchild" work in this case? does it take only the surface level children, or nested children too? assuming FaceAccessory is the categoryParent

rich ice
#

hm, weirdly enough, there's nothing on the docs about that. they usually have notes about edgecases like these

#

iirc, getchild doesn't return deep children, might be a good idea to double check though.

echo ruin
#

Pretty sure it only get the first later of children, and not the nested ones

teal viper
#

Also, it would be super confusing API if it was traversing the hierarchy deep.

rancid tinsel
sour fulcrum
rancid tinsel
#

but i could not tell you if i made it up in my head or not

teal viper
#

If you use transform as a collection, it includes the parent as well iirc. That's about the only exception.

rancid tinsel
#

I just learned properties recently, and was experimenting a bit. I'm a little confused on why this doesn't work, could someone explain it to me please?

rich ice
#

you need a backing field

#

stolen from the microsoft docs

private string? _lastName;
public string? LastName
{
    get => _lastName;
    set
    {
        _lastName = value;
        _fullName = null;
    }
}
#

basically, you need a variable above it for the property to refer to

rancid tinsel
#

right I forgot about that

rancid tinsel
#

seems to still throw an error with both solutions

#

I doubt this is at all a good use of properties anyway tbf

rich ice
modest dust
#

Treat a property in a similar way you'd treat a Get/Set method, in most cases

#

First of all, for a static property you need a static backing field

rancid tinsel
modest dust
#

And using Instance within Instance can cause an infinite loop

rancid tinsel
#

right

#

i did do that

quasi hinge
rancid tinsel
#

seems visual studio might be having an issue

ivory bobcat
#

Create an actual field and return/use that type in the getter/setter

rancid tinsel
#

ive got this now but it still has an issue, VS bug or actually unsupported?

modest dust
#

You still didn't implement the getter

#

How is it gonna know what to return

rancid tinsel
#

idk why but i assumed get; automatically does return instance

#

no clue why

#

youre right that was it!

modest dust
#

Treat it the same was as Get/Set methods, as I said

#

Doesn't matter what they do, they gotta do something

rancid tinsel
#

but yeah this works now 🙂 no more error

modest dust
#

A property just looks like a field but is a bunch of methods under the hood, each method separate from each other, needing implementation

earnest wind
#

ask if u have any questions about the variables, im here for solving the bug ;)

#

the 1st video shows the problem, its inverted when camera is down

ivory bobcat
#

You might want to provide a question to be focused on instead of making people try to interpret the unworking condition

earnest wind
#

btw thats only for Z axis, the blue one, so its kinda weird

ivory bobcat
ivory bobcat
#

Invert the behavior is below etc

#

I haven't looked at the code yet.

earnest wind
#

im sorry i think i dont understand cause english is not that good

earnest wind
#

i kinda dont understand what u meant but i think i am already doing that

dense tartan
#

Even though direction is only taken once at the beginning of the coroutine, it's still taking value from input every frame and makes the dash go shorter if the input is released and goes back to zero. What am i doing wrong? thanks

private IEnumerator Dash()
    {
        Vector2 direction = new Vector2(movement.x, movement.y).normalized;
        yield return new WaitForSeconds(0.01f);
        canDash = false;
        isDashing = true;
        stamina -= 25;
        float duration = 0.6f;
        float elapsed = 0.0f;
        Invoke("StunTrigger", 0.6f);
        while (elapsed < duration)
        {
            playerRb.AddForce(direction * _dashpower, ForceMode2D.Impulse);
            elapsed += Time.deltaTime;
            yield return null;
        }
        yield return new WaitForSeconds(1.1f);
        isDashing = false;
        canDash = true;
        isStunned = false;
    }

I've tried adding a bool flag but it also didn't work

ivory bobcat
#

Log the dot value and see if it's an acceptable value. If not, log the projected delta and drag delta

#

Acceptable as in, it's correct relative to what you'd expect

ivory bobcat
hearty glade
#

Hi, help please. Why it won't return false?

rich adder
naive pawn
#

yeah they're obviously false there

#

what are you expecting to get?

hearty glade
#

it returned true. normal value is just 1 but my condition requires 2

rich adder
#

this is never true

naive pawn
#

dict2 has only 1 pair, (Normal, 1)
dict1 contains Normal, so that's true, negated to false
dict1[Normal] is 2, which is greater than 1, so that's also false

hearty glade
#

Thank you so much folks! ❤️

uneven galleon
#

hey

#

@uneven galleon

rich ice
#

schizophrenia

last radish
#

For a csgo esque shooter, should i use rigidbody or a character controller for movement?

naive pawn
#

either works

rich ice
#

do you want consistent movement or physics based movement?

naive pawn
rich ice
last radish
#

Well im not sure if physics based is needed, as there is nothing else than running along a straight ground going on

naive pawn
#

well players can collide with each other, right

#

and with level geometry

last radish
#

i also folloowed and rb movement tutorial, and i cant seem to fix the fact that there is some sliding happening, but i assume thats my problem.

naive pawn
#

most likely yeah

last radish
naive pawn
#

character controller and rigidbody can achieve the same thing, just that charactercontroller gives you more control but also more to do yourself

last radish
#

oh okay, i think ill stick to rb then.

#

but on that note, could you help in fixing the sliding?

naive pawn
#

what's your movement code?

#

!code

eternal falconBOT
elder raptor
#

Did cinemachine's header change from "using Cinemachine;" in Unity 6?

last radish
#
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Movement")]
    public float moveSpeed;

    public float groundDrag;

    [Header("GroundCheck")]
    public float playerHeight;
    public LayerMask whatIsGround;
    bool grounded;

    public Transform orientation;

    float horizontalInput;
    float verticalInput;

    Vector3 moveDirection;

    Rigidbody rb;

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
    }

    private void Update()
    {
        grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);

        MyInput();
        SpeedControl();

        if (grounded)
        {
            rb.linearDamping = groundDrag;
        }

        else
        {
            rb.linearDamping = 0;
        }
    }

    private void FixedUpdate()
    {
        MovePlayer();
    }

    private void MyInput()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");
    }

    private void MovePlayer()
    {
        moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;

        rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
    }

    private void SpeedControl()
    {
        Vector3 flatVel = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);

        if(flatVel.magnitude > moveSpeed)
        {
            Vector3 limitedVel = flatVel.normalized * moveSpeed;
            rb.linearVelocity = new Vector3(limitedVel.x, rb.linearVelocity.y, limitedVel.z);
        }
    }

}

#

i have speed at 5, and drag at 10.

naive pawn
naive pawn
#

have you tried increasing the drag?

last radish
naive pawn
#

you're using forces, so that's going to have some amount of slide

#

sounds like they did that just to avoid an extra acceleration variable lol

last radish
#

okay so essentially find some sweetspot of the drag value where you can move but dont slip and slide at all?

naive pawn
#

it's not an issue, just weird to me

last radish
#

is it possible to completely remove slide? like to the point where its completely unnoticable?

naive pawn
#

if you want an immediate stop, you could just hardcode that in

last radish
#

so like in update() i could add in an if statement that checks whether a key is pressed or not and just put velocity to 0?

#

or how?

naive pawn
#

something like that, might want to separate the axes

last radish
#

yh ill try

naive pawn
#

quick question though; do you want the acceleration? there is an alternative approach that gives direct control

last radish
#

i think direct control would be better

naive pawn
#

you can set the linearVelocity directly to the axes (multiplied by the speed of course)

last radish
#

how?

naive pawn
#

similar to how you did in SpeedControl

#

rb.linearVelocity = new Vector3(speed * horizontalInput * orientation.right, ....)

#

actually you'd need to normalize that

#

or rather clamp the magnitude

#

one sec

elder raptor
naive pawn
#
moveDirection = Vector3.ClampMagnitude(orientation.forward * verticalInput + orientation.right * horizontalInput, 1);
rb.linearVelocity = new Vector3(moveDirection.x * moveSpeed, rb.linearVelocity.y, moveDirection.z * moveSpeed);
```does this make sense to you?
you can move stuff around of course
last radish
#

yeah i think so

naive pawn
#

you could do like, new Vector3(horizontalInput, 0, verticalInput) * orientation.forward * moveSpeed for example

last radish
#

this is exactly what i was looking for thanks

#

it works really well

#

and i understand it

#

thank you so much

#

i have another question though, when im moving around there is some camerabobbing happening, and i have no clue why

#

this may be due to the map or something but idk

#

if you want i can do a screenrecording

thorn holly
#

Sure

last radish
#

how do i send a video if its above 10mb

#

compressing it made it bigger for some reason

naive pawn
#

lmao

#

trim it down to a section that shows what you want it to show

last radish
#

thats been done

#

its 6 seconds long

eternal needle
#

Windows trim sometime makes the file size larger. Use a site to compress it

last radish
#

im on mac but yeah ill try that

eternal needle
#

A 6 second vid shouldnt also be that large of a file size, you can probably adjust the recording output. At least I know u can in OBS

verbal dome
#

Think about it. In the "Z" mode, you are projecting a mouse coordinate onto the camera's forward (or back) axis. Those are completely perpendicular, doesn't make sense

last radish
verbal dome
#

Converting the world X/Y/Z axis to screen space and then doing the dot checks in screen space is probably easier
I recently did a similiar thing for a 3D editor tool

naive pawn
last radish
#

well i made the entire screen the game view so

#

bear with im compressing it