#💻┃code-beginner
1 messages · Page 412 of 1
first screenshot is from Z- and X+, the second is from Z+ and X-, i cant figure out how to correct the offsets for the other side @hasty sleet
i alr made them in the script
im trying to map 1 voxel to .25 of the uv map ( 1 voxel has 4 colored squares on it with this texture )
i setted them to be on the top left
So i added the code to this function which runs only when the object enters the other object and its still the same
{
if (collision.gameObject.layer == 3)
{
gameManager.addScore(multiplier);
if (gameManager.playerScore >= 10 && gameManager.playerScore % 10 == 0)
{
pipe.moveSpeed += 1;
}
}
}```
I swithced the Render Mode to World Space, its making a difference but not quite
Guys how do I can open the panel which name is = button name was clicked
Cause if anybody has a phone that has low length and more height then it wont be displayed on it
For the cube faces facing toward the Z+ and X- axes, your uv mappings are rotated by two positions
// Normal:
1 2
3 4
// Incorrect from Z+ and X- axes:
4 3
2 1
Can you show the code that's determining these mappings?
i have done this but i dont have intellisense
public void OpenClosePanel(string buttonName)
{
Panels[buttonName].SetActive(true);
}```
Guys how do I can open the panel which name is = button name was clicked
still dont have intellisense
either you missed a step (like restarting your PC after the .net sdk was installed) or you need to regenerate project files and restart vs code
!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.
@hasty sleet
do i NEED to install sdk?
There's a few ways to implement this. A naive solution is to just hardcode a button to trigger a function that opens a specific panel.
Did you remove all of the code that set the vector positions of UI elements?
do i need to install .Net sdk?
@hasty sleet https://gdl.space/tejixizomi.cpp i tried to come up with some different solutions for the different directions
And... how to implement this?
yes, if it was not installed by the c# dev kit then you'll need to install it
With that line, Im setting the position of the gameobject that was created during the script
if I remove that line, the new gameobject wont be positioned
thing is, i have intellisense but not for unity functions and stuff only for c# and not game dev
if only there were instructions for how to configure vs code for use with unity
I don't want make new void for every button and panel ._.
if you cannot figure it out from those instructions, then consider switching to visual studio which is far easier to configure and keep configured
private GameObject _specificPanel
public SomeClass : MonoBehaviour
{
public void OpenSpecificPanel()
{
_specificPanel.SetActive(true);
}
}
// Set the button configuration in inspector to each panel
@hasty sleet i think the issue is im not using the + tileSize at the correct positions. but i cant wrap my mind around where they should go
VSCode doesn't properly suggest things like Update for me
It does recognize them -- it won't warn if they are unused
but it doesn't show up in the suggestion list
Is there a way to trigger animations without using strings or is that not possible
same, like even the input....
UI can be tedious. You could generate a mapping, like you are doing in your code above, from the string button to a panel name, and use a dictionary to map button names to panel names. This would be more efficient, but your code would be a little more brittle since changing the button name by a single character would change the logic.
input.getaxis isnt recognized
oh, well then it's just set up wrong
but how? i get the normal intellisenses... i followed tutorial on yt but it stays the same
It's called a method, not a void.
But make fewer methods that take a parameter. Then just set the button with that parameter
Do the guide you were linked to
@hasty sleet With that line, Im setting the position of the gameobject that was created during the script
if I remove that line, the new gameobject wont be positioned
wich guide
!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
follow every single step in the VS Code link
do not skip any of them
do not re-interpret any of them
like this?
I think you need to invert the (x, y) values for the erroring faces.
- uv values, technically
Let the following numbered faces be "correct":
1 2
3 4
Erroring faces:
4 3
2 1
Inverting all of the x values:
3 4
1 2
Inverting all of the y-values:
1 2
3 4
Yep
thank, I will try
It will be positioned somewhere. Check the positioning and adjust the anchors and pivots.
If you set the absolute position of a UI element, it will not sync up with elements that scale with the canvas
@safe radish Upon reviewing your code, it does look like your +tileSize is at the wrong position.
Try moving the +tileSize to the other vector coordinate for the incorrect faces.
i think i see what you mean, ill give it another go. thanks for the help
intellisense works, thanks guys!
where I can ask about problem why if I want to open my project I need to wait like 30 minutes before open it
The layering of GameObjects is due to their order of instantiation in the object hierarchy.
transform.SetAsLastChild(); works
If there are different parents, then you need to reconcile that separately by reordering the parents or by changing the camel sprite's location in the object hierarchy.
where I can ask about problem why if I want to open my project I need to wait like 30 minutes before open it?
Ok so in the hierarchy they are good in order
LIke that thing is below it so basically in the layering he should be on top
but its not
even disabling the bg
There's no dedicated channel to this. You can try id:browse but I don't think there's any specific place. I haven't had that error.
Show the object hierarchy
Because a white image is the default value of an image component
Delete or disable the extra image component and the camel will be displayed
Voila!
Hm, that's not expected. The background image is in BG, right?
Did you change the sorting order of canvas components anywhere, or change the canvas render mode?
Try manually recreating the camel sprite by hand, place it into the correct position, and check whether it's in front of the background (correct) or behind the background
This is trying to establish a passing case first, and then we can identify discrepancies
@full kite Change Render mode to Screen Space - Overlay
still under the bg
sprite renderers
sprite renderers are not UI components
If you want to use sprite renderers, get rid of the canvas entirely.
just physically position the objects correctly in the world
Trying to position the objects on a "Screen Space - Camera" canvas means that the canvas is sliding all over the place as the camera moves and the game changes resolutions
Now i need to know how to positionate the Image in the script
What's the actual use case for screen space - camera?
Resolved me something in the past tbh and I thought its alr to use it
So, can you help me with that here? Maybe I know why this is happening. I have SO MUCH scripts in my project, like 8-10. I've try the other projects, even new and I've see what this project have loaded in few seconds (like 10-15). I've been see this error in the internet and I wanna say that may be because I don't compilate any scripts and if I made it, I got fast loading project
it's useful when:
- the canvas shouldn't be fixed in place in the world
- other objects should be able to cover up the canvas
- you need post-processing
I mostly use Overlay mode, so that the canvas is drawn directly onto my screen on top of everything else
8-10 is frankly not that many scripts. I'm going to guess you have either a low-performance computer or a very large project with very large files, or perhaps a slow internet. I'm not too sure, though.
How can I move my image inside of the script?
like to set it at a X and Y inside of the script
If you add a compile error and open the project in safe mode, unity skips all importing
I would suggest adding a few empty objects to mark where you want to put the images
Don't set it to x, y or else it will be hard-coded and you will get the same error you had before.
You need to parent it to an object existing on the canvas already, or use anchors and pivots.
then you can just parent an image to one of those points and set its local position to [0,0,0]
he s the child of the carpet
I think you might be able to get away with setting its local position to a slight offset above the carpet, or you can create another object child to the carpet where the camel should go.
position = [0, 5, 0] should work fine for canvas rescaling as long as the parent object is not set absolutely
so now, when spawning it
its spawning like this
(in the left side of the carpet, using pivot and anchor)
Let's take it in order... I recently bought a new disk with 1 terabyte of space. The project weighs less than 1 GIGABYTE of space. As for the performance of the computer, I can't say anything, I don't understand it. But I also noticed that when exporting a project, an error crashes after more than an hour of loading (in the screenshot). I do not know what kind of error it is, but it looks like unity is going to delete itself.
Try opening a fresh project and see if it's still slow
by default
new project was loaded in 10-15 seconds
Try setting pivot y-value to 1
its -6
trying to use rb.position.y but he says i cant use it bcs it is not a variable?
I'm not great at messing with anchors tbh
and now his legs are under the carpet
Try transform.position.y or rb.velocity.y
You can't modify it directly. Make a vector and use that whole thing
nevermind
resolved them
resolved the carpet
i got another carpet that was above that thing
so a vector variable?
did u see link i sent?
Doesn't have to be a variable
new project was loaded in 10-15 seconds @hasty sleet
❌ for accessing an object's y-coordinate by using transform.position.y or rb.velocity.y to get the values? These are valid
You cannot write to .x .y. or .z
yes, i understand it but whats the solution
it tells you how..
Make a vector and write the WHOLE vector to the position
No problem!
why do i first need to set the vector to a transform.position?
You cannot set a rigidbody's vector components.
rigidbody.position is also a vector3
why cant i use rb.position then?
because position is a function aka a property that returns a copy (you're accessing the copy of x,y,z) you can't modify them directly
Assigning to a function is nonsense
You can to READ from. Then write back to it
rb.position returns a temporary value
What I need to nake to fix my problem
I'm not sure. There's not enough information to tell.
im trying to make an if function, so if the rb.position.y = 0 then im gonna set isGrounded = true
I recommend making a new project and bringing your assets over and seeing what causes the performance bottleneck
That should be fine. Show what you got an error on
You can READ the components no problem
You cannot WRITE to them individually though, and that is what we thought you were trying to do
and now coming back Travis. Something is messed up with the drag of the gameobject part of script 🤣
I despise the IDragHandler
!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.
sorry lol
It steals your monitor's soul
Why
can you detect collisions between Ui things?
If they're supposed to be physical objects, and not a user interface, use sprite renderers.
If you're making a 2d game, it's not UI
But this means you need to get rid of the canvas.
So I need to get rid of the canvas, in order to use sprite renderers
and also to see them
in order to use trigger methods
in order to detect collisions
You need to not use a canvas if you're going to use sprite renderers or aspire to have collisions on it
You can have a canvas and use it, but it can't be for sprite renderers or anything involving collision detection.
and how can I change that canvas
Because UI is not for physics logic, but just for displaying information to the user and capturing user feedback
this is my main question
Remove the canvas elements and they shall cease to exist
Remove background, remove camel, remove platform
Since I think you were treating UI as a 2d surface instead of as it was intended
if you don't know what's going on here then i highly suggest stopping what you're doing and using !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ummm, Im trying my best to understand @swift crag tbh. I used Canvas on all of my projects and this is the single one that I meet problems with
I think you might not understand enough of the fundamental of the engine to meaningfully interpret the solutions to some of the problems.
to learn c# and unity, do u need to put in alot of time? or can u get good with a few times a week? or do u rly need dedication and time to put into it other wise u'll forget alot?
Ok, my main question is: How it worked before?
How could I use SpriteRenderer on Canvas and get Collisions
Why could I see the sprite of the Sprite Renderer if I used that code with Vector3 and offsets?
And now all of a sudden, nothing is working
Yes, a lot of time. Definitely not "a few times a week"
Try reading the official docs thoroughly first: https://docs.unity3d.com/ScriptReference/SpriteRenderer.html
https://docs.unity3d.com/ScriptReference/Collision2D.html
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UICanvas.html
ait so mostly everyday?
SpriteRenderers are sorted based on distance to the camera, not their order in the hierarchy
How can i use Random.Range, to pick a number between 0,9 but exclude a certain number.
I mean, that is an unanswerable question. Is everyday good? Sure. Is it necessary, delends on the person
just skipping one number every time?
If certain number, do random range again (but keep a count to not do it forever)
No, i mean picking a number once, but excluding 5 out of the 0,9 so the Random.range doesnt land on it.
I guess you could do Random.Range(0, n-1) and then add 1 if the result is greater or equal to the excluded number
That would slightly favor one over the rejected number, but that is smart
Didn't mean to make that a reply, sorry
no, it's accurate
From stack overflow:
private int GiveMeANumber()
{
var exclude = new HashSet<int>() { 5, 7, 17, 23 };
var range = Enumerable.Range(1, 100).Where(i => !exclude.Contains(i));
var rand = new System.Random();
int index = rand.Next(0, 100 - exclude.Count);
return range.ElementAt(index);
}
garbage collection moment
@hasty sleet i got them all in the correct scale and tiling. but i have them mirrored on the Z+ and X- now
Well wouldn't it be able to land on oke over naturally, then also a second chance in landing on the rejected number ALSO resulting in one over
So a slight increase in chance on that specific offset
For the ones that are mirrored, switch the +tileOffsets for each of the cubes (x + tileOffset, y) --> (x, y + tileOffset)
You aren't re-trying if you get the rejected number
if you exclude 5, then you're remapping like this:
0 1 2 3 4 5 6 7 8
0 1 2 3 4 6 7 8 9
Ohhh, you are reducing the max by one. Gotcha, I thought you meant if it lands on 5 just add one. But you mean add one to ANYTHING over 5
right
Got it. Even smarter
anything 5 or greater
12
34
should become
21
43
```?
Yes
For anything more complex I'd just do rejection sampling
nice ty very much
uvs.Add(new Vector2(uOffset, vOffset + tileSize)); //0,1 Bottom Right 2
uvs.Add(new Vector2(uOffset, vOffset)); //0,0 Bottom Left 1
uvs.Add(new Vector2(uOffset + tileSize, vOffset)); //1,0 Top Left 3``` i still cant visualize it from this code, i should just swap 2 top ones and bottom ones from this?
as in swap top right with top left and bottom right with bottom left?
The x-values need to be flipped, so the first coordinate needs an additional tileSize while the second coordinate needs one less tilesize
Ok so i made a script that connects the position of an object to the ui, but the tutorial i followed with a drag and shoot mechanic wasnt working entirely so i had to improvise and now it only works on one side, meaning that my score goes into the -. is there any way to get rid of the - so it looks normal?
I know this is not the right channel... But the UI toolkit one is not red by anyone... So could anyone help me with this? #🧰┃ui-toolkit message
For a moving object, I would store the player's last hand position in the local space of the object
That way, if the object moves, the player will naturally follow it
You can use transform.InverseTransformPoint to go from world to local, and transform.TransformPoint to go from local to world
So if you grab an object, and then the object suddenly moves 1 meter to the right, you'll correctly conclude that the player needs to move 1 meter
so um, do i do lastHandPos = handpos.InverseTransformPoint? i also set the vr rig parent as the minecart
No, you need to get the transform of the thing you're grabbing
lastHandPos = grabbed.InverseTransformPoint(handPos);
Then, in the next physics update, convert that back to world space
hm let me try
This will correctly handle translating/rotating/scaling the cart
if i do transform.InverseTransformPoint, it will return the** passed in **transform local pos?
Transform.InverseTransformPoint takes a world-space position and returns a local-space position
i have an rb.addforce(new vector2 and then on the y axis i have jumpHeight but idk what to put on the x axis because its really glitchy, i want to put the current x axis speed but i dont know how, and if i jump and i go left or right i am floating lol
im having a problem, i followed the brackeys tutorial using player controller for 3d player movement, https://gdl.space/vuborozike.cpp this is my code, but the problem is when i go backwards then its kindof funky, and when i jump backwards and move my mouse downwards then i go really high, and when i point my mouse down then i cant jump at all
using your current speed as the force value is...weird
remember newton's first law: an object in motion stays in motion
if you don't want to change the horizontal speed, don't apply any force
i dont think transform.InverseTransformPoint(attachPoint.position); will return attachPoint position? isnt lowercase transform a attached script object transform?
i can do that?
of course it doesn't
again, it converts a world-space position into a local-space position
the result is a position in the local space of transform
You then convert it back when you need it
how? if i set it to 0 then its glitchy and weird too
OHH WAIT SORRY
its 3am im stupid rn
transform.TransformPoint(transform.InverseTransformPoint(foo)) == foo
show your entire script.
lemme first install dc on my computer lol, im on my phone rn
I understand the difference between a double and a float with a few exceptions.
Does defining a variable like this have any impact? Do I need to always suffix these numbers with f?
float foo = 1;
In examples similar to the below mentioned, is the number 1 getting compiled differently? Is this format to my disadvantage?
float foo = .5f;
foo += 1;
float bar = .5f;
bar = foo + 1 + .5f;
Is there any reason as to why I should put the f after a "whole number" float?
i do that when i do offsetting, right?
you didn't show your code, so I don't know what you actually did
like i got 2 separate scripts, 1 is for the whole locomotion, and 2nd is for minecart controller (that im trying to grab and follow)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyMovement : MonoBehaviour
{
public float speed = 10f;
public float JumpHeight = 10f;
private bool inAir = false;
[SerializeField] private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
Debug.Log("Game has started: ");
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(speed, 0);
}
if (Input.GetKey(KeyCode.Q))
{
rb.velocity = new Vector2(-speed, 0);
}
if (Input.GetKeyDown(KeyCode.Space) && inAir == false)
{
rb.AddForce(new Vector2(0, JumpHeight));
}
}
private void OnCollisionEnter2D(Collision2D other) {
if(other.gameObject.name.Equals("Floor")){
inAir = false;
}
}
private void OnCollisionExit2D(Collision2D other) {
if(other.gameObject.name.Equals("Floor")){
inAir = true;
}
}
}
!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.
oh sorry
I'm actually not sure!
Rider doesn't indicate a conversion is happening
But we should look at the compiled IL to be sure.
Typing "f" just specifies that the number is a float when it isn't obvious by looking at it
Implicit vs explicit and such
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyMovement : MonoBehaviour
{
public float speed = 10f;
public float JumpHeight = 10f;
private bool inAir = false;
[SerializeField] private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
Debug.Log("Game has started: ");
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(speed, 0);
}
if (Input.GetKey(KeyCode.Q))
{
rb.velocity = new Vector2(-speed, 0);
}
if (Input.GetKeyDown(KeyCode.Space) && inAir == false)
{
rb.AddForce(new Vector2(0, JumpHeight));
}
}
private void OnCollisionEnter2D(Collision2D other) {
if(other.gameObject.name.Equals("Floor")){
inAir = false;
}
}
private void OnCollisionExit2D(Collision2D other) {
if(other.gameObject.name.Equals("Floor")){
inAir = true;
}
}
}
That's a large amount of code
this is my code 🙂
please use a paste site
if you do
var foo = 1
var bar = 1f
it will know that bar is a float
oops...
@hasty sleet uOffset = (adjPos.z % tilingFactor) * tileSize; vOffset = (adjPos.y % tilingFactor) * tileSize; uvs.Add(new Vector2(uOffset + tileSize, vOffset + tileSize)); //1,1 Top Right 4 uvs.Add(new Vector2(uOffset, vOffset + tileSize)); //0,1 Bottom Right 2 uvs.Add(new Vector2(uOffset, vOffset)); //0,0 Bottom Left 1 uvs.Add(new Vector2(uOffset + tileSize, vOffset)); //1,0 Top Left 3 im sorry but i still havent figured it out, if this order is 4213, what order would mirror it?
@swift crag its on the addforce function
It actually tells the compiler how many bits to use.
the "grabbed"?
Maybe I misunderstood the question
sort of; it's part of a numeric literal
we're breaking out the C# specification for this one!
First: to answer your question
I see no difference in the IL
(intermediate language)
The coordinates need to transform:
(old x, old y) -> (new x, new y)
(0, 0) -> (1, 0); // Add the width of a tile to x
(1, 0) -> (0, 0) // Subtract the width of a tile from x
(0, 1) -> (1, 1) // Add the width of a tile to x
(1, 1) -> (0, 1) // Subtract the width of a tile from x
What do you mean 'identically'?
Yes. You want the player to follow the movingo bject.
What's godbolt ?
What about at build? You can not assume the outcome is the same.
The values that go into x and y are both stored as floating point constants
I seriously doubt that Unity changes the fundamentals of the C# compiler that much
There was one instance where unity compiled my C# such that using a when clause was just ignored. Unsure why.
Null check had to be performed manually
You were probably getting tripped up by how Unity objects pretend to be equal to null
Aaahhh that was probably it
When a unity object is destroyed, it compares equal to null
But your reference doesn't magically disappear
Things like the null coalescing operator and the null-conditional operators don't care about this
?? ?. ?[]
void FixedUpdate(){
LocalPlayer.GetGripHand(grabbingHand).handLastPosition = attachPoint.TransformPoint(attachPoint.position);
//Lever Login
if (!LocalPlayer.GetGripHand(grabbingHand).overrideLastHandPos) return;
attachPoint = LocalPlayer.GetGripHand(grabbingHand).handTransform;
LocalPlayer.GetGripHand(grabbingHand).handLastPosition = attachPoint.InverseTransformPoint(attachPoint.position);
}
erm i did this and.... it throws me everywhere
Someone is quoted:
'1.0' is a double (64 bits)
'1.0f' is a float (32 bits)
The code `float f = 1.0;` will not compile. It will fail with error CS0064, with the message:
Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type
Yes, this is true. It also has nothing to do with what I said.
uOffset = (adjPos.z % tilingFactor) * tileSize;
vOffset = (adjPos.y % tilingFactor) * tileSize;
uvs.Add(new Vector2(uOffset + tileSize, vOffset)); //1,0 Top Left 3
uvs.Add(new Vector2(uOffset, vOffset)); //0,0 Bottom Left 1
uvs.Add(new Vector2(uOffset + tileSize, vOffset + tileSize)); //1,1 Top Right 4
uvs.Add(new Vector2(uOffset, vOffset + tileSize)); //0,1 Bottom Right 2```
you asked about what happens when you define a variable like this
float x = 1;
Another person quotes:
The compiler is pretty smart, and if you make it unambiguous that the number needs to be a float, you'll get a float. So like:
float f = 1.0;
The compiler will treat that like a float, no problem. Problems happen when you have something like:
var f = 1.0;
That will be a double, and the only way to make it a float is to use 1.0f or put float on the left-hand side.
that first part is inaccurate
This is wrong.
that's attempting to assign a double literal to a float which is not possible without casting
1.0 is a double. There are no exceptions.
Undo last change. That should have worked. Debug the values using conditional breakpoints
I know that .5f and 0.5f are identical already. My confusion more so lies with adding the suffix when dealing with an already whole number.
I was also not talking about 0.5f and .5f
was the actual quote perhas doing float f = 1; because that is possible. 1 is an integer literal and integers have an implicit cast to float
No it's a direct quote from reddit.
@swift crag 🙏 sory for ping
welp, that person was wrong 🤷♂️
not sure what you mean by that
This is not what I said to do.
- When you grab the object, convert the world-space hand position into a local-space position
- Each physics update, convert that back into a world-space position.
Is there any reason as to why I should put the f after a "whole number" float?
The result is a world-space position that represents where you started the grab.
I know this is not the right channel... But the UI toolkit one is not red by anyone... So could anyone help me with this? #🧰┃ui-toolkit message
Are you asking if the float would be interpreted as something else if you didn't?
OH i might have gotten it now brb
if it is a whole number, then no. as i said integers have an implicit cast to float. however if you are doing division with whole numbers and are using literal values but expect a float, then one of the literals will need to be a float otherwise you are just doing integer division which returns a whole number
Give me 1 good reason that's not eligibility as to why I should suffix a whole number float with f if it's all the same when compiled.
float f = 1 / 2; // results in 0
float g = 1f / 2; // results in 0.5f
Also, keep in mind that the compiler will optimize a sequence of constants down to a single constant.
float x = 1 + 0.5f;
This produces a constant whose value is 1.5f
Does this perform 1/2 and round down to 0 before casting to float?
This is what I'm talking about!
Okay!
I don't quite understand that part
Correct. Implicit conversion occurs at the end.
Ahh
You don't implicitly need to but it can keep your script more coherent to read quickly. (From my experience)
there is no rounding down, it's integer division. but yes the result will then be implicitly cast to float.
@slender nymph What about the amount of bits required to store that variable?
and for the record, integer division is basically that grade school division you learned when you learned about remainders before learning about decimal numbers. so 1 / 2 == 0 with a remainder of 1
a float is 32 bits
Yes
if you're interested in the gory details, I highly suggest using Godbolt to play around with the compiler
if you knew that then i don't understand the question. the variable is a float which means it is 32 bits
notice how this was optimized to a constant
But buy omitting the f will the variable be interpreted as a double (64 bits)?
No.
is this like SharpLab
i forgot about that
float a = 1; typeof will be a float 32bit and not double 64bit
if 1 was a double, then this would not compile
yes because that is an integer that has been implicitly cast to float. 1 is not a double
Okay I understand!
1.0 and 1d is a double
Thanks @swift crag @slender nymph @sand heath 👍
@swift crag i still dont understand why this line of code:
if (Input.GetKeyDown(KeyCode.Space) && inAir == false)
{
rb.AddForce(new Vector2(0, JumpHeight),ForceMode2D.Impulse);
}
is so weird, if i move left and right while in the air then im flying lol theres almost no gravity
Sounds like you're setting the velocity elsewhere, then
I see nothing wrong with that code.
Are there any kind of layers while creating a uxml so I can move to the front a letter?
@umbral rock https://docs.unity3d.com/ScriptReference/Rigidbody.html
Look at the public methods. There are plenty of options when adding force.
Also, are you sure you want Impulse for your ForceMode?
Are there any other external forces at play?
these are my velocitys
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(speed, 0);
}
if (Input.GetKey(KeyCode.Q))
{
rb.velocity = new Vector2(-speed, 0);
}
you're explicitly assigning 0 to the Y velocity here
well there you go
if you set the Y velocity to 0, you lose your Y velocity
😅 A couple of hours ago I put it there... But no one reads it
aahh yes omg, now i can see, if i press q or d my Y velocity goes to 0, hmmm... how do i fix this
that doesn't mean you should post your question in an unrelated channel. don't crosspost. #📖┃code-of-conduct
consider using your current Y velocitry (:
so that would be rb.velocity.y
indeed
Sorry...
My bad
Thanks for the help mate! sorry, im very new to programming in unity 🙂
i have a problem with my movement, i use brackeys method with a player controller, when i walk backwards toward a wall then i start climbing it for some reason
show your !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.
You should consolidate everything into one Move call
Although, the main reason to do that is to make CharacterController.isGrounded work right
and you're doing your own ground check
unrelated to your issue, but if you are using brackey's FPS movement code then you're probably also using his flawed camera rotation code. Don't multiply mouse input by Time.deltaTime, it leads to stuttery controls. Mouse input is already framerate independent so that isn't necessary. And whenever you remove that multiplication make sure to reduce your sensitivity variable both in the code and the inspector (since it is about 100 times too high)
/*if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
controller.slopeLimit = 100.0f;
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}*/
this is very odd; did you just comment this out?
there's no reason to change the slope limit
yeah i removed the jumping because it had too many problems, like when i looked down the jumping just didnt work, and when i jumped backwards and looked down it started flying for some reason, the slopelimit change suggestion was by some commenter on brackeys video, "1.) Trying to jump onto something can cause a stutter/jitter effect because the slope limit(it should be adjusted when you jump and then readjusted when you land)"
Your camera rotation should have no bearing on how you move. Your move vector is just:
Vector3 move = Vector3.Normalize(transform.right * x + transform.forward * z);
Are you rotating the object that has the PlayerMovementController on it..?
yes
This will cause you to start moving up and down if you look up or down
Brackeys videos are debugging exercises disguised as tutorials
what should i do then?
Is the capsule object at 0,0,0
yes
@umbral rock Side note:
https://chicounity3d.wordpress.com/2014/05/23/how-to-lerp-like-a-pro/
You should be interpolating.
are the character controller, movement controller, camera input scripts supposed to be on the root gameobject?
according to the tutorial
why do you say that?
it's fine to just directly set your velocity
I guess if you want a feel for acceleration(?)
https://unity.huh.how/lerp/wrong-lerp has some relevant advice if you want to smooth out movement
depending on the game though you might not want acceleration
(notably, you can't accrue t across many frames if you're constantly changing the start point)
which is the case for movement
i cant find any tutorial that does the movement right
Not if you care about game feel.
while (t != 1) {
elapsedAnimationTime += Time.deltaTime;
if (elapsedAnimationTime > totalAnimationTime) elapsedAnimationTime = totalAnimationTime;
// Ease in
t = elapsedAnimationTime / totalAnimationTime;
t = 1 - Mathf.Cos(t * Mathf.PI * Random.Range(.3f, .5f));
controller.height = Mathf.Lerp(controller.height, targetHeight, t);
controller.center = Vector3.down * (3 - controller.height) / 2;
camera.localPosition = new(0, Mathf.Lerp(camera.localPosition.y, targetCameraPositionY, t), 0);
movementSpeed = Mathf.Lerp(movementSpeed, targetMovementSpeed, t);
yield return null;
}
This is my procedural crouch and yes you can tell the difference (because of the interpolation).
Many games that feel great set velocity directly
You can lerp the value you input if you'd rather too
We're not talking about many games we're talking about his Unity3D (TM) movement mechanics.
And I was too. Many games IN UNITY3D set velocity directly and feel great. You seem to have a very big misunderstanding ahout how it works
its neither here nor there.. 
i use MoveTowards() for my crouch
guess im weird ¯_(ツ)_/¯
if you want a game to feel as responsive as possible, you probably don't want interpolation
Even if the FX last a fraction of a second you still need telegraphing and a follow through.
i.e: Making it go from 0-100 over .25f is better than an instant burst in almost all movement scenarios.
maybe more realistic but it's not an objective thing
This is code for smoothly changing the height of a character contorller.
It has absolutely nothing to do with movement.
what does this even mean?
It has everything to do with movement
You just don't have context
xD
No, you're just posting a blob of irrelevant code to try to look clever.
It is obvious that you should interpolate between values if you want the change to take a non-zero amount of time
While accomplishing the opposite
This is a tautology.
The code block was posted to provide an example to @umbral rock how they may chose to add interpolation.
interpolation to what? You just said "you should use interpolation!"
This is anti-useful information.
what
private void CrouchCheck()
{
if (Input.GetKey(KeyCode.LeftControl))
{
isCrouching = true;
// Height and Center deltaMaxs need to match
characterController.height = Mathf.MoveTowards(characterController.height, 1f, (7f * Time.deltaTime));
characterController.center = Vector3.MoveTowards(characterController.center, playerSettings.crouchingVector, (7f * Time.deltaTime));
}
else if (!obstacleOverhead)
{
isCrouching = false;
// Height and Center deltaMaxs need to match
characterController.height = Mathf.MoveTowards(characterController.height, 2f, (5f * Time.deltaTime));
characterController.center = Vector3.MoveTowards(characterController.center, playerSettings.standingVector, (5f * Time.deltaTime));
}
}``` my implementation.. no lerp here
that MoveTowards is the interpolation there
MoveTowards is equivalent to a Lerp with fixed start and end points, mind you.
Of course, if the start and end points change, it's no longer feasible to do that
It's referring to his question about rigidbody force and velocity???
it's obvious what you're responding to, but it's non-obvious what form this "interpolation" would take
!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.
why are we arguing about interpolation?
scroll up
yup
you got me
i just wanted to be cool
https://gdl.space/cuqocereha.cs does someone know why it isnt debugging anything at all?
must not be getting reached
debug outside it and see if the entire else statement ever runs
if the raycast doesn't hit anything then the log will never print
consider using Debug.DrawRay to visualize the raycast
@swift crag Perhaps not to you it wasn't
Physics.Raycast defaults to a very long max range
also that raycast will never hit a 2d collider 😉
Yes, it wasn't.
why?
pipes, cool it
because it's a 3d raycast
b/c its a Physics 3d raycast
ah, good catch (:
Anyways man, I was just looking to give the guy some food for thought. It's not that deep
Nor anyone that actually understands the subject..
I suggest you do some basic research on it
i glossed over that Rigidbody2D
food for thought should be properly cooked
and how can i make it 2d?
Well I'm sure y'all ain't gonna lose any sleep over it. This is entirely futile.
bro the one liners from fen, 10+ points
nope.. why u still talkin about it?
use a Physics2D.Raycast which uses the 2d physics engine rather than the 3d one (they are separate)
and make sure ur collider is 2d as well. just in case
that last one was hard af..
void PrintFolderToFile(string folderPath, int indentLevel, StreamWriter writer)
{
string[] subFolders = Directory.GetDirectories(folderPath);
foreach (string subFolder in subFolders)
{
string folderName = Path.GetFileName(subFolder);
writer.WriteLine($"{new string('-', indentLevel * 2)} {folderName}");
PrintFolderToFile(subFolder, indentLevel + 1, writer);
}
}```
anyone know how I could add filenames to this? (it prints the folder directory)
the recursive part kinda sketches me out not sure how to expand this..
nvm i think this is it..
am i correct to assume the highlighted line calls OnJump() the first frame the button assigned to jump are pressed, and not the subsequent frames when they are held?
ive never seen that syntax before tbh w/ you
yes
how can i use the RaycastHit2D return? im looking at the docs and i cant see anything that explains it
i just dont understand it 🥲
/* are you sure about that? */
however you are not actually unsubscribing there because you are using anonymous methods and those are completely separate instances of the anonymous methods
i think i got it nvm, im just blind
ohh. i just realized what the _ was
yeah that's just a discard to ignore the paramter passed by the event they are subscribing to
neat.. i always pass ctx for everything
i still dont understand it
what part do you not understand
inputActions.Player.Move.performed += ctx => OnMove(ctx);
inputActions.Player.Move.canceled += ctx => OnMove(ctx);
inputActions.Player.Jump.performed += ctx => OnJump();```
instead of ctx he throws his away
like my OnJump() it doesnt actually need it
im just not sure what it does in general, i know its an input
they are subscribing to the started event on an input action using a lambda expression
you know what => does right?
yeah its the same as {} correct me if im wrong
I know GetFiles was mentioned but there's also EnumerateFileSystemEntries which I think includes directories and files
oh ur a saint
in its simplest form yes
how can i make the raycast ignore the first object/the object that casted it?
sorry i havent used them before but thanks for informing me 😄
use a counter..
note that this is different than a lambda expression. this is expression body syntax which just makes the body of the method one line. a lambda expression creates an instance of a delegate using an anonymous method
if its the first hit ignore it.. if its the 2nd or more.. use it
how do i make a counter for that?
ahh true true..
i dont have an example of that
i do appreciate this, thanks.
ngl i just followed an online tutorial, is there a better way to do it? bc rn my jump does not wanna work lol
DrawButtonAligned("SPWN FUNC 2", MaxLogoWidth, () => {
Debug.Log("Execute FUNC 2");
});``` does this count?
There's two different usages of it, if it's attached to a method or property then it's a "expression-bodied member", which is just a single-line method.
The second is a lambda expression () => term, (input, ...) => term, () => { multi; line; terms; } which takes many forms but is basically a way to write a method inline, which can also "capture" variables in the containing scope
yeah personally ive only seen => use as a {}
if it isn't working then make sure you've actually enabled the inputs. but also you should either store the delegates in a field and subscribe/unsubscribe using that or just give your onJump method an InputAction.CallbackContext parameter and subscribe the method directly
If you're passing a function to a method by declaring it inline then you're writing a lambda expression
thats the first use-case u'll probably use it as for a beginner.. the other types are a tiny bit more complicated and u reach em later
yeah
Oh and I forgot the 3rd usage of it as an expression beyond methods and properties, which is in the switch expression, where you say:
result = input switch
{
query => resultA,
queryB => resultB,
_ => default
};```
That's also not a lambda.

i consider that basically the same as expression body syntax since that's pretty much what it is, but for switch statements
sure, but it is a completely different form of switch statement really, with different requirements and flexibilties
epic
i ended up just using GetFile.. but i'll look into EnumerateFile.
hmm now how to remove the meta's 🤔
ohh lol imma just shutup. i found it in the same Class
I wish you could do some basic patterning matching against other variables with this
e.g.
QualitySettings.SetQualityLevel(setting.Choice switch {
choiceOne => 1,
choiceTwo => 2,
choiceThree => 3
}, true);
you can use when, but I don't remember how flexible that is. I try to reseve it for simple cases
where choiceOne/Two/Three are variables
ooh, maybe you can
int what = qualitySetting.Choice switch
{
var x when x == qualityLow => 1,
var x when x == qualityMedium => 2,
var x when x == qualityHigh => 3
};
thats very clean
not a huge fan of the extra var x in the front
previously:
if (qualitySetting.Choice == qualityLow)
target = 0;
else if (qualitySetting.Choice == qualityMedium)
target = 1;
else if (qualitySetting.Choice == qualityHigh)
target = 2;
oops, off-by-one error
under the new input system, is there something i can use to check if an input is being held via the update method? where i define jumpAction = playerInput.actions["Jump"];
use IsPressed()
if (obj is string s) does this mean i can use is to do string comparisons in my Input Fields?
I don't like all of these newer and, or, when keywords..
and or: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns#logical-patterns
when: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns#var-pattern
in that case, it's being used to test if obj can be assigned to a string variable
if so, it assigns it to s
these are all used in patterns, yeah
whats that got to do with unity though
well, you tend to use C# when making a game in Unity 😛
this is copied straight out of my "graphics settings" handler
I just figured you meant Boo, given that it and JavaScript were both removed a long time ago
i never know 'er
Bolt (now Visual Scripting) is at least extant!
all i know is that javascript is the reason i append "c#" to every unity related google search
lol. where u looking history books? 🤪
This jump code makes the character controller jump to a certain height and take the original velocity of the character and applies it to move in that direction so you cant just move in all directions in the air, but I would like some air control via A and D keys an i tried to +=, -=, add, subtract, mutiply with another float and or velocity but it just doesnt work, does anyone have a right direction to lead me in or help me to get some air control in this code?
void Jump()
{
if (isGrounded && Input.GetKeyDown(jumpKey))
{
velocity.y = Mathf.Sqrt(jumpheight * -2f * gravity);
if (Airstuff == false)
{
JumpVel = moveDirection;
Airstuff = true;
}
print("ISDOING");
//this is to keep velocity
NewJumppvel = new Vector3(JumpVel.x, 0f, JumpVel.z);
}
}
ur setting ur velocity directly? u should factor in ur air stuff in a calculation and construct a vector to use at the end of ur move functions
is there a way to freeze controls? like not register any inputs for 0.2s
just make a bool with early return
wdym
i have a dictionary called damage which holds a vector 2 key and a int value and i have a function that takes a vector 2 and checks to see if its in the dictionary has an int for it, it then either returns 0 if there isnt or the value at the vector 2 in the dictionary.
the problem is im not sure how to find the int that is related to the vector 2 key
public int GetDamageAtTile(Vector2 pos)
{
if(damage.TryGetValue(pos,out var howmuchdamage))
{
Debug.Log("hit");
return //not sure what to write here;
}
else
{
Debug.Log("nohit");
return 0;
}
}
if(waiting) return;
if(Input.GetKey etc.
activate it with a timer or whatever
howmuchdamage is the value, so thats probably wat you want to return
yea
Time.time can also be an option
or coroutine
ya that was what i was trying to use but for some reason no matter what valeu i put in the dictionary howmuchdamage seems to always return 0
depends, how are you assigning the value
also wat is the point of this thing
ok gotcha, last question is there a player form which allows me to edit the velocity directly? as opposed to character control's kinda limited physics interactions with Move()
Move is how you modify its velocity
there is SimpleMove too but that has its own gravity situation going
anything you would pass to a .velocty you would use Move()
i see
yes it would be similar if rigidbody you only assign velocity, all forces are overridden
its for a tile based game the vector 2 is a tile position and the int is the damage at that tile and the code is just checking to see if the tile you are on is getting attacked and how much damage the atatck is doing
are you using tilemap?
where do you assign a value to a new entry to dictionary
also I would suggest you at least use the Vector2Int version rather than the float
public void damagesquare(Vector2 tile, int howmuchdamage)
{
if (damage.TryGetValue(tile, out howmuchdamage))
{
int Damagenow = damage.GetValueOrDefault(tile);
damage.Remove(tile);
damage.Add(tile, Damagenow + howmuchdamage);
}
else if (damage.TryGetValue(tile, out howmuchdamage) == false)
{
damage.Add(tile, howmuchdamage);
}
}
this si the code for that
wdym?
its supposed to be a grid right ? int is more precise
oh ya i ran into problems with flaot before
im using all int i think
wheres the float exactly
Vector2 is literally a struct of 2 floats
thats why I said Vector2Int has the integer version
not saying thats not correct because it should still have decent approximation for ==
didnt know you could do that
where at ? thats prob why they are not matching up
i use it for the actual grid system not in thsi code
did you try printing all your keys/values in the dictionary to make sure everything is correct?
ya i was tryign to figure out hwo to see dictionarys in the unity editor but im not sure how to
you cannot unfortunately
unity doesn't serialize dictionaries
the old school way 🙂
foreach
oh i see
alright ill try that out ty
hopefully it allows me to see where i went wrong
yeah it should, you will be able to see what is exactly there and why its not pulling the value
foreach(var kvp in myDiction)
{
Debug.Log($"key {kvp.Key} : value {kvp.Value}");
}```
oh isee ill put that in teh code
oh it seems like the tiles that are getting damaged all have a int value of 0
it probably a problem in another part of my code ill go figure that out
Debug.Logs will be your best friends here
suggest you learn the debugger though
whichever works, the point is debugging though basically lol
always triple check which values are what , never make assumptions
public void damagesquare(Vector2 tile, int howmuchdamage)
{
Debug.Log(howmuchdamage);
if (damage.TryGetValue(tile, out howmuchdamage))
{
Debug.Log(howmuchdamage);
int Damagenow = damage.GetValueOrDefault(tile);
damage.Remove(tile);
damage.Add(tile, Damagenow + howmuchdamage);
}
else if (damage.TryGetValue(tile, out howmuchdamage) == false)
{
Debug.Log(howmuchdamage);
damage.Add(tile, howmuchdamage);
}
}
the first debug.log give me the right value which is 1 damage but the 2 other debug.logs seem to be giving me 0 damage which im not sure why
!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.
oh
you should put some more details in ur debugs.. if they're all the same it'd be hard to know which one did which.. esp if one doesnt work for example
well i individually changed 2 into comments the nran it and saw what the otehr one gave
oh
but if i remove out the code jsut gives me errors
you're not meant to remove it then just use the temporary variable it gives you
oh
wait so coudl i make a variable and make it equal to howmuchdamage before and use that one in the dictionary instead of howmuchdamage?
what is even the pointof this
int Damagenow = damage.GetValueOrDefault(tile);```
if you already getting the value in the out
oh thats how much damage was on the tile before
thats wat the out is for
can just be
if (damage.TryGetValue(tile, out var oldDamage))
{
damage[tile] = oldDamage + howmuchdamage;
}
else
{
damage.Add(tile, howmuchdamage);
}
@true heart
this was my first time usign a dictionary so im a little lost
k let me try that out rn
oh ya the codes workign now
thank you
I am currently learning game development and discovered that when using Unity's latest Input System, specifically when getting gamepad.Move.readValue<Vector2>(), the direction vector consistently reads as -0.7,0.7 even when there is no input. This causes the character in my game to constantly drift to the left. I'm very frustrated and unsure how to fix this. Can anyone help me resolve this issue?"
Do you have a wireless controller?
Or a second keyboard
And are either connected?
have you added a deadzone processor?
also #🖱️┃input-system
I don't know, it's the system's default configuration. Where can I check to confirm that I haven't added a deadzone processor to help me rule out this issue?
where ever you set up your input action. but you want to add a deadzone processor as most likely there is at least a small amount of "drift" on your joystick
I once installed the driver for the Switch Pro controller on my computer, but I haven't used or opened it in a long time. Could this have an impact?
These are the values I'm getting from the input system in real-time, and they are consistently very large numbers.
that's because it is normalized
how can i fix it
oh and https://screenshot.help
i already told you
So it's because I selected the digital normalized mode?
that is not the reason you are experiencing stick drift. but the input being normalized is why the values are both 0.707 since that is what you should expect when the values on each axis are the same and the vector is normalized
they could both be incredibly small values, but since you have no deadzone those incredibly small values are not being ignored. it could literally be (-0.000001,0.000001) and the resulting normalized vector2 is going to be (-0.707107, 0.707107)
Got it Thanks a lot bro
No, as long as an input device is not actually connected, there will be not interference. Sounds like the issue is what box said though though
Yep I'll try setting a deadzone to see if it solves the problem
What is the preferred way to add gravity to an object not using a rigidbody?
well if you're not using a rigidbody then you just add a downward motion however you normally move the object
And if I wanted acceleration and terminal velocity and such I would need to make that myself wouldnt I
yes
😔
well yeah, you just mentioned without using rigidbody physics. how else?
Some magic thing included in Unity I don't know about so I don't have to spend the next few days learning physics
set a global gravity vector and apply that to all affected objects . . .
the magic thing is physics . . .
I wanted to try to make my own character controller and I've always read the rigidbody-based controllers are inferior to custom made controllers or ones that use character controller
I'm not sure what the general standard for character controller is and what you're 'supposed' to use
inferior? 🤔 depends on who makes it . . .
if u want a decent physics type controller id use a Kinematic custom character controller
use whatever tf you want. if you like rigidbodies then use a rigidbody, if you prefer the CharacterController component then use that, if you prefer a custom solution then make one.
The only reason I like rigidbodies is because they require no effort from me
some are easier than others, but that depends on the person making it . . .
but if I could sacrifice some of my laziness for something I have more control over..
i personally use the Kinematic Character Controller because it is already set up to work well, and i have a lot of control over it
(specifically i want more control over jumping and movements like dashing)
I'll try it
if it has enough already done for me I should be able to just make my own version of it if i need something more specific
(but I also don't want to re-invent the wheel)
Hi all!
I'm trying to make a camera controller that has a sideways "roll" option
but
the X and Y axes stay global when I use the roll function, meaning moving the mouse up and down actually moves the camera sideways from the player's perspective - up and down in world space.
The code is attached to the player gameobject with a rigidbody, collider and camera.
Here's the code I use (the "Roll" axis is set to Q and E in the input manager):
inputX = Input.GetAxis("Mouse X") * mousesensitivity;
inputY = Input.GetAxis("Mouse Y") * mousesensitivity;
inputRoll = Input.GetAxis("Roll");
yaw += inputX;
pitch -= inputY;
roll += inputRoll;
transform.rotation = Quaternion.Euler(pitch, yaw, roll);
change its localRotation not its rotation (assuming you "roll" a parent)
otherwise you'll need to look at the transform class and its various TransformXXX methods to find out which one is right for what you need
I've tried transform.Localrotation and it has the same effect, the script is parented to the main gameObject, but if I specify playerRigidbody.transform.localRotation I still get the same results
are you rotating the parent object for the roll?
Yes
and the transform.rotation = line is affecting the child object or the parent object?
Here's the hierarchy, the script is attached to the "Player" object, with a rigidbody specified as a public variable, I then dragged the player object's rigidbody into it. The camera and spawner are children of "Player" and move together with it.
so then when i asked if you were rolling the parent of the object with this script on it, the answer should have been "no". and now you can go re-read what i said before
I am rotating the parent object, the player is the parent object, I now specified exactly how I rotate it
but you aren't rotating the parent of the object with this script. you are rotating the object with this script
The player is the parent of all the other objects, are you saying that there should be an additional object above the player in the hierarchy with the script attached to it instead?
no i am not saying that. i told you what you can do if you are rolling the same object that you are rotating the view for
your only suggestion so far has been changing rotation to localRotation
it definitely wasn't the only suggestion. but since you refuse to read the other suggestion, which i conveniently linked you to again, i won't be helping you further
getting snappy in the beginnner coding section because you refuse to elaborate... why are you even writing then?
"Duh, re-read what I said"
mate i'm not getting "snappy". i just refuse to help people who refuse to help themselves. i told you what to look at to find what you need
put some fucking effort into getting your issue resolved
I think he’s talking about this
unity is freezing my game whenever i reload my scene or use the on click event i have set to reload my scene, anyone else ever have this issue? only the music/sound effects are still going, everything else is frozen. 😦
the transform class (to my understanding) is just whatever you put behind transform (the documentation also links there) - I've tried rotation, localRotation, transformDirection, I've tried using both X and Y inputs for both, offsetting their incluence based on rotation of the object and nothing worked
have you actually looked at the documentation like i suggested?
great! did you bother looking at the methods i suggested you look at?
"the various TransformXXX" ? like I said I already tried?
show what you actually tried
although i will say that all of this would be easier if you did just have another parent that you used for the roll
however that isn't necessary as you have these convenient methods to transform a Vector3 from local space to world space
"I've tried rotation, localRotation, transformDirection, I've tried using both X and Y inputs for both, offsetting their incluence based on rotation of the object and nothing worked"
I could also say "re-read what I said"
also tried quaternion, eulerAngles, localEulerAngles...
and i said show what you tried. obviously implying i wanted to see your actual attempt in code. but if you want to be a baby about this i'm just going to block you
my code is way too long to post here
you can post your !code so that someone who is willing to help you further can see it
📃 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.
In a ragdoll object, how can I identify what part my bullet shot? Do I need to make colliders for each part or?
getting angry at a beginner for not knowing immediately how to express their problem, when I posted my code and video of how it works, then saying "now go and re-read what I said" when all you said is "go look at the entirety of the transform class documentation" (I already have, to the best of my ability) is beyond unhelpful.
that would be the way to do it, yes
Ahh okayy, thank you!
i'd also give each part of the ragdoll a component that can take damage and relay that to whatever the "main" health object is. that way you can just TryGetComponent on the hit part to get that specific component and then that component can take the damage and pass that damage along to the main part. Doing this would also allow you to optionally have individual health values for each part in case you wanted to be able to break specific parts off or something when they've taken enough damage
Ahh yes, I remember doing something like that before. Thank you!
You need to actually show what you tried if you want help. Specifically what you tried with TransformDirecrion which is one of the three Box was suggesting
This is completly on you, hes getting angry cuz youre activly against working him
I would have long called you hopeless and blocked you lol, hes way more patient then many of us.
Don't bite the hand that feeds you!
@slender nymph regarding your bio.
if you dont want random dms from people asking for unity help you can do this btw:
i am aware. but that still doesn't stop it if someone shares a completely different server with me. which still happens quite frequently
I made a SinCos struct with trig identities for 45 and 90 deg turns. But on second though, I could have just added extension methods on Vector2 for that. 
can i set 2 coordinates as a public variable which i can change using some marker ?
for example i want an saw to move from point a to point b
so can i make the points an variable and then set those points as position of the markers ?
make it easier and use 2 transforms, then make fields for transform
but then i would have to manually enter the coordinates every time /
how do you want to set them then?
wait i can set those as position of a child game object and i will just move around the game abject
I mean thats what i was trying to tell you
Hello,
What is the best method to save data for a videogame ? I see some tutorial use text file , JSON or with PlayerPref
Looking for advice. I got a Player object that is a child of the Unit object. I was wondering, where would I be putting the code for player movement? In the player object or as a seperate class altogether?
Don't use PlayerPrefs to save data as those are usually intended for saving Player preferences (e.g. volume settings, graphics settings, etc.) Serializing your scene data into a binary or making a JSON separate from PlayerPrefs would be better.
By "player object" do you mean some kind of a script/class?
Or a gameObject?
with my player im applying rb.velocity to it so that the movement is instant and doesnt accelerate or deaccelerate, but for some reason after ive let go of either the left or right key to move it continues to move for about half a second, is this normal velocity behavior or is something going wrong?
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerController : MonoBehaviour
{
[SerializeField] float speed = 5;
private Rigidbody2D rb;
private float horizontal;
[SerializeField] private float jump = 5f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
}
void FixedUpdate()
{
// horizontal movement
// horizontal movement
if (horizontal != 0)
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
// jump
if (Input.GetKey(KeyCode.UpArrow))
{
rb.velocity = new Vector2(rb.velocity.x, jump);
}
}
}```
Yes. It is a normal behaviour in physics in general(real world and game engines).
Newton's First Law (Law of Inertia): An object at rest stays at rest, and an object in motion continues in motion with the same speed and in the same direction unless acted upon by an unbalanced external force.
In your case it stops because of dumping and friction. Which are external forces.
right ok, thank you 🙂
If you want it to stop immediately, remove that if statement that checks if horizontal is 0 or not
Script/class
What is it responsible for?
how does that effect it?
Handling data specific to the player. Stuff that other units wouldn't care for. I know I'm being vague at the moment on this front. Currently just thinking about the movement part atm
It prevents you from changing the velocity to 0.
ah right
If the movement is the same for player and npc, I'd put in in a separate "CharacterController"(or something) script.
Gotcha, that's where my mind was at initially, just wanted to make sure
i dont understand something about the camera rotation calculations, every video i watch on how to move the camera like in an fps game they do this,
yRotation += mouseX
xRotation -= mouseY
what is this calculation? i know its if u move your mouse but it doesnt make sense to me
Depends on how they use it after that.
I'd assume that it's Euler angles
`public float moveSpeed = 0.3f ;
public Transform startPosMarker;
public bool movingToEnd = true;
public Transform endPosMarker;
private void Start()
{
transform.position = startPosMarker.position;
}
private void Update()
{
Vector3 targetPos = movingToEnd ? endPosMarker.position : startPosMarker.position;
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
if (transform.position == targetPos)
movingToEnd = !movingToEnd;
}`
why doesnt this wor
the if statement doesnt work
its not switching target pos on reaching that position
rather than
if (transform.position == targetPos)
try
if ((transform.position - targetPos).magnitude > 0.1f)
For the following, I was wondering if the Update function will run directly after the #1 mark? Or wil it wait for the function to finish execution before running the Update ufnction
public static SmallMissileScript Attach(GameObject go, float speed, Vector3 faceDirection)
{
SmallMissileScript missile = go.AddComponent<SmallMissileScript>();
// #1
return missile;
}
private void Update()
{
}
Function is called in the FixedUpdate function of another monobehaviour
standard functions are never interrupted by Unity messages
The Update method runs the first time during the update phase next frame
I meant the newly added component’s update fcn mb
no, only the Awake will run at that point
Gotcha thanks
btw, if you want the Update to run there is nothing to stop you calling that from Awake
To make it immediately start running if Im getting this correctly
yes
for positioning and movement
could also be ray casting, anything really that you do in Update but you also want to do as initialization
that would depend on your use case, it could also be purely used so as not to duplicate code
yes
Well, then that's the answer to your question
shouldnt it be if ((transform.position - targetPos).magnitude < 0.1f)
btw it still doesnt change when reaches the end pos

this should work
but it doesnt
oh ok i got it , basically i have the end pos and start pos game object as child objects soooo , when the saw moves the end pos and start pos move along with it
it isnt becuase of the if statement
does anyone know why TMP text is so blurry?
(this is the view from game mode)
and these are the settings
And if it affects anything, this is a BRP project
Is the game view zoomed in?
nope, the scale is normal
actually even the text in TMP example scenes is blurry
its fine in editor mode though
hello, im watching a tutorial on how to make an endless runner because i wanna make flappybird, and i came across the instantiate function but i dont understand why he sets the position of the instantiated object to transform.position? he has 2 objects that he wants to spawn, an object thats flying and an object thats on the ground, but somehow even tho he sets the position to transform.position the objects are at different heights?
he doesnt say to the instantiate function where he wants to spawn the object, he just says he wants to spawn them at the transform.position, but why are the 2 objects at different positions?
This should be the first thing appearing in the dropdown when typing this class' name. The namespace will automatically be added when pressing the Tab key
i have a script that references a gameobject, but from donotdestroy, the original is destroyed and the new instance is kept instead, and so if i switch scenes and come back the script does not get referenced anymore.
does anyone have code that preserves the original gameObject and destroys all other clones?
Several overloads of the generic Instantiate method have the Vector3 position parameter, which spawns the Object at the specified position. Apart from this, I wasn't able to understand your issue further.
You only have to google "unity singleton" and copy-paste the code to the created script
oh ok thanks
well, in the tutorial he sets the specified position to transform.position wich should spawn all objects at the same place, but they spawn at different positions? how is this possible, because he spawns in flying objects and ground objects... i searched everywhere in his code but he just has an instantiate(gameObject, transform.position, quaternion.identity)
Perhaps, I would be able to answer your question if you share the code
private void Spawn(){
Vector2 randomPosition = new Vector2(
Random.Range(minPosition.x, maxPosition.x),
Random.Range(minPosition.y, maxPosition.y)
);
GameObject obstacleToSpawn = obstaclePrefabs[Random.Range(0, obstaclePrefabs.Length)];
GameObject spawnedObstacle = Instantiate(obstacleToSpawn, transform.position, Quaternion.identity);
Rigidbody2D obstacleRB = spawnedObstacle.GetComponent<Rigidbody2D>();
obstacleRB.velocity = Vector2.left * speed;
}
}
this is the spawncode
look at the instantiate, he gives it a position transform.position
wich is logical if u want to spawn 1 object at the same place, but he spawns 2 objects at 2 different places, wich isnt logical to me anymore
hello again, I implemented singletons, but the original gameobject was deleted
note that ChooseSong(false); still chooses the song
yes, code is executed from top to bottom, you do not stop this
I am trying to modify the color of my particle system, but every time I change something a new error pops up. What's the right way to go about this?
transform.position is the position of the current GameObject and is not constant, which means, it's going to change according to the position of the current GameObject.
sorry, I am still slightly confused about the implementation of singletons
You may look in #archived-code-general, I was trying to link you this thing #archived-code-general message
ok
under what circumstances do you expect ChooseSong not to be executed?
when the script is an instance (thus ChooseSong only executes for the original gameobject)
why, nothing in your code indicates that is what you want
i was assuming that the if else loop deleted the gameobject
yes, and the code continues to execute
thus the script would stop running and thus everything else after would run only if the script wasnt destroyed (thus was the original)
i see
That's right
why would you assume that?
The script stops running when the object is destroyed
This code is the same
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObjet);
ChooseSong(false);
}
else
Destroy(gameObject);
Are you saying the object is destroyed when starting the game?
essentially in pseudocode i want
IF no other instances
{
ChooseSong
}
ELSE
{
some magicky way to detect if the script is the original one or a cloned instance
destroy the cloned instance
}
You should change mainModule do main
You should copy one of the generic Singletons I've send you, derive your class from it, and easily implement this thing
then why not just put the DDOL and ChooseSong inside the if statement you have where it belongs
Great, now read the error
I did. As I said, new error whenever I change something
What does the error tell you?
this works to keep only one of the gameobject alive in any scene, but it doesn't preserve the original
ok
but he has the objects as prefabs, then they dont have different current positions right?
wrong
if (no instance)
set instance = this
set DDOL
ChooseSong()
else
Destroy
As I have mentioned, transform.position is the position of the GameObject, whom the script is attached to. This means, the position of every GameObject may differ. Prefabs are GameObjects.
hmmm, ok, still dont fully understand it but i guess i'll leave it by that, its weird bcs the 2 objects are used as prefabs and both their positions are 0 0 0
Why would this be different from what they have implemented?
Unity doesn't call the Destroy method instantly
then it might be another error - ill give you some context
essentially i have a script that gets the length of the current song being played to know when to play the next song. This script is attached to my musicplayer, which is carried via DDOL to other scenes.
However, if switching scenes concluded with deleting the original, then this would result in detaching the musicplayer, and thus the script would reference a missing object.
so now we have htis
Not sure what exactly you don't understand
If you want to make sure, print the GameObjects' positions before instantiating them
how? you must be destroying it explicitly
are you perhaps calliing CreateSingleton somewhere else?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine;
using TMPro;
public class musicplayerscript : MonoBehaviour
{
public AudioSource source;
public AudioClip clip1;
public AudioClip clip2;
public AudioClip clip3;
public AudioClip clip4;
public AudioClip clip5;
public AudioClip clip6;
public AudioClip clip7;
public AudioClip clip8;
public AudioClip clip9;
public AudioClip clip10;
public AudioClip clip11;
public TextMeshProUGUI songname;
public TextMeshProUGUI timeleft;
public TextMeshProUGUI songid;
float playingtime;
string clipname;
int clipID;
int random;
public static musicplayerscript instance;
[HideInInspector]
public int score;
private void Awake()
{
CreateSingleton();
}
void CreateSingleton()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this);
ChooseSong(false);
}
else
{
Destroy(gameObject);
}
}
void Update()
{
playingtime -= Time.deltaTime;
if (playingtime <= 0)
{
ChooseSong(false);
}
float Playingtime = Mathf.Floor(playingtime);
if ((playingtime % 60) < 10)
{
timeleft.text = (Mathf.Floor(Playingtime / 60)).ToString() + ":0" + (Playingtime % 60).ToString();
}
else
{
timeleft.text = (Mathf.Floor(Playingtime / 60)).ToString() + ":" + (Playingtime % 60).ToString();
}
songid.text = "ID: " + clipID.ToString();
singleton has been called nowhere else
Then there is no way this gameobject will be destroyed
DontDestroyOnLoad(gameObject); btw
well, now i understand it, but i got a weird thing where im instantiating pillars from flappybird, but theyr spawning in the middle too, i just want to spawn them at the edges of the view, i dont know what im doing wrong atm, could i send u my spawning script?
ok then
we can try another route
in this case, when switching through scenes, these things get disconnected right?
Sure thing, go ahead. Don't forget to use a specific site if you're going to send the full code
lets say if the object referencing musicplayer was scene-specific
how do i do this via the website?
!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.
Save your code and send it here
anybody know how i can fix this, so that i can make y random?
a powerful website for storing and sharing text and code snippets. completely free and open source.
is it that?
a powerful website for storing and sharing text and code snippets. completely free and open source.
or this
Random.Range and float values end with the letter f
Both are fine
The code spawns a random object between the minimum and maximum spawn positions. I see no issue here.
ok so i have decided to simplify the issue by tackling a simpler problem:
referencing textmeshproUGUI elements with gameobject.find doesnt work
am i forced to use <GetComponent>?
yes, thats true, but the problem with that is that they spawn in the middle, wich cant happen in flappybird if u know what i mean
alr thank you
Lets say I want a Navmesh agent to dash forward.
What would be the best way to go about doing this? I could stop it, then use Warp I suppose, just wondering if theres another way to handle it or not.
I do know Flappy bird. You should first try to combine all your thoughts into a certain objective, then code it
maybe dumb question but why are abstarct classes used
lol, im utterly bad at coding haha, i dont know what i should change about this code
In Unity, you cannot add an abstract class to the GameObject. This is useful when creating a script, which should not be attached to the GameObject, and requires additional classes to derive from it, which are then attached to it.
This includes classes, which don't have a specific functionality by themselves, and do require other classes to implement it.
why not just change the agent speed?
That's why I'm asking you to code in your own words by sharing your objective here
so you can define multiple similar but different things, think Weapon as abstract and Sword and Gun are 'real'
the only problem i still have right now is that the spawning objects are spawning in the middle, i want them to spawn at 2 different specific heights, wich i just dont know how to code
look, they spawn in the middle
instantiate uses a position.. just define 2 vectors with ur Y position at those heights
and alternate
so i'll have 4 random ranges between y axis?
For example, I may have a class EnemyBehavior, which cannot be attached to an Enemy, because it doesn't possess any functionality.
I create the classes EnemyFoo, EnemyBar etc., which are functional and already do things.
Vector2(0, Random.Range(0f, 2f)); something like that
or throw in a variable u can change w/e
Vector2(0, Random.Range(0, RandomY);
RandomY = Random.Range...
Specific heights? Do you want them to be screen size dependable?
nope he just needs flappy bird pipes
i want them to only able to spawn at the top of the view i send u and the bottom of the view
wait, why isnt this working in my code than?
it should be.. show what code u have
because i use a minPosition and maxPosition
a powerful website for storing and sharing text and code snippets. completely free and open source.
So you have:
boolean: spawn the pipe at the top or the bottom of the screenheight: the height of the pipe

