#đ»âcode-beginner
1 messages · Page 558 of 1
the movement shouldn't, be in the camera?
Welp time to make a character
thought there was one..
I was trying to avoid it bc I'm too lazy to have to model a character
friend lets try to code pong without the ai first
I'VE MADE PONG IN SCRATCH
it unchecks
do it in unity then
what
I just wanna get to the fun stuff
That's the thing - learning how to do stuff is the fun part
Only reason for this game is bc I wanna make it vr, but first I'm making it pc
reason for it being vr, to force my parents to buy me a quest
and u can do it with ai and asking everyone in here to fix the code without learning
OFC
how did I not think of that before
Oh god am I fucked
Welp I'm gonna go make the character
any recommendations on a character maker?
lol
Do you know why it counts 1 two times ?
brother google how to screenshot
I don't have discord on pc
where do u set jump to 0?
I'm in the middle of a refactor, and in so I've renamed my old classes and started rewriting them. In my IDE I can set those old classes to no longer compile but Unity seems to override that. I still need to reference them until the refactor is done but they are throwing errors now due to the new code so I can't test. Any way to set them to not compile without changing them to text files or something?
so is the code detecting midair jumps?
Yes, for now, I want for it to count to 2, for double jump. I can make it work if I set maxJump to 1, but I want to be able to set maxJump to two, I just need to make the jumpCount be 1,2,3 and not 1,1,2
I don't know why that happens
its probably being set to 0 the frame after u jump
or
actually
when is jump performed done?
just perform the jump after the check
I think this is the problem, but no idea how to fix it.
Does it really matter when jump performed is being done ? If the check is in the update, isn't it being checked every frame ?
yes
it matters about when in the frame its happening
i cant remember exactly how update works rn idk
i would use a delay buffer for the check but idk the context of your code so idk if it will work
Yeah... It's fixed now, I just had to move the isGrounded check to the jump performed instead in the update. Thanks a lot!
Sometimes I forget that update works frame by frame, maybe if I had the check in fixedUpdate it would work, but it works like this aswell
awesome
maybe if u had the check in lateupdate* probably not fixed
but yea
Honestly, I thinking fixedUpdate and lateUpdate wouldn't work either way, because one is frame independent and the other comes after the update, and jump_performed is it's own method, so I don't if it does it's thing before or after the update, but it seems like it does before the update
You know Unity docs has this wonderful chart which explains exactly when things fire, perhaps you should look at it
void moveTowardsClosestBuilding(){
if (currentObjectFocus == null){
allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
float prevDist = 0;
float dist = 0;
for (int i = 0; i<allObjects.Length; i++){
dist = Vector3.Distance(transform.position, allObjects[i].transform.position);
buildingProperties = allObjects[i].GetComponent<BuildingProperties>();
if (buildingProperties != null){
if (dist <= prevDist || prevDist == 0){
prevDist = Vector3.Distance(transform.position, allObjects[i].transform.position);
currentObjectFocus = allObjects[i];
}
}
}
}
if (currentObjectFocus != null){
pointToMoveTowards = currentObjectFocus.transform.position;
directionOfTravel = pointToMoveTowards - transform.position;
directionOfTravel.Normalize();
// Movement
distanceToCurrentBuildingObject = Vector3.Distance(transform.position, currentObjectFocus.transform.position);
if (distanceToCurrentBuildingObject > 4){
transform.Translate(directionOfTravel.x * speed * Time.deltaTime, directionOfTravel.y * speed * Time.deltaTime, directionOfTravel.z * speed * Time.deltaTime, Space.World);
}
}
}
void destroyBuilding(){
if (currentObjectFocus != null){
if (distanceToCurrentBuildingObject <= 4){
buildingProperties.buildingHealth -= attackDamage;
}
}
}
}
``` For some strange reason when the enemy gets within attacking distance of building, crashes and says no instance is assigned to the line where the building takes damage in destroyBuilding()
I am quite sure there is an instance assigned
so buildingProperties is null
lol
debug it and find out instead of just assuming you are right
it would only be null if the building blck is destroyed in it's script before the last call of that function
which shouldnt happen, because the currentObjectFocus is a reference to that same object, so if it was destroyeed, the function wouldnt execute anyways
ill just debug it
not at all
buildingProperties = allObjects[i].GetComponent<BuildingProperties>();
if allObjects[i] does not have the component it will be null
that part of the script only executes if the currentObjectFocus is null
so if the block was destroyed and it was finding a new block
Isn't there a term name for when one script only does one thing? I can't recall it
ya
yeah ill debug, a bit confusing to look at my code xD
well that's the only code you shared which sets that variable
not documenting it very well at the moment because im just trying to pump out funcionality lol
Thankyou for your help, ill try debugging it now haha
Even tho I already fixed my code this would help a lot, but I can't find it, can you send me a link ?
Thanks ! Really helpful, might even print it so it's always next to me xd
imprint it into your brain, it will save you hours of heartache
Bro you wer atully correct hahha, it was that line causing issues
veteran
why am I not surprised?
lol
hi all I'm new to unity, I've got collisions but keep falling through the world, I've watched a bunch of vids and tried loads of different things to fix it but I can't figure out how.
is there a rigidbody on ur player
idk
he is falling so i assume he has rigidbody on player
u need an actual plane to stand on
make a terrain object
This has been cross-posted from #đ»âunity-talk
Hey, I'm stuck on the Unity lobby service idéa where you add a scroll view to list all the lobbies. I'm wondering if somebody could possibly help me with that?
why isnt this scoreIncriment++ working do i need return value or smt its my first time working with coliders
what r u expecting to happen
r u looking in the inspector
and the value doesnt increase?
to add 1 when it colides
What makes you think it's not working
yea
Add Debug.Log to make sure the code is actually running
inspector
i did it is
Show us
show the inspector of the object with this script
You're looking at the inspector for the wrong object then
and show the inspector of an object its colliding with
i mean there could be other reasons
I don't see debug.log in your code
wait what
so the code is logging
but value isnt going up
well i delited it let me put it again
Where is this log? It's not in the code you showed
And which object is the script on
the ball
see i added debug and every time the ball colides it prits one
nut doesnt incriment
lol
You're literally printing 1
Debug.Log(scoreIncriment) maybe
What else would it print
u dont understand i dont want to print one i want to add 1 every time the ball colides to scoreIncrismen variable
r u fr
If you don't want to print 1 why did you print 1
Print the actual value of the variable
I understand what you're trying to do
i dint understan u sorry wait sec
You need to debug your code, which is what I'm helping you with
it dubgs 1 but in the inpector it doesnt change
and it shuld be like 1 then 2 the3 exc
do u set scoreIncriment to 0 anywhere else?
nah
Is there more than one ball
Is the ball getting destroyed
Is the scene getting reloaded
Etc
no and no
Show us the full script
lmao
!code
đ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
đ 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.
wait
Also set the variable to Private
There's no reason it should be public and you might have other scripts changing it by accident
show all ur objects as well
My recommendation is this to rule out any other scripts changing the value
its my text meshpro id dint need it
comment it out then
ok
i deleted it
Got it working thanks there was one thing schanging it value or smt
Yep, another script was doing it right?
This is why public variables are a bad idea
yea i set it to public so i can get it to another script
i know geters and seter and stuff i need to learn more
whats serialze field for?
Show it in inspector while its private
why wont this work i have the tag ball on the object but i dont know why it isnt taging
The documentation talks about the meaning of "serialization" a bit
https://docs.unity3d.com/6000.0/Documentation/Manual/script-serialization.html
Tags only exist on gameobjects
When a field is serialized, Unity will:
- show it in the inspector
- save the value in the scene (or in a prefab)
Serialized fields are used to configure your components. You can give different enemies a different amount of health, for example
Public fields get serialized automatically, but you have to explicitly tell Unity that you want to serialize a private field
So, fields that only have meaningful data while the game is running should not be serialized
So how would i do osmething only when the object colides with a certan object and not the oher. And i know about layers but it wont work for me
well, look at what Collision2D gives you
have you looked at the documentation for that class?
Well as far as i know (COlision2D collision is the object i colide with)
Wdym?
Read the documentation!
One nuisance about the names...
rigidbody is the thing you banged into
otherRigidbody is your own rigidbody
how silly
it would be confusing no matter the name
I'd have settled for ownRigidbody or something
but that presupposes ownership
a collision occurs between two things, one of which is notified about the collision
that's enough of a "self" for me
But what if both are
Ohh i got it working
one is notified at a time :p
yes but you canât make it not confusing
i thoutgh its a variable
but colider and collision isnt same
you know what i mean
anyway thanks
ah, yes, people mix up the two pretty often
you still have to know which is the âownerâ and which is the âotherâ
Collider2D is a kind of component. Collision2D is an object with some information in it
the owner is the one being told about the collision
I presume it doesn't pass the exact same values to both sides of a collision. That would be a nightmare. You'd have to check whether the thing you hit is rigidbody or otherRigidbody
Some would assume itâs the one sending/causing the message
"the other rigidbody" explicitly sounds like it's referring to...well, the other one
there is just no way to solve that kind of situation with names
and the other is obviously not ourselves
i think it's significantly better than the current naming
and nothing here is âobviousâ
yes, because the names suck đ
otherRigidbody is a mental speedbump every time I see it
well, just telling you that other people see things differently
can give some advice? im following a tutorial but ran into a problem that googling and chatgpt isnt helping on, when my character touches a wall, he starts jittering all over the screen and flipping upside down, can you check my rigidbody/collider/controller and see if you can spot whats wrong? đ thank you so much
AI said that I dont need a rigidbody on a character controller on the same object, but i dont see where in character controller it would deal with collisions otherwise...?
you should not mix rigidbody with a character controller
okay! so it was right, but i dont see where i would find a collision then...
when i turn off rigidbody it stops detecting if i hit the wall
character controller is collider and controller
rigidbody needs a collider
so i need neither my collider NOR my rigid then since i have my character controller
right?
you pick whiever controller you want to use
so then... why can i not detect collisions then..?
detect which collision?
i have an OnCollisionEnter with my blocks around my character so that when he hits them they change color and a log is printed
but with JUST character controller, nothing happens
something only prints and detects a hit when i have both sphere and rigidbody on
OnCollisionEnter will not work with CC but there is also a replacement
oooooooohhhhh
or more reliable you use physics casts
physics casts are unity specific functions in the Physics class for example
raycasts and alike
hmm, thats a bit over my head
so am i editing my C# code to use OnControllerColliderHit?
if you want CC replacement for OnCollisionEnter
CC works with triggers only besides that
You already have Basic Rigidbody Push script that uses that function already
so.. i wont lie.. now im even more confused then
im looking up all this other documentation and youre giving me physics stuff to look up, but i really just dont understand what i need to do to fix this problem
i think youre speaking way above my level
sadly
As I said you can either replace your OnCollisionEnter function with the one I sent that is for CC only, OR use the Physics class to use for example a cast, to detect whatever it is you're detecting
new settings using your method suggestion
still nothing sadly
deleted rigidbody and went with CC
where did you put this script on
all the surrounding cubes i can run into,
thats wrong, thats why is not working
script goes on CC
because its a CC function
hence the name
the cube is the thing im going to make reset the character though
and each cube i hit would do something different
so what would i attach to the cube
okay cool, so now i print out everything the player touches
which is another thing ill prob do later
for footsteps or whatnot
can just make the script detect the cube and from there you get whatever function from it
you can access whatever components you might add on Cubes
is that the more common way to do it? track what the player touches and update things as it goes?
what if i like, shot something though or hit it with an arrow
depends on what it is ofc, most of the time the player is doing the detections for interactions or whatever components
each script you add is a component , cleaner to have a script handle specific features and nothing else
hmmm, well i got now to print out whatever my main character is on at every second
thank you đ
but still when things hit my cube it doesnt do anything aha
to any script i attach to the cube
you have to replace whatever logic you had in the previous OnCollisionEnter to the new function
what do you want it to do OnCollision with Cubes?
simply i just want it to print something to the log, i just want it to be able to detect, from there i can probably figure things out
but the cube will just not. detect. anything.
why would the cube detect anything ?
because thats the homework assignment im trying to follow....
what is the assignment because sounds like you ain't following the instructions correctly then
is there a way to make rigid bodies go up stairs? if i add a character controller it flies up to space so idk how to do it
make the stairs ramp shaped collider or switch to cc
you cant mix rb with cc
alrighty got it
This was answered 3 days ago?
#đ»âcode-beginner message
oops sorry completely forgot
I've got a system to place Building objects on a planet; they're not allowed to overlap so at the moment I give them all colliders and the one I am trying to place has a ColliderChecker script which just has a bool which is true if it's colliding and false otherwise. I feel like there might be a better way though?
(Also if I want to place buildings instantly, does OnCollisionEnter fire immediately, or with some delay? E.g. placing buildings for an AI or placing them procedurally at the start of the game)
Thanks
For a semi realistic shooting game (ie not CSGO kind of arcade), should I do hitscan or use actual projectiles for gunfire?
For instance simulating tank gun fire like War Thunder
Depends on if you want the impact to be instant or after a delay depending on distance
You may want to have a look at Physics.OverlapBox/Sphere methods.
Would something like OverlapSphere and then check if the array isn't empty be a good approach?
Yes
Itâs not wrong to use scripts with OnTrigger callbacks, just more spread out and annoying to deal with. Sometimes unavoidable.
Trigger callbacks fire on the next physics frame.
In placement systems you often have to do some trickery to have all the triggers fire correctly and in a way you want them.
Makes sense, thanks!
After delay
Then Iâd suggest pooling some actual projectiles
This is not what AI is for
You should not ask it on what is best
As I now realized in the hard way, yes
If you're a beginner programmer you should not even touch AI
Learn by doing, ask actual people for help
hehe, you get in trouble asking people for whatâs best too, just on a larger scale. Everyone should aim to be able to recognize for themselves whatâs best. But that seems to be a lost art. #tutorialculture
Not even senior devs know what is "best", or they wouldn't need to rewrite software and refactor all the time
the trick is there generally is not a "best"
Some AI can be good to ask for guidance. Not specifically whatâs the best approach, but more âWhat are the pros and cons using X over Zâ and then determine yourself
Ask the AI "what are my options" and it will show you a pro/con list and you can evaluate yourself
whats the best way to learn all the unity syntax
not rlly syntax but the operations and stuff like that
âBest wayâ will differ from person to person, so youâre likely to get a generic answer that wont be tailored for anyone
@pliant robinBy developing and keep making games
You only deep dive when you run into problems
yes but im about as beginner as they come
Do some of the unity tutorials
unity doesnt have any specific syntax
learn c# syntax, and unity apis
Ask âWhat are are some simple ways to move an object in a 2D Unity game using components and scripts?â
It will give you basic, advanced, and more alternative operations. Then you put a promt like âCan you give me some simple tasks to implement movement by script in a 2D Unity game?â.
Thatâs an efficient way to be specific and also let the AI help you learn
thats a rlly good idea
i don't think that first one will be very consistent, or even useful, in the long term
genais hallucinate, that's their entire thing
use it to your advantage, asking it to generate ideas, not answers
As unintuitive as it sounds, you can become good at making prompts, just like you can become âgood at googlingâ
but you can't control the ai being good at giving truthful answers
The tool doesnât do the work for you, you learn how to properly implement the tool.
@naive pawnI have had great success at code generation, you just have to review it, and make tests
honestly movement in games just boils down change position, change velocity, or change acceleration
Thatâs true. But you test and try what it gives.
and you expect beginners to be able to do the "review" and "test" part?
probably not a good route for beginners
@naive pawnNo, they should ask "explain this code step by step" etc. and run it and see if it works
i don't deny that genais are tools; but they're tools that kinda masquerade as doing more than they really do
that's a pitfall for beginners
and that's how you get hallucinations
and just because code works does not mean it's good code
Not really, depend what AI you use, some are good at breaking it down
Probably not. If you use it to do your homework, you wont learn anything. If you use it to help teach you, it can be an amazing tool. Itâs tempting to have it be the first option
gen ais hallucinate. that's what they're designed to do.
Not always
no that's literally how LLMs work
Mm not really, they pull from a knowledge base and when they cant find the knowledge they make it up, kinda lika humans do
it can be. you can't force someone to utilize it as a tool
you can treat it the same as "doing homework" and a beginner still wouldn't learn much
genAIs don't have a knowledge base, they have a language model and they make up sentences that sound plausible. sometimes they're right, but they aren't designed to be
No, the knowledge base is the trained data
Hence itâs about how you use the tool that determine whether it will be a good tool or not.. as with anything, really
Gen AI does not read documents on the fly from somewhere
I did a similar about "should I do hitscan for my bullet system or just good ol trajectory with rigidbody physics"
Which it does say if the bullets are fast then I should do hitscan, but it just didn't say you can do ccd
(which to be fair the bullets would do sth like 1000m/s, but probably lower in reality)
genAIs make it much easier to misuse the tool and take the answer at face value
my point is; tools can be misused. genAI is very easy to misuse. you have to already have a certain level of experience to use it well. and beginners don't have that experience.
other tools don't make up lies while you're using it
I used AI to write 700 tests because I could not be bothered to do it, I just reviewed the code, so it's not hallucinating it
it is hallucinating. that's how they work
sometimes the hallucinations are right
fwiw, the general consensus throughout every support server and platform ive seen, including this one, is to not recommend genAI because of its pitfalls.
It's a tool, it's about how you use it
I don't trust a PR by a junior dev either
Without reviewing
it's a "tool" that misleads people and beginners can't tell if it's hallucinating useful code
and do you think a beginner will be able to accurately review
don't recommend genAI to learners
it's only a useful tool when you know how to look past the hallucinations and how to verify answers correctly
that's not what a beginner is
Never trust anything 100% is what I get from the AI
we have been on this many times already
Although I am using the AI pretty much "don't trust the AI too much and you should research with it as a semi guideline"
in my 3d movement after i let go of a key, it slides that direction for like a split second more, any way to fix it?
ai has helped so much for me especially in creating math equations and also for complicated c# docs
It's because of the way input manager works. Use Input.GetAxisRaw instead
Works exactly the same as Input.GetAxis without the smoothing
bold guess..
thanks
because someone else has had the same problem as you
nah i havent tried yet im saying thanks in advance đ
so it gives you the equation that person has made
lmao
nah
for future reference, you need to provide quite a bit more info to get a meaningful answer
I've had that problem a few times already
it can definitely do math
because it uses python for math
its probably the best at math over anything
not genAI
It's nice that this input smoothing comes right out the box but I dont need it
ohh alr mb
@eager spindleSome AI can learn by reading actual code then apply it, I tested this throughly where the AI was not able to undertand a library API by itself before I fed it custom docs
it worked cheers
đ
im mkaing a google doc of the very few scripts ive successfully made so i dont gotta struggle w this in the future
â
I'll just speak from personal experience, I had to implement playfab backend in a project recently
there's a lot of things that could give that effect though
Playfab's story: it's a backend service providing User Auth, data storage and other things
@eager spindle
It got bought over by Microsoft in 2018, and Microsoft deleted all the docs and moved it to their own page
is ai even that reliable for scripting?
no
i rememebr i used to use it and i had to tell it to fix its code so much
is ai reliable
no
This doesn't solve the original problem, input.getaxis's value doesn't go to 0 immediately. Input.getaxisraw does though
All AIs kept giving me old API instead of the new one even though I had specifically mentioned it
It was completely useless
it does solve the problem in a way
there's way too little info to actually say for sure
The thing is I, a human programmer, already have the context needed to solve the problem
@eager spindleIt could have run out of context length
AI does not
AI doesn't know everything it's not e god
AI doesn't know the intricacies of Input GetAxis Vs Input GetAxisRaw
GetAxisRaw removes the smoothing towards the input as well
so if they wanted that, but an immediate stop, that would work
You don't have to be a god to know these basic things
i, also a human programmer, don't. where are you getting this context?
Anyone knows how to make a child position independent from Parent Position? I have my player prefab with an extra camera for respawning (when the player dies the camera switches to one looking at the map from the sky). The problem is that i have to put the spect camera as a child of the player or i cannot add it in the serialized field of my player's code (bc it is a prefab) and doing that the camera moves with the player... I need its position to be fixed. Any ideas?
Also there is less code in game dev to train on that web dev, much less
@eager spindleNo, you need experience
You can't, that's just how transforms work
You can make a camera controller scirpt
just make it not a child
a child object inherits its parents position/rotation/scale, that's the whole point of the hierarchy
Also if you make the camera a child of the player, if the player rotates then the camera will rotate too
ye i tried but then i cannot put it here
Depending on your game that might not be desireable
ye actually
what is that? what's the context here?
Not exactly sure what you mean by you can't drag it in
Also those are all prefabs
ah, prefabs.
of course
there was a link for this
Unity huh how?
i think so yeah
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
I need to assign the spect camera to switch between the two
wdym?
that doesn't give me any useful info to solve your problem
you're getting more specific
i need a broader view
oh mbmb
alr one sec
but this should tell you the majority of what you need to know from here
Tell us a few things.
âą is this screenshot taken in prefab view?
âą What's the type of SpectatorCamera?
alr lemme see this first
also I'll make this very convenient: you can get the main camera by using Camera.main
need advice
is it possible to make a command prompt like things (not a console dev or smth like that, but a things that similar to a CLI in linux) in a platformer game?
yes
lethal company made one
Yeah it's taken from the player's prefab and the SpectatorCamera is a GameObject, so i can call the function SetActive() on it
so, what should i learn to make something like that?
as long as you know how to use TextMeshProUGUI and TMP_Input you can definitely do it
if you'd like to I can make a tutorial on it
it'll take a while before it comes out though
fr?
Why is the numbers changing to random ahh numbers
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
whats random? the run speed
its being set to 12 properly like ur code says from what i can see
check if u have initialized them somewhere in script
ohh i forgot to change the ones under too nvm sorry
also in the crouch feature is there a way to make it smoothyl come up instead of just snap back to the default scale
is there a variable i could use or sum
i use a delay buffer to smooth things like that but there are tons of ways u could do it using a smoothing function dedicated for player movement
but for small changes like this its probably easier to use a delay buffer
also i am assuming ur talking about the full collider being restored to default position and not just the animation
yeah yeah
really?? I've been stuck here. I have a final semester assignment (group assignment) to make a game. My friend wants to make a 2d platformer game with a cyber security theme, the goal is to educate the players (students). He wants to combine a command prompt like thing into 2d platformer like i say earlier. But we have zero experience in unity.
been following this video and i need this for my final project https://www.youtube.com/watch?v=gPPGnpV1Y1c&list=PLGUw8UNswJEOv8c5ZcoHarbON6mIEUFBC&index=2 around 13:55 in the video and i got these errors
The second video in the Lets Make a First Person Game series!
đIn this video we are going to setup the foundations for our interaction system.
Come Join us on the Discord!
đź https://discord.gg/xgKpxhEyzZ
đ Thanks for watching!
Helpful Links
https://dotnettutorials.net/lesson/template-method-design-pattern/
are we waiting for the errors
slow laptop sorry
show your script
basically whats happening at least with the top 2 is that there are 2 namespaces that have the same definition
so you need to clarify to the code
about which one you want
player interact
oh wait
you have 2 scripts called PlayerInteract?
and 2 scripts called PlayerUI
player ui
how?
oh it duplicated it when i transferred into a folder
thank u thank u
do u know why it keeps duplicating whenever i save the file?
is the name inside unity different than PlayerUI/PlayerInteract?
no
how i play an animation when im walking
lol
make a new script and copy everything inside the old script over, but not copy the public class line at the top
i fixed it
k cool
if i have a unity file connected to the cloud is there a way for me to download it on a different device since it isnt showing up on that devices unity hub but is connected to cloud
This is a coding channel #đâfind-a-channel
So I updated to the new version of unity recently and while working on a project I noticed that Cursor.lockState=CursorLockMode.Locked and Cursor.visible=false both take an initial click on the game window to get focus everytime I enter play mode, even while on Play Focused. I found this to be a "new feature" of the unity version but i was wondering if there was a way to bypass this since everytime i even pause the screen, it takes an extra mouse click after unpausing to refocus.
how to I make my player not collide with enemy during dash
do u want them to not collide during just the dash? or just never collide at all?
Why the coroutine is stopping?
only during the dash
what
u can try rigidbody.detectCollisions=false
where are you executing StopSpawn?
In an event
so the event is happening then the coroutine is stopping? or wdym
other.gameObject.GetComponent<RigidBody>().detectCollisions=false;
but remember u have to turn it back on after the dash or else it wont detect collisions again
then i will make it true after set amount of time so like i put under it 5 -= time.deltatime if 5 = 0 set it to true? for example
Yeah, because the log is working but the function "StopCoroutine(SpawnEnemy1())" not working
also remeber that doing this might cause the enemy to fall through the ground since collisions are being turned off
probably because its starting again since you have it to start inside the coroutine
what you need to do is set it as a variable
or make an if check before starting again
Ok
a remidy for that is to also turn the gravity to 0 temporarily
and turn it back when ur reseting the collider
yes
yes
if anyone has any has any solution for this I would really appreciate it, its really annoying to have to click on the screen everytime
for Rigidody2d its gravityScale which is directly the scale but for Rigidbody (3d) its rb.useGravity =false cuz its a boolean
Are you using the escape key to pause?
yes
You'll get unwanted behavior in the Editor as escape key removes focus on the app in the Unity Editor
It's not anything new.
This has always been a thing.
Use a different button for testing in the Editor
damn it didnt cause me trouble in the past .. but maybe that was because i use it as an input from the input manager
this shouldnt be a problem in build tho right?
Yes, it'll not be a problem with the builds
okay ty
I think ESC always has unlocked the mouse in editor
yes but even after i replaced ESC with some other key it still requires the initial click to focus the first time when u play which i dont remember being the case
I could be wrong tho so idk
This is another editor-only behavior
they know but its about saving time
you would be "saving" a very minuscule amount of time
What the line of code to cancel ALL collisios cause rigidbody2d.detectCollisions = false aint working it just says error
Share the error
rigidbody2d doesnt have detectCollisions
if ur using 2d then u have to get a referrence to the collider
for example
BoxCollider2D collider=GetComponent<BoxCollider2D>();
collider.enabled=false;
detectCollisions is only for 3d Rigidbodies
oh ok
there is another method to do it using Physics2D.IgnoreCollisions() but you would have to set up layer masks for that
ty
also are u not using autcomplete in ur editor?
Please configure your editor if you are having this issue. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
âą
Visual Studio (Installed via Unity Hub)
âą
Visual Studio (Installed manually)
âą
VS Code
âą
JetBrains Rider
âą :question: Other/None
wdym? i am pretty sure ridigbody2d doesnt have detectCollisions function
That's not what I said
If a user has to resort to checking the Unity console for missing signatures, it is a very good indication of a misconfigured editor
Because with a configured editor they would receive help before having to resort to compiling to trigger errors
It doesn't suddenly add the signature, if that's what you thought I meant

Any recommendations on good character creators for 3d games
blender
anyone knows a good inventory system tutorial or documentation?
i was just gonna say isnt it just blender?
wdym character creator?
"inventory system" is extremely broad. Every game has unique requirements for such a thing, and they are large and complex. So it's best to first list out your requirements and then tackle each thing one by one.
Yeah, inventories are up there with "ability system" and "quest system"
This is a valid inventory system
public class Inventory {
public bool hasGun;
}
somebody, PLEASE! get this man a gun
!code
đ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
đ 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.
yea im not helping this person lol they are fully writing their game w ai and asking in here for help constantly
ya just invest some time into learning blender man, it will help out in the long run
or just dont code in 3d cause 2d is superior
this is a code channel
just a quick question, is box cast better for ground check? i am used to just doing a raycast but I read on a thread that box cast is sometimes better
A boxcast will more reliably find very spotty ground, I suppose
Raycast can go through a small hole
imagine standing on a bunch of thin vertical slats
Sphere/Circlecast gives good smooth normals
If you need the surface direction, that is
Usually in 2D I just use the collider methods and make a bunch of them for detection
stuff like that
okay for the current project i just need a good enough check for a lumpy terrain so i am just gonna use boxcast
i used to do that too but racasting was much more convinient so i switched to it, also i am coding in 3d so i think this method covers all the bases
Hello, does anyone have comprehensive and detailed notes on the Asset Pipeline V2 that they could share? Most available resources seem outdated, inconsistent, or contradictory. The Unity documentation provides limited detail and is fragmented across multiple topics, making it difficult to understand the process step by step.
Iâve attempted to gather the information myself but lack access to the source code, and the stack trace offers little useful insight. Any in-depth resources would be greatly appreciated.
Anything would be good as long as it aligns with current execution of the Asset Pipeline.
For context, Iâve already reviewed Unity documentation across several versions, blog posts, and Unity Talks on YouTube about this topic.
hm, is there something you're looking for in particular?
pages like https://docs.unity3d.com/Manual/AssetDatabaseCustomizingWorkflow.html seem pretty comprehensive
I am seeking detailed information about the Asset Pipeline, specifically what occurs step by step from the beginning of a refresh to its completion. I am currently developing tools for my game and need a deeper understanding to avoid potential issues with Unity's systems. The list of questions would be very long, so i would appericate if there is anyone who already dug in it deep and want to share his notes.
its just high overview and missing few steps
this is just the order of operations, yes
there are more details on the specifics on the page..
im aware of that "For context, Iâve already reviewed Unity documentation across several versions, blog posts, and Unity Talks on YouTube about this topic."
What sorts of questions do you have?
The list of questions would be very long, i will post it here after some time.
You should come up with something concrete, yes.
I dont have simply one or few questions. Thats why i simply asked if someone have in-depth notes about this topic and would like to share with some begginer fellow. Also i like informations which are backed by some tests/ code/ stack trace, just something that proves it is right so there is no need to dig in to it again. So i expected that when i start spamming with questions i will simply receive links to docs or responses how someone feel or guess how it may work like. I would appericate if someone with in-depth knowledge of this topic DM me, so it will be possibble to avoid spamming this chat with people who are here to judge.
People are going to be much less likely to help you if you ask for a very nebulous, possibly unbounded amount of information.
it's the same reason people are told "don't ask to ask"
indeed, thats why i asked about some in-depth notes of someone who already had to dig in to this topic.
so the question part would be skipped
So i expected that when i start spamming with questions i will simply receive links to docs or responses how someone feel or guess how it may work like.
you'll get links to docs or other resources when they're relevant. existing community resources are generally better than a single person's response
if you're getting opinions about how things supposedly work, that's just bad support, and this server is active enough to discourage that.
you won't know until you actually start asking. https://dontasktoask.com
make a thread.. keep referring people to it.. every answer may get answered eventually..
The "in-depth notes" would be the existing documentation
or i'd ask 1 at a time to not overwhelm ppl
I doubt that anyone has a secret encyclopedia they're hiding from the internet
Until you start giving us some context and asking pointed questions, I can't tell you much more than that
i mean "in-depth notes" can go a few different ways, right
- it's from the author/maintainer - in which case, those notes are docs.
- it's from a user, and the notes are public - in which case, those notes are docs, but separately hosted
- it's from a user, and the notes are private - there's no guarantee of accuracy.
I am also studying the importer system, because I am writing a number of tools that involve asset postprocessing (including some that I'm planning to publish!)
if I have a list of objects of a class how do I check of which type of inherited class any given entry is?
like, let's say I wanna list a bunch of "weapons" but I need to know if an individual weapon is of class axe : weapon or sword : weapon
You could use GetType(), but if you need to directly check a type then it probably means you can do it in a better way
Like using enums as weapon type identifiers, or making the child weapon class override the functionality of the weapon (or use an interface)
In what context do you need to know the type? What are you trying to implement?
I'm trying to pull from a pool of possible drops
the pool includes all classes that are dropable, but what happens on drop depends on the exact type of drop
I assume the super classes are made by you, then u can just add GetType() method in the classes to indicate what they are.
I guess I could try going for overriding a method now that I think about it
you might want to just have a method for that that's called indiscriminantly, to make use of polymorphism
spooky
ok this is all a bit much to process at once so Ill dig into it and see what I can make work
but thanks for the input
is is very handy for downcasting
although I always get suspicious when I have to downcast
i fell like this is too complicated for what little functionality she needed, wouldnt it just be better to add a getter method to the parent classes?
appropriately
yeah idk about that...
is works fine
i mean ... as long as she understands all the code its fine ig ..
rn Im thinking, there's an abstract method in the parent that I always gotta call when I want to make use of it - so I may as well have all children set an Enum to a value that represents their sub class so I can easily check for that later in code?
if you already have the class hierarchy, why not utilize the parent
polymorphism is a thing
exactly
typically, when you have a class structure like that and you want to implement behaviors that each child has slightly differently, you implement it on each child instead of having a centralized switch-case
the point of the hierarchy is to not have that centralized thing
if everything is passed as something like an Item, you probably need to use Is assuming the behaviour splits somewhere in the derived classes such that Item -> Weapon has a method Attack(IEntity target)
But maybe something like a Use(IEntity entity) method could solve all and just not implement it in another Item type that is not Weapon
it's a drop, but there's a bunch of different types of drop (like health, an upgrade, or an unlock) that cause fundamentally different things to happen on pickup
I guess I should move from calling the pickup function on my Handler class to calling it on the object itself, so I can do another override
huh
that's neat
u can just return an enum and put it in a switch case
compare
void doAll(List<Parent> children) {
foreach (Parent child in children) {
if (child is A) {
/* A logic */
} else if (child is B) {
/* B logic */
} else if (child is C) {
/* C logic */
} else {
Debug.Error("forgot something");
}
}
}
```vs```cs
class A : Parent { void doThing() { /* A logic */ } }
class B : Parent { void doThing() { /* B logic */ } }
class C : Parent { void doThing() { /* C logic */ } }
void doAll(List<Parent> children) {
foreach (Parent child in children) {
child.doThing();
}
}
there's no risk of forgetting an implementation when you add a new object type, and each child is responsible for its own logic
I just need to move where code happens for that to work, yeah
I was kinda stuck on having it all happen centrally but it really doesnt need to be
you as the helper need to be more observant when someone is posing an xyquestion
you're answering their question, but not their problem
that's what i mean when i said it's not quite appropriate
I think, anyways
folks, I appreciate all the input
it can be a bit overwhelming but ultimately I should either be able to decide which suggestions help me or clarify further if Im unsure
that's my responsibility as the one asking
imho
if you're going to do the free work, then maybe put some effort into it đ€·
if you're too tired to do a good job, go get some rest
LMAO
yeah no
Take it to DMs please..
did you read the xyproblem website?
answering the question, when it's an xyproblem, is not very productive
there's been an entire convo about this exact topic a few days ago lmao đ
the consensus is not gonna change
can anyone help me with problem its probably pretty easy to fix but i cant find anything online
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #đâfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
specifically that last point
noone can help you when you don't tell anyone what you need help with
i have an animation that just makes the players scale jump up and down for a jump, but having it enabled means i cant flip my character when hes walking either left or right
like the assumption that a beginner is asking about their actual problem, rather than an attempted solution?
why cant u flip your character?
you sure this is a code question? is this about your animator controller setup?
you need to reread https://xyproblem.info lmao
im not gonna engage in that any further
possibly but i have no idea how its messing with my character flipping
if its the scale of player sprite thats increasing and decreasig then thats not animation its just code, but it would be helpful if u could post ur code for player sprite flipping
trying to debug.log an error and i cant figure it out.. basically i have an array of sprite renderers but im going to their gameobject to find their image component. One of the obbjects is reporting not to have an image component, but when I look for that gameObject, it looks like it does
How to post !code
đ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
post them separately, it's a pain to read/copy/reference
that doesn't guarantee that you dragged the right one in, or if it's changed at runtime
Use the context parameter for Debug.Log so you can click the log and have the relevant object highlighted
its logging from a manager script thats accessing the array though
Debug.Log($".. name stuff..", box[i]);
so it doesnt know what box[i] is does it
oh ok let me try this
Selecting the message should highlight the object in the scene
gotcha i forget debug.log has these things
How can I prevent the stutter effect that happens when weapons get in between limbs?I dont want them to get through.I know I can make weapons trigger but I want them to collide.
o yeah that already showed me something thank you
probably misclicked one of the 240 times
This is the code channel, is this code related? If so, you may want to provide code.
what exactly do u mean by stutter ? like camera stutter? this just looks like couple of ragdolls could u provide more context?
yeah youre right
so just to clarify u want to stop the camera stutter? or the ragdoll from shaking
I mean the thing happens when the weapon collides with other player
ragdoll shake
well ragdolls are notriously difficult to control but u could post the code here so people can check for any bugs
I only have a balance script about the ragdolls
using System.Collections.Generic;
using UnityEngine;
public class balance : MonoBehaviour
{
public float targetRotation;
Rigidbody2D rb;
public float force;
// Start is called before the first frame update
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
rb.MoveRotation(Mathf.LerpAngle(rb.rotation, targetRotation, force * Time.deltaTime));
}
}
its on every limb
the stutter seems to happen when the stick gets in the neck joint so u could try making the collider wider
it happens on every joint I think
what did you mean by wider?
like make it so that the the stick stop slightly before reaching the joints
make the colliders slightly bigger than the the limbs themselves
well they are ragdolls so there isnt really much else i can suggest
I tried also making swords heavier so it pushes the characters but didnt work
oh that's interesting
Im not entirely sure yet of all the needs I will have for the child classes, hence I cant say yet if this is viable for me
Use pattern matching. The is syntax returns true if x is y where y can be the same class or an inherited instance.
Alternatively, consider using an enum to define the weapon if you have it under a specific group. There are multiple ways here.
rn Im running into the issue that unlike the class without any inheritances I cant actually fill in a List of the class on a ScriptableObject in the inspector anymore
Note GetType return the actual weapon type and if you compare this against an inherited type, it will not return true since the types are different
I'd say an interface IFireable would be better here in which case it would implement the fire method, but that's my 2 cents.
You know, in case you have a weapon that doesn't fire for some reason
IWeapon might be more suited for an actor which purpose is being a weapon, but more as an indication that it can be wielded
That's my thought process, just wanted to share
Yeah, for example
this is my actual use case btw
Sounds more like an abstract class might suit this if it's a general group like that, but interfaces can also work
there's a manager who, like, creates pickupable objects that get filled with some reward. and I realised that instead of telling the manager what to do specifically with which type of pickupable (generate some random values on spawn, increment certain values on pickup) I can just tell the class itself that it was spawned or picked up and have all the different functionality happen in the override of the child
that's my solution as of now, anyways
still very much WIP
but the resulting code already looks a lot cleaner lmao
next thing to tackle will be how to create a pool from which to randomly choose a drop to spawn; as outlined earlier my previous solution of creating an SO that I just fill with values manually is not viable anymore, sadly
You could use a weight system
It allows for rarity, but it depends on your use cases
hi y'all if I have a wireframe cube that I want to not display and display again, how should I do this ? Do I need to update all the time that I do not want to display it in the update part ?
(and also how do I not display it?)
u can just turn on and off the mesh rendered when needed
turning it off will make the object invisible
to do this u need to get the reference for the connected mesh rendered
and then do rendered.enabled=false;
and make it true when u want it again
ok thanks
also, another thing, when I get position updates once in a while to display an object, how can I make the motion smoother? are there some functions that can smooth the path of someting when you specify positions in an asynchronous way ?
I am using a lidar that gives position updates every about 0.15 s (but this also changes slightly), and is not very smooth
There's no out-of-the-box interpolator component, but you could certainly use something like Vector3.SmoothDamp to smoothly move towards a target position
Catching up on this, if your drops are scriptable objects then what's stopping this from working?
How do you define/configure a drop?
So i am making a little test game about going down a hill and because it has a rigid body and the floor has no friction the object gains speed. However this causes the object to have massive amounts of jitter after a certain point
messed with surface properties and drag values?
if drag/mass is semi realistic it should act in a similar way
But think is it also glitches and jumps in the air randomly
Guys am 100% new to unity, can someone help me understand the basics?
I want to make 3d games
but I do NOT know how to do anything
use animator states + transitions to do the animation changes
if it gets to some crazy high velocity then that explains it. it shouldnt if it has a big mass with drag and the floor/it has non 0 friction
something wrong with them? did you disable exit time, set the conditions and change the transition time? enabling the transitions to be interrupted may help too.
Exit Time is for all Transitions disabled.
Conditions were set.
The script i provided earlier, it uses a Joystick. When the Joystick is dragged, the Player moves.
That does work, but it does not play the Walking Animation. It just sticks with the Idle Animation.
check in edit mode if the condition is changing and is stable (remains true consistently) and if the transitions are setup correctly. Not much else that can be wrong.
you can see in the UI when it transitions and what anim is playing in edit mode so should be easy to figure out
can u show the idle->walk transition inspeactor?
here u see the param name is "isMoving"
here u have put it as "IsMoving"
change the case
it should work
or wait
I dont understand, they are both in upper case?
my bad it is IsMoving
ya sorry i am on phone so i couldnt see it properly
all good
did u debug and check if the param is actully becoming true when ur walking?
Iâm struggling with Unity Animator and transitions. Iâve set up the Movement animation with a Blend Tree for Idle and Run, but I canât figure out how to properly set the transitions and parameters between Charge, Hang, Jump, and Wall Slide animations. I would really appreciate any help
Got the same issue since yesterday.
Do you have a code that triggers those Animations?
yeah but its not about the code idk which conditions or parameters i need to use

newbie
u can just create a parameter and then trigger it from script when the corresponding action is executed
yo so my first person camera is only going up and down? whats wrong with my script?
(it is a .cs file not .txt)
transform.localEulerAngles = Vector3.right * cameraVerticalRotation; well ur just telling it to move up and down
so thats what it is doing
Its not becoming true, thats why i think the line of the script is not being executed
ah shit
this needs to be
cameraHorizontalRotation+=inputX;
transform.localEulerAngles =Vector3.up * cameraHorizontalRotation + Vector3.right * cameraVerticalRotation;```
if u could provide a video of what exactly is happening then that will be helpful
So i have the Problem that when i shoot at the player he is losing damage but i see his health and mine at the same time
Has anyone calculated how many months you wasted waiting on compilations on script edits?
My project isn't even big yet and it takes a solid 1 minute
This is why I never save my scripts
also kinda bogus that by default it'll recompile if you're running the game in the editor
like who wants that
Can I not set it to compile only when I hit play button?
You can turn off auto refresh yes
https://discussions.unity.com/t/can-i-stop-auto-compile-after-edit-create-or-remove-a-script/878449/2
If hot reload is so good, why is this feature not in Unity 6
gotta remember though the editor won't update if it's dependent on that script
Not sure how that is a question. It's good because someone saw a need and addressed it with their own asset.
It is, but it isn't very easy to use
Unity's version of code hot reloading. Making sure your project survives Unity's attempt to serialize all state and restore it takes some effort
Oh, I might buy this asset if I can tab back into unity without having to wait 1 minute per ctrl+s
is it bad to use the old input system of unity? like does it affect the project in anyway? I wanna shift to the new system but it seems too much work to change everything if there is not gonna be any objective change whatsoever
It doesn't affect the project in any way, no.
I hear input latency is lower on the new input system backend on mobile.
If you're hoping to handle multiple input types, or various parts in your game that require different controls (driving vs flying vs walking etc, or even for handling UI), the new system is much easier.
But games were made with the old system successfully
old system is fine and works right out of the box.
can't be arsed dealing with events when I just want to pump out some game for a jam
this feel stupid to ask but can i still use different actionmaps while having part of my code in the old input system?
You can use both, yep
But you will still need to handle the state of the game with the old system, so you're not reading inputs when you don't need them (vs the current system that just lets you toggle entire maps on and off)
right got it
its probably better to convert it anyway cuz unity keeps depricating stuff
how old is the old input system exactly?
It's the original system
The current system has been out for 5 years maybe? I forget
hmm i will switch up just cuz it seems more convenient for the long run
April 2020 was 1.0, before that it was in preview for approx. 1 year
ya so about 5 years approx
I would have guessed it is older đ
Messages mode is pretty quick, at least comes with benefits of new input system
how can i make the players shooting raycast ignore the player collider, but the enemy raycast not ignore the player collider? Also im not sure why but my enemy isnt following the player. can someone help?
use LayerMask, put player in the layermask Player, make enemy only hit Player, make player ray only Hit Enemy Layers
don't forget you have to put the gameobject with the collider to that layer
how do i make it only specific to a layer
because im pretty sure i tried something like that and it wasnt working
Raycast should have parameter for Layermask, that specifies which layers get hit
ahh ok, Thank you so much
@lucid quiver after 4 Hours i have solved the issue with the Animator.
CC: @winter wadi
Solution: The GameObject that has the Animator Component, make sure this Animator Component "Avatar" field is set with an Animation Avatar.
i have no idea what u said but i am glad it works now
this can not be None
Thank you so much for helping tho
i dont think i set that other than while making the animation clips ... let me check tho
I have done what you said, yet my player collider is still blocking my own player and my enemy cant detect the player, am i doing something wrong.
up mine is set to none and it still works, pretty sure whatever u fixed this had nothing to do with it
i have also set this.
avatars are for skinned meshes only#
and vice versa
there is a setting for raycasts to hit things they begin inside of I think đ€
thats what im trying to avoid đ
pretty sure if u add a layermask it shuldnt be a problem
if its a capsule collider you can move the start to be the radius + some small value?
it is a capsule collider
is that the problem?
use this overloaded version Physics.Raycast(startPos,direction,magnitude,layermask)
all the positions need to be vec3
Nah that just makes it easier to do what I suggested:
Vector3 dir = (end - start).normalized;
start += (radius + 0.01f) * dir;
or fix layer masking if they are seperate
guys im really new to this, i have no idea what any of this means đ
RaycastHit2D ray = Physics2D.Raycast(transform.position, Player.transform.position - transform.position, PlayerLayer);
this is what i have
player layer is the layer masl
mask8
is the enemy layer put into portable layer?
dont do this this will obviously trigger if it hits playercollider
oh.
try this
bool hit=Physics2D.Raycast(transform.position, Player.transform.position - transform.position, PortableLayer);
hit should be true if it hits
ok Thank You!
Okay so how do i manually set the magnitude of gravity in 3d? is there even a way or do i have to implement my own physics system for that?
no for 3d its just useGravity checkbox
set it in the project settings
the "gravity constant" should be set as -9.81 y in physics 3d settings
can i access it from script?
ty !
I am using Animations from Mixamo
is it 3d?
yes
had to make it to Humanoid
No problem, if you're doing animation, you'll get better help there instead of a coding channel . . .
yeah, at first i tought it was a coding problem
is it possible to change the gravity for a particular object only? or is that only possbile for 2d
hi im making a mini golf type game and i want to add bouncers, does anyone know how i can give these bouncers behaviours similar to that of pinball bouncers?
what exactly do u mean by bouncers?
uh is that even possible in 2d?
or do you mean just the scale?
no i mean in 2d each rigidbody 2d component has its own gravity scale
Probably your best bet would be AddExplosionForce, which emenates in a sphere from a specifed location. If it comes from the center of the bumper, it'll push the ball away from the center
....so you do mean just the scale
ya
yeah i don't think there's an equivalent to that, you could disable gravity and do it yourself
For a 3D rigidbody, you'll need to add force manually
welp
in fixedupdate, addforce Physics.gravity * scale
If you want less gravity, add for up. If you want more, add force down
or disable gravity and add it yourself entirely
well adjust based on the fixed time scale cus i presume gravity is m/s
depending on the force mode, time is already factored in
for gravity you'd use force, which does factor time
sorry wrong reply
i should've probably mentioned that this is a 2D top-down game sorry, do you know if there is a 2D equivalent to this because i am getting an error and in the unity docs their example code has a 3D rigidbody
but what direction would i add the force?
for that again i need to know what exactly u mean by bouncers
something like this? (great drawing i know)
drawing coincedence lol
but basically the white circle (the golf ball) collides with the purple ball (the bouncer) and it gets bounced back by some force and into some direction
You can get the dir from ball to bumper and push it the opposite way
well if its a circle u need the reflection angle too
im simplifying it but yea if you really want to be accurate you want the actual normal of where it hit
dont see much difference though đ€
if u want to be able to control where the ball goes then yes u need to be physics specific
if u just reverse the direction of velocity it will always go in the opposite direction
then you can get the dir when it hits and do some random 2d rot like +/- 5 deg?
i wouldnt do this but u can do it for simplicitie's sake
how can i rotate it's dir vector?
how do u even calculate if it +5 or -5? is it random?
float range = 5f;
float randomDeg = Random.Range(-range, range);
dir = Quaterion.Euler(0f, 0f, randomDeg) * dir;
something like this? The concept is to rotate the dir by some small random amount.
idea is there random or not
Guys i really need help organizing my project
so get the reflect vector then add a small random amount to it
I have created enemy object, player object, tree object, and I'm having troubles choosing where to put logic. This is eventually going to be a client -> server game, and right now a low of objects are checking for the raycasts of the player, which I think is the correct thing to do, but Im just not sure how I could send player input to the game objects, or server to be processed.
Like if there are multiple players, how would I put the logic in my project to be checking for their raycasts on all objects within the game
would I create an array of the players and their raycasts or something? or a list?
Also is this the correct thread to ask that question in?
Hey guys, Can someone help me with a code? I spent all day trying to fix it and I just remembered that this server is a thing
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class TextNumberThirst : MonoBehaviour
{
public TextMeshProUGUI counterText; // Reference to the TMP Text UI element
public int counter = 100; // Initial Hunger value
// This method will allow other scripts to add points to the counter
public void AddToCounter(int pointsToAdd)
{
counter += pointsToAdd;
UpdateCounterText(); // Update the text display when the counter changes
// Check if the counter exceeds 100
if (counter > 100)
{
SwitchToScene(5); // Switch to Scene 5 when hunger exceeds 100
}
// Check if the counter is lower than or equal to -1
if (counter <= -1)
{
SwitchToScene(6); // Switch to Scene 6 when hunger drops below 0
}
}
void Start()
{
// Start the countdown process to decrease hunger over time
StartCoroutine(Countdown());
}
IEnumerator Countdown()
{
// The countdown process that decreases hunger over time
while (counter > -1)
{
counter -= 1;
UpdateCounterText();
yield return new WaitForSeconds(0.06f);
}
// Switch to Scene 6 if the counter drops below 0
if (counter <= -1)
{
SwitchToScene(6);
}
}
// Method to update the TMP Text display with the current counter value
void UpdateCounterText()
{
counterText.text = counter.ToString();
}
// Method to switch scenes by index
void SwitchToScene(int sceneIndex)
{
SceneManager.LoadScene(sceneIndex);
}
}
Heres the script, for some reason the TMP doesnt change to -1, and it still switches to Scene 6
Yes I used gpt
can't see the scripts like this, send through links !code
also screenshot inspector for player gameobject and enemy
đ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry i got distracted
RaycastHit2D hit = Physics2D.Raycast(transform.position,directionVector);
if (hit){
Vector2 reflectedVec=Vector2.Reflect(directionVector,hit.normal);
}
if u want to reflect it
the direction of relfection is reflectedVec
all good! ^ ^ thank you, i've figured it out now. thank you for all your help!
Please chat, help a brother out here
while (counter > -1) means it stops before -1 so at 0.
what's the problem
So what shall I do? Change it to 0?
it stops when counter is no longer more than -1. after the loop, counter will be -1
oh shit yea how did i miss that đ
no shit, this is the most overconvoluted broken code I've seen this month
i blame bad ai code for my mistake
The scene changes even if the score isn't even low. (There are things that add up to the number)
"when counter drops below 0"
compares against -1
truly, remarkable quality code
Unfortunately currently it's the only way đ€Ł
rando scene changes happening in the add/remove hunger functions is pretty bad too
The thing is, I have another code that's litteraly the same, and it works perfectly
i mean you're reducing hunger by 1 every 60ms
that's 16.67 per second
your other checks say 100 is the max
so it'll drain in, at most, 6 seconds
I think it's some other code blocking this one, but where is it.... đ€·đ€·đ€·
add breakpoints to the scene changes to see why it happens (use a debugger)
Yeah, there are items that you press to regain the points
Hey, is there any way to debug draw a plane?
Gizmos can draw a mesh solid/wire so maybe that?
nobuilt in way but you can use DrawLine
gizmos and handles can both do it
is no plane, but you could use a thin cube, or i would just use DrawMesh and create the mesh in code
with 4 lines
a plane is just 2 triangles
handles are more complicated but also can be nice if you want it to be interactive
Actually cant you use DrawCube with one axis at size 0?
Can someone help me fix my rigidbody controller, I am on Unity 6 and whenever I release WASD it takes at least a second until my player stops moving. My movedirection is being printed in the bottom left and it seems like its the problem as its taking a long time to update only if I had held any directional key for a little bit already.
This is my code also https://paste.mod.gg/vzgevvygjwzo/0
A tool for sharing your source code with the world!
check the axis settings as it wont reset to 0 instantly unless you change it
are u getting Inputs in FixedUpdate?
You can probably use Raw
ya, use Raw input see if it helps
Thanks ill try it right now
ur movement runs in fixed.. i wouldn't imagine the delay between fixed updates are long enough for it to be that noticeable (updating the speed)
hi, for a weird reason when i click near the player, the bullets are shot with a lower speed, how i can fix this?
{
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 shootDirection = (mouseposition - transform.position).normalized;
GameObject riflebullet = Instantiate(rifle_bullet, transform.position, Quaternion.identity);
riflebullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(shootDirection.x, shootDirection.y) * rifle_bulletspeed;
}```
u can make physics a bit more snappier by lowering the fixed timestep.. but try the raw first
yeah changing it to raw fixed it thanks
when i read it i instantly assumed ur vector wasn't normalized
then i read the code.. and now idk
put the mousePosition.z at 0
like this?
{
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseposition.z = 0;
Vector3 shootDirection = (mouseposition - transform.position).normalized;
GameObject riflebullet = Instantiate(rifle_bullet, transform.position, Quaternion.identity);
riflebullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(shootDirection.x, shootDirection.y) * rifle_bulletspeed;
}```
assuming your player pos is at z 0
it is
