#💻┃code-beginner
1 messages · Page 490 of 1
Hey, back with the same old problem, cutting straight to the point- i'm trying to achieve a transform similar to the transform you get in the editor, but in-game
so far i managed to cook it up, the cube's moving on xy based on the mouse position
i also made some basic scripts for the handle which basically tell me if someone clicked on the axis handler or not
but i can't for the love of me figure out how to implement drag axis to drag cube
Im setting up a VR-project with ambisonic sound (360 surround) and want to know...
where objects are in relation to where the player faces...
...so I can pan the sound of the objects in external software.
How can I go about to get a value that represent this, that I can convert to degrees, what solution/technique shall I use? Dont know where to look atm.
dot product will help you see how close to the sound source the player's looking at
Quick vector subtraction will tell you the distance
correction: dot product will tell you if the source's behind or in front of the player, 1 is directly in front, -1 is directly behind
once u click on handle you could use the mouse position + raycast and project on plane to the plane parallel to the handle and then just use the delta to move the object around
That makes sense, how would i set up a virtual plane at the handle position?
also, wouldn't defining a plane make it so i can move it on both x and y axis of that plane?
nvm,you're talking about a plane parallel to the cam?
How can I see left or right panning placement? Can you please point me to a script or tutorial that shows this. I am installing the project on saturday.... I really want this to be a part of it.
https://paste.myst.rs/v39ev94z this is for a camera scrolling system
a powerful website for storing and sharing text and code snippets. completely free and open source.
for a top down map style cam controller.. but ```cs
if (Input.GetMouseButtonDown(0)) {
Plane plane = new Plane(Vector3.up, Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float entry;
if (plane.Raycast(ray, out entry)) {
dragStartPosition = ray.GetPoint(entry);
}
}```
im guessing its similar to that
I wouldn't know of a tutorial\script to point you to, sorry
but it'd involve a bit of vector maths, which i'm rusty on, unfortunately
basically subtract playerpos fom soundsourcepos relative to the playerpos
Not sure what this means, could you elaborate, please?
if the result's positive, it's on the player's left, negative means player's right
i guess ud just use the cubes forward, right, or up and then the cubes position
I have several obects in a scene that the player (with VR-headset) can interact with. When the player turns around, or move the objects, I want the objects sound sources move accordingly. So I can pan this around in a 7 speaker circular setup. I use external software for synthesis (PureData). I just want a value for each object in the scene that represents its position (in relation to the player) in something similar to degrees. Then I send this out over UDP/open sound control. Everyhing is working OK, except panning. Please tell me if I should clarify.
Thanks for the explanation. I am sorry, I am not familiar with VR
It should be the same, its just compared to the player camera position
I'm trying to wrap my head around it
How would you represent the position in degrees?
If you try to think of it as a degree distance from the direction of the camera to the player, there will be a possibility of the objects in the same "line" having the same value
Jeus christ this is so frustrating
i just want to manipulate objects ingame like you would on the editor
First of all, they are supposed to be paths, not pixels
ya, tbh not a straight answer comes to mind..
thats the kind of thing i'd just have to tinker w/ to figure out
Doesn't it literally tell you?
I don't know how to do what its telling me
If I get a value that is 0 if it is in front of the player, 1 if it is on the right, 2 behind, and 3 if it is to the left then I am set. The distance does not matter
thats when you break it into pieces.. and figure out how to do the thing u dont know how to do
Hello this might be some sort of quirk of unity but in case its not I would like to understand whats causing it. Im checking positions on my grid in 2D and when I change the float in my IsPositionOccupied function to 2.5 and get to a gamestate where the code is being run Unity consistently freezes
Vector2 spawnPosition = Vector2.zero;
bool validPosition = false;
while (!validPosition)
{
spawnPosition = new Vector2(Random.Range(-3, 3) + 0.5f, Random.Range(-8, 7) + 0.5f);
validPosition = !IsPositionOccupied(spawnPosition, 2f);
}
// Add position to reserved list
reservedPositions.Add(spawnPosition);
bool IsPositionOccupied(Vector2 spawnPosition, float radius)
{
foreach (Vector2 reservedPos in reservedPositions)
{
if (Vector2.Distance(spawnPosition, reservedPos) < radius)
{
return true;
}
}
Collider2D overlap = Physics2D.OverlapCircle(spawnPosition, radius);
return overlap != null; // If there's a collider, the position is occupied
}
Do you know where the variable sound of Ladder is?
I don't
Got it. How do we consider the degree angle range of what's included in each direction?
This is your script, right?
it is telling you to assign sound of ladder
No, I was following a tutorial because I wanted to throw a simple walking sim thing together for friends
you then must know where the variable sound of ladder is
Does this mean you cannot code at all?
I do not
Yes.
show us 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.
and also please take the time to !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
instead of copying and pasting everything
We do not help people, who don't know what they are doing, here, since they are the guys, who cause the most troubles.
You'll probably have to either follow the tutorial better or start actually learning game development
show me your ladder script, please use one of the paste sites in the link
I would like this to be a float, so 0.5 is forward-right, 0.75 is forward-right-right. Each scene has between 1-10 objects and they should have their own panning data. Does this make sense?
I sent it
It's in the thing I sent
I put it on the paste site I usually use
that site appears to be absolute garbage for sending code. there's no line numbers or syntax highlighting
ah I see, did you assign the sound variable in the inspector?
I was trying to, but it... won't let me?
I figured that's what the problem was, but it doesn't allow me to alter it
I've tried clicking and dragging both the audio file and the one assigned to the player, neither are accepted
audio files are not AudioSources. those are AudioClips
an AudioSource is the component that plays an AudioClip
what object is the AudioSource on
LadderClimbSoundEffect is the audio source
I click it and drag to assign and it doesn't accept
do not assign it on the script asset, do it on the actual Ladder object in the scene
what compilation errors do you have
Lemme try it again, one moment
Do we do this in 2D, neglecting the objects, which are on top of the camera?
we do it in 2d, neither height or distance will be considered
still just this one
this is a runtime exception, and has absolutely nothing to do with compilation. it tells you exactly what you need to do. you have an instance of the Ladder component in the scene where the sound variable has not been assigned
How would I easily locate that instance? i've not been able to find it
you can use the search bar in the hierarchy, search t:Ladder to find all instances of the Ladder component
Works now, thanks!
This is proving way too troublesome so i'm gonna be straighter here
Is there an easy way to replicate transform gizmo behavior without implementing the built-in gizmo system?
Hey everyone! I dont know if this is anything to do with the code, but im facing an issue.
In my runner game for some reason after I added a road model and the obstacles, it doesnt let me jump as I want to, but if I keep pressing the arrow key it works eventually, maybe its the collider or something I dont know
Heres the script
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private CharacterController controller;
private Vector3 direction;
public float forwardSpeed;
private int desiredLane = 1;
public float laneDistance = 4;
public float jumpForce;
public float Gravity = -20;
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
direction.z = forwardSpeed;
if (controller.isGrounded)
{
// Reset vertical speed
direction.y = 0;
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Jump();
}
}
else
{
// Apply gravity when in the air
direction.y += Gravity * Time.deltaTime;
}
// Lane switching logic
if (Input.GetKeyDown(KeyCode.RightArrow))
{
desiredLane++;
if (desiredLane == 3)
desiredLane = 2;
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
desiredLane--;
if (desiredLane == -1)
desiredLane = 0;
}
// Calculate target position based on lanes
Vector3 targetPosition = transform.position.z * transform.forward + transform.position.y * transform.up;
if (desiredLane == 0)
{
targetPosition += Vector3.left * laneDistance;
}
else if (desiredLane == 2)
{
targetPosition += Vector3.right * laneDistance;
}
// Smooth lane movement
transform.position = Vector3.Lerp(transform.position, targetPosition, 80 * Time.fixedDeltaTime);
}
private void FixedUpdate()
{
controller.Move(direction * Time.fixedDeltaTime);
}
private void Jump()
{
direction.y = jumpForce;
}
}```
The last line of Update breaks the whole thing. You cannot directly assign to transform.position when using a CharacterController
transform gizmos behavior ?
An easier way than what?
than what i'm trying, i've been around for a few hours
hopefully this will get across what i'm trying to achieve, i managed to get a simple when mouse move cube move type of setup
but i'm trying to do that on the cube's local axis, and move along it when i drag one of those axis handles
So then what do I do to fix it
are you using Vector3.forward for example instead of transform.forward ?
'ello again all. So, I've figured out the whole rotating a skybox using a custom skybox shader. I'm struggling a little with the Maths involved in getting the directional light that I'm using as my sun to rotate in sync with the skybox though.
Here's The Code
https://hastebin.com/share/fadufedapi.csharp
And here's the 'layout' of the Skybox Material. I figured grabbing the vectors and using those to control the sun direction would be the way to go, but the sun, while rotating, barely moves and I'm not really sure what kind of multiplier I should be using (I've tried a bunch of values in increments of 10 so far).
I will say that it's late and I'm very tired, so could be something ridiculously simple and obvious. Just want to get this bit done and then go to bed. lol.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yup
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you probably want transform for local
this is the code in the cube right now
Dangit, forgot the image. lol.
also you're multiplying moveSensitivity twice
Do not use transform.position, use controller.Move() to adjust your lane position.
i just can't figure out what feels like the simplest of things
which is
when drag blue pill
cube move along blue pill axis
it feels so stupid
oh transform.Translate is local so vector3 shouldbe local
why is that
It's very much not simple to replicate this as close as Unity does it
ya, i was gonna say.. to me it feels deceptively easy
You'll need planes, raycasts, vector projections in order to adjust the object's local axis being moved to the mouse
i'm not trying to do the fullfeatureset of gizmos
theres assets on the store that do this.. runtime transform gizmo or w/e but they pricey for what they are
just move it around , and rotate it in a single axis
i think imma give it a try later on today
already have a pickup and carry script + top down isometric camera controller
sooo thats both pieces i need.. i could combine them probably and get something working.. i'll give u a ping if i do caecpr
transform.controller.Move()????
Do I use it like this? If not then Im getting errors
transform does not have such a property
i had that in mind
i knew that'd take a lot of moving pieces, but still
i can get this working
Not sure from where you'd even begin to implement it, but it would be something like below (taken from your image). This would "track" your mouse cursor perfectly from screen space to world space:
Red mouse position is the resulting world position of raycasting the plane
so, first things first
i gotta dynamically create a plane when an axis is clicked
^ thats what i was trying to get out earlier
and then raycast to it?
that diagram is 🔥
Agreed
thanks for the diagram btw
so if i have a plane and a line on that plane
i can just get the closest point on plane to line
Yep, building the plane requires a point and a normal. That could be the center of your object (for the point), and for the normal a few if statements could solve it:
Clicked gizmo is Z => normal is transform.up
X => same
Y => any of transform.forward or transform.right
Then you feed your ray from Camera:ScreenPointToRay() into thePlane.Raycast() and get the position on the plane
And for projecting there's a few options available
oK
Let me try building it so far beforehand
feels like i'm calling it wrong, also that
that is what visual studio's telling me
Plane is a type, so you need to make a variable and put a new instance of it into it
Plane p = new Plane(normal, point);
lol he explained it sooo much better than i tried to
Ok, I understand this may be the most uneffective and badly written code EVER, but for some reason my game crashed when the roundtype is one and the "laser round" starts. I have no clue why.
https://pastebin.com/PFS5DDYR
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.
How do you expect that while(true) loop to ever end
There shouldn't be a while loop there at all
what is this loop supposed to be doing?
so that it can run even if roundtype changes
Well, you set all of those booleans to true, then start your loop that's going to run a number of times based on your framerate then always go into the complete3 condition since that one has the lowest timer
So, if roundType is 1, it's going to freeze for about a second then do that one always
oh
Loops run to completion
Until the loop is exited, literally nothing else can happen
So, every frame, you're going to loop that while loop until it runs the condition for complete3, then next frame it'll do it again
thank you! I rewrote the code so the while loop isn't needed
Hii could I use some advice on my game
you would need to say what advice you need
I was working on a project, created a terrain. I saved and closed the project. When I opened the project, all my stuff was gone and it onpened a DemoScene, I can't find where all my stuff went.
open your scene? should be there
!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.
Tried implementing this and
Well, i don't know.
might be generating a plane, might not, i can't find a way to debug that
i tried to make it so it spawns a gizmo on that plane, just to i know it's there, but no luck on that front either
The goddamn plane probably needs to be centered on the object, not the screen space mouse position.
when i create action unity add using System; namespace and cant use Random.Range because UnityEngine.Random and System.Random have same class name Random. is there way to fix it
i forgot i named the variable that so when i read your notification i thought you were giving very agressive advice
Two ways to fix this
Either type UnityEngine.Random.Range every time you use it
Or put this at the top:
using Random = UnityEngine.Random;```
really?
Really
You understand why this is a problem right? The System namespace also has a class named Random
So it doesn't know if you want System.Random or UnityEngine.Random
The solutions I showed you above remove the ambiguity.
yeah yeah i already know the solution but it seems unprofessional
whats not profesional about using system.random or unityengine.random?
You could also do something like:
using UnityRandom = UnityEngine.Random;
using SystemRandom = System.Random;``` and then use ```cs
float result = UnityRandom.Range(a, b);
int anotherResult = new SystemRandom().Next();```
if you want to use them both for some reason
¯_(ツ)_/¯
i am professional beginner developer so that it
beginner and professional should not be in the same sentence
just use the functions normally like a sane person
rofl, a beginner worrying about appearing unprofessional
i m kidding
well still #💻┃code-beginner message
im not sure why you would need to rename and assign them differently
in unit test runner, how the heck do I reference a class in scripts folder?
Obviously using this suggestion won't work because the csproj is stupidly enough auto-generated.
You need to put all your code that you want to test into an assembly
then you can have your test assembly reference the main code assembly
my lord
To make assemblies in Unity you use Assembly Definition files
It's really not as scary as it sounds
Here's a good guide on how to set it up: https://www.kodeco.com/38240193-introduction-to-unity-unit-testing/page/2?page=1#toc-anchor-005
Thank you!
Gee, and now I get like 50 errors of missing references 🤔
I thought it'd be easy to set up, turns out it wasn't.
- The TMPRo ones are because you didn't reference the TextMeshPro package in your game assembly. Fix that by adding a reference to TextMeshPro
- The Drawing one - not sure - it depends what this "Drawing" class is and where it lives. Most likely the fix is adding another reference, or moving that script into the assembly if it lives outside.
But even though there are "50" errors it looks like really it's only two
UnityEngine.Rendering doesn't even exist in the assembly definitions
Are you using URP?
Not sure why it referenced that though .. So I can just delete it
I should be good, just needs refactoring
Okay, I'm good. I was just referencing pointless things.
Thank you 😛
Anyone has a good tutorial for a 3d character movement that has walk run jump and crouching??
do you want a RB based character or a CC based character
That's going to be hard to find one with everything. Better to look for individual mechanics and add them together . . .
its not hard to find a basic movement controller like he asked
most of them provide what he is asking
but its best to !learn unity before you dive into unity quickly
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Huh?
I did I don't know how to connect them all I just started unity so idk anything barley
Idk the difference
RB = Rigidbody, CC = CharacterController
I'm learning by making
do you know what they are?
Yea but idk the difference
if not its best to follow the link i provided
Okay
What link
#💻┃code-beginner message
this is a free course to teach you all about unity
Okay thank you so much
how can i have a repeating texture for the background of my camera?
sprite renderer
hi! The facial expressions on the triangle represent the trust level between the characters. I want to update them when the trust level goes up. Right now im testing that by increasing the trust level of each relationship when I press numbers on the keypad.
The saddest face represents trust = 0 and the happiest face represents trust = 3. There are a total of 4 facial expressions. By default, all the faces are set to the saddest face and each face is named after a pair of characters(ex) annie-edward). However, when I press the number keypad, I see the trust levels increase but the facial expression sprites don't get updated. For instance, when I press one, the relationship at index=0 should increase in trust level and the face should be changing to a less sad one. I'm not sure why these changes in sprites aren't appearing when I press the keypad.
how do it repeat infinitely
there is an option on the texture to be tiled and set it repeating on sprite renderer
oh okay
Is anyone here particularly knoweldgable on the MetaXR toolkit?
ive got this basic playerRotationScript running on the root gameobject; https://hastebin.com/share/ujacizoqem.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this is where im debugging from : https://hastebin.com/share/bajamubaki.csharp this script is also running on root object
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You are debugging many different things. Keep the transform.forward log only.
Or add more info to your logs, so that we can understand what variable it is.
the other ones were just me trying to see if im dumb
ive done rotation before its the first thing most people do idk why this is giving me so much issue now
like the prefab rotates and the transform.forward should change idgi
Well, I told earlier. .forward can't be 0,0,0 so I don't know what variable it is that we see in the log.
oh
Don't ever debug the values alone. It's a very bad practice.
what should I debug instead?
Something meaningful, so that we understand the context of the log
For example "transform forward: {value}"
so transform.forward is actually stuck at (0,0,1) (my b)
Great, that's progress.
My guess is that the transform that you debug doesn't belong to the object that you rotate in the scene.
Debug the name of the object
hmm, I thought the transform keyword automatically would, but let me use GetComponent to make sure and debug the object
No need to use GetComponent. It would result in the same thing.
object seems to be correct
You can also pass the object itself as the second parameter of the Log. That would allow you to click the log message to select the object in the hierarchy.
doing that now
yeah its the root object, as expected (i opened the hierarchy and clicked to confirm)
this is strange
Okay. And the one you're rotating is the root object as well?
yeah the PlayerRotation is running directly on the root
and in the inspector its y rotation is changing
maybe since its rotation is always (0, x, 0) . transform.forward will actually always return the same thing? (idts)
cause the blue arrow in the scene is changing
I see that there's networking involved. I wonder if it is related.
yeah but rn the networking stuff isnt doing anything, it could be some of the overhead
like Network Object for ex
How are you rotating the object?
Log the transform.forward tight after rotating it.
you're on to something
its updating properly
So, it's something resetting the property afterwards.
is it a read only variable, could i be resetting it"?
well i cant set .forw but ig i can reset rotation
ill look into it, i might have a bigger issue here. Thanks for your help
It's not. You can set it.
you can set transform.forward?
Yes
oh, ill look out for that then. Im going through my whole tick cycle rn
That would rotate the object such that it faces the direction.
@teal viper I fixed the error by swapping the exectution order of PlayerRotation and some other script. The playerrotation was applying the rotation after the Transform.forward. I am still a little confused, however, because I do not think that transform.forward would be resetting on its own. There may still be another error with my code
Transform forward represents the forward direction of the object, which depends on the object rotation. So when you rotate the object, it's forward changes. Same is true the other way around. When you change the forward dir, unity rotates the object.
I see, not trying to be rude but I dont understand your point
I was trying to clarify your confusion.
Ah, maybe I misread.
I'm making a 3d tower defense game, currently adding exploding missiles that need to hit multiple enemies when they explode.
I saw a Brackeys tutorial where he uses Physics.OverlapSphere to get all colliders within range.
On the docs of Physics.OverlapSphere is says consider using: Physics.OverlapSphereNonAlloc, when should I use which? Is this a good way to make exploding missiles in a TD?
Transform forward does not reset on it's own. It must be either your code or potentially other components(like the networking related stuff).@crisp token
ugh i hate not knowing why a fix works but it works perfectly lmao.
if there was some reset, its not like this would fix it anyway
im wondering if it has to do with the fact that there is a rigidbody on the object and I manually call the physics simulation
Well, think. You changed the order of execution and it fixed it. That would imply that something in the script that was executing earlier before was modifying/resetting the rotation(or forward/right/up) of the object.
Very much possible. Assuming you sync the rb to the transform in update.
Just tested it by reversing the order of execution and using Rigidbody.Rotation (which apparently is proper way) and it works fine. So yeah, that was the issue, glad we figured it out
thank you again @teal viper
https://discussions.unity.com/t/explosion-raycast/706738
Try this maybe
ah raycasts again 🙂 definitely an option
Physics.OverlapSphereNonAlloc is always better, it doesnt allocate.
though similar to the discussion yesterday, raycasts alone dont work here either
the post they linked you doesnt even have a solution.. its just someone saying it doesnt work and there not being a real answer
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
they don't?
Physics.OverlapSphereNonAlloc does seem a lot simpler
a raycast gets you information in a straight line, you arent gonna reasonably use it to get you everything in a sphere. the only use for raycast here would be checking line of sight
but you can just fire raycasts all around not?
Do you have a reason to check the line of sight? For example are there obstacles that would prevent explosion damage even if the target is inside the blast radius?
it's an option, but I don't think it's necessary, I don't mind my explosions going through the walls
Then I don't see why you wouldn't use OverlapSphere as it's literally one line and the simplest way to do it
I'm currently trying to make a hinge-joint onto a gameobject that needs a non-kinematic rigidbody, but was concave....
So I cut the object into 6 convex pieces as child objects, each with their own piece of meshrenderer/meshcollider, and connected them together with fixed-joints.
I'm having issues though using that parent gameobject to hinge-joint onto something... the item just starts floating away.
Is this a problem because the colliders aren't on this object, and are instead child-objects? or how do i solve this
nvm just ignored the parent, and did it on the 1 child thats closest.
this whole joint stuff is still "wobbly" though... time to tinker
the amount of code doesn't matter, it's about optimizing performance
I don't see how firing dozens of raycasts and pruning the hits for duplicates could be faster than one overlapsphere
Premature optimizations: make it more code and less performant
I have no idea about the performance of physics, but you're probably right
i wasnt even really referring to the performance. raycasts and overlap spheres solve entirely different problems.
raycasts cant solve the problem of finding every object in a sphere.
First issue is raycasts in 3d by default dont hit the object they start inside of. Theres workarounds to this but its not the main point
2nd issue is just math. As the sphere grows larger, you arent gonna add more raycasts to cover the range of the sphere. Refer to the image i made. Even if you say you can add more raycasts to check, i could always just make the sphere larger in the example and draw a box between the raycasts near the edge of the sphere. Even if this is an extreme case, it still shows cases where raycasts will fail
i cant name my parameters please help it ruind all my code and i am really stuck please help me
Image
don't crosspost. this is not a code issue. have you tried restarting the editor
so where should i post this and do you mean restarting unity?
you've already asked the question in the correct place #💻┃unity-talk
this is why you shouldn't post questions all across the server. and yes, typically when people refer to "the editor" they mean the Unity Editor, which is the application you use to actually edit your project
what would I use to draw lines across my grid in 3d to show the path monsters will take
I want to draw this in code since the path is dynamic
just for debugging purposes? because you can use Gizmos for that
no to show in the actual game
been searching for it for a bit, but can't find exactly what I need
Line renderer
LineRenderer or you can draw the lines manually with GL.LINES
so I add a linerenderer component on my current grid node?
what you attach the linerenderer(s) to entirely depends on your setup so we can't really answer that 🤷♂️
Presumably it's a game wide mechanic, so you probably should implement it as a singleton or a manager. Basically, one GameObject that draws all your desired lines.
At least that's what I'd do probably.
ok why wont this work? Should i use OnColliderStay?
GetKeyDown is only true for the first frame that the key is pressed and OnTriggerStay (as well as all of the physics messages) is only ever called on FixedUpdate frames so you are likely just missing the input
Which part is not working? If you don't see OnEnemy in the console then you have an issue with your trigger, not sure what that even is OnTriggerStay?
i believe it triggers as long as you come into contact with the other game object
yeah seems right, so do you see the OnEnemy text? there's several potential issues if you don't
nah i dont see anything, not a single message unfortunately
the tags are assigned
ill try to figure something out with what boxfriend said and ill see
show us your objects in the Inspector
boxfriend's message only applies if you see the OnEnemy in console
if you are not seeing the OnEnemy log then go through this: https://unity.huh.how/physics-messages
This is the enemy that the player is supposed to collide with as a trigger
i might have to check Is trigger one sec
no collider
i just added one, compleately my bad, but it still wont work ):
Go through the steps in that link, one by one
👍
Gonna bookmark this too 🙂
ill go trough the site thank you all for your time
Unity should hire boxfriend as a Discord helper 🙂
lol as much as getting paid for this sounds nice, i definitely don't want to be required to help people lmao
can confirm, went from moderating a big discord voluntarily to getting paid to do it part time, leeched all the fun out of it 😄
I figured it out on the website, as i was using a 2D space i had to use OnTriggerEnter2D. I didnt know that. thank you guys so much
If you want to show support then you should donate to Vertx who made the site
Especially considering how often it is used
oh shit, sorry
I'm not sure if this is a beginner question. But i'm having trouble with referencing a script. I've never used any type of help from chatting before so bare with me.
Maybe explain better what you're trying to do and what the script is depicting?
Okay. So i created a gameobject that has an exp bar (ui) which has a script attached to it to update the current xp value which changes the fill amount of the exp bar. Now i cloned that exp bar (because i need the player to be able to instantiate multiple exp bars) the issue is just, when i update the amount of exp (by the press of a button) it only updates the value on the original exp bar and not the one cloned one
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I hope that kind of captures what i'm trying to do
i'm not the best at coding but i'm trying to learn
trying to reference to this
public class progresbar : MonoBehaviour
C# is case sensitive
Represent the object's position relatively to the camera's direction
The classes in C# are called with PascalCase, so YourMethodIsSupposedToLookLikeThis.
Also this.gameObject can be removed, since the GameObject.GetComponent method can be used without the GameObject reference because of your MonoBehaviour already deriving from it
Ok can someone help me fix my player because the player turns when i pick up an item and i open the window here's the code and a visualization of the problem
Share the !code correctly:
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i don't understand I'm new to the server my friend
Do you not see the bot message above?
Is it bad to first do transform.Translate(newPosition) and then after that clamp the x, y, z values and set transform.position = clampedPosition?
Or would it be better to just set the transform.position to the clamped values? Not sure if .Translate does anything special
Why would you even use transform.Translate? why not just transform.position = newposition?
To share large code blocks (more than a few lines of code), click one of the code sharing services. Copy your code from your script and paste it into the site. Press the save button on the site. There will be a save button usually at the top right or left. The URL should have changed now. Copy the changed URL and paste it here.
Because they do different things.
Translate moves the object by the movement vector that you pass into it. Setting position sets the object position to the specified position.
{
if (relativeTo == Space.World)
{
position += translation;
}
else
{
position += TransformDirection(translation);
}
}```
Seems pretty similar?
So it's just transform.position += amountToMove then? Not sure why there's a function for this? Am I missing something?
why is there a function for that? why don't ppl just += instead?
There are many functions that don't have much use.🤷♂️
cool thx 🙂
Also, if you note, it can be convenient if used to move in local space.
The difficulty would be subjective to the individual. A person could also potentially argue against CC and RB suggesting Physics casts and manually implementing gravity etc
so back to my original question
is it ok to set the position, clamp it and then set it again?
or would it be (noticably) better to only set the position once? so calculate the new position first, clamp it and then just set it once
There's isn't much difference imho.
Doubtful that it would make much of a difference but you ought to determine the final output before actually applying it to the Transform if possible.
Negligible difference, don't worry about "optimizing" stuff like this because you're unlikely to improve anything
We're talking about a mere nanosecond difference here for setting a value
Unless you've got physics sync with the Transform enabled or something.
yeah mostly asking so I get a better understanding of how things work 🙂
noticable, probably not, totally illogical, most definitely
was thinking that too after I asked lol
@stuck void Ok can someone help me fix my player because the player turns when i pick up an item and i open the window here's the code and a visualization of the problem
https://paste.ofcode.org/34UznaDnnfXsYeFpRjRtUec FirstPerLook script
https://paste.ofcode.org/ZKpHqRzxhgRYCLUTFPvegP FirstPersonAdvancedMove script
https://paste.ofcode.org/CNPmVMJK9TMNVA8Dsq3n3i Inventory Manager script
https://paste.ofcode.org/9EG83EaWVdBRAx6M2AvQYq Item Pickup script
https://paste.ofcode.org/zT2WF47ketFvzzgnxAWXbM Item script
https://paste.ofcode.org/z293kmJqnnbNFbFnYgj9CA Radio manager script
If you stumble upon needing to improve your performance this would be one of the last things you improve on
What is your issue? I have no idea what you are talking about
well I'm just prototyping atm, but still better to learn things the right way not?
Also, six files of code is not something anybody is going to debug
Sure, but one person would say to avoid code duplication or excessive calls, and the other would tell you to keep it simple
I tell you to keep it simple and worry about optimization later.
You just need to avoid setting the rotation in your FirstPerLook, when a menu is open.
Probably not as well. Just plan the basics, implement what you can with your current skills and research the necessary. If you're just experimenting to learn then trying to find the absolute best way to do something could be a rabbit hole worth investigating.
AI Generated code ?
{
Vector3 newPosition = transform.position;
if (Input.GetKey("w") || Input.GetKey("z") || Input.GetKey(KeyCode.UpArrow) || Input.mousePosition.y >= Screen.height - panBorder)
{
//transform.Translate(Vector3.forward * panSpeed * Time.deltaTime, Space.World);
newPosition += Vector3.forward * panSpeed * Time.deltaTime;
}
else if (Input.GetKey("s") || Input.GetKey(KeyCode.DownArrow) || Input.mousePosition.y <= panBorder)
{
//transform.Translate(Vector3.back * panSpeed * Time.deltaTime, Space.World);
newPosition += Vector3.back * panSpeed * Time.deltaTime;
}
if (Input.GetKey("d") || Input.GetKey(KeyCode.RightArrow) || Input.mousePosition.x >= Screen.width - panBorder)
{
//transform.Translate(Vector3.right * panSpeed * Time.deltaTime, Space.World);
newPosition += Vector3.right * panSpeed * Time.deltaTime;
}
else if (Input.GetKey("a") || Input.GetKey("q") || Input.GetKey(KeyCode.LeftArrow) || Input.mousePosition.x <= panBorder)
{
//transform.Translate(Vector3.left * panSpeed * Time.deltaTime, Space.World);
newPosition += Vector3.left * panSpeed * Time.deltaTime;
}
if (Input.mouseScrollDelta.y != 0)
{
//transform.Translate(Vector3.down * Input.mouseScrollDelta.y * scrollSpeed * Time.deltaTime, Space.World);
newPosition += Vector3.down * Input.mouseScrollDelta.y * scrollSpeed * Time.deltaTime;
}
newPosition.y = Mathf.Clamp(newPosition.y, 3, 15);
newPosition.x = Mathf.Clamp(newPosition.x, 1, 18);
newPosition.z = Mathf.Clamp(newPosition.z, -2, 7);
transform.position = newPosition;
}```
simple enough not? sure it took a few minutes, mostly just asking here, but at least now I understand what is happening 🙂
I would split the logic that checks the keys from the logic that actually updates the position.
you have been on this server long enough to know how to post !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.
Like, you currently have a bunch of if statements that are long because you check for input
I'd put that separately
what happened to keeping it simple? 😦
Either by having the method return what to add to newPosition, or even by returning the Vector3/direction as an enum
How is it not simple?
Readability is part of "simpler"
Sure, putting it all in your update method is simple, but this turns unreadable quick
What happened to keeping it readable?
well I don't know how to do it so lol
Considering there are two different logical steps in the code, you could separate the two
You should create a Vector2 out of the keys and apply the movement once
this structure makes a lot of sense to me, not sure why it's not good
I already explained
Because it looks bad
This
Or an enum
I'd is the individuals personal take on it.
If it works, it works.. but others can still criticize it.
Regardless, it should be clear that keys return a direction
You may create a list, which contains the keys
Well, it would be a readonly Dictionary<enum, List<KeyCode>>
not sure if you're trolling me or not lol
Why would I?
Although, in your case, there is an additional condition, so Func<bool> is required
But, honestly, using the new input system is the best variant here
I don't think I would put in a dictionary myself
The if-statements are long and complex
lol I literally have no idea what you're talking about so I'm just gonna leave it like this
Well, do you know what a dictionary is in C#?
yes
I would just separate it from the newPosition and into a new method that returns the Vector3 direction
yeah that part I get
So what's the issue?
You asked for improvements, I'm not sure how else I could explain
I think it's overcomplicated and makes it less readable tbh
Then I see no point in discussing it
agree 🙂
You'll see why this matters once your project grows, probably
I didn't understand how to keep things simple until I made a massive project
Yeah, just keep your code filthy 🙂
This mostly only matters if your script grows into different parts which makes it unclear when the next thing happens. In your case it's two parts, which is still readable to an extend
A ton of if statements is not preferable either way
how else would I detect which key is pressed?
Dictionary :p
Do exactly what sashok said lmao
A dictionary will just be unreadable in this case
Getting rid of the if-statements only make sense if they are not this complex
Alternatively use a switch statement
To comment on this, this is part of a map editor I am writing https://gdl.space/zisanutefu.cs
This is the splitting I am talking about
Two different groups of input, and then other logic
probably wrong channel, but since we're on the topic, is it me or is my line moving as I zoom in & out?
must be lagging from the complex if statements
You got your priorities wrong if you still think a few if statements are going to lag your game
Especially the ones you shared
I don't see lag, I just see a camera that isn't smooth
This is how I would implement it. Make sure the names are changed, since they are bad.
private readonly Dictionary<Vector2, (List<KeyCode> keys, Func<bool> condition)>
_directionKeys = new() { ... };
private Vector2 GetDirection()
{
Vector2 direction = default;
for (int i = 0; i < _directionKeys.Count; i++)
{
var directionKey = _directionKeys[i];
var directionValue = _directionKeys[i].value;
if (directionValue.keys.Any(k => Input.GetKey(k)) || directionValue.condition)
{
direction += directionKey.key;
if (i % 2 == 0)
i++;
}
}
return direction;
}
I'm joking 😉
any tips on that? or should I google unity smooth camera?
try to narrow down your problem
tell us what you tried and what exactly is not working
you should at least be able to identify in which part of your code it's going wrong
You have to lerp it with a coroutine
The line looks like it's moving because of how rough the camera movement is
ok so this definitely does not do what I want it to do:
transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref velocity, 0.1f);.
camera movement becomes extremely slow and zooming is jittery
Camera uses an actual position. Add a "target position" that the camera constantly lerps to based on its current position. When you update the camera, instead update the target position and have the camera move itself.
and if I lower the 0.1f it's back to rough movement
If i have, say a Cube, with a NavMeshAgent and a Rigidbody and SphereCollider, and i want the cube to move to a specific point, and "jump up on a chair", to sit on the chair, im using a "sittingPoint2 on the chair. But, when my cube comes to the chair and i call the change for my "sittingPoints" transform, the cube ain't lifting from the ground. How come?
private void RotateTowards(Transform workPoint)
{
Rigidbody rb = GetComponent<Rigidbody>();
if (rb != null)
{
Vector3 newPosition = new Vector3(workPoint.position.x, transform.position.y, workPoint.position.z);
rb.MovePosition(newPosition);
}
}
First of all, check if rb.MovePosition is called at all
Is it? You can use logging for example
Secondly, log the value of workPoint.position.z when rb.MovePosition is called and verify it changes
Ooooh, so i have to make the change in the rb.MovePosition... Got it, ill try!
I mean, having it called 🙂
if (rb != null)
{
Debug.Log($"Position Before: {transform.position}");
Vector3 newPosition = new Vector3(workPoint.position.x, transform.position.y, workPoint.position.z);
Debug.Log($"Position Expected: {newPosition}");
rb.MovePosition(newPosition);
Debug.Log($"Position After: {transform.position}");
}```
oh cool, that looks nice!!
line still moves though
Got it to work now @ivory bobcat and @burnt vapor , thanks!
Hello, trying to find a tutorial on how to program a creature that is swimming in the water but everything coming up is about the player swimming. Can someone point me in the right direction for how to have, say, a shark patrol the waters?
what you want to do is look for two separate tutorials.
1- swimming -> the player swimming tutorials will give you the swimming bit.
2- "shark" patrol -> find tutorials about general AI/ NPC patrolling
You are unlikely to find a tutorial about swimming sharks patrolling
Yeah it doesn't have to be that specific, Im just confused on how to make the model "float" in the water while patrolling
Don't see anything from a simple video
Perhaps it's just adjusting based on how close the camera is, idk
I think it's a camera issue, it's breaking my hexes as well
I know there's a pixel perfect camera for 2d projects, but that won't work for 3d will it?
turn on anti ailiasing for the hex breakup
whatever type is totally up to you
I think I'll just switch to an orthographic camera, makes more sense for my game anyway
I tried SMAA but didn't help
try TAA if unity has it
Disabling TAA because MSAA is on.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
spammed in console
but anti ailiasing only does so much, it entirely depends on how many pixels you have on your monitor
look at logs in the unity folder
i dont know what would be causing that
ah there's another dropdown in the camera settings to turn off MSAA
TAA fixes my hex graphics, but my entire game is flickery now
show me what you mean
not sure if u can see it, the line makes it a bit more obvious
ah yeah it shows pretty clearly
ok, so I made my camera Size scrollable and now the jitter on the tiles is gone somehow 🤯
the red line is still flickering though
ok it seems to be only at certain camera positions, not everywhere
if that solution works, i believe you are good
you can turn the quality setting up more or try FXAA (if needed)
whats the error here?
In VSC, the error is shown as a red underline on ContextMenu
im currently learning enums
the error is pretty clear, no?
please tell me
did you read the error message?
yes but i cant understand it
what does it mean by method delcaration
it is only valid on methods. did you place it on a method?
okay, do you know what a method is?
no
well, that's a problem as it's a basic concept and very important . . .
you have a method in the image you posted. not sure how you don't know that . . .
public class <InsertClassName> is a class, not a method . . .
i recommend following a beginner C# tutorial to learn the basics. these are concepts you really have to understand . . .
does this hav anything to do with it?
no. you placed [ContextMenu] above a type declaration—which is not allowed, hence, the error. i posted what and where the type declaration is. the error states it is only valid for method declarations (which i also posted what and where that is) . . .
what should be the correction then?
I am using contextmenu to show my enums
wait
[ContextMenu] is used to add a menu item in the inspector. you place it on methods to call them from the inspector . . .
why does this work
- remove it from the type declaration because it cannot go there
- move it to the method declaration because it goes there . . .
by default, your enums will display from the inspector . . .
when posting !code, follow this . . .
📃 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.
use formatting for small blocks of code or a paste/bin site for large chunks . . .
@timid ember
yes i saw
// namespace yo
{
public class the : MonoBehaviour
{
[SerializeField] GameState myCurrentGameState;
[SerializeField] ammobullet ammotype;
[ContextMenu("Show")]
// Start is called before the first frame update
private void ShowGameState()
{
Debug.Log($"state :- {(int)myCurrentGameState},{(int)ammotype}");
}
// Update is called once per frame
public enum GameState
{
Loading, //0
Gameplay, //1
Gameover //2
}
public enum ammobullet
{
heavy,
rifle,
pistol,
smg
}
}
}
those 3 marks at the beginning are backticks . . .
specifically, which part? where do you expect an error?
uhh, i'm not sure how else to explain it. as the error states, [ContextMenu] is only valid on method declarations. in this snippet, you correctly have it placed on top of a method declaration. That is why it works . . .
Hello, have this code, And when the enemy gets hit, he sometimes get hit and sometimes he dont, does someone know why?
depends how you move the sword
also [SerializeField] is to expose private variables, public are already exposed
hence the 3 dots telling you so
it says comparing tags with == is inefficient
what can i do?
oh, okay
use CompareTag. I also was specifically talking about the 3 dots on the serializefield attribute.
anyway show how you move the sword / enemy
earlier, a provided an image to show where the [method](#💻┃code-beginner message) declaration is . . .
serialize field is a method?
no, that is an attribute . . .
The sword (the yellow thing is the radius of the attack but its the same) is that, and when i click it activates and then disactivates
and the red thing is the enemy
@rich adder
so it doesnt move?
also Idk if OnTriggerEnter gets called when collider is already inside does it ?
@timid ember a method is a block of code containing a group of statements. they can only be defined in a type . . .
idk let me see
the object must exit the collider and re-enter to trigger the collision again . . .
so, if i stay still, it dont gets hit, but if i move it gets hit
how can i do that?
if an attack was executed and the sword is still inside the collider, you can register that as a hit. you'd have to create the logic for this, though, it's much easier to use an OverlapXXX or CheckXXX method instead . . .
wait
i did something more simple
i enabled and disabled the box collider
and it works
Thanks!
@steep rose after a lil searching and understanding stuff I think I choose cc and also the learn.unity Which one. Should I choose
alrighty did you follow the course i provided? just remember a CC is hard to implement for beginners so it might take some time
also wdym which one should you choose?
why doesnt it show up
did you save? do you have errors in the console?
i saved and the only error is cauze i need the field for a object
what is Einteractcanvas? that variable is not in the pic . . .
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
☝️ get configured
if you have errors, post them. your script will not compile and unity will not update if you have errors . . .
well no shit its not gonna compile if you have compile errors
there you go. PlayerInteract does not exist. do you have a type: class or struct called PlayerInteract?
get your IDE configured , pretty sure this was mentioned to you yesterday also
#854851968446365696 before you get help , you need a configured IDE
that is for the serialized field
it doesn't matter what it's for. if the type does not exist, you will receive an error . . .
configure your IDE like everyone said and Create PlayerInteract
so it actually exists
create it
how
Create > C# script
or just keep coming back each time you can't figure something out basic (don't)
use this to post !code properly . . .
📃 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.
Post the script with the error as well
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInteractUI : MonoBehaviour
{
[SerializeField] private GameObject EInteractObject;
[SerializeField] private PlayerInteract playerInteract;
private void Update()
{
if (playerInteract.GetInteractbleObject() != null)
{
Show();
}
else
{
Hide();
}
}
private void Show()
{
EInteractGameObject.SetActive(true);
}
private void Hide()
{
EInteractGameObject.SetActive(false);
}
}
redo this and follow what the bot said
i did a turtorial
so i dont know how
no i mean the improper code you typed #💻┃code-beginner message
You literally just posted code correctly why would you go out of your way to post it wrong the second time
mind boggling
that was a other code
I am aware
reformate 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.
Follow these instructions at all times, no matter how much scripts you need to post here.
One link per script, to not disturb the line numbers
(they are useful in case you have errors)
playerInteract != PlayerInteract
i am watching the tt from the beginning
again.. you need a configured IDE this wouldn't have happened probably
as it would probably give you the correct one
you dont need tutorial for now, just know the basic first.
If your code editor does not underline errors or does not suggest things as you type them, you indeed need to get it configured first.
Note that this step is required to get help here.
!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
• :question: Other/None
we can't help you if you dont show a configured IDE
@pulsar meteor even misspelled/capitalized wrong with a configured IDE it would auto correct to most likely correct one
i dowloade visual studio with unity it is configuratet
mate its clearly not configured.
just because you downloaded it from Unity doesnt mean its auto configured
you need to actually configure it
and based of the 1 screenshot you provided, it doesnt look configured
thats not the only step to it
close vs , click regen project files button, open script by double click
then show what it looks like in vs
it needs to update
Hi all,
Would anyone be able to take a quick look at my code and see if they can see where I'm going wrong and what is causing my wheels to do this please? Been staring at it a while and it' baffling the crap out me 😕
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
try using local position
and local rotation
wait wait wait, why not just make them a child of the wheel colliders in scene view?
I did, and it did the same thing. 😕
Really weird thing though is that it's putting the 'root' object (empty) of the wheels, which are the objects that I'm referencing in the code, in the correct positions/rotations, but it's offsetting the actual visual mesh (which is a child of the root object), which I don't reference anywhere.
And making them a child doesn't work because the collider moves independently of the GameObject it's attached to.
Just tried assigning the wheel meshed directly and that works fine. Something a bit screwy going on when the meshes are children of something else. 😕
why does it give me a NullReferenceException? if (playerControls.Interacting.Interact.WasPressedThisFrame())
!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
Log and see which variable is throwing the nre
reference the parent?
through? in what sense?
@nocturne kayak if you mean how parent moves the child transform , you can't
I'm doing a sprite swap Toggle (UI Element) and modifying the isOn on one of the Toggles, but the sprite swap doesn't change to display the right image unless I click on it
using a child to move a parent
some people that have been putting up with my BS might have read what i'm trying to do, but basically, i want to use the blue and red axis as transform handles
by default, the parent moves the child. if you want the child to move the parent, then move the parent instead . . .
move them through physics and you can push anything
just make sure child has bigger mass when you do
ohh you're not trying to make them collide? this is a grab tool ?
You need to script it then.
damn bro you a baddie fr
That's more or less what i meant to say, sorry, i'm getting kinda tunnel visioned, but there's a long way to go in this project and i need it done by january, so thought process isn't really it's best right now
thanks boo
Instead of moving the child, just move the parent
Oops someone else said that
Problem with that approach is
the movement constraint is tied to the handle
So how would i go about moving a parent based on a child's movement constraint?
Is the best way to just take how much the child has moved, subtract that movement to the child and apply it to the parent? or is there a better way?
The better way is just directly moving the parent. Im not sure what movement constraint you're talking about but I dont see why you cant just replace the reference for what's being moved in the code on the child object
I think I may just end up implementing my own toggle system as Unity's doesn't work
wdym it works just fine
right now i'm using meta's XR sdk
So i achieved that movement through meta's components alone
just reference the parent transform and move that lol
setting the isOn on the toggle via script does not update the Toggle's sprite when using a sprite swap. It only changes when pressing it (must be in the onpointer down that changes the graphic)
are you talking about the Ui.Toggle or the UIElements.Toggle
ohh so you mean the checkmark doesn't come up when you do change value via code?
not the checkmark, but the sprite transition doesn't occur
ohh those like the "hovering"
those are coming from EventSystem
ah and it looks like the eventsystem interacts with Selectable. Using Select() on the toggle does what I want
oh nicee.yup was gonna send the docs link but wanted to link the new one
couldn't find it but forgot now its inside a package link lol
Yea I started with like the first one
Nvm I figured it out which one
how do i fix this error "PUN got region list. Going to ping minimum regions, based on this previous result summary: cae;52;asia,au,cae,eu,hk,in,jp,kr,ru,rue,sa,tr,uae,us,ussc,usw,za
UnityEngine.Debug:Log (object)
Photon.Pun.PhotonNetwork:OnOperation (ExitGames.Client.Photon.OperationResponse) (at Assets/Photon/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:2487)
Photon.Realtime.LoadBalancingClient:OnOperationResponse (ExitGames.Client.Photon.OperationResponse) (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:3052)
ExitGames.Client.Photon.PeerBase:DeserializeMessageAndCallback (ExitGames.Client.Photon.StreamBuffer) (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PeerBase.cs:877)
ExitGames.Client.Photon.EnetPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/EnetPeer.cs:595)
ExitGames.Client.Photon.PhotonPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PhotonPeer.cs:1778)
Photon.Pun.PhotonHandler:Dispatch () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:232)
Photon.Pun.PhotonHandler:FixedUpdate () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:152)"
Theres a photon related chat pinned in #archived-networking
When called through CollideMeleeHitbox() CheckCollisions() gives "Object reference is not set to an instance of an object" because the collisionManagement is null, even though it is defined in Start(). CheckCollisions() works perfectly in other situations. Summon melee hitbox is called through a timer that takes in an int and an Action as arguments.
!code and you should show the error since itll include the line number. If its telling you something is null, then it is.
📃 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.
Yes but it shouldn't be; I used this setup and the bottom log came from Start() and the top from CheckCollisions()
I need a bullet to move in the direction a player is facing using a rigidbody. how do I make the new velocity vector face in the forward vector of the bullet?? Sorry, I'm rusty haha
what is line 44? your image does not show line numbers. this is why they asked to post a link of your !code so everyone can see . . .
📃 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.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I linked the code bot message for a reason, screenshots are sometimes a pain to go through and I cant see line numbers. Theres no guarantee here that these logs are even related from my pov
Read the bot message..
You can directly assign the velocity from the transform.forward of the player. You can also set the transform.forward of the bullet to be that same vector or create a rotation with LookRotation
How would I make a public variable assignable from only one subclass
Cant send the text because I dont have discord nitro lol
huh? choose a paste or bin site. copy/paste your code into that website. click the save button, then send us the generated link . . .
!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.
nitro is not required to send links . . .
Lines 84-125: https://gdl.space/oxuqavovob.cs
Lines 33-46: https://gdl.space/itibaqofev.cs
Thanks, I have the rotation already I just need the velocity, I think transform.forwqrd will work best
Why does it get stuck? The button I'm pressing is supposed to move the cube forward https://cdn.discordapp.com/attachments/497872424281440267/1286651434170843238/2024-09-20_14-32-44.mov?ex=66eeaf06&is=66ed5d86&hm=441034b1ea56e46ed65bd77eafebb4d5818971e9859437830c1c45d87c1617da&
public class KeyboardController : MonoBehaviour
{
private Camera playerCamera;
private Mouse mouse;
void Start()
{
playerCamera = Camera.main;
mouse = Mouse.current;
}
void FixedUpdate()
{
if (mouse.leftButton.isPressed)
{
Vector3 mousePosition = mouse.position.ReadValue();
Ray ray = playerCamera.ScreenPointToRay(mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.collider.TryGetComponent(out Keyboard keyboard))
{
Debug.Log("u");
keyboard.DoSomethingInThisKeyboard();
}
}
}
}
}
public class Keyboard : MonoBehaviour
{
[SerializeField] private UnityEvent theEventToDo;
public void DoSomethingInThisKeyboard()
{
Debug.Log("y");
theEventToDo.Invoke();
}
}
public class OtherPlayer : MonoBehaviour
{
private Rigidbody otherPlayer_rb;
void Start()
{
otherPlayer_rb = GetComponent<Rigidbody>();
}
public void move(float speed)
{
otherPlayer_rb.AddRelativeForce(transform.forward * speed * 600f);
}
public void rotate(float speed)
{
otherPlayer_rb.AddRelativeTorque(-transform.up * speed * 600f);
}
}
move is basically being called in FixedUpdate every frame when I'm pressing the button
are you pressing the button the unpressing it?
no, while that strange effect happens the button is pressed
That is a massive overuse of regions..
Also your debug doesnt show anything for collisionManagement. Debug collisionManagement == null
It does show in the lower log which is sent by line 37
show me where move and rotate are in your code
But not in the top one which is sent by line 43
@steep rose here
Regions let me collapse code and makes everything easier to read and work with
they're called from event
You can already collapse methods. And yes you say it shows in the log which happens after the error. Before the error its clearly null. Im not really sure what the confusion is. Its null, the console isnt lying to you.
Yes but they dont stay collapsed when you reopen a file
Ohh right
So for some reason CheckCollisions() is called before Start()?
Even though the hitbox is Instantiated before the collisions are checked
try debugging your input to see if it deactivates or not
sorry for the late response I was building a flight stick
lmao you still kept the example names I gave you ?
yes
what do you mean deactivaatees
I think it's problem with that force thing
if the input stops or not
did you debug other movement
pretty sure this looks wrong
-transform.up is probably changing as you rotate
since its the local direction according to the transform
yeah Vector3 way seems to be working better
public void move(float speed)
{
otherPlayer_rb.AddRelativeForce(Vector3.forward * speed * 600f);
}
public void rotate(float speed)
{
otherPlayer_rb.AddRelativeTorque(-Vector3.up * speed * 600f);
}
actually you are suppose to do that since you are already using local space
i totally forgot about that
and i even looked at documentation
how can I make the cube rotation not accelerate?
I got a headache from watching this.
You have to use the Rigidbody.MoveRotatation method, which smoothly changes the direction, checking for any Colliders on the way
- Only apply the force once
- Set the angular velocity directly
- rotate it manually
it doesn't have noclip problems, right?
"noclip problems"?
MoveRotation does not respect collisions
yeah, when you rotate on a high speed and it noclips
Set the angularVelocity - or only add a force once
It does respect collisions.
Not sure what "noclips" mean
noclip means some object is going through the other object
No, MoveRotation checks for collisions
If required, use transform.rotation to teleport the Rigidbody
mmh, not really. Only for kinematic rigidbodies it does have any difference compared to simply modifying the rotation
isn't MoveRotation like Moveposition, it makes other RBs respect its physics movement but itself doesn't collide with anything properly like AddTorque ?
That's what I thought, only when it's kinematic though
Moveposition doc says its mainly for Kinematics, but doesn't mention anything on MoveRotation page , the name makes me assume its similiar? not sure 😅
how can I disable a main class script and all subclass scripts in one call
all on same object
a loop probably
Call GetComponents<BaseClass> then just disable them all
Why would a single object have a "main class" and "subclass" scripts on it?
That seems like a weird setup
wouldn't it only have one?
I'd assume it is the same. If I had to guess, .velocity and .angularVelocity fields could be used to indicate the movement of the object only if it was kinematic
Haven't tried whether they change when calling MovePosition/Rotation though
Yeah this seems to be the problem, but why does it happen?
from my understanding the 3D engine kinematics don't have either one of those velocities, so I assume those are why those methods are the alternative to velocity
What I meant is that those fields could be used to hold the velocity of a kinematic body when calling a Move... method since they are not used otherwise
OH I see yeah , I assume they are not overwritten in the next physics frame right?
what's the purpose of fixed update fixed delta time? isn't fixed update already fixed by itself?
I can't figure out how to address all subclasses just by the main class
like calling a method on a subclass just by doing main.method()
instead ends up with a missed reference
Ok fixed my problem by moving everything from Start() to Awake() in the script
the MoveRotation way works but can I make acceleration and deacceleration there?
public void move(float speed)
{
otherPlayer_rb.AddRelativeForce(Vector3.forward * speed * 100f);
}
public void rotate(float speed)
{
// otherPlayer_rb.AddRelativeTorque(-Vector3.up * speed * 100f);
Quaternion deltaRotation = Quaternion.Euler(new Vector3(0, -speed * 10f, 0) * Time.fixedDeltaTime);
Debug.Log($"Adding rotation to an object: {deltaRotation}");
otherPlayer_rb.MoveRotation(otherPlayer_rb.rotation * deltaRotation);
}
if you want acceleration use the AddTorque then clamp the AngularVelocity / stop adding torque if threshold reach, depending on behavior you want.
MoveRotation will not care about mass or any of that acceleration, you would need to write your own (could potentially just use a animation curve / lerp)
Just tried with a simple test script just to make sure my assumption was correct and indeed both .velocity and .eulerAngles do change when MovePosition and MoveRotation was called and only happens when the body is set to kinematic. Non-kinematic body just gets teleported and doesn't behave well at all with other bodies when moved or rotated with Move... methods (just tried and confirmed it happens with the rotation as well). Interestingly enough if I call the Move... methods only for a one frame (for a kinematic body), the velocity fields will not change immediately but can only be detected the next FixedUpdate and then the next FixedUpdate they will reset to all zeros
Ahh that's very good to know, I have only used those methods when its kinematic, yeah dynamic were giving me other issues (and the whole not stopped by other dynamic bodies/colliders)
I wonder if its the same on Box2D.. iirc that has velocity for kinematic? that always throws me off lol
As far as I know, the 2D engine works pretty much the opposite and non kinematic bodies actually do work well together with the Move... methods. Don't know how it works with kinematic ones but the way I understand it, calling Move... on a non kinematic one will just change the velocity fields so the given position will be reached during the next physics step (assuming nothing is blocking the object)
Interesting, I'm gonna test some stuff out. Very informative btw , thanks 
np, bit confusing how the 2D and 3D engines work differently but I guess it's just a consequence of Unity using third party physics solutions which are not meant to have the same functionality
there's angularVelocity for AddRelativeTorue but is there a similar property for AddRelativeForce?
nvm I found it
literally velocity lol
it was renamed in 6 though to linearVelocity
what do you mean by "missed reference"?
And what do you mean by "addressing all subclasses"?
Hello, is adding an event to an animation in the animator the best way to assign hitboxes to a move?
I want to add hitboxes to specific frames and this has been the only solution I have found
animation events are a good way to call methods when something within that animation occurs. there is no best solution, but this sounds like a good one to use and test if it works for you . . .
Like missing reference error
Like put a different subclass script on different objects, but a main controller script with 1 reference to the main class
NullReferenceExeption or NRE?
Missing Reference means the object was destroyed
Are you sure it's that error?
You should share the actual code and the exact error message you are seeing
how much of a performance drop if any would using rigidbody bullets from 5 to 10 people or ai and the bullets are shooting at a rate of a quarter of a second compared to translated bullets of the same size of people and rate?
just wondering since i will have to implement a bullet system soon
physics on 20 - 40 objects per second as opposed to physics on 0 objects per second?
is that what ur asking? lol
technically yes 😅
well
i would still be translating the same amount of bullets at the same size of people and rate of fire
Thanks, im used to working by frames and the only way I can do it seems to be this way. I think I have a way to make it work with animation events.
but instead i would have to check collisions with OverlapSphere and just delete the bullet on impact for the translated bullets
rigidbody gonna be better, no need to reinvent the wheel
I should I'm just not at my PC at the moment
There's no way to answer this, you have to test it
Most likely it would be faster than using scripts to manually move the objects though
alrighty thanks for the input 👍
Is this a bug? I'm running into a minor issue where scripts attached to a deactivated parent object are still being called, giving me some weird errors
I can bypass this by running a manual check that the parent is deactivated, but shouldn't Unity do that by default?
what exactly is being called?
A function that shoots a bullet when the left mouse click is pressed
it was getting to this part and stopping since it couldnt access the prefab due to the object being disabled
you can manually call public methods from deactivated scripts. only certain unity update methods won't run . . .
I don't recall this bug happening before I updated to 2022 LTS though
did you debug to ensure it's being called? did the debug to ensure the script from the deactivated GameObject is calling a method?
The only major trouble it caused was reducing the bullets in the magazine of the reserve weapon but I can block access to it by manually checking if the parent is active
Ye
I put a Debug.Log that returned the name of the weapon the script was being called from
I could also tell the script was being accessed since ammo--; was being called in every left click
Even when the gun wasnt actually firing
It's a bug - in your code, not in Unity's code
Look at the stack trace in your Debug.Log to see where it's being called from
Likely an input handler of some kind
to check if an object is deactivated is if (gameObject.activeInHierachy) . . .
My guess is you are perhaps using the new input system and you subscribed to an input action via someAction.performed += SomeFunction;
and you never unsubscribed
Yes I am using the new input system
side note: you should format your code an can probably condense that if statement check . . .
But as I previously said it also didn't happen in previous versions I had the project on
And I was using the new input system aswell
are you subscribing to an event in Start?
yes
Any function can be called as long as it's accessible. The disabled script would just stop the Unity callback methods from occurring each frame - for the most part. The caller would need to evaluate if it's supposed to be called or not instead.
So it's exactly as I said
Trust me - this has nothing to do with Unity versions
you are simply not unsubscribing your input listener appropriately
It either:
- did and you didn't notice
- You never disabled that object
- you never pressed the button after doing it
- your code didn't access anything destroyed or disabled before
You would not be able to convince folks of this. Likely the difference in behavior lies with the change of something other. Subscribing and unsubscribing to events isn't a pattern specific to Unity.
Havent touched the code that handles the firing since I wrote it in 2019 LTS
Typical approach:
void OnEnable() {
myAction.performed += MyListener;
}
void OnDisable() {
myAction.performed -= MyListener;
}```
I do _not_ recommend using Start
Look - the most likely thing here is you're simply misremembering some detail.
you're not going to convince us with this anecdote
Perhaps
because everything you're saying is pointing towards an obvious error in your code.
please do not use Start to subscribe to events. you want to be able to subscribe and unsubscribe in—your—case you need to deactivate or stop a script or system from running. as Praetor mentioned, use OnEnable and OnDisable . . .
!code for whoever sent that
📃 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.
Does anyone know how i can fix my combo script from constantly triggering Attack1
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What do you mean by "constantly triggering" it?
Like when i spam click Attack1 Triggers over and over
I tried adding a timer but it did not help
Ok that's not "constant" that's whenever you click
so what you are asking is how to add a cooldown
Well first you should add some Debug.Log statements in here to see what's actually going on.
because as far as I can see - this comboStep variable and the correlated if statements should prevent Attack1 from triggering more than once
I would put them in each of those combo step if statements
ok
inside PerformCombo
quick question how would i be able to get the specific transform of a point in my array
public Transform[] WPTransforms;
[SerializeField] private int RandomPoint;
private void Start()
{
RandomPoint = Random.Range(0, 4);
}
void Update()
{
WPTransforms[RandomPoint] = //something
}
i am just now learning arrays
WPTransforms[RandomPoint] is the specific transform
Transform example = WPTransforms[RandomPoint];```
All the combo steps are in the log i think im just clicking so fast its resetting to Attack1 before the animation finishes
oh, alright
you already have it. the line in Update accesses the specific element in the array . . .
yeah im not the best at arrays as you see 😅
i put them off for a while
thank you though
well you need to decide how you want it to work. Do you want it to jump straight to the next animation without waiting, or do you want the user to have to wait for the animation to complete? Or what?
Yeah i want to keep exit time so the full attack plays
then you should prevent the player from being able to attack again until the animation is finished
you can do this with an animation event for example.
Thats the part i dont understand because i Have a animation event that sets canAttack to true but it dosent work
Well, canAttack is ALWAYS true
because your code never sets it to false anywhere
ooooh ok you think i should set it to false untill the animation event triggers it back on?
yes
Ok i shall try thank you so much
Honestly no clue where this question should go since I guess it's editor related but kinda not,
What's the vibe on running IEnumators without a monobehaviour?
I've seen some examples online on how you can kinda run through them yourself but my initial testing of them seemed to produce results that ignored yields?
IEnumerator is a thing outside unity. unity uses them for coroutines. yields arent ignored, but they likely dont do what you think they do
Ah ok, probabably a good time for me to learn how they actually work 😄
For context im trying to do some webrequest/downloadhandler stuff for editor related things but was curious outside of that usecase aswell
am i on the right track here to finding the transforms of the overlapsphere colliders?
[SerializeField] private Collider[] overlapcolliders;
Transform overlaptransforms;
void Update()
{
overlapcolliders = Physics.OverlapSphere(transform.position, 50f, WPtransformmask);
foreach (var hitCollider in overlapcolliders)
{
overlaptransforms = hitCollider.transform;
}
currentpointtransform = overlaptransforms[RandomPoint];
distfrompoint = Vector3.Distance(currentpointtransform.position, transform.position);
}
overlaptransforms is not an array or a list, so no, this won't work.
It should also be giving you an error.
it is giving me an error, im currently trying to get it to work
would i make it an array then get the hitcollider array of transforms or just the transform
I don't know why you need to store all the transforms into another collection, you have them all in overlapcolliders
thanks Osteel, you're a lifesaver!
arrays are tough, at least for me
How do get a parent gameobject and find the child of that gameobject parent and then disable it ?
you get a GameObject by referencing it from the inspector, using Find methods, searching for its tag, or a component attached to it. once you have the GameObject, you can search through its children to find the specific child transform and access its gameObject property to disable it . . .
i got it !
Is there anyways to set the transform of an animations that plays?
I have one playing on the main character but the position is way off
again, !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.
https://hatebin.com/cgghykmunu so this is my code and when i try to test my game it just goes on forever and ever
Using find methods are very inefficient and slow. you should reference your gameobject in the editor instead by making a public variable and dragging in the reference
i dont see how your code has anything to do with it. i think your editor is just bugger or slow
ok
try disabling domain reload in project settings, if its on
its off
would the possibility of clearing Library help them at all, since they say they have restarted the editor several times to no avail
this happens to me sometimes whenever i have a large project that im working on, but it never takes more than 10 or 20 seconds
ive tried that but its never helped me so probably not
ok, i leave it to you guys
same it normally takes 5 seconds to do that part of the compiling
what version are you using?
yeah this happens to me on a similar version
i dont think this will help, but you should try closing your project and deleting your library folder, like Hunanbean mentioned
where is the library folder im quite new to unity
found it
will this make me restart my project?
make sure you only delete that, and make sure your project is closed.
so i delete the library folder
after you delete it simply reopen your project and the files will regenerate on its own
yes, just that
it'll take a few mins for the project to reopen
