#💻┃code-beginner
1 messages · Page 797 of 1
I want examples because my brain is not braining, I can't think of handling player inputs and a state machine over the network
thank you in advance for the help 🙂
since there are so many updates and stuff happening, having this script on each player would be chaotic...
I can't wrap my head around it
I'm hoping maybe someone can give me pointers as to what in the heck I'm doing wrong here. The enemy is supposed to approach the train when they touch the ground.
As it stands, the code I have is thus
" private void Movement()
{
Vector3 targetRotation;
targetRotation = new Vector3(player.transform.position.x - transform.position.x, 0f, player.transform.position.z - transform.position.z).normalized;
enemyRB.AddForce(Vector3.forward * speed, ForceMode.Impulse);
}"
when I place this inside my fixedUpdate it works as intended. Great.
But when I move it into an if block, it stops working entirely and the enemy just stands there.
effectively this makes it stop working
" private void FixedUpdate()
{
GroundCheck();
if (onGround == true)
{
LookAt();
walkState = true;
Movement();
}
else
{
walkState = false;
}
}"
The groundcheck works. the bool clicks on. I must be making some minor mistake somewhere. Can anyone tell me what I am doing wrong?
!code
if doesnt' work with if onGround being true, its probably not working reliably as you assume / should also test it without LookAt()
📃 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.
I tried removing the look function and also moving the groundcheck to normal Update. Still nada.
I also tried setting onGround to toggle on and off manually, so like, that's still not doing it. It'll look in the correct direction, but the addForce never seems to take.
I halfway wonder if it's because I'm using a wheel collider for the enemy to slide around on, but that should theoretically still work inside an if block.
what do you mean the player has a wheel collider on it?
The skeleton. it has one so it can slide forward and back towards the player.
Other code functions in the IF block. Just not the addforce(Vector3.forward) bit.
thats probably causing issue
Why does it work outside the if block but not inside it?
That's the thing I'm trying to figure out.
Because it functions 100% as intended outside the if statement.
I'm not actually influencing the wheel collider. I'm just adding force to the rigidbody.
the conditions are not met, there is no other cause
if it only works outside if statement, its pretty straight forward
Yeah. I'm just... If it's "If onGround == true" and it doesn't work even if I manually toggle that on and off, the conditions are being met.
where are you toggling it?
Which is the entire problem. It can't be my raycast to groundcheck not working.
In the editor. Also in code. I tried both ways.
put log inside the code itself and double check
Debug.Log($"onGround ? {onGround}");
if (onGround){
Movement();
Yeah. Debug.Log pops up just fine.
yes but whats important is what is it printing before if statement
uncheck Collapse if needed
Collapse? Edit: Oh. Collapse. Got it.
It says it's registering as true.
Yet my movement still doesn't work inside an if block.
send entire code as is now
!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.
Hi, I have a question regarding unity and supabase (or any db hosted services). Basically I need to make a game that makes use of a database, So i created a supabase account and created the db and setup the authetification system. Now to communicate with my service, what do i need to do exactly? Do i need to setup an api, download an sdk or dlls, etc. I am very new to all of this and any help would be greatly appreciated!
Basically what i want to do is retriever a plyer state, which would store player data and scene number
You should only communicate with your database through a server using common methods like REST API
you should never have any information about your database like connection strings inside your unity Game or anything Local
A tool for sharing your source code with the world!
Think I did this correctly. It's a little sloppy. First project and all.
Well, first in Unity anyways.
ok and would you know where i could find documentation about th whole procedure? like how to make a script that would connect to supabase with the proper data, and use the api , and how to setup the api?
there isn't exact documentation generally this is done with accumulated experience knowledge, Id say start with how to create simple WebApp / Rest with .NET core then you simply make the Get/Put requests through Unitys Webrequests
Oh darn it. It was working right. I had the mass on my npc set to a stupid number. Oh I'm so sorry for bothering you. Thank you for taking the time to deal with me not looking at everything in my project.
There's no need for a skeleton to weigh 1000kg.
that mass is crazy high, also kinda threw me off that with same mass you said it was working without if or you changed mass after >?
Yeah. I'm thinking it only worked before because the NPC started spawned in the air and had no friction or resistance so could build momentum before it landed. I had it all messed up!
ye i read the documentation in second link but perhaps i am missing something but i dont find where to like create my own api
but thanks for the extra ressources
the first link / third link for example you create Functions that you can call that do the operations in the second link
thats all the API is, common function that perform an operation
"I want to give player X , 100 credits"
call myappurl/giveCredits?100 with proper verified auth token and do the thing
Hey everyone so im making a top down 2d game in unity and i want to make a simple setup where i can shoot an enemy, he takes damage eventually dies after 10 hits, and he also shoots projectiles to me and damages and can kill me so i have the shooting system for both the player and enemy setup but they arent dealing any damage to eachother for a reminder im a beginner and i have done most of my code with ai help and right now im stuck because even ai doesnt know what the problem is😭 heres a small video of what it looks like so far
so if i get this right, in unity i will only use libraries for networking and io, and use the api, the supabase will do all the work related to the db and authetification right?
in Unity youd only use WebRequest to make common calls like Get request, Post request etc.
the webapp is basically an app running on a server that listens for Auth, Put/Get requests that then handle the Supabase operation such as inserting database entry or modifying it
alright now this makes way more sense omfg
istg all the videos i saw
were talking about installing an sdk
and adding the right dlls and all
even gpt was tweaking
there might be an SDK available for supabase but probably third party..
thanks a lot for clarifying thins man
yep exactly on a github repo
which makes it even more a pain
the point is, you never want to store directly information about your database in unity
anything that lives on the users PC can be decompiled
they would know your databse keys and insert their own data or worse, corrupt / overload it
i mean wouldnt the anon key and the project url be safe to expose?
form what i read only the secret key needs to be kept private
you should have control over it at all times, I would never store any keys locally if it has an SDK that can handle certain things with a public key then its different but you still need proper auth
its less likely that user could get keys if you have those stored on a server app
all they see if they decompile your local project is that you make Get requests etc.. pretty useless to them
true true
well man thanks a lot for ur time fr
i rlly appreciate it
uve been more helpful than anything ive seen lol
np. n goodluck.
Remember to start small, lock in the concepts and slowly go into a bigger scale
start with API with no Database and only stores in memory, then move into doing extenral database talks
Hey nav sorry to bother you but you seem like you know how to programm well any chance you could help me with the problem i have?
the video doesn't work
jus make it mp4
use an mp4
did you use OBS it has built in converter
you can't just google "mkv to mp4 online"?
how do you define a unity input system input map in code?
if i wanted to reference it in start for example
you would construct it, i imagine
ok, do you want to define one, or do you want to declare a variable to reference one
k here
a you have a bunch of console message you seem to be ignoring.
also you have to show code
are your layers set up correctly
normally yeah
im not
whats the usecase what do you mean define action map? you mean reference it ?
wait im so sorry guys i have to go eat i can give all those infos in like 20 minutes ill be back im so sorry again
what do you mean "normally"
is it not set up correctly now?
yea reference my b, in my script i want to disable or enable the action map when in OnEnable ans OnDisable, so i want to tell the script on start what the variable i made is tied to (the action map)
did you generate a c# class for it or no
i think it made a script for it yea
Called PlayerControlls
Player Controll Inputs
im not rly sure
made a script and generated c# class from action map are two different things lol
i am just wondering is there code to reference an action map
so i can disable/enable it
There's no InputActionMapReference, annoyingly
I've thought about trying to make one myself
even if my script that uses input system is disabled, it will continue doing inputs for it
you can, of course, find an action map from an input action asset
you could use InputActionAsset and find it there
I just generate a C# class from it so its easy / type safe
this way you can do
MyCustomActions myCustomActions
myCustomActions = new()
myCustomActions.Enable()
myCustomActions.Player.Shoot etc.
just dont name it anything unity has like common mistake is PlayerInput cause it collides with the component
the script generated by the input asset has a bunch of errors on it
like wat?
are the errors also in unity console
i think it is
why do you have PlayerControllerInputAsset and PlayerController
so which scripts do you want me to show? btw the enemy is a boss
probably the ones that relate to the shooting. / actions to do when projectile collides?
i had a duplicate of the script in another folder
thats probably why it errors
or from another one of the input actions i had made in the past
whoops
@rich adder the script has no errors now, but i am not sure where to go from here
You should be able to access it as regular object like I shown here
#💻┃code-beginner message
okay here:
i think a main problem i have is that my codes a mess?
the big problem is you wrote none of this and let something write slop for you which you understand none of
yeah ik i just dont know how to start
i can understand prob 50 percent of it
you start with learning the basics , then work your knowledge up so you can actually put pieces together you can easily understand
so im not skilled enough to make this game yet right?
put it on pause and start simpler
also i dont understand how is this code that bad like could you give me examples possibly?
alright
where you wrote all the code and know each line
its mainly bad because you wrote none of it and don't undstand what its all doing so debugging will be more diffcult, also you need to check if the gameobjects have the tags that they require
lots of redundant / outdated functions too
okay that makes since I did this because i do the same thing as all beginners i think i can make a big project but end up failing i just dk how to like actually learn and start cuz ive done like 5 of unity's tutorial games and i remember like none of it and i cant code a single thing basically
mm okay makes since
at least you are aware
thats a good step
yeah
haha
if you start small, in no time you will get to bigger projects
if you start big right away, you will crash and burn quick
yeah but the thing is idk how to start cuz like i said ive done like 5 tutorial games from unity and basically learnt nothing so idk what to do to start actually learning
like functions
learn nothing because you most likely didnt practice enough what you just learned, especially on your own without the guidance of the tutorial
You cant / should not move on the next lesson if you didnt practice and can repeat what you learned on your own
okay
okay thats true
how did you start coding?
I started with modding HalfLife with some C++ then realized the same thing (hit limits of low knowledge)
started small with unity and c# and built up knowledge
hihi! hopefully simple to answer, but how would i reference the "source image" field of this component in c#? I'm relatively used to working with gameobjects but haven't done much with UI yet, and need to change the sprite of this section of the UI to display the player's health
every tutorial I find online seems to reference either an older version of unity, or uses a method i can't adapt ^^;
yeah but like which tutorials or whatever did you use? should i try just looking at the functions that exist and try to like make a programm out of them?
the reverse, try to make something and figure out what you need to make that thing
right. Like "How to move an object"
not. "how to make movement like zelda etc."
try to be more generic
ah yeah that'd do it
thank you !
okay
also now they have decent lessons on https://learn.unity.com
when i started it barely existed
okay so like id prob say like doing the thing where you do like tim.deltaTime * speed blablabla is that old code i saw from ai or is that relevant?
and then like xvelocity and y velocity * speed blablabla
once I understood what deltaTime is you more or less know when to use it
in a nutshell its used to give you consistent values between diff framerate speeds
if you did timer += 1 in update, your timer goes up faster on higher FPS
if you did timer += 1 * Time.deltaTime it increases the same speed no matter the fps
deltaTime is the time in seconds it took since the last frame processed
yeah see thats the thing like with C# you cant think normally to move a player for example like you have to think mathematically like u cant just put Player.movement = if w key pressed move forward... right?
you don't have to think mathematically, no
ohhh thats a rlly good way to explain it
c# and unity api / gamedev concepts are kinda different
why do i feel like thats the case then?
you have to think logically, and keep the cyclic nature of Update in mind
oh okay
c# itself is just a tool / language to accomplish something,
Unity gives you API (functions and whatnot) to maniupulate its engine
mmm okay
Update and such are Unity concepts not necessairly c# related
you learn them through the manual
so API is kindof to link the coding and the gamengine to make the code work as functions right?
its a common language you can use to communicate with the backend
ohh thats interesting i thought that was part of C# basically
in this case c# was chosen
its like a telephone number you can dial local to get connected to a bigger system
okay
the original engine is written in c++
so if i want to start learning right now what tutorial or whatever should i do right now?
oh then why doesnt it use c++?
probably because c# is much much easier to pickup
mm okay
do a bit of traditional c# courses + unity specific ones on the https://learn.unity.com/pathways
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
learning traditional c# is important, objects, logic flow, types etc
it seems boring and basic, but pays dividends
okay thank you ill save this
yh thats the hard part
thats the learning curve aspect, but its pretty low not steep
thats why you balance it with unity, so its a bit more fun
rly like as soon as i know the basics i can just pretty easily go up from there u think?
mm okay
yes like anything else, a painter doesnt start with a mona lisa, you have to learn how and when to apply certain tools, brush type, color etc.
yes very true
seeing object move because you learned how to manipulate values is satisfying
yeah for sure
alright well tysm you were an amazing help to me im looking forward to speak to you again if i need any more help
could someone please help me 😭
maybe..try asking a specific question
have you tried like, googling that
yeah
it's a pretty general question, google will have plenty of answers, and it'll be faster and easier than asking and waiting tbh
package manager -> remove package
if it's locked, it can't be removed because some other package is using it
you're doing multiplayer but don't know how package manager works, ouch
:[
hey so nav can you make like mods for games or like plugins for any game with C#?
i am struggling to get the input action maps to actually disable when i have the script referenced in my code, I have the script referenced in my code (1st image) and then when the script is disabled/enabled it should turn the input maps on and off right? am i doing something wrong?
movement is my action map
first I'd put logs to see if that part of the code is even running
just tried it and when it was disabled it did put a log
idk why it wont disable my input map, it so confusing
i have an action that involves clicking but it still lets me do it even with script disabled
is the clicking action in the Movement map ?
and where in the code are you using this map
in a script called movement, i have a function for each action that gets the inputs and makes player move/jump/dash
that is also the script where i enable and disable the stuff, should i make it seperate perhaps?
if you planning on disabling / enabling on demand you should track in one spot
i do have two states that the player can be in (normal 2d controls a powerup that changes controls), so maybe i could put that in the script that deals with swapping states?
You could always verify that the actionamp is enabled / disabled with a log as well
Debug.Log($"is movement enabled ? {PlayerControllerScript.Movement.enabled}");
verify its actually disabling it when you do / before using it
probably. you should also show where you utilize these actions in code
make sure you're linking the correct map
i found a dumb way to do it
i just disable the player input component
baboom
idk if thats a good way to do it tho
you were using PlayerInput in the first place ?
is that a bad idea to use the player input component?
its not but you should not use both
you shouldn't be mixing them thats prob why you got odd results
wait i am confused
if you already have a generated class from the ActionMap, you don't need the PlayerInput component at all
PlayerInput is mainly used if you use Inspector to link Actions or/ using the SendMessages modes
ok so wait, if i am using the player input component on my player object, should i not worry about using the script generated from the action asset
or should i get rid of player input component and change how my player controls work? i have been using that to get my controls, by adding events that are triggered by code
like I said use one or the other, the whole point of a generated class is to skip using the inspector and you already have type safe properties like
Movement.Jump would show up in code
your IDE doesn't look configured peoperly ? are you even getting the intellisense suggestions
yea im not sure, how can i set up the intellisense stuff correctly
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
i think im gonna stick to the player input component
Hi, trying to make a track which is flat and goes around in 1 loop but this little junctions keeps happening. Could anyone help me? Thanks in advance.
Put yourself in a wheel and roll until you being to see it go in a spiral.
Has the image component changed? Why do I have to manually set my assets to 2d sprite?
not a code question.
and they made it sprite- multiple for default sprites so dragging the root in a sprite field doesn't work, you need to change it back to single
what
Wait what?
It's sarcasm.
this is a help channel
Oh 😂 yeah I am kinda fried been at this for some time 😂😂😂
if you are going to comment on someones issue try to actually help
So I finally have the slam ability setup but I have this issue where sometimes when using the normal slam its not going as fast as its suppose to so sometimes its fast sometimes its slow.
are you cancelling your vertical velocity before the slam happens?
if youre still moving up when you decide to slam it could counteract the downward force causing it to be slower
youre not i just checked
do that and see if the issue persists
Yes in my playermovement script I got
{
Vector3 v = rb.linearVelocity;
v.y = 0f;
rb.linearVelocity = v;
rb.AddForce(doubleJump * Vector3.up, ForceMode.Impulse);
doubleJumpUsed = true;
} ```
isnt this just for your jump?
Yes just for the jump just confused at this point.
how do you do the highlight?
asset store
then it has nothing to do with your current issue
and you should try doing what i suggested
you also dont have to overcomplicate it like you did it in your jump script, im pretty sure you can just do
rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);
add this to both of your slam methods.
also why are your slams 2 seperate functions at all?
Just found it easier one is for when your high = stronger slam and the other is when your not high = weaker slam
you should keep it as a single function and just parameterize it
Is there a good tutorial going over the in-engine variables (object parameters and such) and going into detail on how to find and use them?
That sounds extremely vague.
"in-engine variables (object parameters and such)" is way too vague to be meaningful
It is extremely vague, yes. I'm kind of taking a shot in the dark.
Let me try to narrow it down...
Can you explain what you're trying to do? Just learn to be comfortable programming in Unity?
Have you looked at !learn?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You have bad spline segments
Yes. Problem is, I have no idea what I'm actually looking for and I don't really want to skim through 'over 750 hours' of stuff to figure it out.
So let me see if I can try and get an example of where I'm stuck...
here's an example of this sort of thing in Blender
You don't skim through all of it. Start with the junior programmer pathway to get familiar with the basics of scripting
this happens because the two nearby spline points have very large weights
they both want to push the spline very hard
so it kinks up
So, I know 'the basics of scripting'. I have an associate's degree in programming. (And then I never got a job because I live in the middle of nowhere and was unable to compete for remote work and am now about two years rusty, minus some playing around on CodeWars to keep a modicum of basic skill up)
My problem is, I don't know how to, say, get the variables that govern the size of a game object into a script so that I can then have it make another game object change in size proportionally whenever that first object's size is changed.
the junior programmer pathway isnt just there to teach you coding, if youre new to unity you still stand to benefit from watching them
as they will teach you unity specific stuff* like this
(It's arguable exactly how much that 'keeping up a modicum of basic skill' actually worked, but here we are)
but other than that what you are actually looking for is the unity api
you should check out the documentation – both the manual and the scripting API
you also still need to learn to use the editor itself
for example, this explains what GameObjects are and how they work – including Transforms
you can then consult the scripting API to learn about how to interact with these things https://docs.unity3d.com/ScriptReference/Transform.html
"Size of a gameobject" is also pretty vague, but in general you're going to need to look up all these specific things whenever you need them until you get used to them. becasue there are literally thousands of components and variables. You can't just read them all and learn them. The best way to learn is to look them up as needed and you'll get familiar with the ones you use a lot
But "size of a gameobject" could mean anything from its scale, to the extents of its renderer bounds, to something custom in the context of a particular game
I believe what they're asking is literally being able to attach a setter to the transform component
sounds like you're mostly looking for Transform.localScale here
I've actually been vaguely curious about a tangentially related topic myself. Not nessicarily in response to any problem, but how extensible is Unity?
Being closed source and all. I've seen some interesting prospects of plugging into the physics engine, but nothing beyond that
The "core" of Unity is closed-source C++
Scale is what I was referring to. Please forgive me, I'm mildly stressed out by the fact that I'm having as much trouble as I am.
Thank you for the help so far. I at least feel like I have an idea of where to work from now.
very extensible, depending on your definition of extensible
Many of its features are implemented in packages, which are mostly C#
for example, UGUI (the Canvas-based UI system) is all in a package you can go look at and modify
I see
The core stuff is a bunch of thin C# wrappers that call into native engine code
guys i am trying to make multiplayer into my game and its really just messing it up. i decided to have copilot help me with this but i can t get a sync correctly andd everytime i get copilot to try and fix it i feel like it makes me code really bad. anyway thats something i have to manually fix laster going throught all the code to see what bs it did but now what i want is some help to sync it correctly so the game can work. i have been at this for 5 hours i really need help would appreciate a call
theres no voice channels here, if you need help you should share what you did, what you are trying to do, any relevant code etc.
be as detailed as possible
you should also probably take this to #1390346492019212368
i don t know what i should send. also maybe something is wrong in my unity side .
Start a thread, share you scene setup, objects, components, then code involved in the multiplayer and syncing. Then screenshots or video of the issue and explanation of the steps you took to debug it.
Hey, why can't I make a list of a struict?
Why not what's stopping you
I get an error CS0308
show your code
Why did it disappear ><
No one remembers errors by their code. Stop being lazy and paste the whole thing.
📃 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.
probably just took a little to refresh
How would one use OnPointerEnter?
Cause im trying to add a visual upgrade system that pauses the game (Sets timescale to 0 after a level up). Ive done it but I can't seem to well. im using oncollision enter and the pointer handler thing for the script isnt working
hard to explain
for me atleast
What does OnPointerEnter require
wdym?
Unity's docs have no matches with OnPointerEnter are you certain it's a thing? (i swear i've heard the thing but like there are no docs for it), also i think they mean what is the interface it's from
There is in the ui package docs.
You need the IPointerEnterHandler interface
how would I get it?
You need to implement the interface. Similar to marking a class inheritance
Make sure your class implements it. How did you even get to that code without knowing about the interface?
it didnt tell me :p
Who??
is this a different doc then the scripting api?
public class MySuperCoolClass : MonoBehaviour, IPointerEnterHandler
I did that in the screenshot
now you need to correctly implement the method
Yeah, packages have their own docs that are not indexed very well in Google. Try searching for unity ui package docs.
it's just an error for me. And the method doesnt show up
i did not know this, thought it was all in scripting api :/
wdym "the method doesn't show up"?
Nope. That one mostly only includes the core api.
This is normal. It means you need to implement the method
So I just type it in myself?
The error is telling you you have implemented the interface but have not implemented its requirements
it's not a member of the inherited class. just right click the interface name and use the quick actions to implement it
Man I needa learn unitys particle system badly
alright
OHH
I SEE WHAT YOU MEAN
Now imma hope this actually works :p
interesting i found it but it seems deprecated no? the last version to have any documentation on it was 2023.2
it's in the UI package docs because it comes from the UI package
It's 3.0. Check 2.0. It's the same version since 2019.2.
3.0 was probably a discarded experimental version.
yes that matters. if this is a UI object it needs a graphic to work. if it is world space it needs a collider
I figured out why I just dunno how to fix it without removing the crosshair
it works I just need to remove the crosshair
make sure your crosshair is not a raycast target
question, how long have you been programming for?
random unity encounter???
it's pointless to check if color is null because Color is a struct. the expression will always be true . . .
my fault
love your name btw
i used to change it more often, depending on the season, but it was RandomUnityXXX . . .
"XXX" was replaced with smth different, but this has stuck for a while . . .
it used to be ... but they gave me an upgrade to . . .
you'll find smth that fits. give it time . . .
Hey im new to game development and i just for the life of me figure out how to make a slide function for pistols and if anyone can help me out a bit heres the code of one version out of many of my attempts
using UnityEngine;
public class SlideRack : MonoBehaviour
{
private Vector3 startLocalPos; // husker startposition
private Quaternion startLocalRot; // husker rotation
public float slideLimit = 0.2f; // hvor langt ned X kan trækkes
private Transform grabTransform;
void Start()
{
startLocalPos = transform.localPosition;
startLocalRot = transform.localRotation;
}
void LateUpdate()
{
// Lås rotation
transform.localRotation = startLocalRot;
// Lås Y/Z og kun bevæg X
Vector3 pos = transform.localPosition;
pos.y = startLocalPos.y;
pos.z = startLocalPos.z;
if (grabTransform != null)
{
// Håndens position i parent-local-space
Vector3 handLocal = transform.parent.InverseTransformPoint(grabTransform.position);
// Kun X, clamp mellem start og start - slideLimit
pos.x = Mathf.Clamp(handLocal.x, startLocalPos.x - slideLimit, startLocalPos.x);
}
transform.localPosition = pos;
}
// Kald dette når hånden griber objektet
public void Grab(Transform hand)
{
grabTransform = hand;
}
// Kald dette når hånden slipper objektet
public void Release()
{
grabTransform = null;
}
}
it tells you where the point is in relation to this object.
basically it translate world space x,y and z too local space of an object
Yeah this just tells me that I needa learn more stuff
is there anything wrong with my code it didnt work when i press d
oh
we dont use that anymore. I think you can enable the use of it again
but we use
hold on
this stuff now
and this
But I am sure you can definintly re enable the old one
im not sure though
what to do then?
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
ty ill ty
what to do now
hold on I was doing something
ok
i apply both so i can use both old and new type?
if you want
then click apply at the bottom
dont forget that. Idek if it reminds you
it restarted when i did
ty for tell i am struck there for 3 days
if u dont mind can u tell differ b/w = and ==
= is used to assign something
==
is checking if the variable is equal to whats on the right side
if == false what is the point of writing it down
you can use it for other things like
if (integer == 1)
{
Do this
}
For bool variables you can just do
if (boolVariable) - Checks if true
if (!boolVariable) - Checks if false
ok one more thing where can i learn code
oh
Well.
Idrk?
So its either you learn it from Unity Learn
which is useful
watch youtube videos, look at other peoples codes and searching up what they used and how they used it
its a bit. Weird if you dont have a school program for it
I do, they just dont teach C# :p
or an online course.
Like Code4Fun
clearly lied here by accident 😭
ill try those sources ty
when generating terrain with fractal noise how do i interpolate between noise samples? when i do linear interp the terrain looks low quality cause its just a bunch of squares and i cant use bicubic because it creates wavy terrain
using UnityEngine;
public class paddlecontroller : MonoBehaviour
{
public Rigidbody2D padrb;
public float speed;
private float paddleInput = Input.GetAxis("Vertical");
void Start()
{
}
void Update()
{
padrb.linearVelocityY = paddleInput * speed * Time.deltaTime;
}
}
Why doesn't this make my paddle move
I have no idea what I'm doing
you need to continuously read the input. in update, assign the paddleInput to Input.GetAxis("Vertical");.
Also, I don't think you want to multiply the speed by deltaTime here. Often you want but in this case linearVelocity is already velocity in units/second and unity makes sure the object actually moves at that fixed speed regardless of the framerate. Multiplying by deltaTime here would do the opposite of what you want, it will make the object move at different speeds with different framerates
Thank you it works
I made an Enemy script moving by following a path , after reaching each "Waypoint" , it will check if the relative distance between the enemy and the waypoint is 0 , if it is 0 and it isn't the last waypoint, it will keep moving.
It has been working super fine until now , for some reason the relative distance appeared that number whenever the Enemy reached SECOND waypoint. It's not even the first . I can't find a way to bybass it , I don't even understand what it is.
I use a spawner to spawn waves of enemies , which have been working fine until this happens . It also should be noted that if I drop a prefab of the enemy into the scene, its moving code work just fine. So I think it's a problem with the spawner, which I don't understand what it is since it's only job is to spawn stuff.
Pls help, im dying
This is the moving script
Is this a bug, or did I do something stupid
Please help aaaaaaaa
That number is close to 0. You should never use == with float numbers, as they are never 100% precise. You can use something like mathf.approximately
THANK YOU, IT WORKS
hey so I was trying to edit the bloom.active variable using a script to enable/disable bloom at runtime. toggling it via inspector in editor mode works fine, but as soon as i start play mode - even using inspector doesn't do anything.
i use volume.profile.TryGet<Bloom>(out bloom); in Start() method to get the bloom value out from the Volume volume component and then edit it via bloom.active = true/false. I can see the changes to the variable in inspector (aka the box ticks off) but it has no effect on the game itself.
BUT when I remove the TryGet line entirely - suddenly I can edit the bloom and all other post-processing effects in inspector in play mode. what's going on? all tutorials use this structure and i have no idea why i it doesn't work for me specifically
Show your entire script best case
public Volume volume;
private Bloom bloom;
void Start()
{
volume.profile = Instantiate(volume.sharedProfile);
volume.profile.TryGet<Bloom>(out bloom);
}
void BloomSetting()
{
bloom.active = false;
}```
its really nothing special
bloom starts turned ON and i just try to turn it OFF
i also tried the version without volume.profile = Instantiate(volume.sharedProfile) to no avial
it looked like this:
public Volume volume;
private Bloom bloom;
void Start()
{
volume.profile.TryGet<Bloom>(out bloom);
}
void BloomSetting()
{
bloom.active = false;
}```
and you dont get any errors?
no
hm actually i do
NullReferenceException: Object reference not set to an instance of an object
well, your bloom is not working getting returned but you access it I guess
you can use the tryget inside an if statement to check, if the out is actually delivered
the bloom should be the one in your volume profile
Bloom is out! Bloom(Clone) (UnityEngine.Rendering.Universal.Bloom)
UnityEngine.Debug:Log (object)
the bloom IS getting disabled but it has no effect on the game
bloom is still active
if i remove the TryGet then i can change the bloom in inspector just fine
but with TryGet - i cant even do that
i also fixed this error, so it has nothing to do with it
Then I guess the error might be, that your bloom is not the correct one. Its targeting not the instantiated profile
which script are you using now. The instantiated or the simple one?
also curious, you said, when you remove the tryget entirely. But are you still assigning a new profile to the volume in the line above?
i dont understand what you're asking
but it changes in the inspector?
right here. when i remove tryget i can change it in play mode just fine
manually in inspector not through code
And the line volume.profile = Instantiat eis still present?
i tested with and without
same result
When is BloomSetting() called?
hi can you use gameObject.activeSelf to check if scripts on game objects are active too? or is it only for the actual game object itself?
If the gameobject is not active, scripts arent either (in terms of the unity game loop)
when i press a button
what happens if you try inside the method
if(volume.profile.TryGet(out bloomComp))
bloomComp.enabled = !bloomComp.enabled;
else
Debug.Log("No bloom");
Not tested the code, if there are any typos 😄
nope
does not work
also its .active not .enabled 😅
Active should be referring to a game object rather than a component. Bloom would be a component and use enable?
well ill be damned but intellisense says otherwise
'Bloom' does not contain a definition for 'enabled' and no accessible extension method 'enabled' accepting a first argument of type 'Bloom' could be found (are you missing a using directive or an assembly reference?)CS1061
Guess it might be active for the specific volume component
https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@8.0/api/UnityEngine.Rendering.VolumeComponent.html
It's not a component, more like a component of a component. The actual component to enable is the Volume, but the Volume Profiles are their own individual thing that doesn't have any conventions to follow
Hey im missing something, im following https://learn.unity.com/pathway/junior-programmer/unit/basic-gameplay/tutorial/lesson-2-1-player-positioning?version=6.0 and im at step 7, but it doesnt work anymore?
using Unity.Mathematics;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float horizontalInput;
public float speed = 10.0f;
public float xRange = 25.0f;
public GameObject projectilePrefab;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.position.x < -xRange)
{
transform.position = new Vector3(-xRange ,transform.position.y, transform.position.z);
}
if (transform.position.x > xRange)
{
transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
}
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
}
}
}
``` its trying to move but keeps getting stuck at 0 0 0, and when trying to move the max position is gonna be -0.1
what did I do wrong?
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
what did you set xRange in inspector as ?
try higher number
at the player its at 10 but will try 40
so you put it to 10 and its not moving at all ?
now it works but now the border isnt working as I can go futher t hen 25.
And why does it work on 40 and not on 10?
no its trying to move but when I dont press a button anymore it still on 0.0.0
xRange is the border... if you set it to 40 then you can go up to 40
The number 25 in the code is the default. The value you put in the inspector is what it uses
check thanks
is it possible to do something like GetComponent<(Image || CustomImage)>().value as long as both of them have the value field?
no, C# doesn't have union types in that way.
the type system is nominal, not structural
they'd need a common parent that has that field
I see, thank you!
Hey guys, I'm trying to apply the new Input System to some old navmesh tutorials. I've been through a lot of the documentation regarding the new Input system, I've checked previous posts on reddit and the Unity site and even searched for an answer in the Discord chat here. I saw someone using these .performed/.started/.canceled methods with their input controller, but mine don't seem to have a definition for it.
I've messed around with the input actions editor a bit to see if I could find anywhere that these methods were mentioned, which didn't work. In the example given, they also didn't provide any other context other than "this will work", so I don't really have any other key information to google at this point.
Is anyone able to shed some light on these by any chance? Cheers, tried to provide as much context as possible!
You need to generate a C# class from the asset to be able to see the type-safe names on the right
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/manual/ActionAssets.html#type-safe-c-api-generation
hi guys, have a very generic question
how can i make track for bike racing type game. if possible please share some resource, i couldn't find proper resources
in what sense? mesh ? checkpoints?
what exactly are you talking about, this is a coding question?
You can use common methods like Spline tools, unity has one built in or get an asset purposefully built for roads
in sense of large map.
i am making road rash type game, where map can large and will have many obstacles in between. like tyres, pedestrian, cars, baricade, animals, carts etc etc.
do i have to manually place all of these objects in the map?
Yikes, there goes about 1.5 hours I'll never get back when the answer was right there 😄 Thanks a lot! I hadn't added a Player Input component😅
also thinking about, how the unity will render such a large map? does unity automatically takes care of optimization?
Player Input component doesn't make it look like the screenshot on the right you sent. Just to be clear its a separate use than fully "in-code"
it uses inspector
depends, some games will want this to be consistent and manually built
some games will generate them with randomness or some randomness but still predictable
You have to code these in, and there is minimal optimizations for objects not in view but thats about it, the rest must be optimized by you
road redemption is made in Unity so its totally doable
thats the closest I've seen to a road rash clone
You were correct, it was actually that I had missed the layer reference entirely in one of the places, thanks again!
cool, how does this sound? will make the track, trees and other static object will places on map.
dynamic objects like cars, pedestrian will spawn based on certain distance from bike and destroy accordingly
correct me if you can think of a better idea
sure, if you want to make it a bit more "complex"
Unity has splines tool like I mentioned, you can actually get the points on this spline so you could technically create incoming traffic, obstacles etc. on the fly
its usually the "middle" part so you can kinda figure in the width of each lane / road itself to get more accurate / consistent result
cool thanks,

basic ointro + sample unity includes for roads
https://youtu.be/FbSvEieELXo
more complex code/parts like figuring points on the road etc.
https://youtu.be/ZiHH_BvjoGk?t=328
Let's learn how to make Roads using (Custom Mesh) in Unity using the Unity Splines Package!
Get my Spline Mesh Package (It's FREE) 👇
https://github.com/AnanD3V/SplineMeshUnity
****** IMPORTANT ******
⚠ A BIG UPDATE has been made to the package ⚠
You can now download the Git version of the package, and install it directly from the Pack...
Roads are more common in videogames than you might think so in this episode we'll look at how we can use Unity's new spline package to build out a tool that procedurally creates a road mesh along a spline, and ALSO handles intersections at the same time. While we're at it, we might even decorate it to look pretty using URP Decals too!
Get the p...
Hello, I'm trying to build a tree, how can I do that? I was trying to make a recursive struct but that doesn't work
How does a gameobject can contain another gameobject as a field for instance
You can use whatever component is on that other GameObject as the type, or just use GameObject
{
Node node;
}
public struct NodeStruct
{
NodeStruct node;
}```
Why does the first one work but not the second one?
because structs are value types
it has no idea what size it needs to store it, reference types you're storing a pointer and they generally have a set size
computer: How big is NodeStruct?
answer: It needs the size of node,
But node is another NodeStruct
which contains another NodeStruct
which contains another NodeStruct
… forever, so needs infinite size
Ok thanks a lot that makes sense
To understand recursion, you must first understand recursion 😉
Oh I have a meme for this but can’t post it here
thank god there are loops
hi is 1f from Time.deltaTime actually equal to 1 real world second?
cuz it feels way slower for some reason
Yolo
It should pretty much be real close
its in seconds yes but you probably take into account discrepancies, you're still at mercy of speed inside the engine
It'll be scaled by the timescale too, but otherwise yes if timescale is 1 then adding deltaTime to something until it reaches 1 will be approximately 1 second (with some very slight variance based on framerate)
And electro gremlins

notably, if the game hitches for long enough, Time.deltaTime is clamped
the default limit is 1/3 of a second
that's probably not causing issues for you, though
I thought that 1/3 second cap only applied to physics but that seems to similarly apply to max value for deltaTime. Makes some sense, but the tooltip and documentation weirdly enough only talk about physics there. One of those poorly documented features
the actual docs are good https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Time-maximumDeltaTime.html
Oh, I only checked the Time settings one from the manual side. I honestly didn't even know of that value, of course it has to be named differently too MaximumAllowedTimestep = MaximumDeltaTime. https://docs.unity3d.com/6000.3/Documentation/Manual/class-TimeManager.html
No links or mentions of the Scripting API equivalent
im having a really annoying issue with my 2D platformer, im trying to get a drilling mechanic working correctly. Basically when my character dashes it makes a hitbox that when coming into contact with surfaces on a certain layer, you enter a drill mode that toggles another hitbox that waits for OntriggerExit2D to detect if that collider has exited. Randomly my drill mode instantly swaps me back to my normal 2D platformer controls when entering a surface and i have been trying to find the solution for ages
if any coding genuises would be okay with potentially getting into a voice call and i could screenshare id be okay with that, i feel it would be hard to get help with just images
we don't do vc's here, it would negate the benefits of having a community server to begin with
you can share screen recordings to show your issue if needed
i won't be free in a few mins, so just some general tips - play around with the mechanic a lot in various scenarios, different terrain, different angles if that's a factor, etc - try to find what the common denominator is, to then reliably reproduce the issue
from there, debug to see why the issue is occuring, possibly drawing debug or gizmo stuff to make sure stuff is lining up as it should
Log the collider that's being exited in the OnTriggerExit2D method
Maybe you're exiting a collider that you didn't expect to be there
The bug could depend on how many frames you get between each physics update (by defualt, physics runs 50 times per second)
📃 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.
I see that you set swappingStates to true until the next fixed update. You aren't currently doing anything with that variable
my first suspicion is that the drill and dash colliders don't quite match
i noticed that you instantly exited drill mode while moving upwards
If you want to check if every element matches, you can either:
- iterate over them and compare each element
- use LINQ
nooo the question vanished
int[] foo = new int[] { 1, 2, 3 };
if (foo.SequenceEqual(new int[] { 4, 5, 6 }))
{
}
here's an example of using LINQ; it provides the SequenceEqual method
comparing for exact equality wouldn't be useful, since it'd just tell you if they were the same array
(i think, at least; i haven't really thought about the array equality operator before...)
also, the reason you got an error was that {1, 2, 3, 4, 5} isn't an array: it's syntax used when constructing an array
but it's not valid on its own
Newer versions of C# do have array literals, like this:
int[] foo = [1, 2, 3];
but not the version that Unity uses
can u ellaborate on dis?
also does ontriggerexit tend to trigger twice perhaps?
no, it only runs once each time a pair of colliders stop overlapping
i'm wondering if the drill collider is briefly exiting the ground as you enter drill mode
okay wait i just found something out
i can send clip
i realized that the drill always fails when the exit collider is positioned at the direction of the surface you drill into
at the start of the game the drillcollider is in the center of the player but after one time it always is where it last was upon exciting a drill mode
could that be important?
the green circle on the right side if the collidr
ok im testing it a bunch and that is for sure the issue or one of them
i am confudsed why it causes issues
is it because first frame is outside of wall? before hitbox is positioned to front
this is gonna drive me craaaazy
i think stuff breaks when the collider for drill and movement are overlapping upon entering drill state
but i dont know what to do to fix it, its just one gets enabled and one disabled simple as
i feel youuur paaain
the wonders of programming :]
is it possible that there's more than one collider causing trigger-exits for the DrillCollider?
annoyingly, trigger messages don't tell you what your collider was
only the other collider
how can I use the variable float speed = 0.1f; for the X value in transform.position += new Vector3(0.1f, 0, 0);?
I'm not sure how this works in 2D physics. In 3D physics, if an object has a Rigidbody, it receives trigger messages caused by child colliders
just plug it in!
the Vector3 constructor takes 3 float values
those can be literals (0.1f) or variables (speed)
but it gives me the error "Assets\Movement.cs(4,7): error CS0116: A namespace cannot directly contain members such as fields or methods"
line 4 defines the variable
it shouldnt be since its only on a script that is on a child object of the player object
What does line 4 look like
float speed = 0.1f;
Did you actually put it inside the class
fields are declared inside of a class, yes
I'm trying to make a type of node for mining which have a class that essentialy boils down to
class Node{
string nodeName;
int extractionValue;
int extractionSpeed;
}```
now this class is called in anothere monoBehaviour Object to make an instance of it
```C#
class MiningNode : Monobehaviour{
Node node;
//rest of code
}```
I want to manually set the nodes in the world, how can I manually give each object of the MiningNode prefab have different values in the node objeect through the editor?
would scriptableObjects be a better fit for this?
im trying and trying and there is a slight change i might have found the issue, its the drill collider that is causing issues somehow but i dont know how
scriptable objects would help if you were reusing the same node across different mining nodes for sure. it'd be better organized as well
otherwise you just assign the values of node in the inspector as normal, make everything here serializable
yeah – use a ScriptableObject if different prefabs can meaningfully refer to the same set of data
it'd be the same "node" class but the object itself (like the mesh, the view, animations, along with values) are going to be different
in this case, I feel like each prefab is going to have a completely unrelated set of mining data
yeah they have different values but use the same class
but if there's like 3 iron nodes they would all use the same everything
so 3 iron nodes with different visuals, but the same node values right?
then for sure make that node class a scriptable object
oh i think i misread
the 3 iron nodes would have the same visuals and same nodes, they are the same
but 3 nodes say iron, gold, diamond, would all hold different values
it doesnt sound like you'd really gain or lose anything here making it a scriptable object regardless
even if there's a direct 1 to 1 relationship between prefab and instance of this node SO. I like making things like this an SO just cause it's cleaner to see in github tbh
I see
thanks for the insight
I am finding Unity's rules for physics increasingly nonsensical.
A Collider2D.Cast can't collide with things that don't have a RigidBody2D component. This is somewhat sensical.
But if the GameObject that HAS the collider has a RigidBody2D component, now suddenly it CAN collide with things that don't have a RigidBody2D component?
What is the logical throughline here I am missing
Rigidbody is the component that actually calls the physics engine. If there's no Rigidbody involved no one has access to the physics engine for collision detection.
Whenever any sort of collision happens, each object has a reference to the other, so either one can have the Rigidbody on it
The physics engine knows about all of its rigidbodies, and can basically ask "okay any of my rbs getting hit by something? No? Any of em doing the hitting? Ah, okay cool"
okay... Well this sort of proves a problem for me, because I'm trying to create Pong, and there's not a RigidBody2D mode that give me enough control to accurately recreate Pong
so I simply made a Ball that doesn't use RigidBody2D
Then you're going to need to do your collision detection without the physics engine using primitive shape casts
Or use a kinematic Rigidbody that you have full control over
the ball works fine, but then I went to add triggers, realized that they can't detect the ball and said "ah fuck it well surely just having an inert one wouldn't affect any existing bahviour, right? Maybe?" And then it did
A Collider2D.Cast can't collide with things that don't have a RigidBody2D component.
Are you sure it's not the other way around? The documentation suggests that the object with the Collider2D also needs a Rigidbody2D to be attached to it
nope doesn't need one
or I've been hallucinating that my project works this entire time lmao
Kinematic provided me with unsatisfactory results. It penetrates other kinematics and statics, which wouldn't be AS big a deal if it didn't also collide with things behind the things it penetrates
it also can't be made to move programmatically
That's literally what it's for
A kinematic rigidbody is unaffected by forces and only moves when you explicitly tell it to in code
it's unaffected by forces, yes. But it seems to move exactly once every FixedUpdate and there isn't a method to force it to move
at least that I found
I could be wrong. My research wasn't during the hours of the day when one is completely clearminded
wait, no, I think there was a slide method
Well, yes. Every physics object moves once every FixedUpdate.
but a slide isn't what I need
If unhappy with the physics time step increase it
And you "force" it to move by calling MovePosition
Oh?
How's that work
📖 read da docs
it collides with things between where it currently is and the target of the MovePosition?
That's literally the way you're supposed to move a kinematic rigidbody
If you did anything but that, then you weren't actually using a Kinematic rigidbody
yes it seems to do exactly that
I see... What a strangely named method
let me double check that this is usable for me
Mmm. Is GetContacts only for overlaps or is it anything that the MovePosition Collided with last fixed update?
since it seems to still penetrate statics
but I might be able to give this another shot
assuming collisions are ordered sensibly...
I moved a gameobject with a box collider into a parent and the animation for the collider is broken. Is there a way to tell unity where it is or do I have to redo the keyframes all over again?
You can correct the names in the animation window. Select a yellow one and press F2
Then correct the "Gameobject path"
Oh nice thank you
@swift crag i fixed it!!!
took SO LONG
mostly fixed
still a bit buggy but its not deadass random
The main issue was the usage of ontriggerenter/exit2D
when the collider is teleported (so basically every fixedupdate for the drill collider) it will trigger the enter/exit
i also abandoned using tags to detect in/out and switched to using fixed update for both colliders and detecting a layer on a child object of the ground instead
ok its not fully fixed but it works because it starts drill -> cancles -> starts again so it works in a goofy way
will def have to solve that
can someone check the scripts ive written for my enemy? this is my first project so im not rlly sure if this is the correct way to do stuff since I have 5 scripts and 5 children for a simple enemy that just patrols, follows the player in a straight line if in sight and attacks if close enough
idk if should send them here since theyre long and theres 5 of them
this is 2d btw
if you send them then someone might help
alr i js wasnt sure if i should send it here since its a lot
this is what my hierarchy looks like
i feel like what ive done is a rlly suboptimal way to do it and i dont want to develop bad practices for future projects
It's fine as long as you share it correctly:
There's no command called
vode.
!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.
At the very least EnemyTopFlip and EnemyBottomFlip don't need to be separate scripts
they do almost entirely the same thing
i tried combining them but then i got problems where it would just break because one should only activate on trigger enters and one should only on exits, but if i combine them they both happen
but maybe i was js doing it wrong
am i correct about this If i use Physics2d.Raycast the raycast wont be scene isolated it will raycast through all scenes but if i save a reference to the scene and call it isolatedscene then do isolatedscene.Raycast then will it be scene isolated?
for that you need to grab the PhysicsScene not the regular Scene
so just do something like this ? Scene currentScene = gameObject.scene; and isolatedscene = currentScene.GetPhysicsScene(); will it work with my physics simulator object thats in my scene that has this script on it ```public class PhysicsSimulator2D : MonoBehaviour
{
private PhysicsScene2D _physicsScene2D;
private void Start()
{
Scene currentScene = gameObject.scene;
_physicsScene2D = currentScene.GetPhysicsScene2D();
Debug.Log($"PhysicsSimulator2D started in scene {currentScene.name}");
}
private void FixedUpdate()
{
if (_physicsScene2D.IsValid())
{
_physicsScene2D.Simulate(Time.fixedDeltaTime);
}
}
}```
did you try it ? should work unless maybe you have to switch sim mode to script instead
ill look into script mode thanks
ya still fuzzy on that but maybe for additional scene you might not even need to worry about that..
I think that setting only affects default scene?
Idk if this is "beginner" exactly but i had a query for you wizards.
What would be an effective way to make swappable abilitys
RIght now im running code through scriptable objects that i can drag and drop into my "ability slot" for whatever ability i want to be using.
but my abilities are more complicated then i hoped.
What is the standard approach
Abstract class for ability that every ability devives from? then i just drag and drop the ability component into my object, and remove the old ability?
Im not sure
that doesn't sound super great for doing at runtime
keep in mind your SOs can also have methods
Give requirements
They don't need to derive from a base, but you do need some sort of abstract method that they all share at least.
if only unity had code backups. i went and made a window manager and it crashes the game and editor with no visible errors when i click the chat 🤦♂️
that's what version control is for.
but also, if i had to guess you probably have an infinite loop or infinite recursion somewhere
yeah i did an if statement and it fixed the crash, but it's still not working properly
if you want help then you'll need to be more specific than "not working properly" and you'll have to provide relevant context
i will when i know more
Calling the console "chat" is very cursed
Setting the console to emote only mode
"Oh huh, I don't think that's supposed to be happening. Chat, is this real?"
215 errors
yeah never do it (doing it at least 2,149 times)
@dusty umbra Please don't post off-topic images
Sure my bad
public class GyroUI : MonoBehaviour
{
[SerializeField] private float shiftModifier = 10f;
private Gyroscope gyro;
private RectTransform rectTransform;
private Vector2 startPos;
void Start()
{
gyro = Input.gyro;
gyro.enabled = true;
rectTransform = GetComponent<RectTransform>();
startPos = rectTransform.anchoredPosition;
}
void Update()
{
float x = gyro.rotationRateUnbiased.y * shiftModifier;
rectTransform.anchoredPosition = startPos + new Vector2(x, 0f);
}
}
I want to have a parallax effect when i build this game on my device, but i dont see anything hapenning when i build it and run it on my android tablet.
Does anyone know what im doing wrong?
Do you see the effect in editor?
No, my laptop doesn’t have a gyroscope
Not really a code question but does anyone know why the animation I made with the animation tool doesn't work on my tmp text ?
You can easily create a var in your inspector to fake it and be sure, that your script is correct. if its working that way, log the gyro somewhere in UI and see, if it actually gives you correct information back
why not ask in #🏃┃animation than, instead of asking the wrong channel on purpose 😄
Because i didn't see the channel !
yeah doing that now, but building takes a while
it says my gyro is disabled, but i clearly enable it in start and i am not touching the gyro in any other script
How do I force start an animation on a specific gameobject ? What do I need ? The animator controller ?

No I mean in code
well, you can change an animator's property via code - e.g. animator.SetBool()
the object will need an animator controller.
I think i'll need to work more on animations....
first off, are you sure your device has a actual gyro (yeh, weird question but I have been in the situation to have phoens without it). Second, are you using the old input setting (hence your Input.gyro), or the new one in your player settings? or both probably?
Nope just using old input system, I also double checked the tablet I’m running should have a gyro, but could not find it anywhere in the settings. I have the galaxy tab A9+
You should check, if the gyroscope is allowed in your settings on the tablet too
Also you could install a third party app for testing sensors just to be sure, applications can read from your device
ill try that, couldnt find anything about sensors or gyroscopes in the tablets settings
It probably has none and is using accelormeter or something to fake it
gyroscope works, downloaded a test app and confirmed it
im not sure why it disables the gyroscope because i set it to enabled in start
api does this Input.gyro.enabled = true;
instead of this gyro.enabled = true;
not sure what you mean. Input.gyro.enabled = true; is the correct one.
Right so i am just testing out a piece of code. So when the player collides with the enemy, it should show a message in the log. But it isn't working. Any ideas or suggestions?
neither work, both options and they still start on false
add a log outside the conditional to see if you're getting any message at all
if not, go through this https://unity.huh.how/physics-messages/trigger-matrix-3d
https://learn.unity.com/pathway/junior-programmer/unit/user-interface?version=6.0 is this still the best way to make menus? (like settings, new game, load game, pause button etc etc?)
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
It's feasible and up to date. As with many other things there is no "best"
so games make menus like that? when pressing ESC button, on the start with the screen, and no there isnt a "best" but there can be things that are better then that user-interface method
Why would the official tutorial teach something that isn't usable
Instead of stressing about what way is better than another just start with something
im using RotateAround...Vector3.back for the left one which works fine, but the right one is using V3.forward (because using V3.back would just make it go in the same direction as the left one) which i assume would work if I could set it's starting point further along the rotation path. How would I go about doing this?
{
swordGameObject.transform.RotateAround(gameObject.transform.position, Vector3.back, Time.deltaTime * 100);
}
else
{
swordGameObject.transform.RotateAround(gameObject.transform.position, Vector3.forward, Time.deltaTime * 100);
}```
is there maybe some sort of way to *-1 the rotation so it's mirrored?
Forward should just be 0,0,1 and backwards 0,0,-1 so *-1 would result in the same "issue". Did you try to just -1 the 100?
Right now, you are moving within time. If you want to offset it first, dont use Time related values on init.
yeah it just goes in reverse, basically the same as *-1 the vector3.directions which is what we don't want
Wait, what exactly do you want as outcome 😄
ok see the one on the left? i want it to do that but mirrored
the isFlipped == false is what's doing the one on the left, im trying to flip it so it does that with the one on the right
Okay, and just by using vector3.forward for both but one with 100 and the other with -100 does not do that?
no that's giving me the same as just using vector3.back
It is mirrored, but on the diagonal. If you want it mirrored on the Y axis you can just rotate them so that they start upright (| instead of /)
i dont want them to start upright though it'd be too big a sword swing for what im trying to do 😭
i get what you mean though
I got a question
the starting point is the angle and then it goes either left or right
just ask...
But how is it going to be mirrored on the Y if they start leaning to the right
sorry anyways I want to know if anyone can use c script for a vr game not sure what channel I’m supposed to put this in but mb
Unity uses C#
mb I’m new to unity
Not that new to have not known that, unless you literally took this advice and did nothing with it since last year:
#💻┃unity-talk message
im not sure man, im trying to mirror it after the lean i guess?
so it leans to the left
as a starting angle for the right one?
someone with 2+ years of experience is teaching me
so idk
You're going to have to first figure out how exactly you want them to behave
i do, i want the right one to lean left and move down, which i know vector3.forward will make it move down i just need to figure out how to make it start leaning to the left instead of right, which is why im here
Yeah that's the question you should've asked in the first place
so do you know how?
You need to take your starting angle and from there add your rotation.
Yeah I know, that's what I'm asking 😭
First rotate one of them to the place where you want it to start. Then look at the inspector and write down what the rotation is. Then add this code to Start:
if (us.isFlipped)
{
transform.eulerAngles = new Vector3(x, y, z);
}
Put the correct rotation values in place of x, y and z
Bonus: use a Vector3 field so you can use the inspector directly
ok i need to understand why it's starting at that rotation in the first place im not setting it, and it's not starting at 0 or anything. is it because of the angle it's already in?
What do you mean the angle it's already in
well when i start RotateAround the z-axis starts at around 60~ and I don't undertstand why the rotation begins there as both it and it's parents aren't close to that. In fact just changed the Z-axis of the parents and it changed nothing when it swiped the sword it's still starting at 60ish
are you sure, no parents in combination add up to the world rotation being 60?
the parents resting Z axis is -15 but even when I changed to anything else its still starting at that 60ish lean
everything else in the hierarchy is 0
lets make it plain simple. What does your "sword" look like, when you set the rotation directly to 0,0,0
exactly how it's leaning in that gif, it's parent "holster" is at -15 causing it to be slanted
So you set the transform.rotation of your sprite (red) to 0,0,0 and its leaning?
yes
also just figured it out, i hate how bandaid it is but i cant sit here and fix this all day
no it's straight
transform.rotation = 0,0,0 should be straight. But its not, unless you still have other scripts running
it's fine though i worked out a solution, just added a one time offset of 90 to the time.deltatime * 100
yeah i said, the parent is at -15. but the parent's rotation isn't changing the starting rotation when it rotates around
dont worry about it, its done now, thanks everyone for the help
You dont understand. if you rotate your sprite to 0,0,0, and its still leaning, that is wrong. just plain wrong 😄 But great if you found a workaround.
I have no clue why but if i reference a another integer like "number" here i don't get a out of range array error but when i do use "i" i get an out of range array error even tho the int number literally equals to "i" beforehand
//Initialize offsets
float currentX = 0;
float currentY = 0;
for (int i = 0; i < colums; i++)
{
//Spawn button
GameObject characterButtonClone = GameObject.Instantiate(characterButtonPrefab, partyMembersObject.transform);
//Assign position
characterButtonClone.transform.localPosition = new Vector3(currentX, currentY);
//Assign name
characterButtonClone.name = "characterButton" + i;
//Get text
TextMeshProUGUI nameText = characterButtonClone.transform.GetComponentInChildren<TextMeshProUGUI>();
//If party member exists
if (i < lobbyParty.partyMembers.Count)
{
//Assign name based on party members name
nameText.text = lobbyParty.partyMembers[i].characterName;
//Get current character
Character character = lobbyParty.partyMembers[i];
//For some reason this works.
int number = i;
print(number);
//Add button listener with delegate based on party member
//If i put "i" here instead of "number" i get an error
characterButtonClone.GetComponent<Button>().onClick.AddListener(delegate { PartyMember(number); });
}
//If no party member exists
else
{
//Remove listenrs
characterButtonClone.GetComponent<Button>().onClick.RemoveAllListeners();
//Disable characterbutton
characterButtonClone.GetComponent<Button>().interactable = false;
//Assign empty
nameText.text = "EMPTY";
}
//Add to current list
currentCharacterButtons.Add(characterButtonClone);
//Apply offset by width
currentX += characterButtonClone.GetComponent<RectTransform>().rect.width;
}
I'm very confused
I see. So loops and delegates don't really go well together.
When you use a local variable in a delegate or lambda (often with a loop), you've got to copy the value and use the copy because the delegate will only refer to a single variable even though you're expecting different instances. Something about how memory is managed.
it's not that exactly. it's that the delegate is capturing the variable, not its value.
Doing what you did int number = i; is pretty standard
It's a really sneaky problem
I see. I really should learn more about delegates then. As far as i knew, they were basically like a more versatile way of referencing functions.
This is more of an issue with anonymous functions than with delegates in general
a "delegate" type is just a function type
I've heard that events were better to use then unity events. Is this also true with delegates vs events?
I apologize if that sounds out of field. I'm just very unfamiliar with delegates. You can probably read that.
UnityEvent is very similar to a delegate-typed variable, except that it can be serialized and modified in the inspector
these two are very similar:
public event System.Action Foo;
public UnityEvent Bar;
(the event keyword allows anyone to add functions to the delegate object, but only allows the owning class to invoke it)
that could be great for learning delegates and understanding them better.
i vaguely remember seeing a benchmark where UnityEvent behaved better
but this is a vague memory
i should definitely mess around with that. Thanks alot for informing me.
I see, yeah i know that came out of left field.
Having a UnityEvent exposed in the inspector is really nice for when you need to tie one-off things together
like when you want to add an extra particle effect to one enemy's attack
UnityEvents wrap a delegate under the hood anyway
But they add the convenient inspector functionality
not quite!
they store a list of invokable objects
rather than modifying a single delegate object
of course, a delegate object is, itself, just a list of things that you can invoke
Every time you modify a delegate object, an entirely new object is created. This makes it safe to add or remove targets from it in the middle of an invocation
Oh so it doesn’t wrap a delegate declaration? I thought they did
I'm not sure how UnityEvent behaves, by comparison, actually..
Wait, can unityEvents take parameters like delegates then?
Yeah they’re generic
e.g. UnityEvent<int> takes an int
But, you are limited with Inspector functionality
I'll try that right now.
It's very similar
Yeah, i can imagine.
if (baseInvokableCallList[index] is InvokableCall invokableCall2)
invokableCall2.Invoke();
else if (baseInvokableCallList[index] is InvokableCall invokableCall1)
{
invokableCall1.Invoke();
}
what's going on here 😭
Yeah that’s confusing lol
gotta check twice, just to be safe
I’ll take a look at the API later. Apparently I misunderstood how it works
It's a really pedantic difference, to be fair
As far as you're concerned, it's just like having a delegate object
But either way, I doubt that there’s any substantial difference in performance to use a C# event vs. a Unity event
yeah
Personally I like to just use them in the way of: event for something I want to happen only on the code side; UnityEvent if I expect to have some callbacks that any non-coder could easily set up with the Inspector
the performance would rarely ever matter, it's more about if you want it serialized (assigned in inspector) or not
There's a lot of cases where I just go with c# events because I specifically don't want the functionality tied in inspector. When everything becomes tied in inspector, it becomes a little bit hard to follow the code flow because suddenly you aren't subscribing in code anymore
yeah, C# events still give you some static analysis
I don't think im using unity event at all currently tbh, but thats just a preference
I do like actually seeing it in code
I sometimes use both
Yeah. I suppose there's no wrong way of going about it, as long as your code base is consistent, be it with inspector unityEvents or c# written delegates.
good point honestly.
a C# event for other code that always depends on the event, and then a UnityEvent for when I want to bodge something in :p
Yes I follow a similar way of thinking
Unity Events with Inspector callbacks are very convenient to set up but can be difficult to track down for debugging
there was a point where I was making a main menu and hooked everything up through the existing button on click unityevents. It felt really bad going through that setup just to figure out what's hooked up to what, because some of these buttons are parented under a couple of objects
compared to a script on the canvas which referenced every button needed and hooked up the event in code. I could at least click on the reference and be shown which button I was using
I started making a reflection component that could hook every method that was available by singleton patterns. That way, I did not have to drag drop any reference into every button but just assign the correct method once. Made it easier for me to decouple hierarchy objects a bit
The reflection was only happening in editor mode and later on just the static Class.Instance was called if available
when generating terrain with fractal noise how do i interpolate between noise samples? when i do linear interp the terrain looks low quality cause its just a bunch of squares and i cant use bicubic because it creates wavy terrain
Your noise may have too high of a frequency
if bicubic interpolate looks really wavy, that means that your terrain wants to go up and down really fast
Is it normal that with an almost empty unity project it already takes me 16 seconds each time ?
when does that occur
If your computer isn’t a potato, something’s wrong.
Whenever I make a script change or test the sample scene.
I have a good computer overall
rtx 3060
I literally just added these
I never really worked on unity. any options I should be checking ?
Uhh do you have an SSD or a hard drive ?
i know that my projects were veryy slow when i had a hard drive
It could be because Unity is a heavy editor Every new project loads a lot of things so it also opens slowly for me 🤔
idk then ;-;
Script recompilation takes 3-10 seconds for me, depending on the project size
If most of the time is being taken up by asset imports, then that's a bit weird
You can go to Window > Analysis > Import Activity to look at recent import events
it'll show you how long each import took
e.g. a decently sized model took 2 seconds to import (i have some custom postprocessing happening, and it's...not optimized)
Hmm. how can I exclude some folders from import ?
why do you want to do that?
are you seeing something taking a long time in the import activity window?
Seems like basic stuff, but I have uploaded some of my book's references (out of the assets folder though).
Unity will only import things in the Assets and Packages folders
Hmm then it's weird
nothing in here looks unusual
trigger another reimport and then look at the recent events
Don't sort by duration; sort by Last Import
that wil show you what's actually reimporting
weird, so it reimports everyrthing all the time even if they weren't changed ?
it makes no sense though, all the last imports account for like 3s
Assets are only reimported if a dependency changes. Dependencies can be the file the asset comes from, other assets, project settings, etc.
what are you doing to trigger importing? are you changing a script file?
if so, that'll take a while (all scripts in the assembly, and any assemblies that reference it, must be completely recompiled)
you won't observe this in the importer window
Each import event will explain why the import happened
(you will see script assets, but this only counts the time taken to look at the script file and go "yep, that's a script")
the C# compiler isn't really something the asset import system understands
Yes, everytime I change a script from the 3d empty project I have to wait 17s already?
very different from this
that's a very long compile time for an empty project, for sure