#๐ปโcode-beginner
1 messages ยท Page 461 of 1
What is "display message option"?
i'm making a building tool of sorts, I need to know what direction the mouse is facing. I've got it to work but I'm interested what the most efficient way to do this would be in 2d.
sounds a bit stupid reading it back but whatever
facing in relationship to what?
a tile
then just get the direction of the mouse from the tile and check the x of it
yes but if it's in two directions at the same time it breaks the code
how can it be in 'two directions at the same time'
like i can't check which one to build if it's facing up and left
you need to provide more context, not sure what you are asking
i just woke up the english aint englishing wlel
then check the distance as well
if x is more than the abs value of y then it's right, not up or down, does that make sense?
i showed the script to a friend and he told me it's wrong but didn't tell me how
tbh, no
if you have a direction vector from the tile the x will always be negative or positive giving you left or right, I dont see where y comes into this
i have an if statement later on that checks every direction and returns a different tile for each, if it's both since the mouse is at let's say x = .5 and y = .3, it may choose to place a house facing up even though the mouse is closer to the right?
you've lost me completely, this is beginning to sound like an XY (excuse the pun) problem, you'll need to explain exactly what you are trying to achieve
... that is really hard to explain for some reason
this may help, it's code I use to determine the direction of joystick movement from a gamepad but the logic should be the same for you
Direction GetDirection(Vector2 v2)
{
if (v2 == Vector2.zero)
{
// Key up
return Direction.Origin;
}
Direction dir = Direction.Origin;
bool? on = IsOn(v2.x);
if (on.HasValue && Mathf.Abs(v2.x) >= Mathf.Abs(v2.y))
{
dir = on.Value ? Direction.Right : Direction.Left;
}
else
{
on = IsOn(v2.y);
if (on.HasValue && Mathf.Abs(v2.y) >= Mathf.Abs(v2.x))
{
dir = on.Value ? Direction.Backward : Direction.Forward;
}
}
return dir;
}
bool? IsOn(float value)
{
float i = value;
if (i > 0) return true;
if (i < 0) return false;
return null;
}
it's kind of similar to what i did
You need to "round" the direction to the closest 90ยฐ angle (up, down, left, right), correct?
yes
Can be done with the code above, should be able to do the same logic roughly, with two dot products (up down, left right - maybe diagonally in your case) and a few if statements to know in which quadrant the direction falls in
https://pastebin.com/9LtDHhWg
guys please help
i have code for generating a minecraft type chunk based on a 3d array of block data, then faces are positioned correctly but their normals and uv are scrambled and mixed up
ive narrowed it down to the generate mesh code itself and something to do with the uv array and the other arrays not matching up
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
ive been debugging for the whole day i cant fix it
Looks like an UV issue, they should be in 0-1 range, try to log/debug them to see if they correspond to the correct location on your texture atlas
!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.
UV(0.00, 1.00, 0.00)
128to32
Vertex[0]: (0.00, 1.00, 0.00) (0.67, 0.20)
Vertex[1]: (1.00, 1.00, 0.00) (0.75, 0.20)
Vertex[2]: (1.00, 1.00, 1.00) (0.75, 0.40)
Vertex[3]: (0.00, 1.00, 1.00) (0.67, 0.40)
UV(1.00, 1.00, 0.00)
144to32
Vertex[4]: (1.00, 1.00, 0.00) (0.75, 0.20)
Vertex[5]: (2.00, 1.00, 0.00) (0.83, 0.20)
Vertex[6]: (2.00, 1.00, 1.00) (0.83, 0.40)
Vertex[7]: (1.00, 1.00, 1.00) (0.75, 0.40)
UV(2.00, 1.00, 0.00)
144to32
Vertex[8]: (2.00, 1.00, 0.00) (0.75, 0.20)
Vertex[9]: (3.00, 1.00, 0.00) (0.83, 0.20)
Vertex[10]: (3.00, 1.00, 1.00) (0.83, 0.40)
Vertex[11]: (2.00, 1.00, 1.00) (0.75, 0.40)
UV(3.00, 1.00, 0.00)
144to32
Vertex[12]: (3.00, 1.00, 0.00) (0.75, 0.20)
Vertex[13]: (4.00, 1.00, 0.00) (0.83, 0.20)
Vertex[14]: (4.00, 1.00, 1.00) (0.83, 0.40)
Vertex[15]: (3.00, 1.00, 1.00) (0.75, 0.40)
they match the position x y i have literally no fking clue why they arent working
im about to jump out the window
wait
if i print from the mesh it changes
how
i hate my life
oh wait it didnt change fm
I don't know if that's the issue but it seems that you are drawing your triangles for your face like that
here
// Define triangles
triangles.Add(vertexIndex);
triangles.Add(vertexIndex + 2);
triangles.Add(vertexIndex + 1);
triangles.Add(vertexIndex);
triangles.Add(vertexIndex + 3);
triangles.Add(vertexIndex + 2);
oh wait really
//
using UnityEngine;
public class RagdollMovement : MonoBehaviour
{
public Rigidbody hips;
public float speed;
public float strafespeed;
public float jumpforce;
bool isGrounded;
void Start(){
hips=GetComponent<Rigidbody>();
}
public void FixedUpadte(){
if(Input.GetKey(KeyCode.A)){
if(Input.GetKey(KeyCode.LeftShift)){
hips.AddForce(hips.transform.forward * speed *1.5f);
}
else{
hips.AddForce(hips.transform.forward * speed);
}
}
}
}
my player is not showing any movement
the script is correct ig
triangles.Add(vertexIndex);
triangles.Add(vertexIndex + 2);
triangles.Add(vertexIndex + 1);
triangles.Add(vertexIndex + 3);
triangles.Add(vertexIndex + 1);
triangles.Add(vertexIndex + 2;
should i be doing it like this
FixedUpdate is misspelled in your code snippet here
nevermind your vertices are not in a Z pattern, im trying to see whats wrong
ah ok lol
i dont think its ever gonna be solved
this is worse than that time i used ; instead of : in a hundred line python script
and had no errors
Can I use this channel for like help on how to learn C#?
I see you are setting uvs in AddFace but then you are overriding them line 84
and line 89 Rect rect = GetTileRect(textureIndex); seems to be wrong, try to use rects instead
Not in general, no. This is for Unity specific questions. You can go here for learning C# !cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Okay thank you!
wait could u explain what you mean by using rects instead?
I mean that you are creating a texture atlas and its returning you rects but then you are not using rects in the uvs calculation
I think an easier approach would be to create the texture atlas before you create the faces, then when you create the faces, you can set the uvs to the corresponding position on the atlas
so you can set the uvs only once in AddFace (and no need to override them later)
i have a confession
when i was first turning my array of 2d tilemaps to mesh 2 days ago i used chatgpt as a base because i had no clue how mesh generation worked
the first version of it worked perfectly fine so i just built on it so i dont know how a few parts of it actually worked
but i think u are onto what is causing the problem
GPT is good but you have to really understand what it is doing so its easier to debug and you can adapt what it gives for your specific use case
when i got rid of the entire adjusting to texture atlas part black squares started showing
i think it might be the texture changing orders when they get added to the atlas
yeah i get that
i got lazy because i didnt want to spend a week watching a 12 part tutorial
but i reap what i sow now i spend 12 hours debugging one thing
yes I can understand ๐คฃ
yes that might be the issue
how would ur idea work? do u mean i check what kind of blocks is in each chunk, get their texture and add it to an atlas and then uv map to them after?
ill have to learn how texture atlas work because right now im mapping to individual textures for each face of each block and then adding all to an atlas
yeah ill just watch a youtube guide
btw do you have any idea why my normals are only facing one direction?
so the steps would be:
- create the atlas
- create the faces (4 vertices, 2 triangles)
- set the uvs so the top left vertice match the top left of the texture on the tilemap, top right=top right, etc.. (0 to 1)
- set normal to the direction of the face
(for the normals I think mesh.RecalculateNormals() could do the trick)
iirc normals are set for each vertex, and in your code you are adding only 1 normal per face, should be 4)
ah ok ill see
i tried recalculate normals but it did nothing on the mesh
yeah gpt did that part i just crossed my fingers and then gave up and tried fixing the uv first
ah so does that mean uv, normal and vertices arrays are all parallel lol
like index 0 for each array is for the same thing
yes they should match
wait gpt did add 4
then triangles are just how you link vertices together
i think vertices has something to do with it cuz when i switched the vertices it just flipped all the normals the opposite way etc
this is too abstract for my brain
yes iirc the triangles should be created counter clockwise for the normals to be computed correctly
so
triangles.Add(0);
triangles.Add(2);
triangles.Add(1);
triangles.Add(1);
triangles.Add(2);
triangles.Add(3);
Its ok cause in your code the 1 and 2 vertices are flipped
ah lol
i wish i could visualize it in unity
the mesh gets generated real time so i cant even see the uv map or stuff i just have to use mental imagery
why isnt 3d tilemaps built into unity its 2024
you can visualize normals in rendering debugger>material>vertex attribute>Normal
Also you should try to make only 1 face, get it look right then you can loop to create all others
its easier to debug
nvm, didn't know the rendering debugger does that for you
yeah i can change the size and content of the chunk really easily by just modifying chunk size and depth
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
heres the original code that turns a 2d tilemap into a mesh plane btw
it had the uvs correct but after i surgically transplanted the code it broke
lol i didnt know either theres several hundred sliders and checkboxes there
yeah see it works even now when i copy paste it back
man kill me
lol
also i dont get it
if texture can be split up into sprite tiles, why cant i directly get the sprites by resource.find
instead i need to calulate the rect myself
Hi. I have a problem: I want to change the color (let it be alpha at the beginning) through a script, but this only works when the value in the slider reaches 0 (from 1 to 255, the alpha color does not change at all, and at 0 it changes immediately to 0). What's wrong here?
Color is 0 to 1
Not 0 to 255
Oh, oh... I was just looking at the values here. Thanks
Yeah, that is just for ease of use in the editor, not related to the actual numbers used in code
Understand. Thanks
Color32 bits is what gives you 0-255
hi so i tried making raycasts by following a tutorial because raycasts hate me, when i use the drawWireSphere bit, it puts the wire sphere somewhere else but for him it puts it where the raycast shoots. how do i fix this?
Vector3 collision = Vector3.zero;
public LayerMask layerMask;
private void Update()
{
var ray = new Ray(this.transform.position, this.transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100, layerMask))
{
Debug.Log(hit.transform.gameObject);
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(collision, 0.2f);
}
for context it's supposed to shoot out of the spot light forwards
You never assign a value to the collision field, apart from Vector3.zero?
Seems like you should be assigning the raycast hit point to it
LETS FUCKING GOOOOOOOO
YEAHHHHHHHHHHHHHHH
im gonna cry
heres ur name mispelled
because this wouldnt be possible without ur guys help lmao
holy shit ive been debugging for 14 hours
28 if u count yesterday
14 hours in one day??? Holy
hello, how can I detect if a bullet fly near-by a player, I tried with a collider in trigger mode, but it doesn't work because the bullet game object is too fast, so I think I could use raycast, but as the bullet is going very fast I don't know how to make the calculation take place all along the path and not just at the ball position when updating frames. because, as you can see, since detection is based solely on frames, the bullet wouldn't detect that it had passed near a player, whereas by tracing the bullet's path, you can clearly see that it has passed near the player.
If the bullet has a rigidbody, you could enable interpolation on it so it checks along its path
Interpolation is just a visual so it moves every frame, shouldnt affect the actual collision. You could try the collision detection modes like continuous
Oh not sure if those work with triggers though
If the detection zone is a trigger and the bullet is implement with raycast stepping, then you can see if it overlaps by using a line cast.
Alternatively, this can be done purely with math by calculating the distance between the line segment and the center of the player. If the distance is less than the radius of the detection zone, the bullet went through it.
Depending on of this is 2D or 3D, the math is a bit different, but neither require any complicated or expensive math operations. You can find examples of it online.
If this is 3D and the player is a capsule, you'll want to get the shortest distance between two line segments, where the player's capsule is one of those lines.
Oh, right, that's what I meant, continuous. Sorry, got my terminology mixed up between the two
oh yes it's a good idea !
nope I tried and it doesn't ๐
Nice, it looks awesome ๐
any reason i cant add audio sources in the inspector?
it wont let me drag and drop
is this a prefab
it was but i unpacked it
is the audio source on the same object ? show the hierarchy
which object has audiosource
pixel boy
I dont see it
yes the slot is empty, you need to slide the component in there
its a on hit sound effect
Whatever you're dragging into that slot must be or have an Audio Source component ๐
You need to add an Audio Source component to something
you're confusing AudioSource with AudioClips
AudioSource is the radio, AudioClips is the music
if you want to store the audioclip in code sure
this is just a Reference, not the actual component
it means " I want to do something with this thing"
you still need to assign it which one exactly you want to do thing on
well you wouldn't Play a sound without an audiosource
you need an AudioSource to play AudioClip from
so add it as a component?
yes then drop it in the slot
put the sound you want inside that AudioSource clip slot
alr
then dragged the source to the hit sound
yes
also your IDE did not look configured by the white font everywhere
its still not playing but it mgith be a problem with my collision detectors now
IDE?
yeah your code editor
(And this warning)
im not sure but i dont have anymore time i gotta go to work
check the steps ^ @summer notch
Does anybody know how to check velocity of my rigidbody on the x and z axis? I wrote this code, but it still changes when velocity on the y axis changes
void Update()
{
xzVelocity = rb.velocity.magnitude - rb.velocity.y ;
if(xzVelocity > 13)
{
//Do thing
}
else
{
//Stop doing thing
}
}
var velocityXZ = new Vector2(rb.velocity.x, rb.velocity.z);
float speedXZ = velocityXZ.magnitude;```
or use sqrMagnitude as its faster then do (speedXZ * speedXZ ) >
ty
does anyone know if turning two sets of wheels in opposite directions will actually result in rotation using the wheel collider? I've tried to code it so specific wheels turn in specific directions but it just propels the vehicle forward
I don't know the answer, but I think it would be kind of tricky. I reckon it should usually work to some degree, but for it work really well it seems like that sort of rotation would depend on all of the wheels slipping roughly equally....
I'd be curious if you get better results by increasing the mass of the vehicle, or freezing it's x and z rotations
i experimented a little more and it seems both wheels can turn independently, but when they're both turning opposite directions they barely move on ground contact and the vehicle just kind of moves back and forth slightly instead of turning
i also just dont understand the extremum and asymptote values which control tyre friction
unity documentation is pretty shit at explaining how it works. All they have there is a graph
thats it
what are your guys thoughts on additive scene loading / dealing with scene management. I'm having issues cleaning up everything from scene changes (object pools, etc) and having to subscribe to SceneManager.sceneLoaded for everyone of my DontDestroyOnLoad classes. ideas?
This is the best explanation I ever found, but whatever I read there's never stuck ๐
Im trying to point an object towards a target, but by splitting the pitch and yaw between two transforms
any pointers on this?
thanks, im reading it now
What's the error say?
An object reference is required for the non-static field, method, or property 'MoveMentScript.isGrounded'
Do you get the script from object?
So you can't access the isGrounded field via MoveMentScript.isGrounded, because that's trying to access it as if it were static - that is, a value existing directly on the class rather than any specific instance of it.
You could make isGrounded static, but it wouldn't make a lot of sense here. The moveMentScriptScriptComponent field is initialized to that value when this MonoBehaviour is instantiated, and that happens right when you add this script to a Game Object. You don't really need to know if something is grounded at that time.
You should instead initialize this value in like Start(), from the isGrounded field on the moveMentScriptComponent reference (which is presumably already referencing a specific MoveMentScript instance).
no, that's not at all what's going on
Oooh
movementScriptScriptComponent is a reference to a MovementScript, and trying to assign "isGrounded" which is likely a boolean will not work because MovementScriptScriptComponent is not a boolean
Oh thats true
What do you mean they're split between different transforms? Like, one transform only rotates on the x axis, and one on the y? How does that control the whole object's rotation?
Well, that is what the error was saying. But yeah, that's also a good point ๐
Thanks to both (:
yeah that's what I want - its for a turret. the Pitch transform controls the gun moving up and down, while the yaw transform controls the gun moving side to side
Gotchya ๐
You could get a target direction for each by taking the direction to the target and zeroing out the irrelevant components... how are you rotating these transforms?
for the X axis use Vector3(target.x, own.y, target.z)
for the Y axis use Vector3(own.x, target.y, own.z)
ohh.. bugger
i think i have an idea - I could convert the target's rotation into each transform's space, and try it that way?
its gotta be possible tho.. u a turret functions exactly how most first person shooters are set up
rotating teh body left and right and the camera up and down
aka turret
Work with directions. Compute the direction from turret to target, then split that. Don't use XYZ of positions of objects
thats a solid way ^
I have a problem with combining the same items in inventory. if work mergeItem function,source slot is discharge but doesnt change itemcount of targetslot.
I use scriptable object
Once you have the directions split, you can convert them to Quaternions with Quaternion.LookRotation(dir) and feed that the two transform.rotations
if im understanding this right: i would project the direction onto the relevant plane (since the turret won't always be pointing straight up), then rotate towards that projected direction
That is also an option, with Vector3.ProjectOnPlane()
sick, im only asking here bc my last question got me sent here (from general) for not being complex enough
unless i misunderstand how the tiered channels work, should I only ask here for vector maths stuff, or was the person that responded to me just being a bit dense lmao
Is Slot a struct?
The concept is subjective and not well defined, so something "advanced" for one may be "intermediate" for another
Usually, unless there is a clear lack of the basics (ie. how C# works at a barebones level) you won't be redirected to another channel
alrighty
tbh its right about middle ground. its not very beginner (so top level) but its not very general (probably lower level)
quaternions and rotations always have a tricky++ modifier
I match slot with scriptable object.
funfact, i always try to make something quick and simple to get my brain right for the day..
today I've chosen to follow suit
public class TurretController : MonoBehaviour
{
public GameObject turretBody;
public GameObject turretBarrel;
public Transform target;```
whoops! do you receive any logs?
the hostilities
also, if the items are the same, you don't need to check if both of them are stackable . . .
i was just makinh headers for some scripts and i use caps . . .
you right:)
I GOTCHA!
okay, my problem has been resolved, thank you spr2
whoohoo! what method did u use?
Vector3 direction = currentTarget.rb.worldCenterOfMass - turretWeapon.transform.position;
pointer.forward = direction;
Vector3 p = Vector3.ProjectOnPlane(direction, pitch.right);
Vector3 y = Vector3.ProjectOnPlane(direction, yaw.up);
pitch.forward = p;
yaw.forward = y;
this be my code
finally going to work on a gun using a component-based approach . . .
hope that works out for you - i always preferred inheritance over composition but if it works then it works :p
ok i take it back, my problem has not been solved
it bugs out when placed on any surfaces not aligned with the world up
i started a long time ago and stopped because of something i can't even remember, but it worked (still works) pretty well. i just add components i want to the gun for functionality. everything is executed from SOs (services) on each component. that allows me to swap them out for different behaviour . . .
I might just solve my problem and make it a ball turret
what are your guys thoughts on additive scene loading / dealing with scene management. I'm having issues cleaning up everything from scene changes (object pools, etc) and having to subscribe to SceneManager.sceneLoaded for everyone of my DontDestroyOnLoad classes. ideas?
ooh.. inspector junkies gonna love you ๐
ohh nooo noo
the 2axis part is wat gives a turret its look/feel
Thats pretty much how we deal with it
can you elaborate
Like for example our object pool subscribes to scene unloaded and does cleanup on its objects
Like what you described
Hi. I have a question: I have a public void Set Love(GameObject you). This void is attached to a button (OnClick). I need the void argument to be the object on which void hangs (in 1 button, the argument is 1 button, in 2 buttons, the argument is 2 buttons, etc.). Of course, I could do this manually, but I love you very much and I will get tired of doing it. Is there any way to contact through the script and assign?
so additive scene loading wouldn't solve it?
Im not sure I followโฆ
If you need to reset your object pool when a scene changes then you have to know when the scene has changed. Subscribing to the scene manager events is the way
like holding the ui, level, etc on different scenes meaning you just unload the specific scene when needed
an "additive scene loading" workflow is what its called
not sure if its worth implementing
Sure that is great too. Not sure what it has to do with ddol object cleanup
I only use additive scenes but I dont see how that helps with the object pooling problem (for example), it would just mean you need to be more granular when you clean up your object pools
i guess that's true
what is you supposed to be, this logic doesn tmake much sense
Also they are not called voids they are methods/functions
it just feels messy having if (scene == "Game") etc
well you can create some kind of abstraction for it, like I use a class associated with each scene, and it has PreSceneLoad / PostSceneLoad / PreSceneUnload / PostSceneUnload methods, and then I run my scene-specific setup / cleanup code in those methods
First things first, terminology: these are called methods, not voids. void is the return type, and may be replaced with something else in specific cases.
There is no easy way of getting the object the button is on automatically, especially if the script is somewhere else. You will need to do that manually
Pitifully. Thanks
so i have multiple ddol classes which each clean themselves up. Do you think it's better practice to have them all hook into a some scene loader than handles the loading/unloading. I'm always weary making "manager" type classes though
what do you need to do with that object exactly, there is probably an easier way to do what you want
What do i do when my unitiy hub just gets stuck trying to open my project?
Yes, I'd rather do it manually.
if you think you need it, yeah. Nothing is "better" if you dont actually need it (to be honest I am kind of a hypocrit about this, I like to add many quality of life features).. If it's just one little spot with some gross scene checks and you dont plan on expanding on it much, then I think it's fine to leave it the way it is and focus on other things. However, yeah I think it's usually better to have something that manages scene loads / unloads rather than having to manually hook onto events and such in random classes. I don't know your codebase or the scope of your project, so it's kind of up to you to decide / experiment
I mean, its valid to pass the GameObject the button is on the way you did it..
Woud love to got one week away from unity with out all my prject becoming unopenable
version control is your friend with this one then
I want to change the transformation of an object by mouse (target.transform.position = new Vector2(Input.MousePosition.x, Input.MousePosition.y);), where target is the object that is assigned if I click on a certain button. Let's have 3 objects, and by clicking on 1 of them, I will change its transformation, and that method is the method of assigning target to a specific object
alright so, just assign a new position to obj from the SetLove method
you can in the inspector for onclick assign any gameobject you want in there
but this will be 1 button is always tied to the same gameobject
if you want to switch which object is the target you need a method to do that too
I know that it is possible to assign an object in the inspector, I just wanted to assign the desired object for each link immediately through the script:(
are they UI or sprite gameobjects, how you select them varies
I guess you could have another script on the button with your own event. Hook up the button's event to that script, which raises yet another event to your target object, automatically passing the object this script is on as an argument
Like a relay
I don't want 2 scripts, I want a lot of links
you only need 1 script that selects objects, then a button to run method to move or whatever
I just want to make two objects move in the opposite direction of one another. Why is this so hard?
I can get Object A to mirror Object B just fine, but as soon as I try to move Object B, it instead of moving Object A, Object B just snaps back into position from Object A
what did you try
gameObject.GetComponent<Rigidbody>().position = otherScale.GetComponent<Rigidbody>().position * -1;
I tried attaching this script to both objects but it didn't work
Well, if both of these objects are doing this, then one of them is going to happen first
Hey guys, I'm making a game that uses beat em up style maps (So sidescroller that allows you to move towards the foreground and background) but I'm having trouble understanding the best way to include collisons with objects and parts of the map that are the walls. Would Probuilder be the way to go? I was hoping there was a method where I could sort of connect the dots and wherever the lines connect, it will be unable to passthrough.
MoveOne()
MoveOther()//using new data from One
Imagine A is at 1, 1, 1 and B is at -2, -2, -2
If A runs first, then it teleports to 2, 2, 2. Then B runs and moves to -2, -2, -2
If you want them to actually mirror each other's movement you need to do that when the movement occurs. Whenever one of them moves, you need to apply the opposite movement to the other one
Yeah, I want them both to influence each other equally. So if I move A, B moves, and if I move B, A moves
Right now it keeps prioritizing one over the other
You're not going to get that by having one of them teleport to the mirrored position of the other. You need to actually apply movement at the same time to both
If A moves left when you press left, you need to make B move right when you press left
So for context this is meant to be a scale, like A moves down when objects are placed on it, making B move up
And if you move that same object to the other side of the scale, B moves down making A move up
Yeah, so, whenever you tell one of the objects to move down, you should tell the other one to move up
Yeah is there a way to just have the physics calculate that for me?
Cause writing some "if" statement for this feels like I'm overcomplicating it
Is there no way to just say "Hey, where they go, you go opposite."
If it's just scales that weigh things based on their actual mass, I think you can do something with a configurable joint but that's beyond me, and might be something to ask in #โ๏ธโphysics
hey everyone, can i have some help please?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
if im having issues with my script and animation, is this the right channel to ask in? so sorry, i dont know how to navigate discord servers at all :((
do you know how to read?
if it is mainly for animations please go to #๐โanimation if you believe it is for scripts post it here #๐ปโcode-beginner
ive finished my animation tree with no issues i think, i just have no idea on how to incorporate it into my script so the walking animations occur appropriately
i started programming yesterday
time to do !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
ah, there are many tutorials for your problem, if you truly started yesterday please !learn the engine and its quirks
dang
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you!
I dont really understand the error?
friction is a double. curSpin is a float. You can't subtract a double from a float
use the proper suffix and you wont have error ๐
One of the reasons var can cause issues (not trying to start anything! ๐ธ ). Casting that .1 will help
Avoid using var when the type on the right of the = is not clearly apparent, or if you don't have the inline type hints enabled (not sure you can have them in VS Code, VS and Rider can have them)
(example)
indeed it does if enabled
Oh good it has that, I guess it's because it uses the Visual Studio package, might spin up the same language server as VS's
iirc is the C# Devkit package that does all the magic
does anyone know how to stop the curspin when im not rotating the MouseWheel?
surprisingly thats the one you need license for (just like VS)
i really hate unity for not giving sleep function outside of coroutines
mousewheel is a delta. so just check if its 0
The more I look at the code, the worse it gets, but the use of += in the middle of line 31 here is pobablly incorrect.
As well as line 19 that does nothing
I know
its a place holder
because i want the main function first
hey guys. Which unity joint would I use to make the differrent sections of the snake in the snake game? I'm trying to use the distance joint 2d but ive never used joints before and its not working at all. this is my first project.
interesting, no idea you could use joints for that game..
are you sure its not relative joint you need?
show what you currently have and whats happening instead
what would I use instead?
idk last time I made it I just use lots of math , thats why im interested to know if its some holygrail method i never heard of lol
or do you mean something less old-school like Slither.io
i think its more like slither.io now that I think of it.
because the snake doesnt move on a grid. at least not yet
How to i check the Delta?
just check for == 0
the delta would be no scroll to scroll
thats why you scroll faster you get bigger number etc.
you need mp4 to embed in discord
That makes sense. But i cant type MouseWheel. What do i need to put in?
ah yeas then a bit less traditional, I can see why you would use rigidbody.. hmm I would need to see code as well
wdym ?
first of all store it in a variable so its easier to check values against it
if ( dont know what to put == 0)
Would getcomponent fail if the gameobject I'm trying to.. Get, is disabled?
It still exists ๐
float mouseScrollAmnt = Input.GetAxis(Mouse ScrollWheel)
if(mouseScrollAmnt == 0) //not scrolling
if(mouseScrollAmnt != 0) // scrolling
I would think three hinge joints, no? One at the fulcrum, and one for each weight plate thingy ๐
You may need two extra rbs on either end of the fulcrum for the plates to hinge to so their weight isn't applied to the fulcrum's center of mass
Only the first white circle called "Player" has any script on it. and the script is as follows: https://gdl.space/icipezatih.cs
Thanks!
with
using UnityEngine;
public class Script : MonoBehaviour
{
public Transform body;
Vector3 place;
void Update()
{
place = body.position;
Debug.Log(place);
}
}
I get the error
UnassignedReferenceException: The variable body of Script has not been assigned. You probably need to assign the body variable of the Script script in the inspector.
However, it says its assigned in the inspector, and I get the correct position returned...
nope
however, this is causing errors in my full script
check for copies ?
of the object in inspector? none.
in the hierarchy
t:Script
also naming a component , Script ๐ฌ
I'm not familiar with hinge joints or joints in general. so in the case of a snake made of circles, what would be the fulcrum? each circle?
maybe learn how the joints work first ๐ then start adventuring into doing shapes and movements
well the script is named "dynamicCamera" lol
I just substituted words
wdym says public class Script : MonoBehaviour
It does. You can absolutely use Thread.Sleep anywhere you want
well I simplified, I actually have public class DynamicCamera : MonoBehaviour, place is actually notCam, and body is actually elephantCam, I just didnt want to distract from the simple error I was getting
I'm not too familiar with them either... But I'm not sure I follow how a circle snake is related to a seesaw/weight scale?
I was just thinking something like this, where the black things are RBs and the purple lines are hinges
Edit: Ohhhhh I totally read the wrong question. I'm all mixed up
well you should share it as is, many people know how to read code with, waste to change it up to send lol
anyway just search it by that name then and see if any copies show
here is the result of this code if you want the actual names
either you have a copy like i said or it gets unassigned on start
Ohh i think we misunderstod each other, I'm not making a weight scale I'm making a snake game. a hinge join is probably the correct way to make a scale but obviously wouldn't really work in a snake game where we are adding parts of the snake
no unassignment at start
did you search t: DynamicCamera
where?
on the searchbar of the hierarchy like i said already
Yes - absolutely my bad! I've somehow completely responded to the wrong question. I'm not sure where the question I was addressing is now ๐คช
check all those objects for that script then
theyre all where theyre supposed to be idk man
idk its your project
I only added the script to the main camera wth
apparently not
can I remove it?
well yea..
Because you put them there
if you had multiple objects selected somehow when you put the script that could be a reason
must have been an accident haha, I have been in the code window this entire time and only remember putting it on the camera, if I write in the document that the objects are public then drag them onto the script does that count as assignment?
thats how I selected them, but I only dragged my script from the asset window onto the main cam
its not a "document" its a class
yep, my bad
thanks for the help lol, I didnt know that was a thing, anyways I will def be using that debugging method in the future ๐
and yes thats assignment, otherwise in code its done with =
ah, I thought it only assigned them within the script, not parented the script to the object
I have a question, would it be better to manage the segments of a snake in code or by using unity joint components?
well one requires a lot of math and one doesn't
well not soo much a "lot of math" that exaggerated but you need to understand loops and stuff, maybe collection of sections
rigidbody seems easier if you can pull it off with joints
i would prefer to use joints since this is for a game jam but I thought maybe joints arent even used for this purpose
well if its not a grid you should be good then
Splines sounds like a better option
could work, just a bit more complex
I fixed my issue! the rigidbodies of the segments were set to kinematic instead of dynamic... chatGPT toold me that that wouldn't work
lol
easier than joints, joints are a pain and they eat time to get them right
gpt ๐ฌ
so it works now at least
If an gameobject with components in a list<T> is destroyed, are the components removed from the list?
i.e. will I get a nullRefException if I try to foreach through the list
they will just be Missing
no
indeed
is working with instantiating objects through using data from saved json files considered beginner or should I move to one of the lower channels to ask regarding this? ill delete this message after
what is the question
I have a json file that stores the state of a chunk in my world. At the moment, it contains the position of the chunk, the objects in that chunk, the prefab file path to each object prefab and where they are located in the world. I have no trouble with parsing this data and checked that I've retrieved this correctly.
I am trying to instantiate a prefab from my assets folder using this data and I'm seeming not able to do that
in the code below, it uses a class i've made which stores the data about each object
- objectName (string), the name of the object (like "Cube")
- prefabPath (string), assets folder location of the prefab (like "Assets/Resources/Cube.prefab")
- a float list called objectPosition, this is self explanatory
foreach (ObjectData data in objectData)
{
Debug.Log($"Loading: {data.objectName}");
GameObject prefab = Resources.Load<GameObject>(data.prefabPath);
if (prefab != null)
{
Vector3 newPos = new Vector3(data.objectPosition[0], data.objectPosition[1], data.objectPosition[2]);
GameObject newObj = Instantiate(prefab, newPos, Quaternion.identity);
newObj.transform.SetParent(newChunk.transform);
}
else
{
Debug.Log($"{data.prefabPath} doesn't exist"); // This is always shown when an attempt at instantiating happens
}
Debug.Log($"Loaded: {data.objectName}");
}
Debug.Log("Chunk loaded from memory");
From my testing, it's like the file path I provide just doesn't exist, even though the prefab is in the correct location
did you read the Resouces.Load documentation?
yes
then you should know that your path is incorrect
why is that? what did i miss?
this
"Assets/Resources/Cube.prefab")
for Resources.Load should just be
"Cube"
i'm even more confused now
i tried passing data.objectName earlier and it didnt work
cos I read another article and thats what they did
i tried it now and it works
no idea why that was the case
Ok i see why now, the folder has to be called "Resources" for unity to automatically check there and grab the prefab to load
thanks for your help
well it in fact sleeps
but i expected other things to work while my script is sleeping
Well, you're pausing the main thread. What would you expect to happen?
Only one line of code can ever be running at a time
So it is just that script sleeping
which means nothing else can happen either
i expected non script stuff to still work
In short, it's been what, 3 years and you're still spouting nonsense?
Because lua is a script, not a program
The thing running your lua script has paused completely
waiting for it to finish
during 3 years i tried make coroutines like 50 times and each time they had different kind of error
And I'm sure each of the times you've made wild inaccurate claims too.
Then you should probably have tried doing them correctly instead
why would he want to pause the main thread, does that not just prevent him from enabling it back on lol
You haven't met Anuked, spare yourself and don't question it.
He doesn't want to pause the main thread he just doesn't know what "main thread" is
oh i see
It's almost like an experiment, how far could one go without learning the basics of c#
you're being unfair, of course the computer should just know what I want and if it doesn't then it's broken
wait, you still can't get a coroutine running? you gotta be kidding me? ๐คฏ
thats wild, ๐
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class RollPlayer : MonoBehaviour
{
public List<Sprite> playersToRoll;
GameObject player;
public int[] table =
{
60,
20,
15,
5
};
int total;
int randomNum;
private void Start()
{
player = GameObject.Find("Player").gameObject;
foreach (var weight in table)
{
total += weight;
}
}
public void Roll()
{
randomNum = Random.Range(0, total);
for (int i = 0; i < table.Length; i++)
{
if (randomNum <= table[i])
{
Debug.Log(playersToRoll[i]);
player.GetComponent<SpriteRenderer>().sprite = playersToRoll[i].GetComponent<SpriteRenderer>().sprite;
return;
}
else
{
randomNum -= table[i];
}
}
}
}
why do i get error : NotSupportedException: Specified method is not supported. NotSupportedException: Specified method is not supported.
Unity.VisualScripting.ComponentHolderProtocol.GetComponent[T] (UnityEngine.Object uo) (at ./Library/PackageCache/com.unity.visualscripting@1.9.4/Runtime/VisualScripting.Core/Utilities/ComponentHolderProtocol.cs:70)
RollPlayer.Roll () (at Assets/RollPlayer.cs:42)
sprite doesn't have GetComponent
its spriterendrer
no its not
playersToRoll[i] is a sprite
oooo yea
there is no such method on Sprite type
hence the using Unity.VisualScripting namspace
Hello. I need to make a system in which we store a String (Scenario/Explanation) + Int and String (Outcome/Result e.g +20 Money) + Int and String (Outcome 2/Result 2 e.g -20 Creativity). We need to store all 3 of those together, becuase...
We have more than 10 scenarios which we have to randomly pick from, then show it on the screen, and then update the game mechanics to the outcome values. I'm thinking to make 3 arrays with the values and I put all values in order and it should work.
Or maybe we can make separate methods for each scenario (which will result in 10+ methods, i.e 1 method for each scenario) and we return our values as a return type. But the problem in this is that the code looks really messy as one method for each scenario will clutter up the script. And I don't think we can return more than one datatype in a method.
Can anyone please suggest a way to store all 3 of the values together?
Make a class that has all the values you need, then make a list of that type
Amazing... So simply make a "Scenario" script which has all the values as Constant as I won't be chancing it. Then, I reference it anywhere I want.
if i wanted to make a rythm game with enemies that shoot at you on beat what would be your suggested way of coding this?
the first thing that comes to my mind is delaying enemy bullets to when it should happen in the song but that seems lengthy
find the peaks through analyzing the audio, work your way from there
so im gonna have to manually code the enemies shooting with delays in timing yes?
delays?
like if a bass drop happens 28 seconds into the song
i delay the enemies bullet by 28 seconds before it instantiates
doing manually means you will have to deal with all the songs etc
i only plan on doing one for now just to see if its a sustainable idea later on
it doesn't scale well
coding analyzing audio spectrum, figuring out which frequencies / pattern corresponds to what's happening in the song is always the more modular way
im a bit confused
look at the waves in the song is what im getting
how im supposed to translate that into code is whats confusing me
can someone please tell me what does $ mean inside a string, I've seen it alot but don't know what it does. Here is a code for example:
Debug.Log($"{stat.Key} has reached 20 or less.");
you don't look with your eyes but yes through code analyzing, its numbers
ohhh
string interpolation
still im confused on this part
You read the raw data of the audio eg with audioSource.GetSpectrumData
then you figure out which frequency belongs to what
short to high frequency means its most likely dropping into a beat, etc
its just numbers, plugin a GUI to it, play the song you start seeing what happens with those numbers, from there things will seem easier to create pattern from
Do you know what a fourier transform is?
exactly , you look at the peaks and frequencies that interest you, you then do simple if (thisFreqPeak > min) spawnBullet
I have a demo of this but its on my other pc and forgot to make a repo ๐ Im giving you more or less the ballpark rundown
Basically an analysis of frequencies present in a complex waveform. Mathematical equation to breakdown the wave into the fundamentals that make it up
ok lemme try to reiterate what you said
correct me if im wrong
analyze the audio
certain frequencys will give me different numbers
i take said numbers and use that to determine when the bullet is spawning
more or less.
different ranges of frequency usually mean specific sounds
when the peak reaches certain number spawn a bullet and so on
a Kickdrum typically in low/mid frequencies etc.
so how would i analyze the audio to find these numbers
and how would i use the numbers in my own code?
never thought this far lol
you will need to learn how these numbers work
https://docs.unity3d.com/ScriptReference/AudioSource.GetSpectrumData.html
What is the sample arrag you are getting? The array is the size of the sample rate, and the float is the db-fs level?
The docs are confusing me a bit
samething here
I need to look back at my project its beena couple of years. I saw a few youtubes that explained it well let me find it
this is the series I learned most of this from, stil newbie to it
i think i understand
so on lets say i hi hat if they had a frequency of 18 for exampls
i make my hi hat bullets come at when 18 shows up
yeah but more or less 18 could always be there just very low, its just checking how loud it is at the time
check the guy i sent, he explains it pretty well
the first 3 is theory behind it
thats how most audio waveforms look yes
you have to run through it a couple of times eventually it makes more sense
is there a builtin way to do boolean modification on rectangles? for example, difference/union/intersection?
the math doesn't seem like it'd be that hard, but i also got like a c in linear algebra so
ยฏ_(ใ)_/ยฏ
i found a way to do it, i'm just going to join the sprites by creating a texture and writing to it.
is this the code to retrieve the frequencies?
this samples the audio and gives its raw data then you can read the frequency
did you see the playlist I linked? it explains everything.
i am but it looks like hes using a different code
where..
he literally named a whole video after the method i sent
Support me in creating tutorials by becoming a patron on my Patreon and get access to the full source code of all tutorials.
http://www.patreon.com/peerplay
A new tutorial series by Peer Play, made by Peter Olthof.
Source files download: http://www.peerplay.nl/tutorials/peerplay-AudioVisTutPart1-source.zip
Learn how to code your own music vis...
mate.
those are examples in the docs
they arent meant to be copied every time you want to use the function
my bad
the unity example is very basic, just shows you more or less what its doing.
His is going to show you what each range of numbers mean
hopefully you did not skip the video prior to this, the theory is just as important
ok i got it to work
im more of a hands on learner so i wanted to see what itd do from my perspective
thanks for the help im definetely going to use your help and his tmr when i code my first few bullets in after work
alrighty
watch the later ones too, there is more to refine so you get specific hits or specific bullets for different sounds too

feeling really dumb, how can i convert some timer info into a 0.0 - 1.0 scale?
eg. 30f / 60f = 0.5f
Current / max
If current >= max reset to 0?
For a timer that increases of course
No worries
I need some help with animator and script
Best to just lay out the issue and ask then. If it is animation code, you should ask in #๐โanimation though
I @summer stump I need to make enemy play from idle animation to attack when in player range
@jaunty crag Don't advertise outside of appropriate channels.
Oh, i am sorry
Read the error
The issue isnt with trying to set a gameobject here, the addition part makes no sense
I know it was just so it easier to explain what i mean
I want to get the object 0 of the array when currentBodyPart is = 0?
BodyParts is an array of gameobject?
You access the array with BodyParts[currentBodyPart]
Thank you!
Hello everyone. I reinstalled Unity on my computer. In the past, when I clicked on the error in the console, I would reach the incorrect line of code. Now when I click on the error in the console, nothing happens. What can I do so that when I click on the error in the console, I go to the wrong line?
does anyone have any ideas on how to make a cube stick and walk on wall pretty new at this and struggling a bit (its 2D)
You most likely need to reconfigure Unity and tell it which code editor you're using with it.
!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
As you suggested, I made my calculations and in the end I came up with this formula, which seems far too complicated for me to apply to Unity, and it's highly likely that I've made a few small mistakes ๐
So this is in the 3D, right? The bullet start and end points are 3D and the player's detection zone is a 3D shape? Is it a sphere or is it a capsule?
yes it's 3D and the bullet start and points are also 3d and for the player coordinates I just chose the center of the player
What shape is the detection zone?
what do you mean, because I don't have any physical detection zone in unity? but in my calculous the detection zone is a sphere
Well, in most 3D games, whether it's first person or third person, the player is most often represented as a capsule shape, to mimic the shape of a human. But if your player is very short or ball shape, then a sphere makes more sense. Which one is it for your game?
Oh yes ok, it's a capsule
Then calculating the closest distance between the capsule and the path of the bullet will be best. Otherwise, if you just compare to a single point, like the center of the capsule, bullets whizzing over their head will be reported as further away than those going past their hip.
ok, but how I can do that, because I have a gigantic calculation when I calculate with a single point in the center, so if I calculate with the edge it's going to be worse.
You can look for code implementations of this math by searching for "shortest distance between line segments 3D".
For example:
https://zalo.github.io/blog/closest-point-between-segments/
One of my favorite functions projects points onto line segments.
that gigantic calculation can just be ditched
yes, I quickly realized that such a long calculation was not sustainable.
And if it was not already clear, the line segment to represent the player should be this, not the entire height of the capsule.
A capsule is simply a line segment with a radius, like how a sphere is a point with a radius.
it look so easy now ...
Hi. I have a problem: I want to move an object with the mouse cursor, but when I put this movement on it, its coordinates become very large and it goes off the screen. How do I save the coordinates of an object?
well surely if you for once just properly shared a question and your code, people would actually help you make a proper coroutine. instead you insist on being vague and just complaining that it doesnt work
if you arent aware of how async works in unity, you'll run into issues quickly
you cant directly use Input.mousePosition, this is in pixel coords https://docs.unity3d.com/ScriptReference/Input-mousePosition.html
You might want a function like this https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html though it depends what you're trying to do
Thanks
The second screenshot looks like it was taken from a Rect Transform, so the object is probably on a Canvas. You need to confirm that though, as well as the canvas type (screen space overlay, screen space camera, etc.)
I want to have a variable that is a static material, but it doesn't show up in the inspector so how do I fill it?
Who can help. There is a code that I hang on an object that can be moved by clamping the paintwork. At the same time, this object can enter through other objects (for example, the floor). How can this collision be handled?
Is their a function In C# to calculate the distance between 2 points ?
anything static wont show in inspector, does this actually need to be static?
you could use resources to populate it if static. Otherwise you could use like a scriptable object and pass that around instead
if you want it to not go through objects, you'll either have to move it via unity physics (rigidbodies) or use physics queries to see if its valid to move it in such a way
I guess I can use an SO for this. just don't wanna constantly update prefabs with a bunch of references
https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
its a unity function, since a point is a Vector3, which is a unity thing
Ok thx !
you could just use Resources then. but i really dont know why anything SO related would require you to constantly update prefabs. If you're doing this via code, then you'd have to update the code everytime which is arguably worse.
Sorry for the stupid question, but I created a simple movement script that uses the Force-Features of the rigidbody and works fine on the normal build. But in WebGL my player very very slowly falls and my movement doesnt work at all. Is there a setting for WebGL that I'm missing?
Also as a side question, how do you stop the WebServer that is started in Unity to play the game in Browser xD?
Hmm, maybe I fricked up my delta-time stuff
Definitely an issue with your code. You'd have to show it
I need for a raycast to be able to detect a composite collider 2d of a tilemap whilst still in outline mode. When in polygon mode, the colliders are not perfectly straight and cause serious issues, so outline mode is required. However, outline disallows for raycast detection, so I cannot use raycasts for my desired use. How can I circumvent this issue?
I found it out. I got an SO that has information like Gravity, which is calculated on the OnValdiate Function. And fields that I didnt declared as SerializedField didn't get calculated in the Build and that why my gravity was suddenly 0
Outline mode has no problem with Raycasts unless you're doing something strange
Are you expecting to hit the "inside" of the collider instead of the edge?
What's the goal?
I draw a raycast every frame and check if it is detecting the ground (and give the raycast a layermask so it only detects the tilemap composite collider considered ground) and it only ever detects the ground when it is in polygon mode.
My understanding is that edge based colliders can't interact, so I'm trying to find a way to circumvent this.
Sounds like perhaps your Raycast is originating from the wrong location
This understanding is not correct
good ๐ญ
I use debug.ray to see what im doing.
Ok so let's see it
Show the code and what it draws etc
Vector2 rayOrigin = new Vector2(transform.position.x - 1.3f, transform.position.y - 1.80f);
RaycastHit2D[] bottomRaycast = Physics2D.RaycastAll(rayOrigin, -transform.up, 1, LayerMask.GetMask("Foreground"));
Debug.DrawRay(rayOrigin, -transform.up, Color.red);
if (bottomRaycast.Length == 0) {
playerRB.AddForce(-playerRB.velocity, ForceMode2D.Impulse);
playerRB.AddForce(transform.up * -speed, ForceMode2D.Impulse);
}
if (letItRipTimer <= 0) {
ResetPlayer();
}
it draws a line on the corner of the player's sprite directly into the ground, but detects no ground.
Can you show a screenshot
1 sec
don't mind the garbage pixel art ๐ญ
but you can see the ray in the ground and it isn't detecting it
The ray is starting underneath the ground
You need the ray to pass through the edge for it to detect
Start the ray a little higher up
How to i spawn a random one of the walls? i thougth it was this easy
Walls[yournumber]
is how you access a certain element from your array/list
where can i go and ask for help because i cant find it the support channel
depends for what, they are all support channels
this one is for code
public class PlayerController : MonoBehaviour
{
private Vector2 _movementInput;
private Rigidbody2D _myRigidBody2D;
private Animator animator;
private SpriteRenderer _spriteRenderer;
private void Awake()
{
_myRigidBody2D = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
_spriteRenderer = GetComponent<SpriteRenderer>();
}
private void FixedUpdate()
{
_myRigidBody2D.velocity = _movementInput * _speed;
animator.SetFloat("xVelocity", _myRigidBody2D.velocity.magnitude);
}
private void OnMove(InputValue inputValue)
{
_movementInput = inputValue.Get<Vector2>();
if (_movementInput.x < 0 && _spriteRenderer.flipX) {
Debug.Log("turnleft " + _spriteRenderer.flipX);
animator.SetBool("turnLeft", true);
_spriteRenderer.flipX = false;
animator.SetBool("turnLeft", false);
} else if (_movementInput.x > 0 && !_spriteRenderer.flipX) {
Debug.Log("turnright " + _spriteRenderer.flipX);
animator.SetBool("turnRight", true);
_spriteRenderer.flipX = true;
animator.SetBool("turnRight", false);
}else {
animator.SetBool("turnRight", false);
animator.SetBool("turnLeft", false);
}
}
}
The code prints log texts, but does not change the "turnLeft" and "turnRight" Bools.
whats the error
i don't knwo what i done wrong i watch the video and i have done step by step but is wrong for some reason
any errors? did you write it wrong the bool names specifically
this but it works fine on the other one
there is no error. I can walk without any problems. The variable xVelovity (in fixedupdate) is being updated. but the turnLeft and turnRight bools do not change.
if you see the other 2 photos i send
yeah, your code is not the same as the video
your missing something
then they are being overwritten somewhere else straight away i would assume.
if its got no errors then it has no reason for the bool NOT to change
i understood that but why is working on one of them and the other doesnt
because its not the same code?
so the working code works, the not working code doesnt work
also your overly complicating it, unless you have specific sprite designs.
all you need to do is flip the sprite instead of using whole different animations or whatever its doing
I have a turn animation. I want to play this
i just his code with my one and is the same
When I started walking to the right while standing facing left;
left idle -> right turn -> right walk
I want it to be like
it is not the same, notice the part exactly after <Manager> and before .GameOver()
It's a method
now screenshot the line from the tutorial
Is there any difference between this one and yours?
there is
no just this one doesnt work and idk why and teh otehr one is working
So there is no difference between these two?
yey!
but what is it?
()
because FindObjectOfType is a method
you call a method by using ()
guys i think im having a problem here
Hi all! I'm following Game Maker's tutorial to build flappy. I tried my best to get the zero at where it is. But when I enter the game mode, no text showed up on the screen, the 0 just didnt appear. Help! Thanks !!
I'm sure the zero is in the range of the camera, I tried moving it but it never been able to show up
go to the game view and check if it's visible there, because the rectangle that is fully visible in the scene view there might only be the camera, but not the canvas. Like the canvas I think is the rectangle that is not fully visible there
nvm i fixed it
the camera is indeed the small rectangle. The huge rectangle is correlated with the text, I think it's called canvas, and once I delete it the text also gone, I dont really unserstand this thing
okay so first things first, the canvas itself is not the text, like the canvas is what "holds" all the UI elements if that makes sense๐
So like imagine the canvas as a screen that is always stuck in front of the camera. Whatever image/text is in that canvas will appear in the camera too
you dont even have the camera selected in render camera
i would select it for the UI to show
thank you I ll try that
ok I ve no idea of how to do that, could I get the steps, ty vm
select the canvas, look at the inspector and where render camera is and either click the circle with a dot in the center and select your camera or drag the camera into the field from the hierarchy.
okay just to test something, if you move the text to here does it show when you press play? Like does it show on the bottom left?
i didnt even notice that ๐
that might work but they still need a camera for the canvas to render on.
well they do have a camera already, no? Like it's the first thing in the hierarchy, so if it doesn't have unchecked the UI culling option it should render anyway I think. I might be wrong tho, haven't worked 2D in a while lol
well there is no camera in the render camera field?
im loading in a project to see if we are correct
This worked!!!
Thank you all youve saved my mood and my night!!
yeah you are correct, I didn't notice it was Screen Space, my bad lol
it didn't worked tried that
๐
lol now I'm confused, I have no camera in the Render Camera field and it is working haha. Guess 2D works different than 3D, but now I know๐
ah it says it defaults to Screen space-overlay if no camera is selected
and yeah i have no idea if that affects 2D or not ๐ค
oh okay
I have a small doubt
I am not exactly sure how can i get the "Value" of the dropdown into my "LOCBOX" Script
Can someone guide me through
I have read about get component and also tried creating a public variable but nothing seems to work
to start with the type of your Dropdown variable in the script is wrong, fix that first then it's simple
You're probably using Dropdown instead of TMP_Dropdown which is the correct type here
He's using Text Mesh
yes I have gone through that as well
not sure why this error is appearing
because you are missing a using statment
oh! yes that worked thanks a lot!
If you press control period or just adding the class usually add namespace for you. Sounds like you have an unconfigured IDE
Hi friends! picking up unity after ages of not touching it and feel like I'm basically starting from scratch. Here's my basic pseudocode for this question:
GameStateManager (singleton):
bool toggleable
Awake():
toggleable = false
Update():
OnKeyDown(Spacebar):
toggleable = !toggleable
PlayerClass:
Start():
if(gsm.toggleable):
set color to green
else:
set color to blue
now my question comes with the update function of player class. Since my state logic is in GameStateManager, whats the best way to ensure that when my GameStateManager toggles its bool, the color toggles? Right now I'm doing something horribly messy by creating an internal toggleable bool in playerclass and essentially having two seperate toggleables but that seems prone to mistakes with desynced toggleable states
Use events
Ive seen two types of events, c# and unity events, which do you suggest I use?
honestly recommend learning c# events first, UnityEvent is mainly useful for serializing the event in the inspector, (think unity OnClick event for button)
thats up to you though.
Thank you! I'll look into it ๐
the benefit of Unity event is you dont have to subscribe to event in script, unity does it for you and calls method directly
i have an issue where when i move to the right or forward my camera randomly starts spinning for no reason?
!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.
๐ฅฑ
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
if its first person and camera is parented, did you lock the rigidbody
spinning in what way? make a video of issue
well, if i move forward the camera goes to the right
and if i move right the camera moves left
a tiny bit
there is nothing that moves the camera
either you referenced the wrong transform or somethin
its only when i standing on the plane ground?
idk dude you havent shared much detail on the actual setup or shown screenshots, just flying blind here
the code isnt the issue unless its placed on wrong object or referenced wrong one, I can't tel anything beyond that without seeing it..
Mhmm the error is telling you what you're missing there.
I have this problem, could someone help me?
I want to drag and drop the character freely, but it does this weird thing
if you want us to help you please read the code rules and actually post code and details on what your problem is
nothing anyone can do without seeing some code and the setup on the objects
not psychic
I gave the "Slot" script to "Square" and "Drag" to "Root" and now the character doesn't even move
okay beginner question:
When Unity mentions a "Syntax error: ',' expected.", when it's on a line of code where there is absolutely no need for a comma, what else could it mean?
show us the code
the error is on a preceding line
btw, you should be using your IDE to see these things not Unity
It's telling me it's specifically on the last string, which has one comma for the Range bit, again i've copied this directly from a tutorial
see, only Unity is catching these. my IDE is telling me there's no issues
then your IDE is not configured
public float HeadWidth 0.75f;
is this not underlining red?
oh my discord just updated ๐
discord updates?
I mean the text didnt scroll down past their link
๐
so didnt see steve has replied about ide
Sorry, bare with, having to update said IDE even though i swear it updated this morning. email app being a pain. give me a sec
and no
"updating" isnt the same as configuring it
follow one of the guides in !ide
exactly, with a configured IDE it would be
โ ๐ค ๐๏ธ
I know, but i noticed it needed an update which i figured may help
(this is with note I haven't actually used Unity for a good 3 years so everything's VERY likely severely out of date)
to configure your !ide please use this
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
i guess bot is working for you..
thank you, im on it, my email just isn't getting anything to log back in which is... making this difficult for sure :/
email login?
so configuring is... setting it as the main editor? (using the VS Code one as I appear locked out of Visual Studio, my emails aren't recieving ANYTHING off of them so I can't log in)
oh wait
god it's my wifi. sorry
there is more to this page than it was letting on
okay it begged me to log in and... now it aparrently doesn't need me to
oh my god i'm so confused rn, darn my wifi and darn my email
login is just to sync settings n such
nope. it's logged me into my useless college account
from december
oi oi oi, it might even my PC you know, it's due for an MOT and repair
im not even logged in to my VS and i can use it
??? this just crashed most of my apps what on earth
im dead confused
is this supposed to happen??
yeah VS has been buggy for me lately
i think new update fdup some shite, are you on the latest . Make sure you update to most recent
i can only cancel that message mind - everything else was frozen
yea I just updated it I swear down
well Allow Access for network ofc
it couldnt even let me tick that box, i couldn't allow access, I could only press cancel
see my dilemma? am i insane? ๐ญ
yea my issue is the entire app froze
your pc is borked
yea.. might have to just give up on coding until it's fixed later this year
WAIT. it's working
okay ive asked it to update
if i disappear it's eaten my memory
like a gormet meal
do you not periodically install OS from scratch again ? its good to do at least once a month or two
(on top of this, i've configured the IDE again)
no, but only because my hard drives are pretty delicate and I have a LOT of personal stuff. last time I did that I lost everything. years worth of art, music and more, and honestly it's pretty scary for me. I'd rather pay a professional to extract my stuff onto another hard drive then do it for me if im honest
it's kind of a fear based thing, I know its pretty silly, but I lost even a few paid for software and must have been an idiot kid and deleted the licence emails :( not long till im due money so I should be able to afford it to be done soon
OT but VS is almost installed
only if you haven't got a fucking clue what you are doing, lol
its pretty easy to do
I only had to do this on Windows cause its a shite OS
it just starts fucking up updates or apps for no good reason.
i have 1 pc with windows 10 and another with arch linux, so far i havent ran into any huge problems
good , windows 11 is even worse. Plagued with MS bloatware
both of which are real easy to eradicate
windows hasn't been good since 7
even 7 was crap, XP was OK though
why does my unity load so much faster on linux/mac os than windows.
and when that happens im going to linux on my main machine
yeah xp was greatest, 7 was good cause it was more like xp but with aero, then just went downhill fast lol
basically wat vista was supposed to be
yeah that or run macos on hackintosh (same hardware you got for win/linux)
because the Linux/Unix kernel is so much more efficient than the Windows kernel, it's just a shame that Mac and Linux GUI's are so bloody awful
macOS is an abomination
to society
yeah exactly
and steve is right, the linux kernal is insane on performance but i have to get use to it more
well its UNIX at least
true but still
the gui is not so bad, the only gui that comes close to me(windows like) is Mint
i like arch with plasma 6 because it acts like windows
If I could put an XP GUI on a Linux kernel I would and be a very happy nam
Not the original because it's still closed source
i mean they got hannah montana gui, i so no reason there wouldnt be xp
close enough though
it doesnt have to be spot on
although it would be cool
yes it does, that is the whole point and what is totally wrong with most Linux GUI's, they get close but not close enough
they are usually like 90% close enough, i believe that would be fine
nah, it has to be 100% seamless otherwise it's a waste of space
who cares about the GUI I just want my apps to run fast and not chugg
bro linux is like 8gb anyway lol
or mb
i forget
GUI is what you see, if you donrt want a GUI dont install one
plasma 6 is best (in my opinion)
the only gripe I have with linux is i cant install unity hub/unity or games on arch
arch is a very bare bones distro
Duh, It's the GUI that does that for you, without it you would see nothing
yeah but each app has their own gui all you're seeing is native things like popup windows or other stuff like that
no, each app has handles and hooks into the OS GUI, it does not have a GUI itself
i still have to figure how to install unity on it I know its possible
probably
if you open Steam on linux it looks exactly like steam on windows and macos
you're talking about trivial stuff like titlebars and maybe file explorer for file picker
because they designed it that way
but that contradicts "it does not have a GUI itself"
thats their GUI , all the OS handles is native stuff like popup window, ofc is gonna look like the native os
no, you misunderstand, they take the OS widgets and reconfigure them, they dont reinvent the wheel
yeah I get that part, they're using whatever API the os offers.. just saying its also up to the dev to make the apps look good
have you seen some apps made with windows forms lol
bare minimum
I made a script (A) with like 5 values in it, and I made another script (B) where it can make gameobjects with that script but, I found there is no way to copy A and addcomponent this A to the gameobjects that's are getting made in B with the exact values I want, if I want to edit the values I need to do 1 line for each value I want to edit
wdym 1 line for each value
Can't I just take the A and copy paste it to add it to another gameobject without playerprefs
reference A from B ? whats the problem
So the A can be in the way I want for every new gameobject
put the values in a struct or tuple and pass as many as you want
I'll say it again
so whats stopping you
Just a way to copy an edited component, and paste it in another component the way I edited it u got me?
why dont you explain what type of gameplay or mechanic you're going for, and what is actually happening instead compared to how you want it
in code?
Yes
so just copy the values over? I dont understand why you can't do that
In order to copy them I need to make lines for it
So I wondered
wdym "make lines for it"
Like this:
They mean they have to use their keyboard to write code
Please try to finish a sentence BEFORE pressing enter
Shift + Enter creates a new line
GAMEOBJECT.component.thing1=5
GAMEOBJECT.component.thin2=true
like I said, put them in a struct or a tuple so its easier to copy multiple ones at once
can't I just copy a component and paste it in GAMEOBJECT
Ok thanks
You can
You have to get all the fields from the Type
If you mean copy a component from one game object to another via code at run time, no, you cannot
[System.Serializable] // to edit in inspector
public struct ValuesFromA
{
public int one;
public int two;
public int three;
}
public class ScriptA : MonoBehaviour
{
public ValuesFromA ValuesFromA;
public void SendValues(ScriptB scriptB)
{
scriptB.SetupValues(ValuesFromA);
}
}
public class ScriptB : MonoBehaviour
{
private ValuesFromA valuesFromA;
public void SetupValues (ValuesFromA values)
{
valuesFromA = values;
}
}```
Huh I like it thanks
Another method using Reflection:
-
- Create an empty
Component
- Create an empty
-
- Get the original
Componet'sType
- Get the original
object.GetType()
-
- Copy the fields from it
Type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
-
- Set the value for every field of the created
Component
- Set the value for every field of the created
foreach (FieldInfo fieldInfo in prev.GetType().GetFields())
fieldInfo.SetValue(...);
Yeah man I appreciate it
if anyone here is experienced with unity wheel collider friction, please help me out. Here I'm attempting to simulate the tread behaviour of a tank with wheels. 2 sets of 8 wheels are present on both left and right sides, with the left side running at 1000 torque, and the right running at -1000 torque. With tank treads, this results in neutral turning. As in, turning on a dime. However, with my wheels, they seem to also slip down sloped surfaces while turning. The grip values make absolutely no sense. When I turn up the stiffness for the forward friction (how much force the wheels are outputting while in contact with the ground), then the tank turns. But when I turn up the stiffness on the sideways friction it simply won't turn. If i turn down the sideways friction it starts sliding down slopes. I have no idea how this works even when reading explanations.
Hello, what's the easiest way to find the world scale of an object? I know I can use Transform.localScale to get the scale relative to the parent but what about the objective scale?
Transform.lossyScale
Thank you!
however i think this is only accurate if your object isn't skewed
in which case you can use Transform.localToWorldMatrix
so i got kind of a dumb question i think someone who knows math knows how to solve but I have an isometric camera and i want to move it forward back and left and right, but im not sure how to do that
void MoveCamera(Vector3 position)
{
_transform.position += position * Time.deltaTime * _cameraSpeed;
}
this doesn't work because the camera is tilted so just moving it wont actually move it in the correct way
use global positions not local
transform.forward/left/right/backward is local vector3.forward/left/right/backward is global
edit: ah mistype mb
_transform.position = _transform.position + new vector3(X,Y,Z) and you can manipulate X, Y, Z to get desired affects
i havent tested this but it should give you what you want
i figured it out
void MoveCamera(Vector3 input)
{
var moveVector = Quaternion.Euler(0, 45f, 0f) * input;
_mainCamera.transform.position += moveVector * Time.deltaTime * _cameraSpeed;
}
Does anyone know what's the proper way to check isGrounded for the player when using platform effetor 2d? the thing is, if I have a 3 tile height platform or something like that, when the player is jumping from below, suddenly they're in the middle of the platform and can jump again since I'm using IsTouchingLayers(platformLayer) to check if the player is grounded, does anyone know a solution?
The grip values make absolutely no sense.
Welcome to unity wheel colliders.
You'll want to look into using custom wheel colliders. There's a ton of assets that will do this much better. Making your own from scratch isn't too hard either.
tilemap doesnt update
Hello, how can I generate different numbers without repeating them? I've seen that this is a very frequent question on various forums, but each answer is different and some are extremely complicated to understand. Here is my code:
My theory is that the "random range" takes the number of elements, in which case, when something is deleted from the list, the list reorganizes itself and that element ends up being occupied again, so "random.range" can take the same element again.

