#💻┃code-beginner
1 messages · Page 233 of 1
Just use a bin
quaternion.x does not mean an angle in x
what is a bin?
Did you read the bot you were linked to like six times
read this
READ IT
man i wish i could post the gif of uncle ruckus forcing tom to read
Yes now what is the actual issue?
that looks like a pic to me on mobile
i am having some issues with getting a unit to walk, been trying to figure it out and watched videos nothing is helping. not quite sure what to do, my next thought was scrap and start over again. but i wanted some input first i created terrain and a unit as a capsul i also created a new layer called ground and i baked a navmesh surface into the terrain so that the unit can walk from my knowledge the code is correct i have double checked it and even re wrote it and that is doing nothing
anyway, this will not work, because you are messing with the insides of a quaternion. which we keep telling you not to do
Consider putting a log inside of your raycast and see if it ever actually hits anything
ok thanks. i will do that, where can i look in the editor for the log data. not new to programming. just very new to unity
cool thanks did not see that it is small
i read cornole
cornhole
thanks now that you showed me there is a consol i am able to just debug it myself. appreciate it
Debug.Log("Hit: " + hit.collider.name) this is what i did. or is there a more specific thing i need to type for it to appear in the unity consol
nah tahts about it.. fun fact u can use string interpolation to not have to use the " + " sign and spacing and everything
Debug.Log($"Hit: {hit.collider.name}");```
{variable}
hello
Hello, I tried to make a script to resize a grid layout (in ui scroll view) to fit any screen size. It works perfectly in the editor, but when I do a standalone build, it doesn't show the content of the grid layout (there is a list of prefabs and it shows only the root element of the prefab, but not it's children) Any ideas how to debug it?
RectTransform rectT;
GridLayoutGroup layout;
// Start is called before the first frame update
void Start()
{
rectT = this.GetComponent<RectTransform>();
layout = this.GetComponent<GridLayoutGroup>();
}
// Update is called once per frame
void Update()
{
Rect rect = rectT.rect;
float width = (rect.width + layout.spacing.x) / Mathf.Round((rect.width + layout.spacing.x) / (150 + layout.spacing.x)) - layout.spacing.x;
layout.cellSize = new Vector2(width, width);
}
I tried to but there new Vector2(100, 100) instead and it works (it doesn't do the resizing, but it renders all elements), but when I changed it to new Vector2(100 + width * 0, 100 + width * 0), it doesn't work anymore
Also, the width is probably right, because the width of the prefabs seems ok, but it renders just the gray rectangle and not the content inside of it.
Anything times zero is zero
Yep, and * goes before +, so it is basically 100+0
But for some reason, it still manages to make a difference
is normalize ok to use when using character controller?
or is there a better method to make diagonals same speed
Normalizing is the way
okok 
guysss why my tracer is wrong?
this is in the shoot IEnumerator TrailRenderer trailRenderer1 = Instantiate(trailRenderer); Vector3 startPosition = muzzle.transform.position; //Quaternion startRotation = muzzle.transform.rotation; Vector3 endPosition = /*startPosition + */muzzle.transform.forward * shootRange; trailRenderer1.transform.position = startPosition; //trailRenderer1.transform.rotation = startRotation; trailRenderer1.Clear(); trailRenderer1.AddPosition(startPosition); trailRenderer1.AddPosition(endPosition);
Trail renderers renders trails automatically as object moves, you don't need to set its positions. If you want to use poistions, use a Line Renderer instead.
ok i will try 😉
https://forum.unity.com/threads/input-delay-when-using-charactercontroller-move-function.713942/
this post had the same problem with me in normalize, it does not stop immediately after moving
but cant understand what they meant on the solution
Basically, GetAxis does not immediately return say -1 when you press S, the value is smoothed out over a few frames. Same for when you release the key, it takes some time to go back to zero. So when you normalize, you have that remnant input until the value becomes exactly 0, and it can't normalize a zero-vector anymore
The solution is to use GetAxisRaw, that doesn't have any smoothing applied.
got this weird bug where if the player picks up an item the item gets added it to a list but when the player is moving and they try to remove it from that list it stay in the list and gives me that error at the bottom of the console
I tried get axis raw and it worked
thank you spr
I will use them from now on
It might just be the visual parts of the editor that are struggling. I would probably grab the latest patch for your Unity version and see if it persists.
Seeing how you are removing and handling the dropping in general might be useful.
ill try that but in the meantime its really simple how im doing it.
does vs code not differentiate types and methods in syntax highlighting or is this unconfigured
unconfigured probably i dont know my brother set all this up for me like a week ago
!vscode
you have any idea from the code i sent? im still stumped
This certainly doesn't disprove that the editor isn't just struggling on its own, assuming this is a regular Remove on a List. I would grab the latest patch for your Unity version if you haven't already.
yeah ive got the latest stuff
Do you have some custom editor stuff that could possibly be screwing with this stuff?
no its just the base editor
Does the error occur if you don't have this object selected when you repeat the steps?
what do you mean selected?
Having some other or no object selected in the hierarchy
lol what the hell, having nothing selected fixed it
i thought my code was wrong, sorry about that
Because a lot of editor specific code related to that list doesn't run 😛
@lost anvil btw since you're already implimenting IPickable interface, you can skip the CompareTag step by using TryGetComponent
It is still a bit odd that something as basic as this is broken in a patched version of Unity. Did you make sure to actually start the project with the latest patch you downloaded?
yeah
like TryGetComponent<IPickable>(); ?
Unity editor stuff is quite extensible, so it's possible some thirdparty stuff you put in could be messing with some common Unity elements, but that's about as much I can say.
fair enough, ill look out for that in the future then
you should look at the docs to see how the method is used
https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
Yeah, and out IPickable current in the prantheses
If object has Ipickable component on it it will return true as well as the reference to that component so you can directly call current.Pickup(); inside the if block
Hello, how do I get the size of the RectTransform in world coordinates?
why in world coords?
because I need it for my current issue
yeah i was kind of expecting you to actually provide an explanation of the issue there.
https://xyproblem.info
which involves getting everything in world coordinates to avoid issues with parent transform
Didn't know there was a term for that, imma save that one lol
Well, no explanation is required here. I need to get the size of the RectTransform in world coordinates. I need it to avoid issues with localPosition that's being affected by parent's transform
What is the "issue"?
This isn't a xy problem, just a question
I have mentioned that local transform is being affected by the parent's
this does not make it any clearer why you are trying to do this
and if you would bother explaining why you are trying to do this, a proper solution can be suggested
I am making a panel being dragged inside of its view rect. Now, view rect has its coordinates being get though its Rect, but these min and max positions aren't working properly when the object is being affected by its pivot or parent, which should be fixed (and is on the halfway of being fixed) by using the world coordinates
Scroll rect doesn't work for what you're trying to achieve?
why would using world space coordinates for UI objects suddenly fix your issue?
but this works
That's why I need to simply get the rect's size in world coordinates, which is not achievable via camera's ScreenToWorld
Because world space coordinates are affected by neither pivots nor parents
Generally speaking, UI doesn't and shouldn't care about world positions
why would it work?
Just asking, currently can't even figure out what you're trying to achieve
and UI objects are not in world space
Well, I have wasted enough of my time with those pivots and parents. I mean, maybe I'm just to bad with UI, still I think it's better to use world space, even if that's because I can't figure out the solution with local one
a draggable panel
If you press the "minimize" button on any of your windows, it's going to become smaller than your screen size and you can drag it
that's what I define as "draggable panel"
IDraggable interfaces not good enough?
haven't ever heard about this one
Oh, I see, IDragHandler? I used it, it's trash
It's just a buffer that sets the current dragged object and then you move the element with the pointer
anyway, the logic is the same as mine
i have a problem where when i use a toggle to change to windowed, i close the game and open it again, its still in windowed but the toggle is set to fullscreen.
Show how you're moving the object?
I used it before and found it better to simply use Input.GetMouseButton & Up, Down
My bro is trying to make a character control system using a rigidbody. And it's nearly perfect other than the fact that it hangs up on walls. Anyone encounter something like that before?
use a physics material with a low friction
give it a physics material with less or no friction
Vector2 potentialPos = _beginPos + (Vector2)_mainCamera.ScreenToWorldPoint(Input.mousePosition);
Vector3[] corners = new Vector3[4];
dragView.GetWorldCorners(corners);
Vector2 minPos = corners[0], maxPos = corners[2];
dragPanel.position = MathHelper.Clamp(potentialPos, minPos, maxPos);
now I've implemented it using world coords
"better"
FYI, localRotation.z is not the z axis of a Vector3, but a Quaternion, with a range of -1 to 1 . . .
Yes, IBeginDragHandler has a drag offset which makes it worse than GetMouseButtonDown()
please?
why is this happening? ```cs
float angle = isCrouching ? crouchLeanAngle : isCrawling ? crawlLeanAngle : walkLeanAngle;
float distance = isCrouching ? crouchLeanDistance : isCrawling ? crawlLeanDistance : walkLeanDistance;
if(canLean)
{
if(Input.GetKey(KeyCode.E))
{
if(!Input.GetKey(KeyCode.Q))
{
targetLeanAngle = -angle;
targetLeanDistance = distance;
}
}
else if(Input.GetKey(KeyCode.Q))
{
if(!Input.GetKey(KeyCode.E))
{
targetLeanAngle = angle;
targetLeanDistance = -distance;
}
}
else
{
targetLeanAngle = 0;
targetLeanDistance = 0;
}
}
else
{
targetLeanAngle = 0;
targetLeanDistance = 0;
}
float smoothAngle = Mathf.Lerp(cameraPosition.localRotation.eulerAngles.z, targetLeanAngle, leanDuration * Time.deltaTime);
float smoothDistance = Mathf.Lerp(cameraPosition.localPosition.x, targetLeanDistance, leanDuration * Time.deltaTime);
cameraPosition.localRotation = Quaternion.Euler(cameraPosition.localRotation.eulerAngles.x, cameraPosition.localRotation.eulerAngles.y, smoothAngle);
cameraPosition.localPosition = new Vector3(smoothDistance, cameraPosition.localPosition.y, cameraPosition.localPosition.z);```
The second reason is the threshold which isn't achievable with this interface, making my task impossible to solve with IDraggable
it only does that when i lean to the right
so when i hold Q
kickflip!
Probably from what I just mentioned above . . .
so how do i fix it
i dont understand
what about this?
ah yes, draggable panels is definitely impossible to implement using the event system IDragHandler interfaces which is why nobody has ever done it before and why it is always recommended to do it the hard way by manually polling the mouse, checking its position to see what object it is on top of and moving, etc.
i think it has to do with this
Now why would you use screentoworldpoint when screentoviewport is available?
or maybe the angle part
its probably doing a full 360 to get to that
Maybe I'm not really familiar with it, but how would you do a threshold with it?
You're using a quaternion rotation value where you want to use the Vector3 rotation value . . .
what threshold? keep in mind you have barely explained what the fuck you are actually trying to achieve
so it would be this?
cameraHolder.localRotation = Quaternion.Euler(xRotation, yRotation, cameraPosition.localRotation.eulerAngles.z);
generally, if you go quaterion => euler => quaternion, you probably messed up
and that includes this
I haven't read the entire code but change it to the ruler angle z axis and test. It's a start . . .
this works
Yeah, try that. This is using the correct angle . . .
its the leaning thats not working
yeah it works
The threshold is the distance from the borders of the panel where the drag can be started. Both positive and negative, where positive is outside of the panel and negative inside.
What axis is it spinning on? Zero out that axis and test if it still spins . . .
again, what does that even mean? distance for what? what panel? the one being dragged? are you saying you want the mouse to be within a specific distance from any edge of the panel? you have to actually explain what you are trying to do. nobody here can read your mind
It automatically detects using the raycast distance of the image on the object no?
no
it works when i lean to the left tho
but when i lean to the right it starts spinning
they both spin the same direction dont they?
yea i know... i know the issue.. just not how to fix it
lmao
its wanting to do a FULL rotation to get to ur negative angle
yeah
instead of rotating the opposite way of ur left lean
or right lean. (whichever ones working)
ill look around google a bit to try to find a solution for ya..
That worked. Thanks!
alright thanks man
may have to use some other type of rotation method
rather than setting it directly.. theres different methods u can call that will rotate thats not setting the rotation manually
Let me draw it for you. The rectangle in the middle of the image is an UI Image. The yellow rectangle outside of it is a threshold. A user can drag the panel by left-clicking anywhere inside of this yellow rectangle and moving the mouse, while still holding the left mouse button.
That's why I've asked you whether it's possible to achieve this funtionality with IDraggable interface you were talking about
hello everyone
Yes, you are able to . . .
yeah threshold isn't exactly the correct word for that. you want to be able to click outside of the object and still adjust that object's size. so what you can do to use the interfaces is make that inner panel a child of a transparent panel the size of the "threshold" as you put it. then you can use the interfaces to work with it by resizing that invisible parent
if(buttonPushed)
{
currentMousePosition = Input.mousePosition; // start updating currentPosition
float dragDistance = Vector3.Distance(initialMousePosition,currentMousePosition);
if(dragDistance < dragThreshold)
{
// we've dragged past our threshold
}
if(Input.GetMouseButtonUp(0))
{
buttonPushed = false;
}
}```
i have a similar system where I check the distance from the initial click position
why you would want to be able to start dragging while hovering over some other object or nothing at all is beyond me though
Xy problem
buttonPushed goes true when i click.. and then once ive passed a certain distance from where i originally clicked.. i do my logic
that isn't exactly what they are trying to achieve though. they want to be able to start dragging from anywhere within the green bounds in their image
but yea.. i also raycast on buttonPushed.. to make sure theres a selectable under it
oh, ya thats odd
maybe just a buffer area?
hello everyone i am new to game making so i wonderd if someone wanna help me:)
I only use the drag interfaces because you'd still have to poll in update otherwise even with the new update system
whats this
so I cant be bothered
read it . . .
@willow scroll I do agree, it is weird to click outside of an image and still drag it. What if they attempt to click/select a different image that is within the invisible threshold?
i did it man
this is how
what did u use?
Now, why would I make a script to Instantiate the parent's object for the object with the script and translate the script to this instantiated object in order to use the drag interface, which doesn't even start the drag unless you've moved your mouse a bit, if it's just better to use Input's GetMouseButton?
huh?
i changed them from local variables
and also as the first thing
i passed themselves into the lerp
hey can anyon help me im a bit stupid and i forgot how to code
there are beginner c# courses pinned in this channel
You totally misunderstood the assignment...
lol.. they say dont do that.. ( as its improper way of using lerp ) but if it works for u then i'd say run with it
alr
but i have a specific question
yeah i know but im just gonna keep it for now
maybe in the future change it
okay then https://dontasktoask.com
My original objective was to make user to click inside of the panel, to make me create less object. Obviously, I've also made me able to adjust the panels to be clicked ouside too, as it wasn't a big change for the script
/tableflip just ask the fuggin question 😄
This tells us nothing. We have no idea what issue you have with your code. Checkout the pinned messages or Unity !learn for helpful material to get started . . .
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
alr so i should say that
wait ima show you my code
just give me one second
!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.
The dragThreshold is a float though, I am using four directions. Also I'm not sure whether you're doing it with IDraggable interface
im not.. its just methods and if conditionals running in update
i use distance tho... it doesnt matter which direction..
Yeah, so the logic is a bit different from mine
its a radius from the selectable i click on
thats fair..
I have to check wether the point is inside of the rectangle
yea i realized after box clarified
That's why I was saying I didn't think it was achievable with IDraggable
may have to roll ur own solution.. i've never used IDraggable.. i need to tho just so i kno what its all about
sorry if im being confusing you guys i joined the server like 5 minutes ago but bassicly the problem that is being occured is that I have been wanting to make a level selector for my levels and im using buttons for that. and I put all my button funtions in a seperate class the only issue being that i cant access the functions froms my class
Pretty simple and easy to achieve it...
i gave you a suggestion for how you can achieve this with the interfaces. but you for some reason don't want to do that and would rather work with world space coordinates despite none of these objects even existing in world space
are they public functions?
yes
I can show you the code if you want me to
No, I have achieved the desired logic. It's overthinking, which needs more code written
another thing.. that script w/ all the functions has to be on a gameobject in teh scene..
u drag that gameobject into ur button and then find the method
if you have achieved what you are trying to do, then why are you here?
it is
Did you drag in an object with the script on it, or did you drag in the text file with code in it
can u show the inspector of one of ur buttons? with this gameobject u say u have in the slot?
shure
I have asked how to get the RectTransform's size in world coordinates. But you're trying to avoid this original question by criticising my code. Don't see why though.
You cannot. That is the answer
because it makes no fucking sense to use world coordinates for any of this? none of the objects are even in world space
You have created a Monobehaviour script inside another script
no they are not because I want to find the function Load Level 1
Take that out and make it a seperate cs file
Because that's a different class
(that you can never actually use)
why not
you can only get a recttransform size in world coords in 2D in overlay view IF it is a sidescroller, and even then that information doesn’t always play nice
Because it is in the same file as another class
Because MonoBehaviours have to be in their own file
You physically cannot add this component to an object
Meaning it's impossible you've dragged in an object with this component on it
like you’d have to treat menus the same with the same methods as if you did not have the 2D camera overlay to relate screen-world space
ok but what if I make that class a child of the main class
Irrelevant
ok then what are some possible solutions
That doesn't change anything. You'd still need to drag in an object with that component on it
Just put it in its own file 🤷♂️
Super easy
make a separate file
...don't try to put a class where it can't go?
yea ig but then it will be a bit less unorganised
Why is this in the same script anyway
more organized*
You mean WAY more organized
lmao
I wanted to make it more organized
For that matter, why is this another class at all
Then you've done the opposite
ye sorry i type quick
putting more shit into one file makes it less organized
Putting it in its own file is more organized
Having multiple classes in one file is unorganized, and doesn't even work
you want more separate files with simple classes
SOLID!
You've thrown the laundry into the kitchen cupboard and called it organized. Just because you can't see it doesn't mean it's not still a mess
na because the way I see it is that my game very small so I just want to have the least amount of scripts as possible so I dont have to switch between them
You're functions are there but you have two MonoBehaviour classes in one file. That is the issue . . .
i only combine classes into one file if one class is like <50 Lines of code, and if it makes a lot of sense to combine them
That is the wrong way to see it. Period
but if thats makes it unirganised then ig I have a lot of organisation to do
Here's the million dollar question: Why is this even a different class at all
humour us and cut it up.. the bigger projects u make the more u'll end up trying to keep things seperate..
Literally why not just put the functions in the class you want them to be in
single responsibility
ok thanks for the help
np mate 🍀
well your preference is irrelevant to the fact that unity will not allow you to drag one file with separate monobehaviours, and separately pick one of the two monobehaviours, while accessing each
looked everywhere for a tutorial on how to create a super simple inventory system for my game, couldnt find anything. hoping someone can give me some pointers?
ive already got a system to add and remove objects into an array too.
You won't find a tutorial on a super simple inventory system because inventory systems are not simple
This is incorrect. Having two or three files as opposed to one will do nothing for your game . . .
unity links a file to at most one monobehaviour or scriptable object. If you want to drag and drop it around and keep it on a gameobject or asset file, they must be separate files.
Period
Guys, how do I always stop using the ammo and not the clip when the player tries to reload? The ammunition is only spent reloading the clip and the clip is only spent shooting, here is an example of the error https://hatebin.com/tirkcvzpum
!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.
srry
All good mate no need to be sorry
i’m on mobile, and that code is literally 3 screens of scrolling
That's very specific and would be hard-pressed to find. Maybe one of the tutorials would have that feature . . .
welp,this error is common and everybody knows how to solve it or is exclusive?
First off, horrible way to start coroutines...should avoid starting coroutines in update if you don't need to
For example
Here you can simply start coroutine for reload right under the line wherever your ammo count is being deducted by comparing if it's 0
i made that to make a clearer animation transition
No, you can get the rect's size in world coordinates it by calculating the difference between object's corners.
public Vector2 GetWorldSize(RectTransform rect)
{
Vector3[] panelCorners = new Vector3[4];
rect.GetWorldCorners(panelCorners);
return (panelCorners[2] - panelCorners[0]) / 2f;
}
why does any of that need to be converted to world space for that?
This is absolutely wild
or has this whole issue been because your "threshold" distance is in world space units for some reason
Hi im back after like 5 minutes because my code does not work again and yes now I have made a new script for loading all me levels is it okay if any of you guys help me. I will send a picture of my code right now
and that is not in world space . . .
are you in 2D with an overlay camera?
Yes, so you get it now, right?
The pivot cannot affect anything in world space. It affects just local space.
i get that you are completely ignoring everything that everyone is telling you so i am just going to block you so i don't need to see or deal with your nonsense anymore 🤷♂️
Give reference of the object that's holding levelselector script on your button
This is the definition of an XY problem
You are misundeeatanding a lot and trying to solve it incorrectly
do you even understand what the words "world space" mean? that is not the opposite of local space. world space is specifically the world coordinate system which is separate from Screen Space which is what your UI objects are in
wdym
so this whole fucking issue has just been you misrepresenting what you are trying to do, willfilly ignoring what literally everyone has told you, then expecting anyone to understand with vague explanations that are just using incorrect terminology that further confuses the point
world space = distance in meters.
screen space = distance in pixel.
canvas space = distance in resolution-invariant pixels
Which game object has the "levelselector" script on it?
Yes, do you understand that objects in screen space are affected by pivots and the transforms of their parents? This what makes it complicated to work with. Changing the pivot of the object can complitely mess up your script logic. That's the issue.
Drag and drop that gameobject on your button
Do you... know what a pivot actually is?
i have
Yes, I do
Show entire inspector of your "ui" gameobject
See, your localPosition is calculated from your pivot
So it's gonna be the middle of the object if your pivot is (.5, .5) and its bottom left corner if its (0, 0), which required you calculating the offset to receive the real middle of the object
This doesn't have levelselector on it, you lied to me :v
its on a panel and also forget about the other script its irrelevenet
Show that panel then
yes it does its claed scene levels
called
you understand that worldspace is in 3D, and canvas space is 2D?
I just wanna see there's an object with "levelselector" on it
I just changed the name of the class
Ohh
and going between world and canvas space requires additional information that you do not have in that function
You have to change the name of the class from inside too
Filename and classname should be same
No, just change the name of that class to SceneLevels now i guess
Or change the file name to LevelSelector
Whatever you like
Either is fine
pivot is neither in screen space, world space, or canvas space. Pivot is dimensionless
the file name must match the class name
ok ok
which only matters if you have multiple classes in the file
otherwise unity can figure out “it’s the only one there”
Even if you have only one class in the file, that class name has to match the file name
Going forward, this will no longer be necessary, but as of the current LTS, it's still a requirement
pretty sure not. source: I’ve gotten away with stupid shit before
It works thanks for the help man
you should adjust the file names to match regardless
If you're on the cutting edge release, it's not necessary, but there isn't an LTS version yet that dodges the requirement
That sounds dum, who died and approved that change
i thought the change was made in like 2022.2 so the filename requirement should be gone in the latest lts
eitherway, we can agree that it is bad form to have GrandmaScript.cs contain GrandpaBehaviour : MonoBehaviour
Pretty sure its 2023.x which hasn't gotten an LTS yet
I'm using 2022.3 it's still a requirement here
i’m pretty sure I have gotten away with changing my monobehaviour class name, without updating the filename
Probably doing it from inside visual studio with ctrl + r + r
It changes filename too
#1078093315435679784 message
changed in 2022.2
that's going to cause so much headache when everyone starts using it . . .
Ain't no way this becomes mainstream right?
Oh, huh. Neat. I thought I've had to deal with it this whole time but I've just been doing it out of habit
i do, and no it does not change filename too
you should do it out of habbit anyway
Huh weird, it changes for me
so you should only find out if you fuck up
i have been on mac tho
yeah there's really no need to not follow that convention, especially considering it's just a regular c# convention anyway. but at this point it's only convention and not a hard requirement anymore
Yeah, it's still a good idea to make the names match anyway
Ohh
Yeah, it just seemed like too big a change to be done in a minor revision so when I heard "You can now do this thing" I just automatically assumed it was a major version change
now people will have an issue with their Food class and send us a file named MomsSpaghetti . . .
I was in the process of installing 2022.2 to check, I didn't think of looking at the dev blitz days archive
that's where i'd first read about that change and I don't have any 2022 versions installed so I figured i could probably find the answer in there again
to be fair we don't typically see file names when people share code anyway so it's not a big deal 🤷♂️
Hi, short simple question. Does StopAllCoroutine stop all the coroutines in a script instance, or all coroutines on the gameobject the script is on?
it stops all the coroutines owned by that MonoBehaviour
all of the coroutines on the behaviour . . .
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopAllCoroutines.html
Same Monobehaviour
@young lava
i never actually use that method
me neither . . .
I almost exclusively keep a reference to the specific Coroutine, and turn it off manually
because I usually need to be able to know if the coroutine is running or not, to avoid running duplicates
I am probably going to do that tbh
it's much easier to track when you have a reference to it . . .
usually:
private Coroutine despawning;
…
if (despawning != null) StopCoroutine(despawning);
despawning = StartCoroutine(Despawn());
Despawn coroutine sets despawning = null at very end
or
if (despawning == null) despawning = StartCoroutine(Despawn());
otherwise you have no clue wtf is going on, and can start duplicates of the coroutine, or not start it etc
and every time you call StopCoroutine, you set it null
so it effectively tells you if it is running or not
The problem I am having is I have state/action manager script. In that script I have a coroutine that pretty much tells how long a particular action should be locked for after performing an action. And I am running StopAllCoroutines in another script and it seems to be effecting the coroutine in my state/action script. I have some debug statements that are printing the actionLock booleans and as soon as I execute the StopAllCoroutines, the boolean remains toggled on which leads me to think that it is somehow stopping the coroutine in my other script. I will attach my code below.
State/Action Coroutines:
for reference, my project has 38 calls for StartCoroutine, and zero StopAllCoroutines
don’t have a different script manage your coroutines
other script can call a method, and this class can manage its own coroutines
Code in charge of stopping coroutines. When I switch to the commented out code it works fine.
ok, do the pattern I showed above
kk
do you just have some wacky theme that does not highlight types and method calls or is your IDE unconfigured 🤔
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 will take a look at that
but lowkey I might still switch to manual like loup said thats better practice right?
yeah, it's probably going to work better to explicity stop the ones you want rather than using StopAll. but also how are you starting the coroutines? because if your StateMachine class is the one starting the coroutine then that is the one that owns that instance of the coroutine so that coroutine will stop when StopAllCoroutines is called on that MonoBehaviour
So pretty much I am calling stateMachine.SetAttackActionLockForDuration(randomNumber) in another monobehavior. specifically my script in charge of handling melee attacks. And the StopAll is being called in the same melee attack class which is the confusing part.
yes. not keeping a reference to the coroutine makes managing it extremely difficult
wait so you aren't even using StartCoroutine? or are you passing the returned object from that method call to StartCoroutine?
yeah so if that is the same class you are calling StopAllCoroutines on then this applies: #💻┃code-beginner message
Ohhh so even if the coroutine logic itself is located in playerController, since I am running StartCoroutine in the WeaponController script, if I call StopCoroutine in the weapon controller it will stop the "playerController" coroutine?
correct because that MonoBehaviour instance is what is running that instance of the coroutine
StopCoroutine lets you pick which coroutine specifically you want to stop
Thank you guys!
StopAllCoroutines applies to all coroutines on that one instance of that one class
Yep definitely going to switch to full manual control!
also some info on how to properly use StopCoroutine https://unity.huh.how/coroutines/stopcoroutine
I just started unity and this line of code gives me an error: if (LeftAction.isPressed())
you won’t need the action locked bool either anymore
what is the error
whys that?
you should properly send us a pic of the error. that may help . . .
that code tells us nothing by itself . . .
private void OnCollisionEnter(Collision collision)
{
GameObject enemyObject = collision.gameObject;
// UnitCombat unitStats = enemyObject.GetComponent<UnitCombat>();
bool disableDamage = false;
print(gameObject);
GameObject rootObject = gameObject.transform.parent.gameObject;
rootObject.GetComponent<UnitBehaviour>().getUnitType();
/* if (health <= 0)
{
Debug.LogWarning(gameObject + "OBJECT DEAD");
disableDamage = true;
}
if (_unitType == UnitBehaviour.unitTypes.Dummy)
{
print("OW! Took " + unitStats.damage + " damage from " + enemyObject);
}
else if (_unitType == UnitBehaviour.unitTypes.Melee)
{
print("Applying damage");
unitStats.health -= damage;
print("Applied damage: " + damage);
}*/
}
Why is this printing the name of the collision object, instead of the object that is the parent of this script? It should be printing the name of the object that is the parent of this script, pretty sure that's gameObject functionality. I can't decide if this is a glitch, or if for some reason Unity made the functionality of gameObject different inside of OnCollisionEnter vs outside of OnCollisionEnter, or I've made a very obvious oversight
correct. there is no isPressed method on the InputAction class
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.InputAction.html#methods
it's telling you that the isPressed method does not exist for the type InputAction. also, you should have a red squiggly error line in your !ide. if not, make sure to configure it . . .
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
Ok, recording this with recorder, the jitter is even worse than it was before. I've decoupled the camera object from the camera rig and tried to have it match an object's pos/rot. But there's a jitter. The player offsets a consistent distance. I have a feeling it could be because the camera might be a frame behind.
Anyone encounter something like this?
yeah this is likely due to updating the camera at a different rate or before the object during the frame
Could it be because the character is using a rigidbody to move?
possibly. you've not shown any info about how you update the camera's position or at what rate/part of the frame
because if the coroutine sets its own Coroutine to null, then you know if it is running or not based on whether that variable is null
public class ActorCamera : MonoBehaviour {
public ActorBase user;
public void LateUpdate () {
transform.position = user.transform.position;
transform.eulerAngles = new Vector3(user.lookAngle.x,user.transform.eulerAngles.y,0);
MainCamera.singleton.UpdatePos();
}
}```
Here's the script that operates the Camera Rig.
ahhh ic tyty!
public class MainCamera : MonoBehaviour
{
public static MainCamera singleton;
public Transform targetObject;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
MainCamera.singleton = this;
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
public void UpdatePos()
{
rb.position = targetObject.position;
rb.rotation = targetObject.rotation;
}
}
And the main camera itself.
I have a hunch. Maybe I need to add a rigidbody to the camera rig too and have the rig script operate that instead.
oh god no, don't do that
my suggestion would be to use Cinemachine
and you probably want interpolation enabled on the rigidbody if it isn't already
On the player rigidbody?
Is it bad that I'm plugging in the movement values to the rigidbody velocity directly?
Sorry for responding late but then how do I apply the UnFreezeAnimation to my code with the reload? In this example it works fine but it reloads instantly and I don't want that but for it to run an animation that plays after 0.25 seconds or so and then reloads when it runs, but if I apply it I get the usual error of consuming my bullets. ammo after reloading if (currentClipAmmo <= 0 && currentAmmo > 0) { Reload(); }
i was thinking like this but still with the same error public IEnumerator UnFreezeAnim() { isReloading = true; yield return new WaitForSeconds(0.5f); gunAnimator.speed = 1; yield return new WaitForSeconds(0.3f); Reload(); }
unfreeze animation is an anim which resume an animation state
when the ammo clip is below or same as 0 the animation plays
and get freeze until the ammo is more than 0
to that ammo the clip is refilled and then unfreeze the animation
i cannot shoot
now i applied the if (currentClipAmmo <= 0 && currentAmmo > 0) { StartCoroutine(UnFreezeAnim()); }
instead of the reload one
Does anyone have a solution to unsubscribe all interactions from an Action in the unity new input system?
You could just disable the action
how does one handle stairs and steps on a rigidbody movement system
i tried looking online but couldnt find anything
only videos about character controller
You’d have to make a collider that has a ramp instead of the stairs/step. other approaches are hacks or would be using a kinematic approach. If you care to see a good example for handling it kinematically, checkout the (free) kinematic character controller asset
i saw a way where a person does it by finding contact points
might try that
and then calculating if the contact point is higher than x amount from the bottom of the player
Yes, but that’s custom physics, aka the kinematic way
whatever you do, in some way, you are converting the steps to a ramp
question is just which abstraction for that you use
Can anybody follow up on this?
In itself no its not bad, maybe clamp the values to -1 - 1 but I cant think of any bad sideeffects
can someon help me i dont now what this is
There may be some wonky physics Interactions but you will have to finetune any movement method eventually
You did not set the variable
what was that again ?
The variable groundCheck of PlayerController has not been assigned. You probably need to assign the groundCheck variable of the PlayerController script in the inspector
{
if (beginFunction)
{
if (timeLeft > Time.deltaTime)
{
gameObject.GetComponent<SpriteRenderer>().color = Color.Lerp(gameObject.GetComponent<SpriteRenderer>().color, colorToChangeTo, Time.deltaTime / timeLeft );
timeLeft -= Time.deltaTime;
}
}
}
I have a sprite that I'm trying to transition smoothly from 255 opacity to 20 when the player triggers a collider, but I'm struggling on how to make it slowly change to that over say a second, rather than immediately. When I look it up, I see a lot of use of the Lerp function, and I think I kind of understand how it works conceptually, but in practice this isn't working. I've set timeleft to 1f. nothing is happening, though. im sure I'm missing something easy, but i could be wrong. can someone help?
First off you should definitely cache a reference to SpriteRenderer. GetComponent is slow and you're using it twice per frame
i´m still a beginner and have no idea what that all is
Second, Color uses values between 0-1, not 0-255. All opacity values over 1 are fully opaque
Do you know what an inspector is
Half the convos in this channel:
Q: I don’t understand this error message.
A: it literally tells you what to do. You assign a value to the reference.
Q: what’s a reference?
A: it’s a value that refers to an object in your game and can be assigned to a variable.
Q: what’s a variable?
A: it’s a thing in C# whose value can change at runtime.
Q: what’s C#?
A: it’s Unity’s scripting language.
Q: what’s that, I’m new.
oh, right. thank you, I'm very rusty
yes
Okay, every other noun in that error message is something you made so if you know what an inspector is you should be fully capable of following what it's saying
yes i just dont know what groundcheck is
If only people were that upfront about which things they don't understand in the explanations. Usually it's just "wdym" for hours
You made it
It's a variable you put in your script
i have a python script that fills a json file with data, how do i execute the python file and wait until the python file finishes the execution?
but groundcheck is nowhere there
How are you intending to run a python script at all
Really? Show your PlayerController script
ok, I've cached the reference to the spriterenderer and changed the alpha values into floats between 0-1, but it's still not working.
{
if (beginFunction)
{
if (timeLeft > Time.deltaTime)
{
spriteRenderer.color = Color.Lerp(spriteRenderer.color, colorToChangeTo, Time.deltaTime / timeLeft );
timeLeft -= Time.deltaTime;
}
}
}
Is the issue with the timeleft being 1? I don't know why it's set like that, but it seemed to be a common trend.
theres an api
public class player : MonoBehaviour
{
public float speed = 5;
private Rigidbody rb;
public float jumph = 5;
// Start is called before the first frame update
void Start()
{
Rigidbody2D rigidbody2D1 = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float richtung = Input.GetAxis("Horizontal");
transform.Translate(Vector2.right * speed * richtung * Time.deltaTime);
if(Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector2.up * jumph, (ForceMode) ForceMode2D.Impulse);
}
}
}
no groundcheck
i can easily run the file
I don't know why you're showing me this
I asked for PlayerController
thats not PlayerController script anyway
Also, !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.
im so confused
https://docs.unity3d.com/Packages/com.unity.scripting.python@2.0/manual/inProcessAPI.html
Huh, that's new. I didn't know that was a supported thing. I'm not sure if there's a way to wait for it
the error u shown is not about the script u just pasted
those are different scripts..
Your error is mentioning the PlayerController script. Show it.
oh, i guess i just have to add something to the JSOn that c# reads
Yeah, I don't see anything about using it asynchronously or getting back a status. I think you'll just have to keep trying the data until it ends up with all the stuff you need it to have
wait a minute.. so i can run python scripts now using my unity editor 👀
Can’t learn if you don’t ask good questions…
Yeah, looks like it's meant for editor scripting
Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.transform.position, 0.2f);
isGrounded = colliders.Length > 1;
}
Don't think you can run it in-game
this ?
That is a line that contains groundCheck
But where are you setting it
thats crazy... yea thats fine.. really cool to know tho..
I don't understand what I am doing wrong in this script, I am trying to apply a custom acceleration speed to the player with a rigidbody, but currently the player isnt moving at all. Here is my movement code: ```cs
void FixedUpdate()
{
Move();
}
void Move()
{
Vector3 velocity = rb.velocity;
Vector3 desiredVelocity = new Vector3(moveInput.x, 0, moveInput.y) * speed;
float maxSpeedChange = maxAcceleration * Time.fixedDeltaTime;
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);
rb.velocity = transform.TransformDirection(velocity * Time.fixedDeltaTime);
}```
general_grievous_adding_lightsaber.gif this API will make a fine addition to my collection
CheckGround(); this?
This code is still not working when I set the bool to true. I think it's due to my misunderstanding of what timeleft is- my understanding that it was possibly the framerate? but either way it's not doing anything
Log velocity after you set the Z, see if this code is running and what value it's running with
is something like this colorToChangeTo = new Color(spriteRenderer.color.r, spriteRenderer.color.g, spriteRenderer.color.b, 0.02f) valid code?
You've got quite a few if statements there. Is this line of code running at all?
let me see, it ought to
very interesting code tbh
yes
at my state of knowledge id have to take time to debug that to even know how it functions
ur subtracting the time between frames from timeleft.. until timeleft is less than the time between frames?
{
if (beginFunction)
{
Debug.Log("1");
if (timeLeft > Time.deltaTime)
{
Debug.Log("2");
spriteRenderer.color = Color.Lerp(spriteRenderer.color, colorToChangeTo, Time.deltaTime / timeLeft );
timeLeft -= Time.deltaTime;
}
}
}
both log statements are hit
🤔
Its printing all zeros, for some reason the velocity variable isnt changing at all.
do ur inputs work?
😭 that's probably it. I'm not sure what it ought to be
If both log statements are happening then that line is running. Instead of logging "2" try logging some useful infromation: Debug.Log($"Changing {Time.deltatime / timeLeft} percent of the way towards {colortoChangeto}");
one moment
ohh its just a basic percentage counter
If it's printing all zeros then the velocity is all zeros.
That would explain why it's not moving
I know, I don't know why, because the code is supposed to increase the velocity.
Yes, I just checked
ok thats the only thing i got sorry
looks like it stops at .68 for some reason
the alpha component hasn't changed at all, though
Should i be using color32
i have a script attached to a prefab and this script has an id associated with it, if i grab the script/id (as the prefab reference itself, not the instantiated prefab) will it cause any problems?
im not manipulating the prefab, just need to read some data from it
wait, when I trigger it again, it stopps at .93
either way the opacity is not changing.
if ur only reading i'd say why would it?
but u know my skill - level so take that as u will
was scared some things might not get initialized or something but makes sense there wouldnt be a problem tbh
just had to double confirm, thanks!
Is this even the right approach to try to change a spriterenderer's opacity smoothly
ya.. from what im reading it says make sure NOT to modify it
im sure there's gotta be an easier way
yeah treating it as a read-only source as a prefab
i use color32
its easier for me to visualize
im familiar with 0-255 not so much 0-1
if (timeLeft > 0) what happens if u use this conditional instead.. so it'll lerp until time is fully exhausted
instead of stopping once its lower than the framerate
let me try that. I'm going to switch to color32 since it works better in my brain too
👍 make those two changes and see if some magic doesnt happen lol
Oh, I know why its wont move now, its changing velocity by an acceleration of 1 * Time.fixedDeltaTime
wait. im not sure if u can use Color.Lerp for Color32s
So increasing the acceleration fixed it.
u making a snail simulator?
😈 lol
I made some changes and now it works. thank you. thank you also digiholic
nice! good job
ah wait- it doesn't reach the desired amount at the end of the timer, but i need that to happen
even with the > 0 conditional?
When the timer ends, set the color directly to your target color. A wrong-lerp smoothing never actually reaches the target
you have to do that manually
ah ok I see, thank you
& ohh thats true..
anyone that knows how to check for "any key" pressed with the new input system? (from any type of device)
if (Keyboard.current.anyKey.isPressed)
{
}```
lol.. nah not really
ahh u ninja edited, now my joke doesnt work
it's a bit too choppy, still, it goes from ~150 or around that to abruptly changing to 255. Should I change the final argument in lerp to something else? Is time.deltatime/timewait the culprit?
Probably. I'm not entirely sure what that's supposed to be doing
As that number approaches 1, your color approaches the target
I'll try some floats it is still clear i am not sure how to handle the last bit
this thread looks like it may have a way to detect if any of ur controls u set up in the action map have been pushed
not really what i was searching, but thank you anyway
ya, i didnt see hardly anything from my different few google searches sorry
has to be possible tho.. b/c thats the purpose of the new input system.. scaleability
yes probably, you can see the new Input System is still very young
yo, why wouldnt that work?
if u have all ur different inputs under different action maps u can just run multiple of those conditionals.. checking all the action maps u have set up
{
//doo thang
}else if (inputActions.actionMap.GamepadScheme.WasPressedThisFrame())
{
//doo thang
}else if (inputActions.actionMap.TouchpadScheme.WasPressedThisFrame())
{
//doo thang
} ```
idk, i promised i'd start using it and i havent yet :d
kinda more difficult to use then the old, it's less intuitive
i like the old too, but so far ive only made keyboard input games
kinda a restriction at this point in time
I really hope that works, otherwise I'm gonna need to write a lot of lines of code
I am experiencing an issue, the accelerationMultiplier is changing the entire speed instead of how fast the player accelerates in the desired direction, so lowering the accelerationMultiplier is just lowering the speed. Here is my movement code currently: ```cs
void FixedUpdate()
{
Move();
}
void Move()
{
Vector3 velocity = rb.velocity;
Vector3 desiredVelocity = new Vector3(moveInput.x, 0, moveInput.y) * speed;
float maxSpeedChange = speed * accelerationMultiplier;
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);
rb.velocity = transform.TransformDirection(velocity * Time.fixedDeltaTime);
}```
😄 i can already picture it
lol
you need to calculate ur aceleration seperately
and then add it to the velocity
yea, i cant do the math off the top of my head.. but ya i think u need to calculate the accel seperately.. add it to the velocity.. and then 👇
but then ur gonna need to clamp ur velocity afterwards so it doesnt exceeed ur maxSpeed
acceleration should be a vector and be clamped properly... with this code you'll accelerate faster if you move diagonally, no? (or maybe I'm just sleepy)
the ole.. normalization?
is that not a side- product of TransformDirection? probably not lol
why you need to do transform direction I'm also not sure...
I can come up with an explanation but... code very borked and not quite sensible (sorry)
iono, maybe he came across the issue where his velocity/direction is locked to world space
when he wants it local space (we cant see his rotation code)
That is exactly why I am using it
This is my rotation code cs Vector3 projectedCamForward = Vector3.ProjectOnPlane(Camera.main.transform.forward, Vector3.up); transform.rotation = Quaternion.LookRotation(projectedCamForward);
ya, i guessed b/c thats the only time i ever use it 😄
so... you need to TrnsformDirection the input... then convert it to acceleration (multiply by acceleration mp and deltaTime I guess)... then add to rb.velocity... and then clamp the rb velocity
~~ // make acceleration calc
float accelerationX = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange) - velocity.x;
float accelerationZ = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange) - velocity.z;
// apply to vel
velocity.x += accelerationX;
velocity.z += accelerationZ;
// clamp
velocity = Vector3.ClampMagnitude(velocity, maxSpeed);~~ nvm then
i think this would work
it will accelerate faster diagonally
maybe it's a feature! 😛
maybe he does it in input 
wdym?
unless u normalize ur vectors ur gonna travel faster diagonally than u do forward or lateral
that doesn't matter
This code currently doesnt fix the problem, as the acceleration is still not functioning as acceleration, instead it is setting the speed to whatever the maxSpeedChange variable is.
i made a graph as to why the normalization is needed
u can see right is 1, up is 1.. but if u add them.. ur at (c)
which is longer than the other two..
normalizing puts it at the orange dot... so every direction is equal
hmmm, it was a long shot. as i was typing it out in notepad w/o my editor 😦
!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.
translation doesn't respect physics
its basically teleporting.. so theres times when it'll teleport too far on a given frame.. and clip into walls and stuff.. (then it just gets yeeted out the other side)
if u want accurate physics.. u need to use a rigidbody to move it
and rigidbody functions..
and be prepared to be spending a lot of time on it
or if its a simple enough game.. u can set up boundaries. (like if its position is less than this X) allow it to move..
how?
if its over that position only let it move the opposite direction.. (but thats gets nasty)
its pretty involved, id suggest u look up a tutorial on how to move rigidbody's in unity
you can use functions like rigidbodyReference.AddForce() but the way ur already calculating speeds and stuff u could manualy set the velocity of a rigidbody..
rigidbodyReference.velocity =
just would require a bit of tweaking to ur setup to add the components u need
boom rigidbody 101
Hi, i have a string that has a public getter but private setter. how do i actually set it lol?
public string mainAbilityName { get; private set; }
mainAbilityName = "Name";
that dont work lol
that absolutely would work inside a method in that class
It is simply private. It works the same as any private variable/method
It can be set from within the same class, but not from outside
so it needs to be in a method?
you cannot just have random statements floating around in the class
what if i dont want it to be in a method, but i still want it to be privatly set, publicly get
you can initialize it with a value by appending the assignment to the end of the declaration like public string Name { get; private set; } = "Name";
otherwise you have to assign it in a method
also note that will not work for properties declared in structs
btw how to u do that code tag in discord
!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.
Hello! Is it possible to bake lighting during runtime? If I have a map generated randomly and it never changes, bake the lights before the game starts?
I have been experimenting with brackeys 3d character controller, and it doesnt have drag and momentum, I kind of want to code it using character controller because I want to avoid problems involving rigid bodies, would that be possible? but everytime i try to add velocity or easing speed, it doesnt apply it, as if it is only moving the vector 3 of the object and moving it around the map, and no physics thingy
it is using a quaternion thingy, but i dont know how to hook that or integrate it so i could make easing speed up or speed down on keydown or keyup
It is like I know how the code should look like (but i could still be wrong) but I cant put it into code 
The CC requires you to pass in a velocity for the frame. How you calculate that velocity is entirely up to you.
You can do whatever you want, speed it up, slow it down, change directions.
would easing speed up and down also work? if i stopped pressing w, it would slide easingly after
You can do whatever you want
could you give me a hint on how it could work, I want to figure it out on myself as well, I am confused, but I have a feeling Mouse look has influence over the movement in character controller? where should I look in the code to start adding easing speed up and down?
if ok 
okok, also, this was in mouse look, is it ok to copy the code and add it in character controller? it is a diff script, or can i import it easily?
Again, you can do whatever you want
Unfortunately that means you can do whatever you want
How do Displays work? Im currently using a camera to focus on a small region of the screen and put it on display 2. I don't actually want the user to see this display, Im just using it to take screen captures. Im not fully sure I understand how it works, Im reading that someone with multiple monitors would be able to see it, is this right?
just render the camera to a render texture instead of a display
If I set a render texture will it not go to a display?
Sicne there isnt a none option
how do i know if a number between -1 to 1 is closer to -1 or 1?
if n > 0 its closer to 1 if n < 0 then its closer to -1
if n == 0 its neither
okay but
this worked before when i did .GetAxis, but now i have the raw input from a joystick instead
raw input from joystick is likely analog float, so youll get like 0.93564
getaxis is digital, 1 or -1 or 0
what if the joystick is less than half pressed to a direction
then it rounds to 0
yes that is why i'd rather have it always return -1 or 1 when theres an input
so then check if its above or below 0
above 0 means 1
below 0 means -1
and if its 0 then theres no input
i feel like there probably is some math function to do all this inside the if statement. maybe
but this pretty much does it
you dont need the roundtoint there
oh forgot that one
just use Mathf.Sign
that.. also works
you'd have to check for 0 though since unity's Mathf.Sign returns 1 for 0
I'm having difficulty with movement code again, I still can't get it perfect
it has this weird property where what I think is happening is, when you turn you slow down
and so then when you stop turning, you immediately go back to full speed
which FEELS glitchy
I thought it was like framerate weirdness for the longest time
but I think it's because when I turn, it adds some new velocity in a different direction, rather than like "turning" the vector idk
the code I have right now is pretty simple in theory, it takes player input and adds a vector to the player's velocity based on that, then adds a friction vector that's opposite to the current velocity
Can we see it
the code?
Yeah
If its slowing down then I'd guess something in the friction vector is doing it
but I cant say until I see
// The desired velocity (input with length of acceleration)
Vector3 wishVec = inputVector * groundAcceleration * moveForce;
// Draw velocity
Debug.DrawRay(transform.position, playerVelocity * 2, Color.yellow);
// Friction factor modifies friction based on stuff like sliding
//float additionalFriction = playerVelocity.magnitude / 10f;
additionalFriction = 0f;
playerVelocity += wishVec * 0.01f;
// Friction
Vector3 fric;
fric = playerVelocity * (friction + additionalFriction);
playerVelocity += fric * 0.01f;
controller.Move(playerVelocity * Time.deltaTime);```
this is basically the whole thing minus the mouse code and jumping
inputVector is just WASD but it's localized to where the player is looking
If you were holding two keys at the same time, would there be 2x the velocity which would lead to a higher friction?
I don't know how youve gotten your 0.01 multiplier when adding the friction, but maybe theres a point at which the friction increases faster than the velocity so you actually have a higher resistive motion (friction) when you go faster (turning)
I don't think the keys add together, I normalize the input vector
as for the 0.01 I think my project is weirdy small or something
the smallest increment I can move things with the gizmo arrows seems a bit big idk
Probably a Screen vs World issue
im not sure why the friction would go faster since it's just a proportion of the velocity
also this seems to happen specifically when im holding W and one of the strafe keys
and then turning the mouse to do kind of a sharp turn
I actually tried it in DUSK and surprisingly it seems to work like that there too, but it's less jarring there and I'm not sure why
So its doing the opposite of what strafing usually does and slows you down xd
So when you don't move the mouse, it doesn't slow down?
I mean it does in the sense that im changing direction
I wonder if it's less noticible in DUSK because its acceleration is a bit slower
I mean it makes sense intuitively
I'm turning into a new vector that's not pointing in the same direction as the old, of course it's gonna slow down a bit
im just not sure why the acceleration once I stop moving the mouse feels so harsh
What is better for performance on a space game:
- Create a gigantic repeatedly tiled sprite background
- Constantly compute the offset and have the sprite move with the player
(2D space game)
can someone help me fix the text cause it looks very weird and im not sure how to fix it brbrbr
is there a 'getkeydown' feature for the new input system? im having trouble finding the right implementation for only allowing a single jump, and pressing the escape key for a pause menu
This is a script I found online for a realisitic car controller, I've been reading through it to understand how it all works, but, I can't figure out how the hell its getting input from the keyboard to know what to make the car do. They did say they use the old input system, but I'm unsure what that is or what to look for in that case
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It should be Input.GetKeyDown(); isn't it, or is that the old system
thats old news
Ah, interesting, what the hell is the new system then
whatever is getting input is in a different class
this is a really new question but how would i connect a scene to another scene?
like if i wanted a player in a certain area of a attack to go to a seperate scene
would i just trigger a scene if player in area?
srry english not very good
The entire download to this is linked in the description of this video, I have looked over all his code and can't seem to find it. I'd love some help, as I'm wanting to play with the settings to see how I can improve the handling.
Free Car Controller / Vehicle Physics Project for Unity With Vehicle Damage.
Mobile Coming Soon.....
A free car controller fo...
i tried using waspressedthisframe but that only changes a bool to true once and keeps it like htat. i need something that checks every frame if the esc key (or whatever input is routed there) to pop up a pause menu, and press again to close. Atm my code only reads the value as a button, so if i hold the button down, or not tap super quick, the UI flashes off and on really fast
yeah i'm not downloading that
you'd have to show your code to determine what you are doing wrong
can you do the ! code thingy? paste.ofcode has error 1033 on it
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you literally could have done it there lmao
ohh lol its just cod ehahaha
does someone know how to fix this?
what was that one i could do tabs with
you can also see that in #854851968446365696
A tool for sharing your source code with the world!
you should probably explain what you think is wrong instead of assuming others will read your mind to know
in other words you should think outside the box, friend ;D
i want only my speed to show but it seems like the text also shows how it decreases to zero and im not sure how to fix that, i just want it to display the walk speed or sprint speed etc
and where are you checking the input? also you should really rename that Ctx variable, it is not clear from the name alone what it is or what it is used for
it references the statemachine script
show your code
im probably not gonna change that part bc its too much to change lol. i understand it so far and dont want to screw up the toothpicks holding up this establishment haha
its just a TextMeshPRoUGUI
https://paste.mod.gg/wwnfdpfxymeg/1 part of my state machine
A tool for sharing your source code with the world!
well that's certainly not very helpful. but of course if you just show the magnitude of flatVel then you'll just see the magnitude of that in the text
you could do two if statements consisting of if magnitude reaches a certain threshold it will display this text, and then vise versa for the other speed @cinder crag
most likely they have two variables that they just want to choose from. of course they decided to only show that single line instead of all of the relevant code
or you could... build a statemachine ;3 wink wink
Whats up J-bear?
if (Keyboard.current.escapeKey.wasPressedThisFrame) <- this is a workaround. Id rather the keybinds be 'bindable' by the player later on in the game. but this is okay for now since i only need one or two
I see you typing BOY
Keybdings be bindable? Do you mean its supposed to be able to change to a different key later in the game?
yes
I mean being able to change what keys trigger the actions should be its own class
So ur other scripts shouldnt really care what key is being pressed. They should only key care about the Input Action itself being raised / Triggered
I remember you saying as well that ur jump wasnt working. Were you able to figure it out?
Quick question, what's going on here?
you need to yield return in a coroutine
if you have no need to yield then you do not need a coroutine
I guess that's fair enough
guys how i do for move the slide of the gun because i tried this but doesnt works slide.transform.position = new Vector3(slide.transform.position.x, slide.transform.position.y, slide.transform.position.z - 1);
It's because IEnumerator is the return type of the method. You know, if you declare a method with return type, you need to return something.
IEnumerator is a bit special in that instead of return, you need to yield return.
It should work. If you don't see any changes, then something else myst be resetting the position.
Or slide is not the object you expect to move.
how is this possible? And what is the solution
void OnCollisionEnter2D(Collision2D coll)
{
currentdirection = Vector2.Reflect(rb.velocity, coll.contacts[0].normal);
}
I assume not but does anyone know if Physics.IgnoreCollision works on prefab assets when you instansiate them
Hmm... That would imply that there are no contacts(the array has 0 Length). Log the contacts Length
oh havent thought of using the length
dunno what causing onEnter to not catch who touched it though
is this common?
No. Doesn't sound normal
Just to be sure, can you also use GetContacts and see what it returns?
lemme see
You need to allocate an array and pass it in.
I dont understand what is wrong with this
void Update()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
FireRayCast();
}
}
public void FireRayCast()
{
// Perform the raycast and store information about the hit
if (Physics.Raycast(ray, hit.transform.position, raycastDistance, layerMask))
{
// Check if the hit object has a Rigidbody component
Rigidbody rb = hit.collider.GetComponent<Rigidbody>();
if (rb)
{
// Calculate the force vector from the hit point to the object's center of mass
Vector3 forceDirection = rb.position - hit.point;
// Apply the force to the Rigidbody
rb.AddForce(forceDirection.normalized * explosionForce, ForceMode.Impulse);
}
}
}
Which line is line 26?
Should have pointed that out lol
if (Physics.Raycast(ray, hit.transform.position, raycastDistance, layerMask))
Also for 18 as well
FireRayCast();
what is hit and where do you assign it
Also i see we are good friends with GPT
Hit is RaycastHit hit
maybe :I
and where do you assign to it? because just declaring it does not give it valid RaycastHit with a non-null transform property
Where do you assign it
hint: you shouldn't be using hit at all for determining where the Raycast is at. you should be assigning it using the raycast
void OnCollisionEnter2D(Collision2D coll)
{
ContactPoint2D[] contacts = new ContactPoint2D[10];
var c = coll.GetContacts(contacts);
Debug.Log($"{c}");
foreach(var item in contacts)
{
Debug.Log(item.otherCollider.transform);
}```this fine for testing?
was this code AI generated?
Most of it no, Im just new to it so Im reading docs and using AI
by assign do you mean what lines its being used on?
yeah fuck outta here with your AI generated code. it is against the rules to ask for help with AI generated code #📖┃code-of-conduct
mb
no, i mean assign to it. if you do not know what assigning something is then you should stop what you are doing and instead go through some basic c# courses like the ones pinned in this channel
@teal viper im catching nres here(in the logs) and cant null-check, how to properly use it?
I think a contact is a value type, you don't need to make a null check.
oh maybe just the othercoll is catching the nre
To make it reliable, change that to a for loop and only iterate up to the returned length
Yeah, probably
Really, you only need to debug the length of the contacts array
though, the fact that other collider is null might be giving some clues
If it's an uninitialized contact point, then obviously it wouldn't have a reference to the other collider
weird...🤔
in update: if (!outOfAmmo && currentClipAmmo <= 0 && currentAmmo > 0) { slide.transform.position = new Vector3(slide.transform.position.x, slide.transform.position.y, slide.transform.position.z - 1); StartCoroutine(MoveBackToOriginalPosition()); } the other method: ``` IEnumerator MoveBackToOriginalPosition()
{
yield return new WaitForSeconds(0.5f);
float elapsedTime = 0f;
float duration = 0.5f;
Vector3 currentPos = slide.transform.localPosition;
while (elapsedTime < duration)
{
slide.transform.localPosition = Vector3.Lerp(currentPos, originalPosition, elapsedTime / duration);
elapsedTime += Time.deltaTime;
yield return null;
}
slide.transform.localPosition = originalPosition;
Reload();
}```
I don't think that matters, as that only checks how often collision should be checked, and oncollisionenter is called if it detected a collision only
I don't think that's related.
@queen adder just in case can you manually spawn 1 skeleton, and drag it with your mouse to collide with your player? See what gives the error?
Weirdly, I find discussions about the issue back from unity 5. And no single official reply.
but yea, i noticed it only occurs when the player is being swarmed
Maybe it's just a bug that went under their radar for a long time..?
Might be worth filling a bug report.
when many things push the object, the first thing that touched it lost reference
Ah, but you're using a legacy version...
It could be fixed in the supported versions I guess
You are using 2017 editor might be older issue, maybe upgrade it to latest LTS versions?
i love you ❤️
!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.
Does that mean that your issue is solved?
No dummy, that was just simply a late valentines confession

Hello
I want to make a code, that allows the player to press space if he stays in zone.
But for some reason trigger works only if I spam the Key, which is Space
I made an empty GameObject that refferences as the zone
And a Player with box collider and rigidbody
public void OnTriggerStay(Collider other)
{
if (Input.GetKeyDown(KeyCode.Space))
{
pressSpace = true;
StartCoroutine(spawnManager.SpawnBubbleFish());
}
}
Sometimes when I launch the game it works properly
But sometimes it requires spam
` not '
Don't know how often the ontriggerstay is called, but you would normally just use a bool to check if you are in zone or not
And in update do "if(inzone) -> allow key to be pressed"
Like
ontriggerenter inzone = true
Ontriggerexit inzone= false
In update
If(inzone)
{
If(onkeydown)
{
}
}
Okay, that worked!
Thanks.
But how can I make inzone = false, when I leave the zone?
Ontriggerexit
Yup, works perfect, just how I wanted it to.
Thank a lot
What i suggested above was remove ontriggerstay and replace it with
Ontriggerenter and ontriggerexit
Hope you used ontriggerenter lol
Nope,help me
In that case, comment out all the other places that change the object's position and see if it works.
Welp yeah,the IEnumerator MoveBack is executed (or well,the reload method)
But not the translate xd
I don't see "translate" method being used anywhere
^ I was wrong, it's
Im Curious why this Problem happens. Im Doing Unity Learn and im at Essentials of Real Time Audio.
Downloaded the Foundations of Audio Pack , did an URP 3D Template and imported it. Game Scene Looks Good.
So every time i press play i just fall through the ground .
Tried adding a cube as ground with Y at like -0.1 but still i flot through the ground... what am i doing wrong ?
All i literally did was Import -> Open and Press Play
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController: MonoBehaviour
{
private CharacterController controller;
private Vector3 direction;
public float forwardSpeed;
private int desiredLane = 1;//0: left 1:middle 2:right
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)
{
direction.y = -1;
}
if(Input.GetKeyDown(KeyCode.UpArrow))
{
Jump();
}else
{
direction.y += Gravity * Time.deltaTime;
}
//Gather the inputs on which lane we should be
if(Input.GetKeyDown(KeyCode.RightArrow))
{
desiredLane++;
if(desiredLane==3)
desiredLane =2;
}
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
desiredLane--;
if(desiredLane==-1)
desiredLane =0;
}
//Calculate where we should be in future
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;
}
transform.position = Vector3.Lerp(transform.position,targetPosition,80*Time.deltaTime);
}
private void FixedUpdate()
{
controller.Move(direction * Time.fixedDeltaTime);
}
private void Jump()
{
direction.y = jumpForce;
}
}
See the code @keen dew
Post the !code correctly 👇 and stop pinging me, if anyone can help they'll do so
📃 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 your player have collider?
yes
well i gave him 1 now on the basic settings but then youre spawning on the roof and cant get into the premade pack scene , Y Pos of it is at 0.144 if i change to 0.143 he drops through the ground , everything higher im just spawning on the roof... something wrong with the premade unity pack...
@abstract marlin are u talking to me
i answerd on sexyyounggod , so no
I mean its a Premade Unity Learn Pack why do i even have to make twerks to it ...
Tbh I don't even know what the scene is looking like or what player is doing and what components does it have , can you show video?
Which Program is used here to record videos ? only posted code and pictures , never did videos
I guess it's fine, just show screenshot of your player hierarchy?
I Also did Read some comments about the pack especially at the testing part of unity learn from that , others had blurry images etc , but no one was just dropping through the scene
when i press start i can say byebye to the gamescene from below 😄
I meant inspector aaaaa my bad, show the inspector of your player lol
the "Controller" is absolutely basic at the opening of the pack , but it doesnt say anywhere that u have to mod it...
There has to be some rigidbody in it...it wouldn't fall for no reason
See the child
oh i didnt looked at the childs , gimme a sec
for best practice, which part of the fbx should I rotate, the mesh or the name? (like say it is Chair, and underneath it is Chairfbx, which one should i rotate and scale?
the last picture are the missing settings of the player that didnt fit into the first pic anymore
Probably none? Don't we use the mesh provided from fbx and use it in mesh renderers?
I dont know what that is
the mesh was 100 times larger than it should be and is rotated
Ok so your first person controller handles gravity logic for you. And it's "ground" layer is set to "default"
What layer are your floor colliders set at?
No clue then, but again this is coding channel and this has nothing to do with code.. try asking in #🔀┃art-asset-workflow
you mean this one ?
ah, okok
I forgot
Is that the only collider stopping your fall?....
There's no other collider for floor?
carpet itself looks like this , when i select floor i get second picture
i dont know where else i should look for it , i mean every tutorial was premade and nothing to twerk , why do i even have to manage this as a beginner just using a tutorial course of unity ?
Ok so looks like the colliders in the scene aren't set properly to the size of renderers,
Since you're just trying out the scene try adding a large ground-esque box collider in the scene and make sure the layer of it is set to default
did this cube , is that what u meant ?
gave z a 0.001 and turned off mesh renderer , still falling down
ill come back to this tutorial , maybe someday someone updates the download version so it works again , ill just go through an audio video of unity on yt, thanks anyways!
i would have loved to go through that but if its bugged in the 2021 version ill just miss out of the experience 😄
{```
am trying to make a notes inventory but i and into this and kinda have no clue whats wrong
public void Methdo(int a,b)
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position,Camera.main.transform.forward, out hit, 2, interactableLayermask))
{
Debug.Log(hit.collider.name);
}
}```
when i do raycast, it does not detect fbx that have interactable mask, but works with cubes or spheres
why does it do that 
it works fine with the cubes inside unity, so I tried making my model, but it doesnt seem to log
ah, I needed to add a box collider

Solved?
no
what type do you want selectedSlot to be?
both cause this is the ui slector script
public void OnSlotSelected(ItemSlot NoteSlot , ItemSlot selectedSlot) {
try this
Why do you need it to not be monobehaviour?
What are you trying to do exactly?
Lmao i just typed "hmm" and it deleted it
otherscript script = new()
where exactly are you creating this other script otherwise
So you have some instance of "otherscript" elsewhere and you want "classname" to have it too?
do you know about constructors?
c# course time
Then this should be what you want.
thing with jumping right into unity is that you don't use constructors with monos
Just keep in mind that Monobehaviours CANT have constructors because Unity mumbo jumbo.
But for regular classes, all good
so you miss out on a lot of fundamentals
all good
I remember starting out with a visual scripter called Playmaker 🙃
good times
I remember being very scared of arrays with that plugin.
Thought they were too complicated.
!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.
hey, for some reason when the log is ran, the value of currentGasoline is set to 0, instead of subtracting it by a random value between 15-31. it also isn't updating the text in the component. how can i fix this?
using UnityEngine;
using UnityEngine.UI;
public class GasolineManager : MonoBehaviour
{
public int startingGasoline = 100;
private int currentGasoline;
public UnityEngine.UI.Text gasolineText;
private void Start()
{
LoadGasoline();
UpdateGasolineUI();
}
private void LoadGasoline()
{
currentGasoline = startingGasoline;
}
private void UpdateGasolineUI()
{
gasolineText.text = currentGasoline.ToString();
}
public void DecreaseGasoline()
{
int decreaseAmount = UnityEngine.Random.Range(15, 31);
decreaseAmount = Mathf.Min(decreaseAmount, currentGasoline);
currentGasoline -= decreaseAmount;
UnityEngine.Debug.Log("Decreased Gasoline. Current Gasoline: " + currentGasoline);
UpdateGasolineUI();
}
}
public class ClassName
{
private Otherscript script;
public ClassName(OtherScript otherScript)
{
script = otherScript;
}
public void Method()
{
//Can now use the variable "script" here without issue.
}
}
When you create an instance of ClassName though, you'll need to "pass in" an OtherScript variable.
Is what not everything?
How many times is that function called?
Do this first
Print initial value before decrement
Then print the value to be decreased right after mathf.min
And then print the remaining value after subtraction is done
good idea
Where are you creating ClassName to begin with? On a Monobehaviour?
Can someone help me fix this problem? I've been at it for hours and haven't found a solution.
just add ```cs
if(target)
{
// everything in that method
}
Where do I add this in my script?
Actually just for some clarification, when you write out classes, what you're effectively doing is making a "blueprint". If you have a class called Apple and give it a bunch of fields and methods, you're creating a blueprint for an Apple. What you ACTUALLY work with in code are objects, which use these blueprints to define what data they store and what they can do.
So when you do...
new Apple();
You're creating a new INSTANCE of an Apple. Aka an object that has used that Apple blueprint you wrote to define what it can do/store.
inside the method with the error, then put everything inside
Do you know what the error means?
Target is null
yes, but I am dumb and dont know how to fix it
