#๐ปโcode-beginner
1 messages ยท Page 431 of 1
so if thats the correct one , which one do you think you should change to make it work?
the script
right
but how
should i maybe replace "text" with the text meshpro iu thing
yorursolution was creating a font wich i dotn care about my problem is that i want to drag my textUI into a script i wrote wich tells me the position of my player when it moves foward and i want to drag it into scoretext but it wont let me sorry for the confusion
not good at explaining things
what in the hell..
how did you even remotely get that from what i sent you..
you're like making stuff up i swear
did you scroll up to the code?
the direct link doesn't work well on the learn site its kinda shite
scroll up to the code part
this seems interesting
I have no idea why it linked that
bruh aint no way
how do i delete my current one
i made
ill copy what u sent me
nvm
mate just change the type from Text to TMP_Pro
nothing else
you're overcomplicating it
at some point you do have to know what a TYPE and what a FIELD is so when i suggest something w /them you know what to do..
I don't understand when to use time.deltaTime and when to use time.fixedDeltaTime. Currently, I'm writing a jump script using velocity and custom gravity, does the gravity force downward need to be multiplied by time.fixedDeltaTime and be in fixedUpdate? Also what about the jump force up?
custom gravity with what?
i'm 95% sure that gravity is in fixed updated, and jump is in a regular function without time.deltatime
with velocity
what
fixedupdate is for physics objects
@rich adder am i removing these
why?
correct?
ermm im using a rigidbody
k i keep
is character controller better?
yeah nevermind it wouldnt make sense to remove it
Time.deltaTime in fixed update just becomes Time.fixedDeltaTime
you dont want to use it on velocity no
MovePosition , yes
AddForce, no
ooh can I ask why?
its already waiting for the Physics frame to move velocity
OHH okay
which is fixed time
Position isnt physics based which is why you use time.deltaTime instead?
youll just end up slowing forces applied them by A lot
no time.deltaTime is used to keep things consistent through different frame rates
its the time between last frame and this frame
mainly so its not frame dependant
so you dont get extreme speeds at higher frame rate
slow at low
ect
so when would I use time.fixedDeltaTIme for example?
yes so take a timer for example without deltaTime ppl with faster fps would drain timer faster in update
If you need to apply some value over fixed time
consistency
legit
i actually have never used fixedtimedeltatime i have zero clue why ๐
Im kindaaa confused still I know that fixedDeltaTime happens over some like 60 frames and is slower but when would you use it and is it just more reliable than time.deltaTime?
when you need it to go with the physics step
instead between frames
they're both consistent
but different
what did you even do
what am I looking at
to do that
exactly whathe told me to do
all i wanted is for that textbox to show the position of my player and now its a mess
what does that have to do with changing the type from Text to TextMeshPro
you did some other shite I have no clue about, its like you assume i have telepathy lol
Practical application of fixedDeltaTime could be inside a coroutine for example, which awaits physics frame and you need to get exact time of the last physics frame.
๐
tell me what does have to do with "Showing Player Position"
cause you're making no sense
nthg
that wont give you the player position
u just told me to do that
@round plover Create threads when posting images. Your posts are completely disjointed
show me where ?
alright sir
You can reuse your old thread for this
its what the code showed
just link it here
yeah but that wont give you the player position
you're going to have to learn how to separate EXAMPLES of usecase, from copying verbatim...
all you had to do was change the type lol
man I dont got time for this
goodluck
whatever ill figure it out
ok then
StatManager.instance.baseHealth -= StatManager.instance.enemyDamage;
is this baseheath-enemy damge or am i dumb bcs it keeps saying its nullrefrenceexeption
why not make this a method?
Whats the difference between AssetBundle.LoadFromMemory_Internal vs AssetBundle.LoadFromMemory?
NRE here means StatManager.instance is null
make sure instance is assigned before you access it
imo you should also make itStatManager.instance.SubtractHealth(enemyDamage)
slight improvement instead accessing the instance twice like that
oh i thought it meant baseHealth was NRE
instance = this on the StatManager script
in start or awake?
A variable is not NRE. A variable can be null. But not if it's just an int or a float
Either you didn't put one in the scene or this other code is simply running before that
huh thats weird, theres no documentation for AssetBundle.LoadFromMemory_Internal unless im blind
im probably blind
So it has to mean that StatManager is = null not the var
in awake I put instance = this
where are you running StatManager.instance.baseHealth -= StatManager.instance.enemyDamage
take a look through this
https://docs.unity3d.com/ScriptReference/30_search.html?q=assetbundle.loadfrommemory
this might be what you need
its red can you see it
pardon?
I typed the code in chat its red
Thanks for your input!
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't see any code you sent no
oh well im running it in a method
i have zero clue why internal isnt on there but idk ๐คทโโ๏ธ
So how am I meant to determine the difference ?
Generally if something has internal in the name, it's meant to not be visible to the user.
yeah no shit..
this
///
public void takeDamage()
{
StatManager.instance.baseHealth -= StatManager.instance.enemyDamage
}
this doesn't help
no context to when and how
an empty object called statManager
is it in the same scene as this?
yes it is
Why are any of those static!? ๐ญ
What could cause assetBundle to be null here tempStream is 100% not null, what else could it be?
i thought thats how you reference other scripts to get the variable
Loaded AssetBundle object or null if failed.
Nope. That is a beginner trap. A really really bad way to do that.
Absolutely ZERO of those make sense as static
Do you know why it might fail?
No I do not use them, just going off the docs 
Great!
uh oh
Where are you getting the bytes from? Show full function?
is GetComponent then the script better
It is ok
A serialized reference is preferred
[SerializeField]
The creator has a negative opinion on DI in game dev. Which I kinda get
I still need to play with DI with Unity lol. It never felt good in unity for some reason
so how would I fix my problem ive been at this for hours
I have only had negative experiences with it
I've often heard the argument that dragging things to the inspector is more or less DI Lite
even just this simple one
https://unity.huh.how/references/simple-dependency-injection
doesn't have to be the DI like usual .net injection
that would be awkward
Can you link to the original issue?
I think most common criticism about DI is creating overly complicated frameworks for it. There's nothing wrong with just initializing references on instantiation by simply passing them at that time through DI method.
https://gdl.space/ujavukerom.cs line 48NRE
Debug.Log the instance before you use it
I need help in importing the Hierarchy from the collaboration
can some one tell me how to do it ?
Show StatManager
What is "the collaboration"
And the hierarchy is part of the scene. Be sure you opened the right one
Yeah thats usually trying to do what normal applications with single entry points would be suited for an easy DI, eg asp.net and alike with Program.cs
Does StatManager actually exist in the scene? (On an object that exists before runtime)
i mean we work together in the same project the files is with him but the hierarchy is not like the one with me it's empty
I'll tell hariedo to get on it
I guess DI gets a little funky once you start doing instantiations, or things that are outside of the "root" structure for the game. Can't word that properly atm since it's super late haha, but things like that.
How are you sharing the project?
yes it does
with unity cloud
yeah this one is perfect for unity, its very good to prepare objects between scenes without really needing many singletons
Remove the StatManager variable from basedeath
Unity Cloud is an array of services..
You mean Unity Version Control which is connected to Unity Cloud?
Then make sure they commit their changes, and you pull them
i am new trying to learn
did that did not fix it
Have you done the unity guide on Unity Version Control?
Did you change the reference on line 48 after?
Its still statmanager
Oh wait, sorry. It was already going through the type
Gotta debug it like Nav said a while ago. Use some logs to see what is going on
yes but still not helpful
i fix it some way
Okay i gotta make everything have a value right because im pretty sure I did that
You need to make sure instance is not null
so what did you do? cause you're not very clear on whats wrong
how do i do that
Do have some in YouTube making every thing clear in term of Genral info
that is prob my problem becuase i have 4 NREs
With logs, like we said
Oh... well what is the FIRST nre?
can you screenshot them
yep
It would have been good to know there were 4
this objects wasn't there with my friend
Did you commit the changes and they pulled them?
no he opened the project different way
Have you changed the scripts since you sent them? Line 9 of the version you sent before is an int initializer
did you actually commit them. and did they pull them .
Then how could he have what you did....
Of course it won't show
i don't know 
they are on multiple scripts 3 total
i have not changed them
Then you did not save
let me resend them
https://gdl.space/guxixuwise.cpp
Line 9 here cannot be null
so you probably didnt then?
https://gdl.space/odicudifet.cpp
this is stat manager
Ohhhhhh
You cut off part of the scripts.....
Include EVERY SINGLE LINE
Good, this one looks complete
Yes, get rid of line 9 entirely
If you have a singleton with the value, just access that.
what is a singleton
What you've got with that Instance stuff
singleton aka Only 1
so it lets me access the variable a singleton
Is a singelton?
Every object that you wrote instance in is supposed to he a singleton
You should ONLY have one of each of those scripts in existence at any one point
before you know what a singleton is you prob should know how an instance work first lol
I do not know how either work
im aware lol
So only one instance ever
is the best tool around you teach yourself things you're not sure about
Yea lol i bet its obvious
or ask for clarification + googling
okay so I should be using singletons not what ever i was doing
yea, thats why im suggesting it in a way to learn them a bit deeper
its always good to know what the tools you use do while using them
What you are doing IS a singleton, as multiple people have said
wait what
Not ever. You could have multiple across the runtime, but only one at a time, yes
If you have a static field that is the type, and you set this to that variable, you potentially made a singleton.
Okay so only 1 singleton of one script at once
Yes
I need to learn what a static field and singleton are
I thought it was just referencing the other script so i could use the variable
Singleton just means there should only be 1 of this thing
public static Type Instance
^ static field
static keyword already makes something the only 1 thing usually.
Singleton is literally in the name. Single. You have a single one
It doesn't actually even need a static accessor field, but that is useful
in unity you need to destoy another instance if somehow you have 2 of this script in the scene
but why what does it do
Having a single thing you can reference for data is powerful
like the stat manger thing?
If you only have one, it IS a singleton, yes
So what does that mean
He just linked info....
Okay so what i got isnt a singleton
you've been told many times you have a singleton there with instance
If not, then get rid of the instance variable
Because that is a significant issue if you have more than one
It WILL NOT WORK if there are multiple
Static means there is only one in existence basically. So the last StatManager's awake that runs will be the one referenced by Instance
Okay so i should only ever have one of these public static BasePlayerPrefs Instance;
https://unity.huh.how/references/singletons#implementation
see how its written here. Imagine this is StatsManager
this should only be a field in BasePlayerPrefs
You should ONLY have that inside BasePlayerPrefs and NO WHERE else ever
And only if you are going to only have one BasePlayerPrefs
otherwise it makes no sense to put it in another class
Okay i did that wrong I had it in multiple
So once i have it in there im able to reference it correct?
Yes
BasePlayerPrefs.Instance will lead to that variable
It will statically access the class
use this in very specific times , dont start making everything static Instance in each class
For example, you should not have a static accessor to your StatManager, since you have multiple
It will lead to every varible in that class
It will lead to the class itself.
Every variable and method
Okay thats exactly what I need
instance is the one running and calling those methods
so you only want 1
Classes are just blueprints they don't do anything else
It will lead to only one instance of the class, and never any other.
Just to be clear
that makes so much sense
hi guys, can anyone help me with my top down movement script? How do i make my player stop when i release the walking button instead of keep walking a bit after i release it?
when you do = this
this referes to the current Script on this object
GetAxisRaw instead of GetAxis
Also fix that syntax error where you set velocity
Those are some pleasant editor colors
exactly becuase I need to get the variables to use on other scripts so when I go into the other script i do StatManger.instance.baseHealth right?
No, as I said, StatManager SHOULD NOT BE A SINGLETON
are you talking to me?
Is there only one BaseHealth that everything will have?
well yeah in other scripts this accesses those fields
Or do you want different things to have different baseHealths
thats Lunar Pink Theme
Only the "base" is gonna have that variable I have enemy helath as well
@zenith cypress got the best emojis
You should definitely not make this a singleton
Definitely not have a static variable
Just make their own with their own values
I mean, you could do that, but it seems so muddy to have a ton of health variables for all these different things.
Hard to extend, and gets to be a massive mess real quick
I have base and enemy health i will add more enemies though
Exactly
So i should not make it a singleton
I need differnet variables for each type of helath
I mean, some of it could be. You have the coin multiplier, that makes sense.
But I would do a script for each prefab type that has its own health values
Like an enemy has a health component, and that has a baseHealth, and a currentHealth
You CAN do anything you want though. It is easy enough to pivot and refactor as you go. It will happen regardless of how well you plan.
that is what I get its gonna have differnet script for different enemy prefab
but how would i acess the variables from another script though
Multiple instances of one script? ๐ค
With proper referencing
We have linked you this previously
https://unity.huh.how/references
Serialized Reference when possible
When not, then you are instantiating. And Instantiate returns a reference
For damage based things, often you get the reference from things like OnTriggerEnter or raycasting (and other spatial queries)
Okay so serialized reference
Give an example of what you'd want to access and how the two objects relate.
That only works before you hit play of course
at times its not possible to use it, if you click https://unity.huh.how/references/serialized-references
you can see many examples where you cannot. One example is you cannot drag any scene objects into a prefab
I want baseHealth to be accessed from the enemy when the enemy collision with base i want it to -1 baseHealth from the enemy scritpt. I also need maxBaseHelath in another scene for upgrades
Ill look into what it does exactly
It does what i need it to do
Then do:
OnCollisionEnter
collision.gameObject.GetComponent<Health>()
GetComponent (and preferably TryGetComponent) are exactly what you want for that
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("enemy"))
{
takeDamage();
BasePlayerPrefs.setMaxHealthToCurrent();
}```
that is what i got currently Im gonna have to completely revamp everything
You need the ``` marks at the end as well for formatting btw
i fixed it
Guys i got a fast question, im watchin a tutorial and i just realized that something is worgn cause the dashCounter will never be > 0 and <= 0, right?
oh no
it reduces its value
would it change anything if i put this if (dashCounter <= 0) under the other if instead of inside?
What other if statement?
Whats the best way to convert the Input.GetAxisRaw to direction?
thats the full code i guess
except for the variables
Create a new vector from it.
Who made this tutorial?
Seems so overly complicated for no reason
OOH TY
Jake Makes Games
And where do you want to move the if statement?
lemme make my own code so u can understand it better
but first
Presumably right after the dashCounter > 0 check
using UnityEngine;
using UnityEngine.UIElements;
public class movement : MonoBehaviour
{
[SerializeField]
public float moveSpeed;
public Rigidbody2D rb;
public Vector2 moveInput;
private float activeMovespeed;
public float dashSpeed;
public float dashLength = .5f, dashCooldown = 1f;
private float dashCounter;
private float dashCoolCounter;
void Start()
{
activeMovespeed = moveSpeed;
}
// Update is called once per frame
void Update()
{
moveInput.x = Input.GetAxisRaw("Horizontal");
moveInput.y = Input.GetAxisRaw("Vertical");
moveInput.Normalize();
rb.velocity = moveInput * activeMovespeed;
if (Input.GetKeyDown(KeyCode.Space) && (dashCoolCounter <= 0 && dashCounter <= 0))
{
activeMovespeed = dashSpeed;
dashCounter = dashLength;
}
if (dashCounter > 0)
{
dashCounter -= Time.deltaTime;
if (dashCounter <= 0)
{
activeMovespeed = moveSpeed;
dashCoolCounter = dashCooldown;
}
}
if (dashCoolCounter > 0){
dashCoolCounter -= Time.deltaTime;
}
}
}
``` thats my actual code but i guess im missing something here
omg i pasted too many things
The dashCounter relates stuff looks the same to me.
but for somewhy my dumb square player isn't dashing ๐
You have some other differences compared to the original code though.
It's likely that that's the cause.
ye i don't see why this'd cause it but i'll try
Add debug logs to your code to see what's happening.
Or step through it with a debugger
tbh i don't have idea how to debug my code with visual studio code
i had issues trying to use visual studio cause i don't have 2019
gotta search abt it
[SerializeField]
public float moveSpeed;
public Rigidbody2D rb;
public Vector2 moveInput;
private float activeMovespeed;
public float dashSpeed;
public float dashLength = .5f, dashCooldown = 1f;
private float spinSpeed = 1f;
private float activeSpinSpeed;
private float dashCounter;
private float dashCoolCounter;
void Start()
{
activeMovespeed = moveSpeed;
activeSpinSpeed = 0;
}
// Update is called once per frame
void Update()
{
moveInput.x = Input.GetAxisRaw("Horizontal");
moveInput.y = Input.GetAxisRaw("Vertical");
rb.rotation += activeSpinSpeed;
moveInput.Normalize();
rb.velocity = moveInput * activeMovespeed;
if (Input.GetKeyDown(KeyCode.Space))
{
if (dashCoolCounter <= 0 && dashCounter <= 0)
{
activeMovespeed = dashSpeed;
dashCounter = dashLength;
activeSpinSpeed = spinSpeed;
}
Debug.Log($"activespeed:{activeMovespeed} movespeed:{moveSpeed}");
}
if (dashCounter > 0)
{
dashCounter -= Time.deltaTime;
if (dashCounter <= 0)
{
activeMovespeed = moveSpeed;
dashCoolCounter = dashCooldown;
activeSpinSpeed = 0;
}
}
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}
He's rotating around a corner (the object is a square)
can i change its rotation point or whatever is that to the center of the square?
how to fix this bug guy pls help
surely you meant to have IEnumerator
it isn't a bug lol
please use site for large code https://gdl.space
oh kk
is there a way to calculate a max velocity before it's too high to miss a collision? Currently playing with dropping balls from random heights with UseGravity on and emperically finding the value to be about 29, but that might be fps dependant too
https://gdl.space/wuyaxoqole.cs does someone know or understand why the bullets appear rotated on the map?
the code that makes this thing happen is on line 75 towards the ending
but i shared everything in case it might be other thing causing trouble
your scale is non-uniform
okay, and is that a bad thing?
for rotation it is
it skews the object
imagine your object is inside a cube, as you rotate it starts turn into like a trapezoid type shape
that happens if i only rotate the z ?
make the numbers the same , eg (0.5, 0.5, 0.5)
the x,y,z?
but then i cant make it point towards the player right?
you are talking about the Instantiate?
nope
the line below that one
the rotation of the parent is 0,0,0
so that shouldnt bother it
are you talking about bulletHolder
yes
in the z axis it is
what do you mean?
you have to do it on the prefab
let me try now
yes i did
okay did it and checked
but it still rotates on the x,y
wdym
Ahh i see what you mean now.. I thought your spheres were distorting
just realized its 2d so it probably didn't matter
indeed its 2d
On a side note, I don't understand why direction.z is in here... That's the distance to the player on the world z axis, which seems a little strange to use in a calculation for degrees, no?
bulletHolder.transform.up = Quaternion.Euler(0,0,direction.z-30+ (30*i)) * direction;
I don't think it's what's causing the problem as it's still a rotation around the z axis, but it gave me pause
yeah that looks wrong
thats the way i know in what direction he is
*direction is causing the issue i think
hmmmm, how is direction.z rotating the x,y tho?
I think you can just do AngleAxis
what does angleaxis do?
try var upDirection = Quaternion.AngleAxis(direction.z - 30 + (30 * i), Vector3.forward) * direction;
so instead of euler AngleAxis
What do you get if you log direction.z?
does it do the same thing?
yep
-1
which makes sense
why am i even using direction.z for that?
when its 2d
what did i cook? ๐ญ ๐
My guess is that's part of the problem. You're orienting the object's y axis to a vector with a non-zero z component, so it's rotating on the x and y axis to point in a direction off of the x/y plane
direction.z = 0f;
// ...
bulletHolder.transform.up = Quaternion.AngleAxis(-30 + (30 * i), Vector3.forward) * direction;
couldn't u just 0 out the z direction
sure that would be better ๐
i do not understand
that is some big words
what does orientation the objetcยดs y axis to a vector with a non-zero z component?
my guess si that im trying to rotate it on the y with a -1 z
but i do not see how im rotating it in the y
because im doing that transform.up = "the math"?
Because the player and this game object are at different z positions (which is your "depth" in a 2D game), the direction vector is not just pointing to the player on left/right (x) and up/down (y) axes, but also towards or away from the camera.
transform.up = stuff is setting the game object's rotation such that it's positive y axis is aligned with stuff, so if you assign to it a vector which is pointing towards or away from the camera, then the object is going to tilt towards or away from the camera
okay
i seem to understand it now
and what did navarone miean with 0 out the z direction
look at the code they sent
Before I was creating a new vector which used just the x and y components from direction and 0 for the z. Nav was suggesting to just keep using the current direction vector and set it's z component to 0f. They achieve the same thing, but mine was extra typing and extra work for the computer
and how do you set it to 0 ?
i wanted the z so it has depth, for not overlapping or clipping
in case you mean to set the z to 0 in the inspector
if not this is irrelevant
And they do - the objects are still at different z positions, we're just throwing out the z component of the direction vector in this code because it's not useful in this calculation, and is in fact messing it up :P
direction.z = 0f;
for 2D just use the Order in Layer on Sprite Renderer
also you wouldn't mess with Z for rotation target in 2D
oh
its edited
i thought the direction.z = 0f;
was already there
and he meant other thing*
it did not solve the problem sadly
womp womp ๐ฆ
hahaha
trippy
wait
i think it actually solves it
but since i have 2 enemies i just changed 1 of them in code
so that could be it
lemme check
the code should 100% work
it does indeed work
To make a sound effects manager should I make the sound effects a publishers and subscribe to it wherever I need in order to invoke whatever method is in it? (sorry if this doesnt make sense, I just dont know how to go about it)
depends how many sound variations you got
maybe just make it a singleton
MissingReferenceException: The object of type 'MouseButton' has been destroyed but you are still trying to access it. erm so this happens after i reload the scene... how do i bring back the references without reinstantiating
EventHolder.mouseButtonClicked?.Invoke(mouseButtonType); im trying to invoke an event, and in MouseButton script i subscribe to this event and start a coroutine
Do you unsubscribe at all?
how can I offset an object's X position relative to it's Z rotation?
in OnEnable
UN subscribe ?in OnEnable?
subscribe in onenable and unsubscribe ondisable
how are you subscribing? show code
Like... to have it move horizontally as if it were rolling?
no, offset by a value on the X axis, like if you extend your arm and rotate your shoulder, your hand is rotating with the shoulder but offset from it by your arm's length
idk how else to describe it
I think a drawing could do
moving the object or rotating it keeps the offset
so just local positioning relative to rotation
in other languages I'd use sin and cos for this, but idk how about unity objects
Weapon class -> https://hatebin.com/ybzswrvoki
Ping me when you have a minute
Hello! I'm trying to make simple 2D movement and my player can jump infinitely. I made a private bool called "isGrounded", a public LayerMask for whatIsGround, a GameObject for the groundCheck and a public float for the checkRadius, but now after all these things I do not know what to do in order to check if the player is on the ground or not. Could anyone help me?
nevermind, i found out
why does my rb.AddForce work in the editor but not in the android build?
the code works right, but the it doesnt move when i play it on my phone after building
You can still use Sin and Cos in Unitylandโข, but I'm still not totally clear on what you're trying to achieve...
My best interpretation is that you're trying to keep ice cream man's "shoulder" in the same place when the arm/weapon swings around?
void OnEnable()
{
EventHolder.mouseButtonClicked += (MouseButtonType button) =>
{
if (button != mouseButtonType) return;
StartCoroutine(ButtonClicked());
};
}
void OnDisable()
{
EventHolder.mouseButtonClicked -= (MouseButtonType button) => { };
}
```...
help me with this please ๐
Heya. I'm unfortunately drawing a blank on how you can get one GameObject to create a "pointer" object to another in the world. I have an empty "Ground Point" object which I want the camera to follow, but which isn't a child of the camera, and I don't think it's wise to call GameObject.Find on every frame to locate and point at it.
Ideally I'd be able to create a reference to the world object so that the camera's idea of the ground point's position updates whenever it's moved instead of having to write code to continuously locate and copy its position
something like this. Had to look for the Deg2Rad thing tho
Anyway, short version, if any of you remember how to declare a pointer to a GameObject lmk
there is your problem. You cannot unsubcribe a lambda function
sensei, can you help me?
with this
The problem you have described is not common - there is no logical reason for AddForce() to behave different in an Android build than a desktop build. There may be an issue in your code, but no one can provide feedback on that if you do not provide your code. Given that the issue is specific to a platform, you might ask in the channel specific to that platform - #๐ฑโmobile. But these are quiet hours. I would not expect an immediate response
i yesterday did, everyone said it was not a problem with the code
i just subscribed in void Start() and get the same problem, and i have a separate method now (no lambda)
no. I tried to help you with this yesterday and you just ignored my question. Also #๐โcode-of-conduct
i debuged on every move and it was confirmed
oh, it was late and i was probably sleeping on my chair ๐ญ sorry
Sure sure... But this still doesn't quite tell me what you're trying to achieve with this code... If this code is not accomplishing it, then me parsing it to figure out what it does will not help. Are you trying to keep the "shoulder" in the same location?
the only thing I can suggest is add a null. check for button in the method
You don't need to worry about it anymore tho, I fixed the initial issue, now it's dowwn to tweaking
I will say that if keeping the shoulder stationary was the goal, an easier way to achieve it is to create an empty game object and position it where the shoulder should be. Then you use it's transform.position in RotateAround() to rotate the arm/weapon.
But I'm glad you found a solution, in any case ๐
How do I change variables for different game objects using the same script? I want the โmyMassโ variable of object one to be 10, and the โmyMassโ of object two to be 5. Is there any way to do this easily? I tried a private serialized field to change them in the inspector, but it just outputs 10 twice. Iโm also trying to avoid โif (this.name ==โฆ)โ because if I have a lot of objects, that would clutter my void Start.
private serialized field should work. show !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Alright give me a moment please
Sorry, it decided to suddenly work? Previously, it would show an extra debug saying 0, but now my debug is feeling okay. I donโt know what happened.
probably a compile error prevented updating the inspector
how would I store a clone of a prefab in code? I'd like to copy a prefab to instantiate later, but I'd rather not instantiate this prefab in the scene.
I do have an error saying so it was likely that then, thanks.
presumably this is at runtime, not in the editor
yep
is there any way of making enemies not overlap on top of each other or go in hords that are too concentrated?
that are not*
I don't think it's possible, normally to clone I serialize/deserialize but you would still need a gameobject to deserialize to
working with someone else's code right now, they're hardcoding a prefab in the interaction system ๐คฆโโ๏ธ I'm making it such that it changes the text in their hardcoded button so the interact system displays the name of the interact button correctly
you probably want to use one of the Raycast methods on your generated enemies positions before you instantiate
could you elaborate on it a bit
well let me elaborate first because maybe we dont mean the same thing
they follow the player with a vector that substracts their position from the players one, so more often than not they end up all in the exact same spot
so you are not talking about creating the enemies, just when they follow the player they all converge
so give each enemy a different speed within a range
basically that they stop being like in left side, and more like in right side
but then they will still end up in the same point once all of them reach the "min distance for attacking"
maybe that once they reach the min distance, make them move a bit randomly to attack
some would still overlap but overall not that bad
imma try that
yeah, once they reach min distance you can get them to move in a circle around the player
how could i make them move in a circle
i have thought about that but cant think of a way of coding that behaviour
it's simple to get the points of a circle with radius of min distance from the player, so just use that to guide your enemies
radius of min distance
yes i understand the concept
i will see if i find anything on how to determine those points
,basic math
i dont think that i can get each "red line" position with basic math
well i probably can
but i do not know that math
so i need to first learn it
,this should help
https://stackoverflow.com/questions/14096138/find-the-point-on-a-circle-with-given-center-point-radius-and-degree
Vector3[] GetPointsAroundCircle(int numPoints, float radius)
{
Vector3[] points = new Vector3[numPoints];
var angleStep = 360f / numPoints;
for (int i = 0; i < numPoints; i++)
{
var angle = i * angleStep * Mathf.Deg2Rad;
var x = Mathf.Cos(angle) * radius;
var y = Mathf.Sin(angle) * radius;
points[i] = new Vector3(x, y, 0);
}
return points;
}```
I think..
been a while since
god damn thats some gorgeous math
i find it beautiful how you dont need to create 30 var for useless things
i guess thats the difference
and its also understandable math
Greetings all, I am following the Unity Essentials tutorial, I'm currently on mission 4, lesson 3.5 (Collect the collectible - Destroy the collectible)
I am given the following code for the script of the relevant interaction with the gameObject:
private void OnTriggerEnter(Collider other)
{
//Destroy the collectible
Destroy(gameObject);
}
which is copied into visual studio as the tutorial instructs
however, once I go back into Unity I am given this error in the log:
"error CS0106: The Modifier 'private' is not valid for this item"
I have tried changing the method to public and even taking off that modifier alltogether, but I still get an error on that line
the script seems to be named correctly (as Collectible.cs, as instructed)
I do have a bit of programming background, just not that familiar with C# and with Unity obviously, so I'd appreciate a few pointers on what's happened here
I'm not sure whether it's a mistake in the tutorial, or a visual studio bug, or maybe I've written the code wrong somehow
I did change the collider of the gameobject to a trigger previously as the tutorial instructed
is this an issue where I need to declare the method in the public field and the tutorial doesn't mention it?
usually that's how it works in C
(idk if i should or not "ping you" , but i wanted to show you my code and how i used it to determine close points and select one at random) https://gdl.space/deduhulore.cs
You've put it in a wrong place
this would suggest to me that you have nested the method inside another one
that's odd, it's what the tutorial gives me to copy
but where did you put it?
it is inside the update loop
wrong
my whole code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collectible : MonoBehaviour
{
public float rotationSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Rotate(0, rotationSpeed, 0);
private void OnTriggerEnter(Collider other)
{
//Destroy the collectible
Destroy(gameObject);
}
}
}
yep, nested, it's in the wrong scope
I am dumb
alright the error's gone, I had copied the method on autopilot
works in play mode too ๐ thx
lesson learned, I hope. Coding is NOT something you can do on 'autopilot'
I'll try not to skip bullet points on beginners' lessons ๐ซ
I had thought the wait for a trigger would be something to be done inside the update loop, but it makes sense that it would be async
This missing reference is eating my head, Basically this only comes sometimes, if i add some debug or something in the code and run again its not coming, also in the build its not happening, only in the editor its happening, Is there any fix for this or has any one faced this before? please help.
Error:
MissingReferenceException: The object of type 'UI_References' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.MonoBehaviour.StopCoroutine (UnityEngine.Coroutine routine) (at <2d8783c7af0442318483a199a473c55b>:0)
UI_References.SetLoadingScreen (System.Boolean status, System.String msg) (at Assets/UI_References.cs:111)
LoginManager.Init (System.Boolean isTestUser) (at Assets/LoginManager.cs:102)
GameConfigurationManager.ApplyRemoteSettings (Unity.Services.RemoteConfig.ConfigResponse configResponse) (at Assets/UI Manager/GameConfigurationManager.cs:101)
Unity.Services.RemoteConfig.ConfigManagerImpl.HandleConfigResponse (System.String configType, Unity.Services.RemoteConfig.ConfigResponse configResponse) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:553)
Unity.Services.RemoteConfig.ConfigManagerImpl+<>cDisplayClass46_0.<DoRequest>b0 (UnityEngine.AsyncOperation op) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:542)
UnityEngine.AsyncOperation.InvokeCompletionEvent () (at <2d8783c7af0442318483a199a473c55b>:0)
Hey guys! I'll try to explain what I want: I have a player that the camera should be watching. But the player appears at a certain button, that is, initially he is not in the scene. I press a button and the player appears in the scene and the camera should be working and watching him.
In general, to make it convenient, we consider the camera at the GTA 5
But the problem is not with the camera itself, but that I want to assign it to a prefab that is not in the scene.
Can't help without any code
Also, don't crossposttextmessage
if i write this Vector3[] bestPoints = new Vector3[]; im creating an array right?
how can i set it to a size of 0?
technically it wouldnt matter since i can always modify its size
i want it to be resizable so it only takes the vector3 that meet the criteria
You can't modify an array's size. If you need that then use a List
wasnt it the other way around? a list isnt modifiable and an array is?
no
Hello, why does this not work?
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Coin"))
{
other.gameObject.SetActive(false);
}
}```
how is that possible
Debug.Log("l: current pos Y: " + bsm.owner.transform.position.y);
Debug.Log("l: value to increment: " + valueToIncrement);
Debug.Log("l: destination pos Y: " + bsm.owner.transform.position.y + valueToIncrement);
destionation pos Y should be 8,0064[...]
hi again! im getting this error that says that the index is out of range, but when i click on it it redirects me to a line that starts a coroutine, could this be because im using a list in the coroutine?
index out of range is always smt with a loop/list
okay
https://gdl.space/epewapezuc.cs could you help me deducin where it is happening?
Take a look at the stack trace in the error and click the top-most hyperlink
stack trace?
Sometimes clicking the error itself may point you to the wrong place
which line is it
thats the coroutine itself
The list of "code places" from where the problematic piece of code was called
it doesnt say which line
click on the error
it always shows the line
no clue what that is
I'd show you an example but I'm currently waiting for a train
If you click the error and look at the full description, there should be a couple of links pointing to different places in your code
The top-most one is where the error took place
left or right?
just screenshot it
because if i left click it leads me to the code and if i right click nothing happens
Left-click once
here it is
on the bottom of the console there's an expandable window
Where the full description of the error is
So this
var choosenVector = bestPoints[Random.Range(0, bestPoints.Count)];
that has to do with the return on line 132
yes
but how is that taking a number out of range?
isnt 0 = to the first object?
use
var choosenVector = bestPoints[Random.Range(0, bestPoints.Count - 1)];
maybe because its empty sometime?
Count = amount of items. So if there's 1 item, then it starts at 1.
Shouldn't the Random.Range int overload be max exclusive?
hmm, I'm not sure. Might be yeah, but he can try it this way
yes
it should
but it works
i worked with the max exclusive in mind
since b4 hand i had it being added +1
weard
but then i remembered that (wrong btw) list work like 0=1st object so i let it be the same
lying
i dont even remember anymore
i just know i messed around and that its supposed to be max exclusive
hello, im trying to instantiate an object at my rigidbodys position but just a little to the side
to instantiate the projectile a little to the right of the center of the rigidbody
rbPos + rbTransform.right * offset
Try it out
allright
Hey guys
Cast to Vector3
im on 2d but okay
I have a Missile Launcher in my 2D Platformer, it works correctly, but the Missile which is only supposed to Explode upon contact with Tag Player or Ground, also explodes when it goes out of the Main Camera view
Does anyone know why?
it works kinda but the offset is too much lol
gimmie a min
Can you share the code you're using?
For the Missile or Launcher?
missile
Tried using OnBecameInvisible to force delete it when it's out of Camera View but it still Explodes()
Oh, I think I know what the problem is
I used collision.collider
It should be collision.gameObject.CompareTag
It's evaluating to 0 || 0 no matter what it collides with
what's the difference between using a return type and using an out parameter?
rubber duck concept helped once again
Thanks for being my rubber duck ๐ฆ
Not much difference.
they both achieve essentially the same thing right? what about a ref parameter?
Ref allows you to pass a value type by reference.
works, how can i edit the rotation?
how does that work, then? it lets you use a field for example as a reference and then augment that field?
its quaternion, i tried to do the same thing as the position but it didnt let me so how do i edit it?
Yep
[SerializeField] private AudioMixer m_mixer;
[Space]
[SerializeField] private Slider m_masterSlider;
[SerializeField] private Slider m_soundFXSlider;
[SerializeField] private Slider m_musicSlider;
private void Start() => LoadValues();
public void SetMasterVolume() => SetMixerVolume("MasterVolume", m_masterSlider.value); // calling from OnValueChanged
public void SetSoundFXVolume() => SetMixerVolume("SoundFXVolume", m_soundFXSlider.value);
public void SetMusicVolume() => SetMixerVolume("MusicVolume", m_musicSlider.value);
public void SaveValues() // OnClick
{
PlayerPrefs.SetFloat("MasterVolume", m_masterSlider.value);
PlayerPrefs.SetFloat("SoundFXVolume", m_soundFXSlider.value);
PlayerPrefs.SetFloat("MusicVolume", m_musicSlider.value);
}
private void LoadValues()
{
if (!PlayerPrefs.HasKey("MasterVolume"))
{
return;
}
float volume = PlayerPrefs.GetFloat("MasterVolume");
m_masterSlider.value = volume;
volume = PlayerPrefs.GetFloat("SoundFXVolume");
m_soundFXSlider.value = volume;
volume = PlayerPrefs.GetFloat("MusicVolume");
m_musicSlider.value = volume;
}
private void SetMixerVolume(string name, float value) => m_mixer.SetFloat(name, Mathf.Log10(value) * 20f);```
is there a better way to save the value of sliders
if there were more sliders here, would i write them all one by one
Depends what you want to do. You can convert Euler to Quaternion
freaking epic
Hi guys! I'm new to this... Like all of these...
I just downloaded Unity, and I'm requested to download the editor too. Am I on track?
just from the angle that it spawns at a slight deviation
Yes but in cases like these it doesnt really matter. If you had a ton of settings then I'd look into using some collection to store these all.
About your question for their being a better way, if this suits your use case and works then it's fine. I personally wouldnt go with playerprefs
how would i edit the angle that it spawns at
what are you using? json?
Yes, json is just a file format though. I do suggest writing to file. If you ever need to save custom data then you'll have to write to file anyways.
thanks
can someone tell me what is wrong with my code, im a beginer and I really dont get why it doesnt work
start by configuring your !IDE ๐
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
Also, you should explain what you're trying to do and what is happening (or not) instead . . .
Also, it would appear you have made absolutely no attempt to debug this code
- this is a code channel
- don't zoom your game view, it doesn't scale well
you should probably save the code(ctrl s)
I'm trying to Lerp/Slerp a rigid body using a tutorial and its telling me "cannot implicitly convert type Quaternion to type float." The slerp thing says it wants three agruments (quaternion, quaternion, float) and I have given it three arguments (quaterion quaterion float.) I can't figure out what th eproblem is
2D rigidbody's rotation is a float
oh, alright. How do I fix that? cause I have to use rigidbody for thephysics to work properly dont i?
You'd want Mathf.LerpAngle/MoveTowardsAngle/SmoothDampAngle
A more physically correct way could be to use rb.angularVelocity instead
Not sure if changing rotation directly can cause oddities in 2D
So im trying to make a FreeLook function for my game but im having trouble to make it reset to 0 in rotation when done freelooking
MoveTowards is not for quaternions
there are several things wrong with that. first, localRotation is a quaternion, not a float. and you shouldn't be using the members of a quaternion for logic because they are not represented in degrees
localrotation.y is NOT an Euler angle
Yeah i have no clue what im doing im js guessing my way forward
there are beginner courses pinned in this channel, and the pathways on the unity !learn site are a great way to learn how to use the engine. perhaps you should start there instead of blindly guessing
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
yeah
then spend some time learning, if you dont know what you are doing each line of code should take you at least 10 minutes to write whilst you read and understand the documentation
i took a 4 hour and a 12 hour course for unity but they didnt speak once about quaternions so thats why i was guessing my way forward thinking it was like any other transform, im gonna read some documentation about it now tho
pretty awful courses then as Quaternions are central to the Unity system
you currently have the Unity Hub. The Unity Hub manages different versions of Unity Editors(and their extensions), It's normal to have one version of the hub and multiple versions of the unity editor.
Oh! Thanks... I will work on getting an editor that works for me. Is the different editors laptop specific...?
Nope
The Hub detects which device you're on and installs the correct editor
For now its best that you install the latest LTS version
Inventory script has a function with 2 parameters but it doesn't appear in the editor
is there any better way to write this? Like with some Mathf function or smth?
thanks
you can use Mathf.Max or Mathf.Clamp
you can use clamp
theres mathf.max, returning the higher of 2 numbers
oh okay thanks
but it is not better
though your current code works fine as you might want to have other functionality once your ammo in clip runs out
e.g. playing a click sound to signify you've run out of ammo, automatically reloading,
its only there to be sure i don't have negative ammo in my clip, the things u said are handled by other elements
https://gdl.space/awenapajin.cs i am calculating random dots around a circle circumference that has its origin at the player , and calculating the dot product respective to the position of the enemy so i can assing places to the enemy to move, i think the dot product is somehow taking into acount the positions at the other side of the circle
green = player
red = enemy
blue = possible places
is vector2.Dot supposed to work like this or am i missing something?
Well a dot product doesn't use positions, it uses directions. You are giving it a world position as the second value, so the offset nature of points[i] is making it act weird.
i understand
ty!
Vector2.Dot(-direction, player.transform.position-points[i])
this should work?
okay i corrected it
Vector2.Dot(player.transform.position-transform.position, player.transform.position-points[i])
but i still have the problem with some guys
is player.transform.position-points[i] a direction?
Sure, although that just removes the player.transform.position + you have before, so you probably just want to not do that, and then pass in points[i].normalized as the second.
like is its zero the same zero as your direction?
points[i] is a vector 3
vector3 can be used to show a position or a direction
but im doing player.transform.position - points[i]
which should give a direction
i think
yes p2 - p1 gives a direction pointing from 1 to 2
i use the player.transform.position so it knows where the circle " origin" is
though the dot product wants 2 directional vectors and returns a float that more or less tells you have similar the facing of these 2 vectors are
yes
the first one is player.transform.position-transform.positionand the second oneplayer.transform.position-points[i]
i think they should be directional
the naming of that makes me belive they are not
how can i distinguis a directional vector from one that is a position
well i am going with that you called it position or point
so assuming that is a point in space,
ok, but what i am saying is most uses of the dot product you are going to want 2 normalized directions
oh lets step back, i mis read things
In math, points and vectors are distinct objects, but in unity you just interpret a vector as a point. Only way to keep track is with context and naming conventions really
so used to have spaces around operators i read player.transform.position-points[i] as 1 var not 2
ohhhh
no its a calculation
that uses 2 vectors
player.transform........
and points[i]
yeah just me not fully paying attention, so that should work, since its comparing the play pos to current pos, with the player pos to a poiunt
i would normalize the vectors after subtraction though
btw, another small thing, you don't need the -1 here Random.Range(0, bestPoints.Count - 1). Int random range is already max exclusive (if you didn't know)
yes, i had that same discussion earlier
So is this what you are wanting (green is the final point)
Not sure what would be too advanced about it. It's basically your code, just slight tweaks and a direction fix.
If you have questions about it, ask em
Lets you get a value between a and b at a certain percentage
why that name
linear interpolation
lerp(0f, 2f, 0.5f) -> gives 1.0
id like help leading me in the right direction, im a complete beginner at coding. i want to have "keypress combos for ability's" but im not sure how id go about creating that. for example "Z,X,C,V" being they keys and if "Z,Z,C,X" is pressed in that order you will you an ability. how would i go about doing this? or if there is a name for this kind of thing so i can search for other people implementing it and hopeful learn how to do it
that part is because I didn't want to give a name to the object you have to dispose due to the using. So that trick is just to be lazy
(it's not a discarded name or anything, it's just the smallest you can go lol)
oh
i dont know the code confuses me a bit
i also am a bit sleepy as one may say, so, perchance that might be the issue
btw what do you mean with line 41?
this is something called "input buffering". Basically you listen for input, and whenever a button is pressed you add it to a list. And every time you do that, you also check it the list against the "recipes" you have for moves
if it matches, you do the move
if too much time passes you clear the buffer
it's best implemented with a State Machine
but if you're a complete beginner at coding, this is probably beyond your abilities at this time
you should probably focus on the basics for now and work up to something like this
it's very common for fighting games for example
oh man i would love to learn that and i know i should
but every tutorial on yt thinks that the viewers already have x amount of expertise
if you had a doc that is good i would love it
i cant manage to find good things about that
to be clear the state machine is just the framework on which to build this solution. It's not the solution itself.
The same space being like both being proper directions, didn't know how to word that. In the image the left is the world points, the right is what line 42 is working with. Normalizing just puts them onto a 1 unit circle, and point is just a circle position already, so you don't have to offset by a world position (like you had prior) for the dot.
like i had prior?
im not understanding rn
i understand what world point is but i dont know how that would help me
also, this happens, it somehow takes a position that shouldnt be achievable
What's not achievable about it?
this direction
since it isnt at radius distance
something must be off with the code
but i cant manage to see what it is
Not sure what I'm looking at. The radius you had (in your code + original image) was between the player and the enemy. What is it doing vs what are you expecting it to do? I'm working with what I was given lol
i basically want it move to a position in the " circumference perimeter" that is close to its position ( thats why the dot product)
and what it does, is going to a position (sometimes not even in the perimeter) on the opposite side of the circle
i dont know if it makes sense what im saying
srry but i cant access the code now, in case its needed
Guys, is there a way I can store all elements of the materials array from a mesh renderer via code regardless of size?
Why would you need a separate collection to store them, when you have them right there?
have anyone used Opsive universal character controller ?
yes, an array of course. But as Osteel mentioned the Renderer already has an array, there's usually not a good reason to have your own long-lived copy
I am experiencing a big amount for proccesing time because of animation and physics kind of overriding or having issues in rendering the final simulation of the character ig, it's all scripts prob that's all I know
It's because I'm going to change all materials in the array to a different one and then back, to produce a flash effect
looks like they have their own support forums and discord server: https://opsive.com/support/
Might be easier to just toggle mesh renderers. Or change the materials themselves. But if you want to do it with different materials, then you can create a separate array and store them, sure.
ok so... use an array, that's what the renderer directly gives you back
what's wrong with that?
wow, I d'be dumb to not found that before, thanks :D
I mean I want the array to be able to add any number of materials in the model
yes arrays can be of any length
enemyMaterials = myRenderer.materials;
it's really not clear what you're asking
Have you learned how to work with arrays and the basics of C# yet?
I know quite a bit about C#, but arrays are something I'm still improving on
if you don't know arrays you have a lot to learn about the basics of C# still
Regardless, would this add all of the materials the attached object has?
yes...
Lemme check
Huh, it did add them
@radiant frigate well when you wake up show some more examples to make it clearer what you want or similar. Was playing around with it and got it to do the same logic with less going on.
public Vector2 GetPointAroundCircle() {
var playerPosition = _player.position;
var position = transform.position;
var distance = Vector2.Distance(position, playerPosition);
// move both positions around world origin so atan2 works properly
position -= playerPosition;
playerPosition = Vector3.zero;
// put the enemy on the circle, atan2 takes a position and gives back the radians
// on a unit circle of where it would be on it
var circleDirection = position - playerPosition;
var positionOnCircleRadians = Mathf.Atan2(circleDirection.y, circleDirection.x);
// get an offset to apply to the enemy's circle radians
var angleRange = _angleRange / 2f * Mathf.Deg2Rad;
var offsetRadians = Mathf.Lerp(-angleRange, angleRange, Random.value);
// get a new offset circle position
var positionOnCircle = new Vector2(
Mathf.Cos(positionOnCircleRadians + offsetRadians) * distance,
Mathf.Sin(positionOnCircleRadians + offsetRadians) * distance
);
// take the circle position and put it back around the player
return positionOnCircle + (Vector2)_player.position;
}
That was... a lot simpler than I expected
I thought I add to do the 'for' or 'foreach' loop stuff
hi! im not asleep but i will go soon
i dont think im in condition of checking the code
but if you want i can add you
i did :NumberFormatter.Format(1350)
why it returns 1K not 1.35K ?
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
public class NumberFormatter
{
static long[] powers2 = {1000, 1000000, 1000000000, 1000000000000 };
static char[] abbreviations = { 'K', 'M', 'B', 'T' };
static public string Format(int number)
{
int absulute = math.abs(number);
if (absulute < 1000)
{
return number.ToString();
}
float power = math.min(math.floor(math.log10(absulute) / 3), abbreviations.Length);
int power2 = Convert.ToInt32(power - 1);
double num = (double)absulute / powers2[power2];
num = math.floor(num * 100) / 100;
string formatted = num.ToString("0.##") + abbreviations[power2];
return formatted;
}
}```
Why not debug the code and find out?
attach the debugger and go through step by step, or add log statements at each step and see where things are going wrong
i did
and what did you learn
the problem is in ToString
https://dotnetfiddle.net/s027Jp
Seems it wasn't 1.35
because that works fine
NumberFormatter.Format(1350)
Yes I'm aware that's what you did
but 1.35.ToString("0.##"); doesn't give 1
so num was likely not 1.35 as you said
hmm its strange
So you need to debug your code
Curious how you expected num to be a value with decimals after using integer division
consider dividing by a float
well if num is a double (which it is) that won't be integer division
but... really... this needs to be debugged step by step
Always log when you're not sure and never assume what the issue is without debugging first.
to keep two decimal
Oh, you're right. I always just assumed both operands needed to be floats or doubles or else it'd use int division, but I just checked it and it works. Guess I've been doing an extra cast a bunch of times when I didn't need to
math.floor also doesn't have an int overload, so it will be a float by default 
it has a double overload!
i have this script for dynamic footsteps. the terrain splatmap detection works great. it is not only supposed to work with terrain but also normal gameobjects. the weird thing is, that it "prefers" the terrain. it plays the terrain sound even if a gameobject with the right layername and collider is what the player is standing on. it only works when the terrain is no longer in raycast distance and i have no idea why
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
There is no guarantee on the order of the array you get from RaycastAll/RaycastNonAlloc iirc
You have to sort it yourself if you want to treat [0] as the closest
and how would i do that?
Yep, straight from the docs:
hi guys im making a pong but both players move at the same time lmao https://dotnetfiddle.net/CrVh9g
Test your C# code online with .NET Fiddle code editor.
(is that how you share your code on this site?)
You can use Array.Sort:
Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
That's more of a website for running C# code to see what it does. There's better websites for sharing !code, but this one works for that purpose I suppose
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thx
Show the inspectors of both objects with this script on it
Okay, and are you sure you've set the axes Vertical and Vertical2 to different inputs?
not really, lemme check
xd
ye that was the problem
thanks
i'd never realize that lol
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Friends, I'm sorry, I'm a beginner, please don't judge me. Could you please tell me why what I want to do isn't working? I created a class CarMovementService which is responsible for the calculations to be applied to the car, meaning in the main script CarLogic. Why isn't the car moving? I have a hypothesis: it might be related to the data being sent and not returned, or the rb2d is being passed as a copy and not a reference. Please help, I'm stuck.
https://gdl.space/levuleluyo.cs
https://gdl.space/ijoxawenot.cs
can't i insert my physcs material o my rigidbody2d?
Well, let's start with the super simple things first to try to eliminate any easy solutions:
Is inputMovement getting set by anything? It looks like you've got some functions that are presumably being called by some outside input handling component, but I don't know if they're actually getting called. Try logging it in FixedUpdate, and see if the value changes as you input your movement
!code