#💻┃code-beginner
1 messages · Page 48 of 1
unity does not have hot reload so changing your code while it is already running isn't going to fix it
how do I fix the math, Im confused
i cant remember if i saved or not
so i HAVE to restart unity
yes
oho k
For example, random stuff for the last section would result in an infinite loop
yea the prob was, i saved then contineud to work on it so the past 20 mins its been goign without me realisng
now it isnt letting me close unity
😥
use the task manager
yea i was
its ok it closed
i hope i saved it
earlier
oh yea luckily my code saved even though i had that infinite loop thing
\
am i fine to use this
@slender nymph
@ivory bobcat
ill risk it ig
what is this loop even for anyway?
just a gameplay mechanic, ive been working on this simple loop for like an hour long
If j is zero, you'll crash
6 minus 0.6 any number of times is not likely going to end up greater than 180
but it will be in the negatives before i reaches 180
What are you trying to do?
this also does not answer the question
o wait
yea
i jkust realised
i gotta change the middle thing
to like 5
for now
If your j is less than zero, it'll crash
It seems like... that is not the issue
congrats. you won't even enter the loop
yea i just did the math and realised it will get to - numbers quick
Well, if their j is less than 180 it'll crash
the value never goes up . . .
it does at first
if you would just explain what you are actually trying to do instead of making random guesses at what might be the issue, then a proper solution can be suggested instead of you just changing random bits of your for loop and expecting something to happen
What're you trying to accomplish?
well it is trial and error really
what is?
What is the point of this loop
and if u go up aenough i explained
literally where
Have you tried thinking first, then writing
so i followed the whole guide, i so far have no syntax highlighting and nothing underlined as red, pretty sure i did everything step by step this time.
just saying "it's a game mechanic" says nothing at all about it
Less crash prone if you do the math before running it
yea but ill need to do like 20 sums in my head
Did you remove the Engineering package?
Fen gave instructions here
#💻┃code-beginner message
afk like 2 mins ima think about it
Or, and follow me on this one,
on a computer
don't you know ? its a mechanic to crash the player
well with calc it takes ages to type em
And how does this for loop achieve the timer behaviour you described before
yes
ill explain when im finished its easier
no
Ok. And show your External Tools menu
if you've installed the extension and you don't see any errors in vs code, then regenerate project files and restart vscode
We're not going to code by successive approximations
What is this loop even for
why does it exist
what is it trying to achieve
What are you looping over
and what code do you intend to repeat
Hi, so I'm debugging a C# script with a collection of game objects. I'd like to be able to select objects from the collection in the unity editor as an easy way to find them. I found the Selection.activeGameObjects command, but it doesn't work, because the Editor freezes up during debugging. Is there any way around that?
I've gone up to your first statement #💻┃code-beginner message and have wasted my time. What are you trying to accomplish?
They want a timer that gets faster and faster
I dunno beyond that
must . . . go . . . faster . . .
i have figured it out, since some ppl seem curios ill put a video in works in progress in a few mins
do they? because the math they are using makes it slower over time
yes that's it, but they have yet to explain how this for loop relates to that at all
Forget it, I'll just block.
wym regenerate project files
ok👍
Click the button that says "Regenerate Project Files"
did you even bother looking at the screenshot you posted right before this message?
ima little blind alr
hope this helps 👍
clicked that and restarted vsc and nothing still
wait, where is it?
off to a good start
check the console in vs code for errors
for example, an error regarding the .net sdk or omnisharp
yep
No compatible .NET runtime found. Minimum required version is 7.0.
Dotnet path: c:\Users\randh\AppData\Roaming\Code\User\globalStorage\ms-dotnettools.vscode-dotnet-runtime\.dotnet\7.0.13~x64\dotnet.exe
Activating C# + C# Dev Kit + C# IntelliCode...
waiting for named pipe information from server...
[stdout] {"pipeName":"\\\\.\\pipe\\21bad252-f7fe-4a3e-ac52-ef4fd59c6140"}
received named pipe information from server
attempting to connect client to server...
client has connected to server
[Info - 1:15:13 PM] [Program] Language server initialized```
restart your computer
installing the extension should have installed the .net sdk so you just need to restart to get it into the path correctly
You may need to provide more info to determine why it's freezing. Having a list, dictionary or collection of references to your game objects shouldn't be an issue.
btw if u are curios its in #archived-works-in-progress , if u dont care then fair enough
and that still doesn't explain the purpose of it
oh
ill say now
there is plants, and the player needs to tend to them or they die and u lose, so basically the more the time goes on the more frequent u gotta tend to them otherwise it will go on forever at same difficulty, so i just needed a loop for that
why do you need a loop for that?
so it knows the times, i mean i could manually write them but it would be like 150 differerent numbers if u add up all thje plants
i don't think this is going to do at all what you expect it to do
lol here is where i find out i did it wrong😳😳
you know the loop runs to completion before continuing to the code after it, right?

eya ill jkusty put what i want inside the loop
yea
just
Then the timer will go off that many times in one frame
you should do some beginner c# courses to learn how loops, and just code in general, work
A loop just... isn't what you want at all
I would either put a formula in a method or the getter of the variable
Each time you call either, it updates the time it takes
honestly a serialized animation curve would be a nice idea for the time curve. then just sampling it at different points to get the time or whatever would be super easy
would also allow the curve to be different for different objects
is there not a way where ucan put all teh variables from a for loop in a array or smth, i swear someone said that to me once
I guess... but why? That sounds awful
You can certainly build an array in a for loop though
Then what? You iterated the array?
Why do any of that
ill do that
it seems like easiest way to me
It's a really really bad way to do it. Way harder to get just right too
But ok
idk how to use animation curves or whatever
Look it up 🤷♂️
Or do what I said and just use a method or the getter of a property
A loop is just added complexity for no reason
not sure how i would add a method to achieve same thing
public float GetNextTiming()
{
return currentTime *= .95f;
}
As simple as this, but probably want to find a better formula
But you should definitely just look up animation curves
It'll be exactly what you want
im still a beginner so idk if im read yfor that
that's the easy, beginner way . . .
they're literally so easy
you just create a curve to determine how fast/little the value changes over time . . .
you're doing everything in the inspector, instead of the manual way with writing formulas
ok I think I figured out a little more about my issue
https://gdl.space/isotemihar.cs hi just wondering if anyone could help me find the fix to my issue, the player jump no longer works in game and ive no idea why, any help? thankyou
kinematic rigidbody2d has velocity and MovePosition is called that fixed frame. If you call Physics2D.Simulate, the rigidbody's velocity gets set to zero.... SOMETIMES! In one block of code, velocity gets set to zero, and for another object, it doesn't!
and idk why
doesn't Simulate get called globally for all rigidbodies?
jump animation*** sorry
I mean I can set velocity, then manually call simulate, and immediately after that call, the velocity has changed
i mostly understand the animation curve but i dont understand how i would use it in my context, should i make the x axis 180 long or am i doing smth wrong
anyone??
i am not going to answer any more of your questions until you have demonstrated that you have gone through some beginner c# courses and understand how the code works.
unrelated / kinda related.. when i expose an animation curve to be able to edit it via the inspector i get some weird Editor error..
it isnt even code it is the curve thing u suggested
but sure
dont know the exact error, but i can clear it and it stays gone for atleast a little while
that's fine. i think i used to get that, but not anymore . . .
and if I don't call moveposition, rb velocity definitely won't get set to zero. idk why this is happenning
so if you call Simulate and MovePosition, it will reset to zero?
if I call MovePosition, then call simulate, now the velocity is zero
but not always? I don't understand why
if I set the simulation mode to Script, how does that work with Callbacks/Contacts?
Can I:
Call simulate, do X, then physics system generates contacts and callbacks?
Hello everyone, so to start with this so for VRChat, and i have asked for help from their discord but there has been no response
I am getting a free compile errors and i have no idea how to rectify them. Any help will be appreciated thank you also im sorry if this is the wrong channel im not too sure where else to put this
still getting the same error even after restart
then make sure you've got the .net sdk installed
no
it's not an extension
although i will recommend switching to a real IDE that will be easier to configure
like js visual studio?
i don't know what that js is supposed to be, but Visual Studio instead of VS Code, yes.
just
alr
should i fully remove vs code then?
up to you
keep it for your JS projects
js?
Jack skeleton projects
nothing shows up in the external tools for it
have you actually installed it?
yes
then its not installed correctly.. or u need to restart unity
alr ill restart it
then restart unity and/or your pc
if it still doesn't show up, you can always add it manually
if its in the OS folder (c:) drive or w/e it should be visible
but if not u can just directly point to it as box sed
even installed elsewhere it should show up. i had vs installed on a different drive for the longest time since i had no room on C
aight i restarted unity and it works now
ty
and still no red error lines
but it does seem to be configured
did you install the unity workload?
so thats good
installed it with the instilation of vs
or i may not have
idk where modify is in the tab it dont show
it's in the visual studio installer like the instructions say
yes i installed the thing for unity
regenerate project files and restart visual studio. if it is still not working then screenshot the entire visual studio window with the solution explorer visible
Okay so you didn't fix the one thing that was pointed out to you last time
Once you're finished your conversation, has anybody got any recommendations for courses for unity? Preferably free ones because I'm cheap.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Ah, thanks.
i forgot a space... god damn it im dumb
2 ish hrs over a space 💀
anwyayssss
still 10 errors
What is the point of this method anyway?
And also the thing we told you about last time
raycast for lasers
which is?
that you still haven't fixed
Just go one by one and fix them. They're probably all simple
But... why not just raycast? It seems like an unnecessary abstraction. You're already passing in all the same parameters
yeah, that's certainly an odd choice. i would understand if their static method maybe passed in some specific parameters for it. but all this is doing is just passing the same data to a different static method
Ohhh, could barely see that semicolon in the screenshot. Almost cut off there
Yeah, I thought at first is defaulted some data or parameter... but no. Just renaming the raycast essentially
i actually fixed it there was a semicolon at the end of the public static bool line that broke it
mb for the waste of time
Yes, that is what we said several times
Congratulations, you finally listened
But also, do read what everyone's saying. There's no point in this function's existence in the first place
how does motion happen at physics frame/update?
like, if my RB is at X right before simulation, is it now at X+1 immediately after update?
or does physics sim tell it to have a velocity to go through X=>X+1 between the end of physics calculation and start of next physics update?
Rigidbody has a velocity property
It uses that
^ same answer
In 2d kinematic bodies can have velocity
I'm confused because I'm calling MovePosition(), and sometimes the physics simulation sets my velocity to zero
and I am most certainly supposed to be moving
MovePosition overrides the velocity
ok, that's perfect, but my RB isn't moving
TryCastedMoveWeak(Vector2.left, mover, true, out RaycastHit2D hit);
Debug.Log("after cast move: " + mover.ToStringDetailed());
mover.SetPositionAndRotation(mover.initialSimulationPosition, mover.initialSimulationRotation);
Debug.Log("after set pos: " + mover.ToStringDetailed());
mover.rigidBody.MovePosition(mover.intermediatePosition);
Physics2D.Simulate(deltaTime);
Debug.Log("after simulate: " + mover.ToStringDetailed());```
TryCastedMoveWeak sets mover.intermediatePosition to a new value (that works right), and places it at that new position via transform.position and rigidbody.position
SetPositionAndRotation sets transform.position and rigidbody.position back to their original values
then I call MovePosition to that farthest intermediate position, then simulate. But it doesn't move
- If I only have TryCastedMoveWeak and Simulate, it moves
- If I only have MovePosition to position+ Vector2.up, and simulate, we move
I'm confused as to why it isn't respecting the MovePosition command if I have shuffled it around previously
SetPoisitionAndRotation is for a Transform
Don't use it for physics
I'm just moving both together. both transform and rigidbody position, so they don't desync
maybe I should just avoid moving transform at all?
progress. I'm going to expand to other test case
idk why moving the transform would block it from moving, but at this point i'll take it
holy shit that worked
thanks praetor
Normally with any type of movement mainly character or NPC movements you dont want to modify the transform directly
well, I was trying to move both the transform + rigidbody together, to avoid the need to sync transforms, but I guess not
wait, do colliders live in rigidbody space? or transform space?
transform
could anyone help with this please
that’s bad. I need to temporarily teleport all colliders for a moment
well you can also change the colliders position by itself
i’m doing a sequential physics calculation, where I move blocks A then B then C, and block B is colliding based on where A is after it moves
how would I do that without shifting the transforms
Is it possible to do Resources.Load(searchHere) where searchHere is something like **/ResourceName*
you typically provide the path to the resource you want to load as a string This path should include the folder structure within the "Resources" folder For example, if you have a resource named "MyPrefab" located in a folder called "Prefabs" within the "Resources" folder
uh, not me
sorry that was for toonic lol
im looking into it
anyway, how do I temporarily teleport a whole object with all its colliders temporarily. Just so it can be in the right position for Cast calls, and be allowed to just… put it back after
thankyou
Right, but specifically in this case I have a bunch of external sprites placed inside the Resouce Folder. Where I want it to do like.
Resource.Load(dynamicName) and then returns the Sprite/Image, where it will only ever be a sprite.
But it can also be under a sub folder.
you can disable the physics when teleporting it, which will allow you to change the transform directly without issue
i don’t understand? This is all within one function, basicallt
Call Physics.SyncTransforms() after setting the transform position, it'll resync physics to the new position
his option also works too
Is that expensive to call 10k times a frame?
Probably better to move everything first then call it once
it affects all transforms when it's called
string dynamicName = "Sprites/MySprite"; // Include the folder structure
Sprite mySprite = Resources.Load<Sprite>(dynamicName);
You do mean something like this right
I figured, but I need to move the one thing, one collision at a time, so I can calculate positions of other things
yes, it is.
you will lock up your game
I don’t need to do it for all transforms. I have a reference to the one thing that needs to be moved
Maybe what you need is a Collider2D.Cast? https://docs.unity3d.com/ScriptReference/Collider2D.Cast.html
Yeah, but its not always going to be Sprites. It could be something else. Sprites should be a Wildcard. As should the ending of MySprite.
See what would be collided with if you moved this collider in some direction
"*/MySprite*
I’m using Cast to calculate position, but now I need to set it
because block B then does it’s own cast, and depends on where block A plans to be next frame
so block A needs to cast, go to where it plans to be, do casts with block B, then put them all back. and tell them to smoothly travel to target position
does all of this make sense?
and I’d forseeably maybe do that 10k times a frame
doing anything 10k times a frame is expensive.
public T LoadResource<T>(string dynamicName) where T : Object
{
// Load the resource based on the provided dynamic name and type
T loadedResource = Resources.Load<T>(dynamicName);
if (loadedResource == null)
{
Debug.LogWarning("Resource not found: " + dynamicName);
}
return loadedResource;
}
So you want something like this where you can load various types of resources
i just can’t afford to sync the whole scene 10k times a frame
I don't know what you're doing, but you probably need to rethink everything.
your plan sounds strange
it’s a custom physics engine
it’s going to be expensive
there’s no way for it to not be expensive
yeah thats a lot
we’ll see how far I can push it
this would be super easy if I could just get into unity’s physics update, but that shit is a black box
with tons of injected code
wat
and there are several things I want to do that I’m blocked from because I can’t get the access I need
like what
moving in reference frames for one
what is a reference frame
i spent a literal month going around to figure out how to make a block ride a block in its reference frame etc
block A is moving with some velocity, and if block B is on top, then it rides at that velocity, and B can have its own velocity, which effectively adds
effectors are also a black box
Debug your boxcast to see its position and make sure it is touching the ground
which one the standing or crouching one?
which leads to garbage like platform effectors (used for one ways) cannot be combined with surface effectors
Both just incase
okay 2 mins
You can look into sabastian lague or something like that he does a lot of physics stuff, might be a good watch for what your doing
i’ll check him out. right now I have implementation challenges
@buoyant knotCan you explain very simply what you're trying to do
I saw your messages earlier about moving colliders based on other colliders, but that's still really vague
From what I understand, they want to have a kind of heavily limited collisions. If you have a stack of boxes riding on a moving platform and the topmost box hits an overhang, they want ONLY that box to slide off, but none of the others to even move at all (other than continuing on with the platform)
I saw a drawing they made a while ago that made it sound like that
There's likely a reason that's happening, probably because of performance. Stacking stuff in physics engines and expecting it to behave properly isn't really a piece of cake, from what I've heard from actual engineers.
@buoyant knot you'd probably be better off shopping for different physics engines and porting them into unity
rather than trying to write your own engine or modify unity's black box in any way. which I'm pretty sure violates their tos
I've gone down the rabbit hole of trying to fix implementation-specific things in unity for months on end, so I know how much of a pain in the ass it is.
at this point, I'm more comfortable making my own thing with my very specific needs than trying to fit a square into an extremely snug rectangular hole
I mean, if I'm reading the issue right, you could just disable the rigidbodies on the under-stacked boxes and give them a parent-move type of feature
you'd probably have to manually update the offset of the top box as well too though
I have tried so much shit for that, dude
it was a straight month of going to different sites, and I honestly give up on making it work with the built in physics engine
parent-moving isn't a thing in unity. you can move transforms, which makes collision janky af
Nono.
Like.
I should be able to search with wild cards for teh resource.
it's a thing when you have kinematic bodies
and I've asked the unity devs enough and the general concensus was "uh, yeah that's hard. don't think you can do that champ"
I know. but I need to be able to evaluate them as kinematic RBs to give them full collision
they need things like gravity, and pushing, and collision with walls...
they are effectively dynamic rigidbodies coded as kinematic
anyway, not to shoot you down. But i tried for a month problem solving with lots of people to make physx work, and everytime I try to do physics stuff while keeping to physx, I CONSTANTLY have these little "spend 1-2 weeks to do something simple" bullshit. I'm tired of trying to work in their box.
ok, it looks like collider bounds move with setting RB position, which very poggers
to actually get the physics engine to react to your changes though, you must perform a synchronization somewhere
that's a fact.
Q: if I move RB of block A's position, then immediately cast block B, will it cast based on block A's new position?
no
you must perform a synchronization
which is heavy.
assuming we're still talking about 3d physx and not box2d. I can't help with box2d.
private IEnumerator CanvasTextFade()
{
yield return new WaitForSeconds(loadingCanvasTime);
loadingCanvasTextAnimator.SetTrigger("ActiveLoadingCanvasFadeText");
// Obtén la duración de la animación desde el Animator
float animationDuration = loadingCanvasTextAnimator.GetCurrentAnimatorStateInfo(0).length;
// Espera hasta que la animación haya terminado
yield return new WaitForSeconds(animationDuration);
// Desactiva el objeto loadingCanvas
Debug.Log("Empieza canvas fade corrutina");
StartCoroutine(CanvasFade());
```why when i execute this code it takes a bit of time until the anim ends and the log is printed? Does anyone know it?
What are you asking? Just IF it works? Have you tried it?
box2D
At quick glance it looks fine..
you mentioned physx, which is 3d.
nono, that its supposed to execute all without time spaces... and when i execute this code it takes a bit of time until the anim ends and the log is printed
and I try to almost exclusively use very basic geometries. Basically all box colliders, edge colliders, and some composite colliders with as few vertices as possible
So... you WANT it to take no time? But it does?
I'm sorry, I'm just not understanding you
casting 10k 3D meshes a frame would melt any computer, I think lol
yeah, that
You have two yield return WaitForSeconds(someTime) written there
So... it will wait for those seconds...
also, my engine is going to have no rotation
everything has locked rotation, which should also help make everything cheaper
ECS should be able to handle it
But that is irrelevant and unhelpful here
and simpler, because no quaternions, tensors, or matrices get involved
how many items are you simulating at once
looking at maybe 1000
@topaz gorge does this help?
my plan is to mostly cast each one at a time, and try to avoid re-casting. but theoretically, several may need to be cast a few times. this is like worst cast scenario
So i think i see your problem one sec
Wait hold on but your player is jumping whats your issue? is it the animation
yes the animation i corrected myself after the original post you mustve missed it sorry
So the animation is the problem
Anyone know how I should code infinite tiles around the player, similar to games like vampire survivors? I want it so they can just walk in any direction forever
Can you show me your Animator
floating origin
can you go into more detail? idk what that is
ofc 2 secs
Move the world around the player
Then add more map as you go
world moves around the player. If you move the player infinitely in one direction, you run out of precision, and things will start jittering around.
Removing stuff out of range
you wanna see it whilst in game or just a screenshot
okay so how do I add more map around the player?
this isn't just a 1 step thing
you'll need to google it and get familiar with the concept
yeah I understand, do I use instantiate?
or some function in tile or something
i couldnt find one answer online
you'll need to store your tile data somewhere
for generating the tiles the first time yes, but you will want to make a pool for them for performance
apparently unity has a prebuilt tile system, so most of this might actually already be implemented for you
screenshot is fine
yes how do I create tiles in script? thats what im trying to figure out
when in game @topaz gorge it just shows the jumpanim as false all the time, but before the crouch it worked perfectly
okay, so just moving the rigidbody.position does update the colliders, and keeps collisions up to date
ie if I move rigidbody.position, and then a different collider casts, then it DOES respond to the new position
you need to check if the setter is manually updating the hierarchy volumes
which it probably is
aka synchronizing the physics engine
So there a few things that needs to be changed in the script i will point them out and put comments and so on
my role in the sync is just making sure that casts from the moved collider are correct, and casts that would interact with the moved collider are correct
thankyou i appreciate it
are you still trying to implement this on top of box2d or are you actually making a custom collision response?
I'm solely relying on Box2D to calculate casts
and move things where I tell it to move them
and is this a mobile game?
i have a code which should actiave a ragdoll for my enemy doing an idol animation: but the bullet just bounces off and doesnt trigger the ragdoll and the enemy carries on idol animating. this is my code:
Is there a better way I should be avoiding list duplicates other than just (aside from just ensuring my logic never does it twice ofc)
if (!List.Contains(Item))
List.Add(Item)
hasn't been a problem yet just curious
Maybe using a different collection if duplicates aren't to be had. Hashset https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=net-7.0
If you have to use a List, then you're gonna have to check it with contains or some linq function.
Different data structures can provide faster lookups but you'll have to adjust this implementation. If this isnt a performance issue, I wouldnt even worry about it
Where hashset Add would simply not add the element if already existing
Looks like a premature optimization question.
Yeah, Just had a bad vibe and wanted to double check
if you are contemplating duplicating a list, you are probably doing something wrong
duplicating a field usually leads to bugs where the two are supposed to be aligned, and are not
oh i didn’t understand what you meant by duplicates
I’m pretty sure Linq has .Distinct()
I use .Distinct when I need to cull a bunch of dupes at once
.Contains is O(n), and is good for upkeep.
.Distinct is O(n ln n) i think, and it is probably much better for giant lists with one big cull at once
Maybe you ought to provide more info like the console logs, if any.
alternatively, HashSets avoid duplicates naturally. Depends on what you need
There you go
oh you can remove the namespace
Not sure how i got double using variables those will also need to be removed
would anyone be able to help me with scripting these UI’s along with a round system please
if anyone is able to help them please take this to DM’s.
That's not how this server works. If you have a coding question, you're free to ask it.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Also check the pins in this channel for more resources
@buoyant knotIf your current solution ends up not working, I think you should bite the bullet and just make your own simple custom "physics engine" not involving box2d. The fact that your bodies can't rotate simplifies this 100x.
It would be a pretty damn cool project
I’ll only know once I can stress test it, then deep profile to see where the cost is
and what you’re proposing would simply involve replacing calls to .Cast with something else, which would be tough but doable
Can I see a graphic or something that you're doing
what sort of graphic
a video that shows me what the issue is
i have a diagram
sure
you wouldn't need a cast. you would simply find the overlap and depenetrate. gravity would be simple af
(assuming you write your own custom solution)
besides the general lack of access to be able to screw with effectors
well, I’m casting because I want things to move in reference frame
just to make it a bit clear: say block A is moving left, and block B is riding block A and jumps that same frame
Guys i have a question about, code in general. I know how to read and understand some basic code, like movement, how to move the camera around, how to jump etc. I can read some other stuff and understand it, but i cant memorize it/write it on my own without looking at it. Is this a bad thing? 💀 im kinda new.
in my method, B is casted to the left (movement in A’s ref frame), and then B does his own movement up (B’s personal jump)
the top cube just collides with green static cube and falls off. what am I missing?
It's normal, just keep practicing and you'll get it
you will learn the more you use the same tool
I don't know what you mean by reference frame either
alrighty
imagine you jump when you are in a plane moving at 100 mi/hr. You should move around in the plane just as though you were on normal ground, but now your speed is basically +100 mi/hr
yeah an overlap and bounds check would allow you to see whose underneath you, and mimic their velocity
but now tack on the plane accelerating/turning, and you running into birds flying at 5 mi/hr
I already have a system to define the relationship of what rides what
that was not an issue even with box2D
the box2D challenge was making the physics work out, once you know B is riding A
yeah, the custom physics solution would solve that
what's the issue again? friction makes them all fall?
friction doesn’t really help things track properly in Box2D
even assuming the thing on top doesn’t try to move
friction will apply some force to move together, but not enough to be exact
so in the plane example, your ass would 100% fall off and hit the runway
Box2D’s joints also apply force in both connected things. So the joint would let the plane move you, but block you from moving in the plane, and if you hit a random concrete wall, the plane would come to a screeching halt too
yeah
also box2D only lets you completely ignore pairs of colliders. not ignore force from one specific collider to another specific collider
so if block B is jumping on A, you have a choice between block B falling through A, or A also falling.
my workaround is to literally make two colliders for every object. Which works, but god damn that is a shitty solution
ty burt. i’ll take a look
it used to have working demos. what a shame they broke that.
Can someone help me out here please?
why are you doing the target direction in 2 places, in awake and start
I never removed it, once that part worked, sorry.
my actual issue is with the projection
im looking rn was just wondering about that
so whats the exact issue your having with this
If you see this image, I want to show such black projections on the barrier, but I don't know how to
To create black projections on the barriers you can do this by using a shader that darkens the areas where the balls cast shadows on the barriers
yeah, but my requeirement for the assignment is to do this using vector math. I have created a vvsmall black cylinder prefab & I need to show it & calculate its position & scale it so as to make it look like projection
i see
something like this. I tried this, but I dunno where I'm goin wrong
i got what you need
pls tell me
for (int i = 0; i < wallControllerRef.barriersList.Count; i++)
{
Vector3 ballPos = this.transform.localPosition;
Vector3 normal = wallControllerRef.barriersList[i].transform.forward;
// Calculate the dot product to determine the projection
float d = Vector3.Dot(ballPos, normal);
float D = Vector3.Dot(normal, wallControllerRef.barriersList[i].transform.position);
// Calculate the projected position on the barrier
Vector3 projectedPosition = ballPos - ((d - D) * normal);
ballShadowLine.transform.up = (projectedPosition - this.transform.localPosition).normalized;
// Adjust the scale of the shadow line based on the projection
ballShadowLine.transform.localScale = new Vector3(0.02f, (projectedPosition - this.transform.localPosition).magnitude * 0.5f, 0.02f);
// New code to create shadows
Vector3 shadowPosition = projectedPosition;
// Calculate the height (Y scale) of the shadow based on the distance between the projection and the ball
float shadowScaleY = (projectedPosition - this.transform.localPosition).magnitude * 0.5f;
// Instantiate a shadow object
GameObject shadow = Instantiate(blackCylinderPrefab, shadowPosition, Quaternion.identity);
// Set the shadow's scale, making it look like a projection
shadow.transform.localScale = new Vector3(0.02f, shadowScaleY, 0.02f);
// Parent the shadow to the barrier to move with it
shadow.transform.parent = wallControllerRef.barriersList[i].transform;
}
this should do what you need, i put in comments to explain it
kinda a pain you cant use shaders though
wow wait, let me read it
if you dont want the shadows to parent to the barrier you can always remove it of course
this is what I got 😬
any errors?
none
might be because the cylinders are being parented under the barrier, could be messing up there scale and so on
Can someone please explain class inheritance to me
You have a class that has functions and variables.
You have another class that inherits from that class, which then gives it access to its functions and variables.
hey sorry @topaz gorge this code when added in game still does the same and plays no animation when jumping saying the parameter is false, is there anything else that could be going wrong with it?
I kinda figured it wouldn't fix it, i dont see anything wrong with the code it must be something with the animation tree
If you wanna hop in a call we can debug the problem more effectively
yeah can do man
Dog > Mammal > Animal
||
Eat()
Character
Player : Character
Enemy : Character
Goblin : Enemy
Troll : Enemy . . .
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
🧑🏫 Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
hi guys
Hey SO, I'm STILL trying to get my button to get me to a different scene, HOW IN THE FARK DO I DO IT!!??? 😭
My "Find a game" button is a TMP-Text (UI)
I've added a button component to it for On Click; Hide shit (other menus)
AND, the script which is 'meant ' to take me to the new scene.
I'm not getting anything from console saying that my script is wrong.
Is my script wrong????
Do you have code that loads another scene?
Hard to say if your script is wrong if you don't show the code
It's literally in the photo my dude
Okay, then you just need to look up how to make buttons do something on click
You need to attach that script to an object, then drag that object into the on click field
That should allow you to select the function in the drop-down
I literally did that; it's not working.
You added the script. Not an object with the script...
As Wytea is saying
Is that TMP_Text/ Button not an object??
Okay and is the script with the scene loading code on it?
I've been following tutorials which say I can use a TMP_Text as a button and add the script to it but; I haven't been able to get that working.
Please calm down and read what I said here
We don't mean dragged into the box. The script has to be actually added as a component. And then the object with that component is dragged into the box
It's not the tutorials fault most of the time. You probably misunderstood or missed a step
So one step at a time, show us where the script is attached to?
I tried retracing my steps like 5 times to make sure; when I have dragged the script onto the 'object' it's there BUT, Script is greyed out and blank.......
This
Show this please
You have to drag in an object with a script component, not the script file
We're not saying dragging the script into the on click field
Literally, attach the script onto an object
Your Go2GameScene script
You don't drag the thing I put an X on
Which object is it attached to
Okay and did you drag that object into the slot or did you drag the script file
I'll just step away now
Maybe if enough other people repeat what you said right away they'll figure it out
(Trying to figure it out) 😂
The script file is not an object. You cannot drag the script file into your button the same way you cannot drive the schematic of a car
Just drag the FindGame_Button from the hierarchy into the slot
The button. NOT the script
You drag in a game object with the script on it into the slot
Then you can choose a function from one of that objects components
I actually did that the first time but, it didn't work so, I thought I did something wrong.
It looked like the script wasn't attached to the button in the first screenshot?
Did you add it after we said to?
Not sure why it wouldn't work otherwisd
It was there, hence the confusion.
And my dumb brain not getting around it.
(I have ZERO experience in coding and figuring things out as I go.) 😅
Probably not the smartest idea to go about things BUT, I'm making progress. 😂
Only going to get so far without learning some coding. Best to start now with some c# tutorials.
How can I send data from one client to another? or from one client to the server and the server sends it to all clients? I heard of the netcode thing but how does this work?
I would say this question should be in #archived-networking
ty
when i hold right click and move my mouse my mouse x is inverted
ah nvm
my scene view camera was upside down
xD
What would a way to perfectly subtract a direction from a velocity?
Walking at a wall on an angle, subtracting the walking velocity in the walk that is parallel to the normal of the wall
Project the velocity vector on the surface normal.
Subtract the projection from the original vector
Just to be crystal clear, this is the result I am looking for
I will try this
Though I am not sure what you mean by projecting it
anyone know if there is a way to like wait 1 seconds in soem code
Vector projection
Vector3.ProjectOnPlane
like it pauses the code, 1 seconds later it unpauses
Ah
https://docs.unity3d.com/Manual/Coroutines.html has waitforseconds in it.
i dotn wanna do a coroutine, is there any other ways
Async tasks, probably not as useful for what you want though
Do you have any reason why not to use a coroutine?
not really just cant be bothered to do it all
its a bit strnage there isnt just a : WaitForSeconds(4)
I mean, that's just how it works though
ok ig ill do a coroutine
You can do a timer loop, which is pretty basic
And the coroutine must be out of whatever method you've put it in here
Else Unity won't be able to call it
What IDE are you using, are you checking intellisense or errors? Do you have completion suggestions?
Looks like VS 2022, seeing the font and the indentation guide lines
can someone explain to me how this works?
im doing a regular raycast on the default layer which everything in the game is on right now
but for some reason, the raycast detect whats behind the player
but my debug draw shows it hit the player
it is supposed to hit the player btw, and when i move my character, it does detect my player being hit
void Update()
{
Debug.DrawRay(sun.position, transform.position - sun.position, Color.red, 1);
RegenHealth();
SunDamage();
print("Health: " + health);
}
void SunDamage()
{
if (species != Life.Species.Vampire) return;
RaycastHit hitObject;
Vector3 direction = transform.position - sun.position;
if(Physics.Raycast(transform.position, direction.normalized, out hitObject, direction.magnitude, raycastLayer))
{
print(hitObject.transform.name);
if(hitObject.transform == transform)
{
TakeDamage(100 * Time.deltaTime);
}
}
else
{
print("nothing hit");
}
}
If you remove the layer mask from the raycast, does it detect the player correctly?
Also it's a layer mask right, not just a single layer?
it does not detect my player
yes, layermask
but for now, its on default
Remove the mask, try again, if that doesn’t work make sure your math is right and colliders exist.
already done
This is the default process everyone uses to debug raycasts
can someone help why theres an error (I want to use GetFloat/Int and not Haskey) cs if (PlayerPrefs.GetFloat("sumTime", time); { time = PlayerPrefs.GetFloat("sumTime"); timeTXT.text = Mathf.Round(time).ToString();
well, as i said
already done
spr2 told me to remove it
i removed it
the debug.drawray shows the math is right
and i checked to make sure my collider is there
and it is
which the raycast debug also shows
Extend the ray distance a bit
The exact magnitude from the vector might just be falling short
extended by 50%, same result
You need to use HasKey for the if. The syntax of the if is also incorrect, you're missing a closing parenthesis and the semicolon ; is not supposed to be there.
your debug doesnt use the same arguments as your raycast
Are you trying to check if "sumTime" exists? Why not use haskey?
it uses the same math
that does not matter, if you want to debug something you have to put in the exact same variables, otherwise its pointless
thats kinda impossible as they dont take the same arguments
they take the same values for the corresponding parameters
The debug starts with the sun's position, the raycast with this Transform's position
That's not right
and thats what i give them
i think you spotted it
yes, thats the mistake i did
thanks for your help
and you would have spotted it too if you had used the exact same values for the debug and the raycast and not just assumed that you did it all right
You syntax looks very off actually..; after the if and missing parenthesis 🤔
What are you trying to do
a debug doesnt take all these arguments (for it to be really exact same values)
which is why i said its impossible to give it the same
i understood what you meant wrong
nothing about me assuming i did it right, as i knew i wasnt because it wasnt working
but it would have taken the sun.position
again
i understood you wrong
which is why i didnt catch the mistake at first
but its ok
spr2 helped me see the mistake
you can use this to fix those issues and just have all physics casts be drawn automatically with the exact same API https://github.com/vertxxyz/Vertx.Debugging
Ohh i didnt notice lol, S and s looks so siniliar
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float playerSpeed = 400f;
public float mouseSensitivity = 1f;
float mouseUpDown = 0.0f;
float mouseRangeUpDown = 90f;
public bool canLookAround = true;
CharacterController characterController;
private void Start()
{
characterController = transform.GetComponent<CharacterController>();
}
private void Update()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
HandleMovement();
HandleMouseLook();
}
void HandleMovement()
{
float x = Input.GetAxis("Horizontal") * Time.deltaTime * playerSpeed;
float z = Input.GetAxis("Vertical") * Time.deltaTime * playerSpeed;
Vector3 move = new Vector3(x, 0, z);
move = transform.rotation * move;
characterController.Move(move * Time.deltaTime);
}
void HandleMouseLook()
{
if (canLookAround == true)
{
float mouseLeftRight = Input.GetAxis("Mouse X") * mouseSensitivity;
transform.Rotate(0, mouseLeftRight, 0);
mouseUpDown -= Input.GetAxis("Mouse Y") * mouseSensitivity;
mouseUpDown = Mathf.Clamp(mouseUpDown, -mouseRangeUpDown, mouseRangeUpDown);
Camera.main.transform.localRotation = Quaternion.Euler(mouseUpDown, 0, 0);
}
}
}
My capsule is floating

When walk down
How can I give the player gravity with a character controller? I tried using transform.translate as well as charactercontroller.move, but they don’t seem like the best methods.

Also check the skin width is not the issue https://unity.huh.how/character-controller/skin-width
does ClosestPointOnBounds only use the colliders surface area and not the volume?
Hey guys, I am using on start method this code: Cursor.lockState = CursorLockMode.Locked; But it is not locking the mouse, any tips?
that's just the editor behaviour, try it out in Build & Play
Is there a way to disable collision between 2 layers or objects mid game?
yes
Physics2D.IgnoreCollision(col1, col2, false);
or just Physics if its a 3d game
In Build my colliders of ragdoll doesn't change position or rotation. It's only in Build.
Hey I was wondering what Vector3.Reflect() can be used for? For stuff like bullet ricochet? Raycasting on a surface and guessing how will it bounce? 
Does OnDisable get called when you exit play mode as well?
yes
Well bummer..
it can be used for anything you might need to reflect a direction vector for. so yes ricochet and other things like that would be included in that
Okay, thanks! 
Given a sprite, that has Alpha Padding. Is it possible to ignore the Alpha Padding via shader or by code?
Also for guns that shoot rays that bounce 3 times off walls
I have a loot drop script for dropping items when the enemy is destroyed, and I was trying to keep it completely independent of the enemy logic by instantiating the dropped item during loot droppers OnDisable, but quickly realized how incorrect that was.
Should I just call the item drop from the enemy or is there a correct way to do what I was originally trying that would keep them separate?
Yo, so I need a little help here, I need myself a little bit of guidance on how I would create a 360 degree dashing system, where this ball will dash toward the mouse without using the LookAt() function and have a set speed and time / cooldown
Capture position of the mouse on input (dash button) and AddForce in that direction?
If you want it on a cooldown, just start a coroutine that sets a flag when cd is over.
Is there a way to do that without using 'transform.__' bc I can't use that to my knowledge without using the lookat function
I'm trying to fix the issue of my character bouncing down a slope, I found a tutorial that gave the details to make a method "VelocityToSlope".
But because their original movement is done differently, I can't seem to implement it the same way they show in the video.
Does anyone know how I can use it with my current code?
How would u do that?
If the ball has a rigid body on it, you can use the AddForce function. That's not from the transform component.
And you can absolutely use transform to move without using LookAt. I believe LookAt just changes the Vector2.forward? I could be wrong
I think I got it, thanks man
do you use a dynamic or kinematic RB?
if you use dynamic RBs, bouncing/deflecting will be an issue
what I have done in the past is store last frame’s velocity, and if we just hit a slope (from a not grounded state), then roll back to old velocity, and calculate the new velocity you want
it isn’t perfect, but that happens when you are asking the physics system to do the calculations for you
I don't think it's kinematic that's it set to
i spent a lot of effort on this sort of problem
reverting the velocity and setting it to what you want is probably what you want
at least it is closer
let me back up a bit: you have X velocity on a dynamic RB. then you ram into a slope
the physics system makes you slide AND changes your velocity based on the elastic collision
my solution for this requires like 4 different parts
- When you first hit a slope, revert velocity back to last frame.
- Give yourself zero gravity when on ground/slopes
- when on ground, calculate proper velocity based on slope normals
- when grounded, addForce in a vector dependent on slope normals
i think there was another critical detail, but I think these are all crucial
i am currently in the process of giving up and making my own kinematic character controller
i spent a lot of time trying to make it work with a dynamic RB. You can make it work, but it is not easy
Yeah it sounds like a lot has to go into this 😅
I got a Problem, When steering/rotating, my rigidbody doesnt move in the direction the cube/car is rotated but it just moves on the Z axis (forward and backwards, but not in the direction the RB is facing). Im trying to recreate F-zero movement. Also, i cant move and rotate/steer at the same time, only one at a time
if (Input.GetKey(KeyCode.A))
{
float horizontalInput = Input.GetAxis("Horizontal");
Quaternion deltaRotation = Quaternion.Euler(0, -steeringSpeed * horizontalInput, 0);
carRigidbody.MoveRotation(carRigidbody.rotation * deltaRotation);
}
else if (Input.GetKey(KeyCode.D))
{
float horizontalInput = Input.GetAxis("Horizontal");
Quaternion deltaRotation = Quaternion.Euler(0, steeringSpeed * horizontalInput, 0);
carRigidbody.MoveRotation(carRigidbody.rotation * deltaRotation);
}
else if (Input.GetKey(KeyCode.W))
{
movementInput = new Vector3(0, 0, Input.GetAxis("Vertical"));
carRigidbody.MovePosition(transform.position + movementInput * Time.deltaTime * accelerationSpeed);
}
else if (Input.GetKey(KeyCode.S))
{
movementInput = new Vector3(0, 0, Input.GetAxis("Vertical"));
carRigidbody.MovePosition(transform.position + movementInput * Time.deltaTime * accelerationSpeed);
}
is there a way to link Unity inspector tooltip to the XML <summary> ?\
Hello, does anyone know why my project crashes when I click the "Menu Principal" button? (If you need a code, ask me)
We will always need the code 😄
Can't say much without it
I'll say it doesn't look like a crash to me though. Maybe linked to the wrong scene?
Show a screenshot of the button inspector too
perhaps you're using LoadSceneAsync and did not allow the operation to complete
so the scene is loading forever
but yes. code please.
for not being able to rotate/steer at the same time, use all if, not else if
for your other problem, please google "rigidbody move position with local rotation unity". i found a few results with that
i found a solution, thanks buddy
!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.
a powerful website for storing and sharing text and code snippets. completely free and open source.
This is the button I use to return to the main menu.
whith this script
a powerful website for storing and sharing text and code snippets. completely free and open source.
is "AwakeScene" the scene you're intending to load?
yes
Does that scene work if you start it directly?
check what info messages are being logged, just in case they're relevant
you have them hidden here
The problem comes when you tried to load a second time
oh, you're loading the "Carga" scene
They are only checkpoint messages
which then uses LoadSceneAsync to load the "AwakeScene" scene
is that correct?
I need to see the code that does that.
okey
a powerful website for storing and sharing text and code snippets. completely free and open source.
hm, that looks okay
I would add some log statements to the coroutine
when you start, during the loop, and when you end
LoadScene is definitely getting called, since AwakeScene starts loading
and it looks like the progress bar is full, too
Look, if I remove the "Cargo" scene the same thing still happens
Oooh, I think I get it
Do you set the timescale to 0 when you pause the game?
You aren't setting it back
So deltaTime is always 0
The loading screen got stuck, because it used deltaTime, and the car select + game scenes aren't doing anything
You need to reset it either immediately when you click the quit button, or when you load the title scene
a powerful website for storing and sharing text and code snippets. completely free and open source.
this is my pause menu
if Continue isn't called when you quit back to the main menu, the time scale will remain at 0
thank you so much
and what can I do to correct it
One tip -- use Time.unscaledDeltaTime instead of Time.deltaTime if you want to ensure something is measured in real-world time
I would set the timescale to 1 when the pause menu object is destroyed. That would guarantee that the timescale is reset when the pause menu goes away
Or you could just set it when the button is clicked
It probably calls a method. You could do it in that method.
hey quick question, can anyone tell me how do we get the center of sphere & radius of sphere, without the use of colliders ??
So I have a plane in unity, whose child is a sphere. and I want to get it's center P & radius
If the sphere has a renderer then https://docs.unity3d.com/ScriptReference/Renderer-bounds.html
I'm not really clear on what you're doing here.
does the sphere's diameter match the width of the plane?
I need to check if my projection poin P is within the sphere or not. But I don't wish to use colliders or renderers
yes it does
"projection point"?
explain what you're actually doing here
what are you trying to make your game do?
not "find the center of the sphere". i'm talking about gameplay here.
This is stupid, the center of the sphere is the center of the plane and the radius is half the width of the plane, 1st grade stuff
Is your sphere's radius and center not clearly defined somewhere? Why would you need to "get" it?
There's no way to have a Sphere without already knowing it's center and radius, since those two data points define the sphere in the first place
getting major XY vibes from this
especially since, as Steve pointed out, the math for the example above is completely trivial
what is the best way to make trees in a topdown game
Not sure where the code question is ?
you right
private bool isWithinRegion(Vector3 point, GameObject barrier)
{
Vector3 sphereCenter = barrier.transform.Find("ActiveRegion").transform.position;
float sphereRadius = barrier.transform.Find("ActiveRegion").transform.localScale.x * 0.5f;
float dist = (point - sphereCenter).magnitude;
Debug.Log(sphereCenter + " point=" + point + " " + dist);
if (dist <= sphereRadius) return true;
else return false;
}```
so this is what I am trying to do
I need to check if my "point" is within the sphere
but this doesn't seem to be working
any clue?
Log all the values and see which ones are not what you expected
also consider caching the result of that Find call instead of calling transform.Find twice within the same method
What's with this transform.Find an reading local scale stuff?
Put a script on the barrier and just give it a TestPoint or IsPointInRange function and handle it there
Give it a real "radius" property, don't rely on Transform scale. This stuff is super finicky
i strongly recommend against using .Find
praetor speaks truth
It’s ok to have a script with <50 lines of code. So easy to manage
peeps, this is stuck for 10 minutes now after i added unity play store plug in

is the process over and i can press x or i wat more idk
I'm getting the error CSI 503: Argument 2: cannot convert from 'method group' to 'UnityEngine.Collider2D' when I use Physics2D.IgnoreCollision(Collider, HandL.GetComponent<CircleCollider2D>, false);
Collider is a BoxCollider2D.
HandL.GetComponent<CircleCollider2D>()
Project your movement vector onto the the slope's plane
you'll get a new movement vector pointed down/up the slope
that should solve your problem with bouncing down a slope
I'll give it a try. Thanks ❤️
Hey guys have a problem, When I try to build my game there are 3 errors that point to a script and the build is aborted
Assets\02Scripts\PatchNotesManager.cs(6,34): error CS0246: The type or namespace name 'EditorWindow' could not be found (are you missing a using directive or an assembly reference?)```
```cs
Assets\02Scripts\PatchNotesManager.cs(12,6): error CS0246: The type or namespace name 'MenuItemAttribute' could not be found (are you missing a using directive or an assembly reference?)```
```cs
Assets\02Scripts\PatchNotesManager.cs(12,6): error CS0246: The type or namespace name 'MenuItem' could not be found (are you missing a using directive or an assembly reference?)```
Script:
```cs
using UnityEditor;
using UnityEngine;
public class PatchNotesManager : EditorWindow
{
private string version = "";
private string[] changes = new string[] { };
private PatchNotesDisplay patchNotesDisplay;
[MenuItem("Window/MenuOptions/Patch Notes Gen")]
public static void ShowWindow()
{
GetWindow<PatchNotesManager>("Patch Notes Generator");
}
void OnEnable()
{
patchNotesDisplay = FindObjectOfType<PatchNotesDisplay>();
}
void OnGUI()
{
GUILayout.Label("Patch-Notes Generator", EditorStyles.boldLabel);
version = EditorGUILayout.TextField("Version", version);
GUILayout.Label("Changes (one per line):");
string changesText = string.Join("\n", changes);
changesText = EditorGUILayout.TextArea(changesText, GUILayout.Height(100));
changes = changesText.Split('\n');
if (GUILayout.Button("Send"))
{
if (patchNotesDisplay != null)
{
patchNotesDisplay.AddPatchNotes(version, changes);
string patchNotesText = patchNotesDisplay.GetPatchNotesText();
System.IO.File.WriteAllText("PatchNotes.txt", patchNotesText);
}
}
if (GUILayout.Button("Delete All Patch Notes"))
{
if (patchNotesDisplay != null)
{
patchNotesDisplay.ClearAllPatchNotes();
}
}
}
}```
you're trying to use UnityEditor stuff in a build
UnityEditor is available in the editor only
Stop using Editor only code in your production script
Why are you using EditorGUILayout; ?
If this is for the game itself you should only use GUILayout
ok seems like an editor only script then
it shouldn't be included in your build
how to remove this from my build?
put it in an Editor folder
thanks
So basically i already ahve a code and it works but when i use the same code but try and load a diffrent scene it does not work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader: MonoBehaviour
{
public void LoadScene ()
{
SceneManager.LoadScene("Game");
}
}
thats thew code
What about it doesn't work?
How are you calling the LoadScene function?
Also !code to share code here
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh alr
What do you mean???
sorry im just confused because im new to coding and stuff like this
Code doesn't just magically run on its own
you have to call it somehow
YOu said you are using a button? YOu mean a UI button? Show how you set that up
ok
Im using a button ui and all i did was go and press create ui then well add the button and i named did all of that then i went and added the code like i did with the other button
show it
ok
screenshots
im tryna write a first person camera
using
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
to get the mouse movement, then used
transform.Rotate(mouseY, mouseX, 0, Space.World);
and noticed it fks about and makes the camera roll
what's the best way to combat this?
me and 3d space dont go well together
follow a tutorial - there are many of them and they solve this in many ways
commona pproach is to use two objects - the palyer and the camera as a child of thje player
what it lookes like for what i did before
How do I get my script to show on the TextMesh??
I know my script is correct because, it shows on the TextMesh in the Inspector BUT, it doesn't show where the text 'should be' in the game when I hit play to test it.....
Am I missing something stupidly simple here????
now what i did for it
right see how it says "no function"?
yea
YOu need to set that up like in the first one.
oh alr let me do that
From a code perspective that should work but why are you using TextMesh as part of your UI? TextMesh is a 3D game world text
Did you mean to use TextMeshPro - Text (UI)?
TextMesh is not going to show up in the UI
When I use TMP-Text; it doesn't work in the Inspector at all but, with Text Mesh; it does.
it will work in the inspector as long as you use the correct type in your script
TMP_Text
you have TextMesh in your script, which is wrong
ok so i tried to do that and realized that its not the same
this the one im working on thats not working
you'd have to show the code for SceneManager2
and this is the one thats not working
ok
Code for the one thats not working
Code for one that is working
This is the wrong script
This is SceneLoader
Show SceneManager2
They should not have the same class name
the one that i said is not working is the one up top and i kept changing the name because i thought i did something to it
The name of the script needs to match the class name
You also need to eliminate all compile errors
So i fixed one of the errors in the script but unity still says this
Did you save
yea i did
Show code
- This is not SceneManager2
- Your line of code has a space in it
- You have not configured your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
"The name 'AudioManager' doesnt not exist in the current context" even though its a class in a different script
Explain your problem.
Is it in a namespace?
Show code
yeah
will i have to do
using namespace
at the top
yes
ohh ok thx
Finish a thought, then hit enter. There's no reason this should have been four messages
sorry its a habit
im currently using rigidbody.moveposition for my hovercar controller. How can i let my hovercar reduces its speed slowly after letting go of the acceleration button? Right now after i let go it instantly stops
instead of just calling MovePosition with a value based off of the player's current input, smooth it out a little
e.g.
smoothedMove = Vector3.MoveTowards(smoothedMove, input, Time.deltaTime * accelerate);
If it's a non-kinematic rigidbody, you could also use its current velocity
So you'd move the current velocity towards the player's desired velocity a little, then move the hovercar with that
i have a script (audiomanager) with a playfootsteps() function that plays footstep sound when called. i found that it is being called using debug.log()s and stuff but the actual sound isnt playing. this is the settings on each audiosource that is being played
ive tried this now
for(float currentVelocity = carRigidbody.velocity.magnitude; currentVelocity > 0; currentVelocity--)
carRigidbody.MovePosition(carRigidbody.position * Time.deltaTime * accelerationSpeed);
but its not doing anything, is that how you thought i should do it?
this doesn't make much sense to me

MovePosition moves a rigidbody towards a position
You're moving it towards..its position, times delta time, times an acceleration speed
makes sense
You would want to take its current position and add something to it
Although, since it's non-kinematic, why not just set its velocity directly?
does it?
does it tho
The for loop also does not make sense.
I guess it would call MovePosition more if the velocity was higher
some post on google said movePosition doesnt affect rigidbody velocity
It is meant to be used with kinematic rigidbodies, I think
Moves the kinematic Rigidbody towards position.
so just set the velocity
rb.velocity = Vector3.MoveTowards(rb.velocity, input, Time.deltaTime * acceleration);
e.g.
You could also adjust the acceleration rate depending on whether the input is non-zero
that'd make you speed up quickly and slow down more gradually
guys anyone can help me? ```public class BulletScript : MonoBehaviour
{
public Material toilet;
private void Start()
{
}
void OnTriggerEnter(Collider col)
{
/*if (col.CompareTag("FlushLever") || col.CompareTag("Toiletmxv"))
{
//Instantiate(decalHitWall, hit.point + hit.normal * floatInfrontOfWall, Quaternion.LookRotation(hit.normal)).transform.parent = hit.transform;
var v = col.GetComponent<DecalObjectThroughtShoot>();
v.ShootToDecal();
}
if (col.material == toilet)
{
Instantiate(decalHitWall, hit.point + hit.normal * floatInfrontOfWall, Quaternion.LookRotation(hit.normal)).transform.parent = hit.transform;
}*/
if (col.CompareTag("Toilet") && !col.GetComponent<ToiletBehaviour>().isInFire)
{
var destroy = col.GetComponent<ToiletBehaviour>();
destroy.hitsReceived++;
//Instantiate(decalHitWall, hit.point + hit.normal * floatInfrontOfWall, Quaternion.LookRotation(hit.normal)).transform.parent = hit.transform;
}
if (col.CompareTag("Toilet") && col.GetComponent<ToiletBehaviour>().isInFire)
{
var destroy = col.GetComponent<ToiletBehaviour>();
destroy.hitsReceived = destroy.maximalHitsToDestroy;
//Instantiate(decalHitWall, hit.point + hit.normal * floatInfrontOfWall, Quaternion.LookRotation(hit.normal)).transform.parent = hit.transform;
}
if (col.CompareTag("WeakPoint"))
{
var v = col.GetComponent<WeakPoint>();
v.currentShoots++;
}
if (col.CompareTag("SkibidiToilet"))
{
var v = col.GetComponent<LifeSystem>();
v.life--;
}
Destroy(gameObject);
}
}```
the OnTriggerEnter of my bullet doesnt works
yeah,both objects have a rigidbody and the bullet has a collision trigger
by some reason the bullets bounce off objects and do not pass through them
or maybe it's the gun script, I changed it so that the bullets came out of the gun but were centered on the player's crosshair after being shoot
{
//bullet
public GameObject bullet;
//bullet force
public float shootForce, upwardForce;
//Gun stats
public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
public int magazineSize, bulletsPerTap;
public bool allowButtonHold;
int bulletsLeft, bulletsShot;
//Recoil
public Rigidbody playerRb;
public float recoilForce;
//bools
bool shooting;
//Reference
public Camera fpsCam;
public Transform attackPoint;
//Graphics
public GameObject muzzleFlash;
//public TextMesh ammunitionDisplay;
//bug fixing :D
public bool allowInvoke = true;
private void Start()
{
//make sure magazine is full
//bulletsLeft = magazineSize;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Shoot();
}
}```
{
//Find the exact hit position using a raycast
Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); //Just a ray through the middle of your current view
RaycastHit hit;
//check if ray hits something
Vector3 targetPoint;
if (Physics.Raycast(ray, out hit))
targetPoint = hit.point;
else
targetPoint = ray.GetPoint(75); //Just a point far away from the player
Vector3 directionWithoutSpread = targetPoint - attackPoint.position;
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0); //Just add spread to last direction
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity); //store instantiated bullet in currentBullet
currentBullet.transform.forward = directionWithSpread.normalized;
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);
Debug.Log("it works");
}
}```
its better to pay attention to this
Try drawing a few debug rays for the final direction, as well as outputting the name of the hit object.
Wasn’t sure what channel to ask this in but does Prefab (Isolation) mode work functionally or just visually? Like if I open a prefab in isolation can it still find stuff like singletons that live in the currently open scene? Or is it a proper isolated workspace
You mean the prefab edit mode?
Yes
Hard to say. I think it acts as a separate scene. Might be wrong though.
In any case you shouldn't be relying on any code working correctly in it.
That's what I'm looking to correct yeah. Have a feeling it might be still finding them but wanted to vibe check here before diving into reworking my stuff just incase someone had some wise sage words for me 😛
Can someone help me. I am trying to make climbing physics like the game Tunnels on app lab. But nothing is working. Videos are telling me i need an XR Direct Climb Interactor but i dont have one. Can someone please help? That would be AMAZING!
better way to write this?
If it's VR related, better ask in #🥽┃virtual-reality
Otherwise, share more details and code.
Your way is not really bad, but you could make it shorter:
eatDelay -= Time.deltaTime;
eatDelay = Mathf.Max(0, eatDelay);
Could also put the eatDelay - delta right in the Max parameters.
like this? delay = Mathf.Max(delay - Time.deltaTime, 0);
What would that be like?
ok,I'm going to try to find out
thanka doc
Hey guys, I'm trying to make a day cycle system where I calculate the time of day depending on real world Unix time, however I'm having a problem where the following float is returning NaN, does modulus only work for integers in c#?
```private float cycleFract()
{
return hourFract() % (1/cyclesPerHour);
}
private float hourFract()
{
DateTime getTime = DateTime.Now;
int getSecond = getTime.Minute * 60 + getTime.Second;
return getSecond / 3600f;
}```
Modulo does not only work with ints
DateTime.Now returns the date AND time btw
Perhaps you wanted DateTime.Now.TimeOfDay?
nah that part works fine for me its only when I try to get the modulo of hourFract and 1/cyclesPerHour I get returned NaN :/
Oh that part was just for simplifying not to fix it (which is why I said btw). Sorry for the confusion
What value is cycleFract supposed to be? Can you give a math example, this seems like a weird calculation
its a float between 0 and 1 to represent the point during the current day/night cycle
so say theres 5 cycles per hour
well a more easy example would be 60 actually
basically every second would be 1/60th of a day cycle if that makes sense ig
If it returned a float between 0 and 1, that means you wouldve done % 2, not 1 / X
well this version of the function wasn't finished I was just trying to figure out why I was getting NaN I found a workaround though finally
{
float getHourFract = hourFract();
float getDivisor = getHourFract / (1f / cyclesPerHour);
int divisorToInt = (int)getDivisor;
float lastHourFract = (float)divisorToInt * (1f / cyclesPerHour);
float nextHourFract = (float)(divisorToInt + 1) * (1f / cyclesPerHour);
return (getHourFract - lastHourFract)/(nextHourFract - lastHourFract);
}
private float hourFract()
{
DateTime getTime = DateTime.Now;
int getSecond = getTime.Minute * 60 + getTime.Second;
return getSecond/3600f;
}```
basically this is what I was trying to figure out sorry for wasting time guys :/
If you want 5 cycles an hour, I would just take the minutes and then divide by 12 for the int result
uhm wait how would that work cause like wouldn't it look kinda odd cause I'm trying to lerp between lighting values
so if it was like
wouldn't it kinda like jump tho
like the time would skip a bit cause the integers arent like 100% accurate to a floating point number
idk how to describe what I'm trying to say rn 💀
Yea not really sure what you're trying to say, but this calculation seems a bit extensive for basically an in game timer.
I dont get why you need the IRL time if your day night cycles in game are way more frequent. If you need a day/night timer just add by time.deltaTime and multiply by the cycles per hour
in my coding course i keep getting this dumb one wrong
what is the shorthand for
x = x*y
i did
x *= y
and got it wrong
what in the world?
How was it wrong?
it didn't tell me
thing is i'm doing a bunch of other coding stuff much more complex for my games so this course feels stupid
8 = 8 * 2
Is the same as
8 *= 2....