#💻┃code-beginner
1 messages · Page 815 of 1
checking if an if statement did anything is pretty basic
Debug Logs, visual indication or a debugger will let you know
hell input system even has an debugger thing for this
Hey, guys. I've been trying to get a question answered in the animation channel for the last week with no response. It seems like I'm on at the wrong time or something. May I post the question here to see if anyone can help?
Guess it depends on the issue, what's up?
Any advice would be appreciated. This is a root motion setup, where the character's speed and direction are driven by the animation. My character seems to be playing jump rope between the back run and diagonal back run on both sides. I managed to somewhat solve the problem at certain coordinates previously by just duplicating animations in the coordinates in question, but I'm not sure if it's an acceptable solution since I'm new. I've made all of the animations start when the left foot hits the ground using offset. IK is on, and the layer has IK passing. if I turn either of them off, it all goes haywire.
!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.
^
If it's bouncing between states I'd start with the code controlling the animator, then the conditions for the transitions between states.
I wonder if you need a half-cycle offset on one of the animations
I am also doing humanoid root motion, and I mirrored all of my animations to get left-movement. All of those animations have a cycle offset of 0.5
If one animation tries to lead with the left foot and one lead with the right foot, they'll cancel out and give you a weird hovering effect
i badly need to record new animations 😭
goofy walk
yea. I've offset them to start as they land on the same foot.
here's the relevant code for the animator
animator.SetFloat("Strafe", input.x, 0.2f, Time.deltaTime);
animator.SetFloat("Forward", input.y, 0.2f, Time.deltaTime);
animator.SetFloat("Speed", input.magnitude, 0.2f, Time.deltaTime);
I'm not sure if the dampening is really making much of a difference though
it's an issue with the blend-tree itself, yeah
Fen, when you offset your animations are you setting them when your character makes contact with the ground on the same foot or when they pick up the same foor?
It shouldn't really matter
<@&502884371011731486> scam
I guess you do want both feet on the ground at the start of the cycle, so that you can correctly start and stop playing the animation entirely
(i.e. if you go from some other state to the state that contains the blendtree)
can you show the full inspector for the blend tree?
You want just the one tree or the forest lol. I got a 1d that branches to two 2ds for walking and running.
whatever was being previewed in the video you sent!
Am I dumb and this was a syntax thing with "return;" not sitting within {}
I got it now
so it's causing problems when it blends between:
- Run_Loop_B_180
- Run_Loop_B_R_45
yes and Run_Loop_B_L45
That really sounds like a problem with your cycle offset. What happens if you adjust the cycle offset of one of the two animations by 0.5?
May I ask what the solution was?
It got better! Thank you. It's just an offset issue.
nice (:
I reworked the whole rotationPoint system it wasnt worked as intended
Make sure the walk and run animations are consistent, too
otherewise you will get the same "hopping" behavior as you blend between them
note that blend trees will adjust the lengths of the animations to make them all sync up
This can cause some really weird behaviors if the animations have dramatically different lengths
Yeah I'm starting to understand why many people choose to move their characters with code, but I have to go this route for the combat I'm trying.
Thanks again. I'm going to get right on this.
I use blend trees excessively...in VRChat, where everything happens in the animator
so i've been forced to learn about them, haha
Wdym by "everything"
Like game logic too?
For avatars, it's all you really get
(Worlds can use Udon, which is slow enough that it's often faster to use animators for things like spinning objects)
I've heard nothing but bad things about the performance of Udon
It's a very basic assembly language
it has like six instructions
almost everything is an extern call into a C# function
interestingly, this means you're incentivized to use existing Unity functions as much as possible
the actual C# is fast
YES
I MADE AN ABILITY SYSTEM USING SCRIPTABLE OBJECTS RAHH
can i ask a question
how do i pause everything in scene
ITs all Ai answers and i DO NOT support Ai
to the one who did Google emoji
Apart from googles AI overview its really not...
im seeing plenty of good answers here in the first few results... looking it up myself
Setting timescale to 0 is babys first pause
Update and fixed Update will run?
as i understood it doesnt
Yes but it will "freeze" physics
If you have logic that runs over time that uses delta time then that is affected too
So i can still Manage thro Uis?
is this somewhere i can go for questions on coding for scripts?
or a different text chat?
did you perhaps read the description for the channel you are posting in?
lol
im just trying to write a script for like any tag i put on set entities to be lockable. ill figure out the camera placement after wards i just wanted to make sure if i am writing this correctly so far idk anyone could take a look at it for me.
also not sure if i should use other.CompareTag(nameoftag) when checking for a tag
you absolutely should use the CompareTag method when checking a tag, unlike string equality it won't just silently fail if you try to compare against a tag that doesn't exist, it's also slightly faster
Theres even that new faster overload that takes a TagHandle instead of a string, never seen anyone use it though
ok thats good and since im using this as a camera lock on should i use the same main camera thats on my current character to put it in the folder the lockable entity? or should i make a different camera for it?
hi! i have a modular room system in place, however I am curious if there is a way to make a plane scale between two points, rather than by a pivot point. kind of like setting an anchor on two sides, and having the plane scale that way. Im not too sure where to start, or if its even possible. Thanks!
Set its position to the center of the points (a + b) * 0.5f
its the scale im talking about
Then set its scale to fit the difference of those points
ohh righto
But this affects position so I said that as the first step
yeah
its really annoying isnt it lol
Idk, it became pretty intuitive for me after dealing with vectors a bunch
yeah fr
What I suggested does not take rotation into account btw
yeha i know
But seems like things are axis aligned?
uhh kind of
ive made it so that it doesnt require rotation
all the textures are tiled based on world pos
and everything scales nicely
so when it comes time to make a bunch of rooms for the game I'll have a system that can let me pump out one room every 30 minutes 🔥
So it's like, procedural but pre generated?
in a sense
the skirting is all instantiated in editor
but the script i have uses custom editor ui, and it lets me do all sorts of fun shit
so essentially i have one room prefab, i can scale it on all axis to whatever size i want, have an entrance on any side i want
have skirting automatically done for my
everything is already grid aligned
its awesome
Cool
Yeah grid aligned is what sane people do
Everything else is just asking for trouble lol
Nope
oof
my brain hurts
what would i do to scale it
i know the difference of the two points but
planes are like 5x5units
wouldn't you just measure the gap, move it to the center, align it, then scale it and that would do effectively what u want
yeah ig so
(b - a) / 5
Would be the scale
Division by 5 because of the plane size
im a certified professional dumbass
Isnt it 10x10 though
wdym
The plane
oh probbly
Idk i dont have unity open
actually nah the approach i was doing before is the better one imo
because you need to scale either side of the doorway IF theres a door, but if not, scale the full wall
actually nvm
OKAY
RIGHT
SO THE MAGIC NUMBER WAS 12
WTF
if the mesh is 12 world units long yeah
the stupid thing is
is that i based it on the skirting
each skirting unit is 1.2 units in unity
omg what
ok
@verbal dome wanna call
my brain is melted
Nah im good
aight
i have a wall prefab right
thats what handles all the wall shit
but when i have multiple walls
One coherent message please
it specifically never works for the north or south walls
sorry
SO:
My wall prefab contains the empty gameobjects recognised as the points to scale with.
Example: Border of Door Arch, Room Corner, etc.
I then run those through scripting to scale. It works great. thanks for that. However, my room consists of:
A floor
A ceiling
4x Wall Prefabs (copy and paste, im trying to make it so that you dont need to manually adjust references etc)
And a skirting parent, the object that containts all of the skirting, just for tidyness sake
its not:
Incorrect scaling, im scaling locally so it cant be that
I dont believe its in scripting, Ive tried changing the wall reference in the master Room script from north to east.
Is there a generally agreed upon coding IDE to use for Unity. I am getting suggested a particular one often and im wondering what u guys are using
visual studio is what most people use probably
VS, VSCode or Rider usually
vscode and rider being the other 2 main ones
notepad if im feeling cocky
I don't have much experience with VS but VS Code is the most lightweight, Rider has a good feature set
VS probably sits somewhere in between
Rider is free for non-commercial projects only
visual studios the best option featurewise/pricewise, but its also the slowest
I do not see a question here 🤔
it just looks like you are mixing up world co-ordinates and local co-ordinates somewhere
cant really tell much more than that
How could rider possibly even know if it's commercial or not. If commercial is as broad as I'm thinking it sounds like a useless program
like most companies, they get people when an angry ex coworker dobs them in lol
Honorable vim mention 🤝
VS works perfectly fine, no configuration needed (unlike VSC)
It was chugging like crazy on my machine so it was unusable sadly
Not like Rider uses any less resources 
Yeah, but at least it is usable for me
Fair
I still fire up VS Code if i need to quickly look at some code in another project though
Time to start learning vim for minimum resources 🤝
1 sec vs 10+ sec bootup
I genuinely don't know why VS Code takes so long at time to start
Gladfully only use that piece of software for web stuff
Yeah I just tested it again on my linux system and it's quite fast
Maybe I started comparing it to NPP early on and then the idea of "slower start" stuck
Just tested and Rider took ~20 seconds before I saw any of the code in my project lol
But I just never close it so it's not an issue (unless i run outta ram)
Low specs huh? Rider is not fast for me but not that slow.
Me neither 
Okay it's not that bad if I open thet solution directly
Under 10 seconds
Yeah sounds about what I have too
But it's a bit choppy until it has properly warmed up
Yeah it needs to re-index the entire file structure every time you open it, it's a bit annoying
i just made an xr game, how do i play it on my headset now?
You'll need to enable the corresponding 'plugin'.
If you're using Oculus (Quest) I think you'll need to enable it within the server tab.
ok, but how do i connect it?
i mean the game to the vr because just pressing start with airlink wont do it
If you're using quest you might need to enable developer settings within meta. One second I'll look it up
Not called dev. settings, my bad.
- Have Unity (the game tab) selected when playing.
- In Meta or whatever it is, Settings > General, allow Unknown sources
- Make sure that “Meta Quest Link” is set to On
- In Unity, Edit > Project Settings > XR Plugin Management, make sure it initializes XR on startup.
is garbage collection a thing to keep in mind for optimize?
i dont get, why the hell is this so complicated. i just went to that airlink hub or whatever it it is, then went to desktop and monitor 1 and presses play on unity. i dont get what to do different
there are more inportant things you could optimize your game instead of taking care of manual garbage collection
Waxy you're killing me
so is it important to consider?
Yeah stop that emote spam
Generally you want to reuse class instances instead of allocating them and then throwing them away every frame, for example
But if you are a beginner I would not stress about it too much
Welcome to programming/game dev.
I'm not familiar with the quest stuff. I do steamvr/valve index. So I can't offer much advice.
i mean i do try to make it as optimal as possible, but its really hard most cases not to make new instances sometimes for example position recording.
A position is a struct so it's not very relevant here. It does not generate garbage by itself
when should i use material property block instead of .material and changing it
Struct vs class is a concept you should learn before even thinking about this
Or stack vs heap memory
could it be that you are coming from some programing language where you´d have to do the garbage collecting on your own?
sorry for misunderstanding u, for me im currently doing a system like this:
public struct StateRecording
{
public List<StateFrame> frames;
}
public struct StateFrame
{
public Vector3 pos;
public Quaternion rot;
}
Hi everyone, I'm having trouble assigning my character prefabs to the NetworkPrefabs list in the NetworkManager. Even though I try to drag and drop them, the list doesn't seem to accept the prefabs.
because in c# there is the garbage collector doing this job for you
and whenever i run this everytime the gc just kept spiking up, and lags my game
Need more context. Could be the variable type you're trying to store them in, isn't what they are.
What is it doing exactly?
Are you creating a new list every frame?
Need context
not every frame specifically, every x seconds.
cuz if every frame it lags af
Even though I added a network object to it and registered the character in the assets section, it's not being defined there.
But what happens in the code
Nothing is allocated on the heap in the code you showed
(Heap = gets garbage collected)
In short: You should just reuse the same List instance
The List (class) being stored inside a struct might be a code smell. Show how you actually use it
Sorry for bejn an idiot but i dont understand
Well I also don't understand because you aren't giving any context 😅
How are you using this struct
Show code
^ #1390346492019212368 | NetworkObject isn't a GameObject like a prefab is. So if you're trying to store a reference to a component named NetworkObject, you need the variable/list that holds that reference to be that type.
they are not the ones defining the list
I'm no expert, what'd I say that's wrong
networkprefabs list is a ngo thing
It's not recommended to use material property blocks with URP/HDRP if you are using those
They use the SRP batcher which works per shader variant, not per material, so material instance is preferred (from my understanding)
I'm trying to lookup that term 'ngo', but they did mention "assigning my character prefabs to the NetworkPrefabs list" so they're trying to place a GameObject within a list. Thus the list must be made for GameObjects ( List<GameObject> things = new List<GameObject>();) right?
sure
but they dont get to make the list
they need to add a NetworkPrefab to the list, as that is its type
Is there any general chat in this server?
no
I definitely need to look into the networking stuff.
Kk
I'm having abit of a problem when it comes to using linq for a dictionary. i'm trying to reorder my dictionary by name. But order by seemingly is doing nothing here.
//Assign to debug list
this.storedDataTiles = storedDataTiles;
//Update debug ui
debugUI.UpdateStoredTilesText();
//Sort keys by name
storedDataTiles.Keys.OrderBy(key => key.name);
//Return stored data tiles
return storedDataTiles;
}
OrderBy returns a new IEnumerable, it does not modify an existing one
Keys are read only anyway
And dictionaries dont care about order or try to keep an order so this is a dumb idea
If order matters you need a new collection like a List with the keys in some order you want
@tender mirage ^
(Man that site is annoying on mobile, popups, ads, and it opens the keyboard when i try to scroll)
i never knew that feeling when theres an adblocker
I totally forgot that dictionaries didn't care about ordering.
Thanks for the reminder.
General advice. public void StartRecording() should return bool to indicate success
So the only real allocation i see here is the new() for the frames List
So you can reuse it instead by replacing that with .Clear instead
Also do you know how structs vs. classes work?
Creating lists with a good initial size and clearing them will improve things a lot
Structs are copied when you pass them around
Classes are passed by reference (not copy)
Thats a new thing to me
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types
This explains the differences with value types
And yeah rob's advice about pre-allocating it with an initial capacity is good
Otherwise the list starts with a capacity of like 4 (or 0?) and then every time you add more and the capacity is exceeded, it will allocate a new internal array double the size of the original
4 -> 8 -> 16 -> 32 -> 64... Lots of allocations so if you know you will have for example ~1000 elements then create the list with that capacity: new List<MyType>(1000)
If that went over your head then just focus on the value vs. reference type for now
If we can set the intial size and it improves the gc then good
But is it ok if we dont use all the space?
That's fine, you just "waste" a bit of memory but it's miniscule in this case
Better than constant pressure on thet garbage collector
Allocation and deallocation has cost so its usually better to use a tad more memory instead
If you know you may need to add up to 16 elements but it could be only 8? Make the list be 16 to start.
the thing is i dont know what the duration of the recording is.
I was cooking up some analogy about apartment sizes, moving to different apartments and getting new family members but i gave up
i got it dw
so like less ram?
In that case you can maybe make a guess for the start size
Yeah with "memory" we usually refer to RAM
random guess but you could probably add the size of a second when you start + whenever you fill that up? or a similar amount of time
Just know that when a list needs to resize all data has to be copied to the new internal array
alr
well then i think either i make the recording duration constant or just set to like 1000
And as you maybe just learnt, an array of a struct has a lot more data to copy.
Anyway you should use the profiler to check if such things are actually an issue before trying to over optimise.
From this message I assume you profiled it?
does an array of classes makes it better?
yea but maybe its not really from this script in particular but the sum of the idiotic scripts i made
It does but then we start getting into more advanced stuff (as iterating over an array of structs is a lot faster)
I dont want to get too deep here and confuse you. Stick with a struct.
i really wanna improve, so go on
Have a read on the topic here. The overview though is that data thats all together in RAM is quicker to iterate over.
Classes are reference types so a list of them is actually just a list of pointers to many places in ram (where the class instance data is).
https://gameprogrammingpatterns.com/data-locality.html
thanks man:)
Cant believe ppl do this for free u could start a course (lowkey) xd
can someone lmk like the best way to learn how to make a third person game with a camera kinda like how roblox's looks (without the zooming in and out), like I just need to know what exactly Im meant to use in the script. I believe I should probably put a camera as a child of a parent object which I will have as my player, and then I make the parent object rotate according to my keyboard input, right? but how do I do that whats the logic
Ive been trynna find a way to actually learn things but Ive never really found an actual useful video or anything, theyre all about copy what I just did
look into Cinemachine
Ive seen that pop up but isnt that just something to make things easier
I wanna be good at the fundamentals
third person camera are just generally hard
there's a lot of ways you can configure one with that being said
control relativity is up to preference
my issue is mostly: lets say I want the camera to be always at a specific radius from a certain position
and I want it to not rotate looking up or down past x angle
I dont know how to achieve that
with clamping the rotation
float newAngle = Mathf.Clamp(currentAngle, min, max)
I should make this clear btw Im super new like downloaded unity a couple days ago and opened it once 🥀 mb
thanks ill look through unity documentation
Friends, I need help with setting up a sleep system and logging system, including shelf and product registration. Please write to me.
no one will dm you, just aks here
It's actually not ideal to child the camera to your object, but in many cases it will work fine. It's just that you're more likely to run into desync issues if your character updates in a different timestep than the update of the camera.
Which is why cinemachine is a good option too as it handles a lot of that complexity
as a noob I assume you mean for example if I want the player to ALWAYS be visible it'll cause me trouble, yes? for example if I approach a wall I wouldnt want the camera to since its always at a certain distance to its parented object, the player, go through the wall, and to handle that it'd be a mess while having it as a child of the player?
More that character controllers update in a fixed update but smooth out their translation in update, but this can somewhat conflict with how the camera captures it all. Usually just keeping the camera movement in late update works fine, but it's not unlikely you run into some frame inconsistencies.
But you're also correct about it being a bit more complicated to manage camera collision when it is child to the object... which cinemachine also does pretty well lol.
How can I create a sleeping system and a shelving and product storage system? Can you help me?
it's probably one of unity's best tools that's for sure
Cinemachine
use cinemachine men haha i try to make a system of camera and it is hard asf for nothing xD
camera systems are the last thing you want to spend time and procrastinate on in game development
good for learning, but for production I would just use cinemachine 
even for learning,if you don't have a solid base, you will just get lose or get a bad system
(I talk by experience hahaha)
please ask a particular question, really unclear
It doesn't record the shelf. When I start and stop it, it goes away. I want it to record when I put the shelf somewhere.
so post the relevant code
Where can I send it? There is a furniture controller, there is a rafspace controller.
!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.
so for the .material, this will create alot of material instances take up memory but run best if the scene use different materials from same shader
and materialBlock will only need to create one instance for every renderer, and run best for when gpu is peferred like lots of object from the same material
did i get it right fr
Something like that yeah
Main point being that SRP batcher (urp/hdrp) only cares about shader variants, not materials
MaterialPropertyBlock was more useful when we wanted to avoid creating new material instances, to avoid breaking batching in the older GPU instancing/batching system
You might want to test it though and/or ask in #1390346776804069396
Hey, so im struggling to understand list despite watching tutorials. But basically, i have multiple list inside one list. How can i make so that the first element in the list can be a gameObject ? Thanks !
By the way, i would like to thank you for the support ! I was very busy to say it but you really took time to help me and this is very kind of you :)
First element of which list? listColorList or colorList. All elements inside the list would be the same type.
Of "colorList" ! Ah, i see...
What exactly were you trying to do? If you can explain, we may be able to give you further suggestions.
You dont, a list can only have one type.
By the way i dont exactly understand how to ask for "floats" instead of colors ! Sorry if this this code is disgusting 😅
Sooo im working on a gameEngine for a SpaceShooter, i want to allow my classmate to easily create various enemies.
I want them to be able to create multiple attacks using list. One list is a attack, and the list containt :
1 - The GameObject to summon
2 - The time before the attack start
3 - The duration of the attack
4 - The duration of the cooldown
But i dont think i have the knowledge to make it easily 😅
wut? your ColorsList take a float but then after you try to access a list from a float
you changed your lists to be of type float from the last image being of type color and you are tying to return this float as a color
Ah, i understand my mistake now.. So i should use public float GetColor() to avoid this error ? (Or a int)
no a float is not anything close to a color
I think I'm confusing the name (of the classes/functions) with the types 🤔
Because i no longer wants any colors, only float
What type would you use to return a Color?
Sorry if i look dumb 😅
then the question of would this work is yes but you should change the name of the function to match.
also this only ever returns the first element meaning there is no point to it being a list in a list
a Vector3 i think.. But now i no longer want a color, i only want lists you can put float inside !
not a vector3 colors are 4 different bytes one for each colour (red, green, blue, alpha)
You should probably change the name. colors imply it's a list of color(s).
Thanks for your suggestions. I changed the function's name and type, and added "valA" and "valB" to go through the entire list.
Now, im being hit with the error :
'float' does not contain a definition for 'value' and no accessible extension method 'value' accepting a first argument of type 'float' could be found (are you missing a using directive or an assembly reference?)
I do understand that i'm using the wrong type, but i dont understand what else should i use..
the two underlined parts should match
you just currently have two completely seperate lists in different classes with no reference between them
Are you simply trying to make a multidimensional array of floats?
I dont understand, have you underlined the wrong line ? "float" instead of "ValueList" ?
If not, im basically deadlost
no i underlined the error, or well what'd make it
like "Values" and "ValueList" should match but doesn't...
public List<Values> colorList
Guys, thanks for the help. Now it's time for me to walk outside as i did like 40h of unity in one week and i think im starting to become like.. Crazy or smth.. 😅
True...
- ATTACK ONE
- CooldownA
- Cooldown B
- Cooldown C
ATTACK TWO
- Cooldown A
- Cooldown B
- Cooldown C
this is how it should appear
so i think "Values" should be renamed "attack"
Yeah and value would be cooldowns
!lern
There's no command called
lern.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Herreee we go
Now it's time for me to WALK OUTSIDE or sleep idk 😅
Thanks guys !!!
Oh, i forgot about context.
In my school we only have two weeks to make a entire game in group and im the only programmer so i have to learn everything on the road.
Once the two weeks will be finished, i'll make sure to watch the tutorials !
does unity have any data type that allow assignment of logic? I have been using SerializedReference but these get erased as i change the class' name
other than that there is reflection but i doubt its any faster
composition and usage of scriptable objects
ye but is there any data type that accepts a delegate?
that can be selected in the inspector
You can serialize unity listeners /events with the editor but otherwise need to write some extra boilerplate to bind stuff like that
I see. Thanks
Usually those have limited data types too. I think it's usually just like int/floats/strings
and usually you don't expect return values anyway
Like the Button class for instance
ye i guess serializedReference is the best option rn
Godot's signals a bit more versatile because the typing isn't always specific
The problem isn't so much that you couldn't serialize it all, it's just that Unity's editor doesn't really have that support.
Much like interface serialization, it's a bit ambiguous without a bit more of that boilerplate
having an issue with no global 2d lights showing up in my build: i have a main menu level select scene and levels, and scene transitions are done with SceneManagement.LoadScene(). When i dragged all my levels into the hierarchy to test the level transitions in the editor, i initially got a “more than one global light on layer…” error that went away after unloading the level scenes and leaving only the main menu. after building, it appears as if all of the lights are gone, the scenes all look super dark, except for the canvas UI. i had one global light 2d in each scene, set to light “everything” in the layer select
hello, i have a problem, i have an object that orbits in my player(the object rotates in the mouse position), but when the player and the object are in a wall and i move my mouse opposite the player the object will push my player but i dont want that, i even deactivated the collision between the two in the physic collider matrix
do you need the collider on the orbiter object
I can do a simple job for 5-10 euros. I have some experience writing code in Unity. If you need anything, please let me know.
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**
An alternative would be use an interface and serialize a monobehaviour reference.
Would need validation however in OnValidate()
yeah, im trying to make a magnet so to attract something i need it
guys how do i play a unity game on an ocolus? 1. im in the engine 2. i pressed on start 3. when i press a button on the joystick the fingers move but i cant look around and move.
you can make the collider isTrigger but still use the colliders boundaries
but if i attract something the object will trapass the magnet
you could manually correct the position of the incoming object
can my question please not get ignored?
ok i could try that thanks
no that cant work because it will trapass walls
Make the collider ignore whatever layer the player is on
hello? i have a question in #🥽┃virtual-reality
Dont crosspost
if someone has an answer youl get it in #🥽┃virtual-reality
you also spammed your question multiple times and ignored every response you got.....
well i never got an response
now you're lying
yes, i did got an answer, but it didnt really work, and my questionw was "how to play on ocolus" and the only answer i got was something with dev settings or smth and it dosent really work
Ask a full question in the appropriate channel and wait for an answer without spamming, then someone might answer it
i did ask a full question and sorry that i dont want to wait 3 hours for an answer
Then like you've been told before already, do you own research
but you didnt ask a full question, at least not one thats clear
How?
@timber nacelle Use appropriate channel and stop bickering
i asked the question on the virtual channel but after 2 hours not even a single answer
No one here is at your beckoning call to give you answers. When people are inclined to and have time they will answer. Also if they can understand the question...
it is still allitle bit unclear what you want to achive but you might want to take a look at these
You need to explain in more detail what you are actually doing, and maybe illustrate it with a video or screenshots.
you could also open a thread in the #1390346827005431951
Preferably, yes ^^
okay
Can someone give me a basic explanation as to why the Add Score function in the second picture isn't working, I'm working with guides and have 0 experience coding otherwise
Says I'm having a CS1061 issue
do you have a gameobject with the tag Logic in your scene
that also has a script called "TriggerScript"
Attached to a txt in order to display a score
attached to a what
theres no triggerscript there....
you have scorecounter... not triggerscript
youre searching for a triggerscript component in your code
Oh wait nevermind I have it attached here mb
Thats where my trigger script is
It's just named 'trigger script', but it's a custom script
I barely know what I'm doing I am sorry I'm a day one learner
right, but the game object needs the tag "Logic"
i think youre missing some very basic fundamentals here
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i suggest you start learning with the unity pathways
I did it's on the logic manager lol
Unless you mean both need it
I Realllyyyyyy think you should go through those learning pathways
because you are writing code that you have no clue how it functions
thats not good, and its not a good way to learn
day 1: use tag to find script
day 2: stop using tags they are shit
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and...
I'm just following this guide
from 3 years ago
Never trust those who sell shovels in a goldrush
use the pathways, much better tutorials
I cant comment on its quality but comparing tags and finding objects by name are not things you use past the beginner stage.
Fine to use to get started and learn some things but after this id recommend against it.
I'm just gonna finish this tutorial and then move on to newer ones
If I give up now I ain't ever learning lmao
Yea its best to find some tutorial and try to complete it to learn some things!
Any pointers? I'm a hands on kinda guy, I don't really like listening lmao
If you can serialize a reference to something (drag in a reference in inspector) then do that instead of trying to find something by name.
Why? Brakes way less often 😆
So I'm either really dumb or over looking smth obvious(i am quite tired), but my isGrounded is working
cs
using UnityEngine;
public class GroundedCheck : MonoBehaviour
{
public bool isGrounded = true;
private void OnCollisionEnter(Collision collision)
{
if(collision.collider.tag == "Player")
{
return;
}
isGrounded = true;
}
private void OnCollisionExit(Collision collision)
{
if (collision.collider.tag == "Player")
{
return;
}
isGrounded = false;
}
}
It is retuning false, it is being called in my movement script
This is so real, i have broken smth one too many times by not using a serialized reference lol
hi all, I am just starting off and going through tutorial on Unity website. aI have got this far but Unity is saying there is an error with this and I cannot see where. I triple checked the tutorial to see but I cant spot the mistake. Can anyone see it ? thanks
show us the error
Place some logs and see what they print
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
Oki
Still showing true, could it be that the collider somehow isn't running OnCollisionEnter and OnCollisionExit?
trying this now thank you so much
Isn't that the purpose of the logs? You would know.
you could place the logs outside of the if statements
inside the collision methods
Setting the default to false still returns true when on the ground. Being in the air doesnt make it false
ok, one sec
does this help ? thanks. Here is course I am following https://learn.unity.com/course/2d-beginner-game-sprite-flight/tutorial/random-obstacle-size-direction-and-speed?version=6.3
In this tutorial, you’ll write your first Unity script to control how each obstacle behaves. By assigning random properties — like size, direction, and speed — you’ll make your game world feel unpredictable and alive. Along the way, you’ll learn key C# scripting concepts, how to edit prefabs directly, and how to test and tune behaviors...
d - > D
So they aren't running. Great
I only get true in the console
oh my god. Its College all over again 😄 thank you
does the object this groundcheck class is one have a rigidbody?
Just checking for reasons why it wouldn't run
What about the collider type that this class is using?
No, the parent(player) has one
Circle
Sorry could you send a photo of the collider in inspector
Thats the game scene not inspector ~_~
I suspect you are using a trigger collider and which if you are you should be using OnTriggerEnter not OnCollisionEnter (same with the exist function)
Edit: nvm you arent
Sorry, im very tried lol
All good
I will try making it a trigger and use those funcs instead one sec
!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.
That isn't the issue. For a collision event to occur, one of the two objects need a rigid body component.
oh yeah
Thought my tired dumbass over looked smth 😭
They did say the parent object has one; is this not enough?
Wait but the parent has one?
Right? I could of sworen it was
Try putting the ground check in the parent object
oki
I had only seen the inspector shown above.
im trying to understand this code. its doing the same thing as this screenshot right? https://paste.ofcode.org/36kVT7RfAVjfb38gakQvPYQ
It works!
like where you add callback context to make your input handler work
all that used to be in my character controller
Nice i would still recommend making the circle for ground checks a trigger as this adds an extra height lifting the character off the ground when not
I think the issue is the overlapping colliders
Yeah, now i gotta find a way to fix it tho
If you add a layer to the player object (not ground check child) you can set the ground check collider to ignore that player layer
i made that script before there were manuals to the new input system... should i keep it how it is or change it like the guy is doing in the tutorial/screenshot
Hmmm, okay. So pretty much just make a player layer(lol) and make the trigger ignore that
Yeah
The exlude layer in layer overrides here is how you would
Yeah ik, dw. Thanks tho. I will report back to you if it works or not
It works, thank you so much!
does anyone know a good way to keep NavMeshAgents/enemies following a path from forming "conga lines" when they're trying to get somewhere as a group? can I get away with making the characters themselves NavMeshObstacles or is there some particular way I have to manipulate the path's corners?
would you just make them ignore eachothers physics colliders
that's the complete opposite of what I want
because then they'd just stack onto each other and pile up at corners or intersections
that's totally besides the point
theres a lot of ways to approach this imo, your best bet is local avoidance of some kind
theres like a spacing thing around the player i was looking at on linkedin earlier
do you have an example I can follow?
it's worth noting I'm not entirely using stock NavMeshAgents and I have rigidbodies following a path calculated for them
make them select spots around the player and go there instead of to the player
force them to pick different spots
You can randomize the avoidance priorities per agent
something like: agent.avoidancePriority = Random.Range(30, 70);
that alone makes them less likely to form a conga line, but its a subtle fix in the end, all it does it makes them all yield differently so they stop following the exact same paths, with leads to more lateral separation
does this also affect the paths NavMeshAgents themselves generate? (that's how they get their paths)
im not exactly sure
youl have to test it out
Another thing i personally did was have different agent "personalities" inspired by pacmans ghosts, certain personalities behave slightly differently, and the randomized avoidancePriority was built into that
if it doesn't work where can I start for calculating avoidance myself
Im not sure if anyone can help me with my script that im having trouble with. To walk through the point of my script i wanted to set a tag that i can give to entities that i wish to be "Lockable" and if that said entity has that tag and you use the middle mouse button on it, it would start to lock on to that entity. In order words i am trying to create a target camera lock on system like something from elden ring or zelda. It is giving me a couple of issues being: Monobehavior not being found, Locking.Locking() must declare a body. And that it needs a return type and im just at a loss right now.
!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
I'm confused on the purpose of this command? Should I send/show or specify something?
oh ok thank you
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Help me to learn
Nobody here (or anyone for that matter) is going to be your free personal tutor. Unity has plenty of resources for getting you started.
Create, create more, create again, learn from mistakes, don't fret over making an entire game at first, make projects for the sake of learning, read, watch tutorials but actually look into what they're saying don't just copy-paste.
is there any way i can learn unity if i already know c#
every tutorials i watch just say "copy paste this complicated code" without explaining
There's definitely a way and if you're already familiar with the language you're off to a great start.
My process was taking the code from the tutorial and changes certain values, etc. And seeing what happened / how they relate / etc.
Is there a specific example of your issue?
i want to make a fps game and every time the tutorial types code it confuses me and he never explains what each variable, arguments or methods do and how they get information from the engine.
and since the tutorial is kinda outdated, i come across errors that he doesn't
That's quite the umbrella, whenever you come across something you don't yet understand I'd recommend Unity Docs. so you can see an example / usage / related properties.
Yea, some old tutorials can use some deprecated functions. But there should be new ones, might use some extra variables or whatnot but serve the same/similar purpose.
There's also the forum where you might find someone else with the same question and hopefully an answer to it.
How can i call "Unity_SampleGradient_float" in a custom function in hlsl ?
thanks bro
No worries. If you have a specific example / error, someone in here can probably help if they see it.
u already learn wuts class and instance?
you mean objects?
yeah i learned them from bro code. i watched the entire c# playlist
the public member variables of a class will be displayed in the Inspector of the editor, so if you create a new code file, write a class that inherits MonoBehavior, and then write something like this: public Transform A; Then you go to the editor, add an empty game object, and add the class you wrote. Then you can see this A variable, and you can drag other game objects into this variable. This operation is equivalent to assigning values in the code
if the member is private, then u cant see it
and u can write some methods that unity will call them in ur class
Update, or FixedUpdate
so basicly u just code some members, drag something into it in editor, then code something in Update method, unity will call it
Unless being referenced by another script, I don't think public variables is advised. If anything [SerializeField] if you REALLY want to drag them in the editor.
yeah, thats another way to make it, u set a member to private, then give it a [SerializeField]
if u know wuts it
its a "attribute"
since u just started it, not need to know how it works, just use it, if u learn fps, i can give u some words then u can search the tutorials as a study path
u need to learn: ray, collider, rigidbody, new input system
im learning from the essentials pathway rn and i just completed mission 1
Can be hard to break habits, start with good ones.
since u used to use C, u need to know: if some methods(function u can think it is) wont used in another class, set it to private, or u dont want it to be used in another class
and also private members wont be seen in the Inspector
i already know this
public int A {get; set;}
That's the same as 'public int A'
u can set the read and assign setting(public or private) for this field separately
and "get;" means nothing diff
Hi im coming from c++
the get set part was a bit confusing
or return another private value cuz u just dont want another class get that value directly
so i dont know how to use this for the moment
also like : set{_value = something;}
i mean value not _value
well its like something in java
u made a private value, lets say HP
others should change the value, thats cheating. but u also wanna get the value
so u write "public int GetHP()" method to get it
but Field just for more ez to make it
How hard is it to learn c#?
well can you explain with this example? and what's value?
no need to learn a lot if u learnt C++
i learn C++ before, then i just quickly use C# without learning
sure, wait a sec for me pls
not too hard, and since you know c++, learning c# will finally give you the will to live and not kill yourself
Ok cool then I just need to learn how to use unity which shouldn't be hard at all
SerializeField makes a variable accessible within the editor.
As a better standard though when working with scripts, you should look into UnityEvents and Public functions that 'return x' the value in question.
Making a variable public creates opportunities for cheats, etc. Not bad when learning, but not good long term.
create a project with "essential pathway" to learn unity
Essential what?
Making a variable public creates opportunities for cheats, etc.
this is completely wrong, cheating is completely unrelated
in this example, the get do nothing, it just give the user the speed value, BUT the set do something that it detect wuts the number of the value, then clamp it
and value means...let me make a example
Could've sworn I read this somewhere, how so?
i agree, what does cheating have to do with a public modifier
you can access whatever you want at runtime
That's a 3d project?
Guess i need to learn more, i'll shutup lol
in this example, bro code prevents users from changing speed to like 1 000 000 000 000
access modifiers do not exist in compiled games really, it's just something to help devs
here, "value" is the "1" in "Speed = 1;"
both can be learnt
no hating just pointing out 👍
How long does it take?
around 1- 2 hours i think
I got time to kill anyway might as well
C # has no header files, no function declarations, and no need to worry about pointers and memory leaks (references and GC management), so its basicly more ez version C++ and more better cuz there are a lot of methods u can ezly use to do anything
more better
fun fact: the # in C# means C++++
What about circular dependency?
when i use C++, i was using UE4, but i changed my mind into unity, so i just ask my friend wuts the diff, so my friend just tell me the default things(public or private when u didnt write it) is diff sometimes, and C# is more ez, and u need to know C# method can be: public void Hi() => ...; for one statement, so i just use C# without any learning
well, yeah
but diff
its just diff, once u met it u'll see, but tbh i didnt trigger it for a long time in C#
the last time i met this problem is about maybe 3 years ago
if u use unity, i think its not a problem, cuz u just wont write codes like that if ur good at it
Its only an issue with structs that try to contain eachother as members
C++ is the outlier with how its compiled as modern languages all take multiple passes
So if let's say file1 includes file 2 and file3 includes both of those. How is that handled in c#?
Wym?
Its not a problem at all
there is no concept of "including"
Oh
nah it wont happen
This will make life so much easier then
u will see it after u write
i mean its not a problem
Debugging that problem in c++ was so difficult 😭
cuz C# just is more ez and simple
that's kinda why people use c#
Anyway im sure you know in cpp we can use defines or #pragma once to overtime this issue
than when i use C++
I did use include guards but it was just the way my files were included
thats true, and when i use ue4, i mean its a little easier but still hard, and i dont like the way how to code in ue, so i use unity with C# now
perhaps you did something funny or are confusing this with 2 types including each other as non pointer members
Kinda wasn't thinking atm I guess
That's probably the first time I actually had that problem anyway
Sometimes we have to do weird things but c# is good in that respect
Unity has a very stable api too
I like those chances
at least i never met it in Unity
i just met once or twice in winform
its a... QT like thing u can say
Now there's only one problem left. Finding out how to embed lua🫠
people have already made that work in c# and for unity
u mean XLua or SLua?
What are those?
nvm, just found its all chinese
skip the link i send
I can't read chinese💀(yet)
They have english docs it seems
and it appears as the lib is english too so its valid so id say either option is good
Its very common for libraries to be in english regardless of the creators home language
I'd run the dotnet command outside of unity right?
you cant use that to manage a "project" because unity doesnt use that
some people use this package to grab stuff from nuget https://github.com/GlitchEnzo/NuGetForUnity
The "slap random files in your project" solution is outdated and a bit shit
It's possible to use c++ in unity?
thats a bit like cheating on Unity lol
u can compile C++ code as a dll then use it at runtime
Im not gonna use it im just asking because I see il2cpp in a few games I play which are unity games
i tried to do it before cuz i already have a small compiler C++ dll so i put it in
IL2CPP is a option in project, u can turn it on, then game wont be Mono but be IL2CPP way
yea il2cpp is not something we can use at will. you can use native code but it cannot interact with unity apis
And it'll behave like c++ even if written with c#?
if u mean write C++ code in unity, u need a dll
well, C# will compile to IL
then IL will compile to C++
this can't interact with unity api afaik so it'ds very limited
so yeah, u can say that
Why does that exist?
haha it very much does NOT behave like cpp
why dont you just learn c# and do it the normal way
cuz sometimes IL2CPP just faster than Mono, but IL2CPP is not the way u mean "C++"
I was just curious. Im not interested in it.
its just a build way, u can build by IL2CPP way
cool then lets end the discussion
Ok
people usually ask how to use c# in unreal engine but you asked the opposite question, kind of funny though
It's because I see il2cpp.dll pop up sometimes
did i say Unity API somewhere?
in the context of the question of "can i use c++ in unity"
cool
Ok I probably asked that wrong
no your question is fine
what's mono
The old ass backend that unity uses to run c#
They went with mono as it was the only way back then to run c# on platforms other than Windows
u can just think its one of these build backend, and it can run c# in diff platform cuz its cross-platform
wait il2cpp isn't cross platform?
Who doesn't love mono
il2cpp can cross cuz it compile by diff compilers
its a...AOT thing
compile these C# codes to machine code so it can run in diff platforms
but mono is a runtime way to make it, it just run IL at runtime
like java use JIT
I was gonna use c# for scripting one time
from what i know, il2cpp is also faster
It is. Its a more recent addition however.
Unity used to support JS and boo but as well for scripting but ditched them
thats too old things, il2cpp already here maybe after 2014
In relation to the engine existing it is recent
there are some vids to show it, i saw a vid talking about coroutine and UniTask with mono or il2cpp
anyway there is plenty of information online about mono and il2cpp
so go check that out instead of half baked explanations here
Goated for modding tho
now we can even build C# into machine lang directly
Melon loader 
with Roslyn or NativeAOT
unity physics are the best
Could someone please help? everything works fine, but after i restart the game, nothing in the main menu works and idk why, like literally nothing
well, the first step would be debugging
Hello ! I've created a projectile that every enemies shoot. But how can i pass parameter to the projectile (Speed, damage, lifespan) so that every enemies can shoot a different one ? Thanks.
(im using the instantiate's function but if you have better suggestion, i'll take !)
by getting the projectile class inside it...
when you instantiate it, you get back a reference to the gameobject
use that reference to get the projectile class component
Oh really ? It's that simple ? :0 ?
So i do something like...
"instantiate(projectile) projectile.speed = 12 projectile.damage = 16"
no
var projectile = Instantiate(projectilePrefab);
var projComp = projectile.GetComponent<ProjectileClass>();
projComp .speed = 12;
projComp .damage = 6;
like this
ahah omg it's that simple thanks !!
and if the player get hit, to access the projectileDamage value, i do like
collider.GetComponent<ProjectileClass>(); too ?
if collider is the object that hit the player yes
but, use TryGetComponent
not GetComponent
to prevent null references in case it was not a bullet that hit the player
after the game restarts, the buttons are no longer linked to the game manager (function), is that normal?
well, no
find out why
ok ty
By the way...
var projectile = Instantiate(projectilePrefab);
Whats the point of creating the "var projectile" value is it's not used later ? Im trying to understand unity's logic 😅
wdym
it's used locally
and you might prob need it to set the position and stuff
(and it makes the code look cleaner) lol
var is to just auto assign the value type btw
it makes the code look somewhat cleaner
OOOH okay now i understand better 😅 thx :>
Opened unity and now i am ready to learn
And appearntly the editor i have installed have a security issue
Because i never used unity
I downloaded it a while ago and it was just sitting on my computer
Yea i am just updated the hub
what version is it?
6000.2.5f1
yeah it's old
6.0 or 6.3 LTS
though 6.0 is much better and mature
6.3 works just fine tbh
I can't update from the editor menu? I have to do a full install on the new version?
eh considering everyone who comes with problems is always with 6.3 bugs
i never had tbh
yes
So im seeing windows support il2cpp does that mean if i wanted to export to windows i would have to have il2cpp enabled?
IL2CPP is just different backend type instead of Mono.
there are pros n cons
22gb for my basic needs is wild
(it's pretty good tbh) XD
laughs in Unreal
unreal is 50gb+ alone
Really?
you might wanna add linux
Already added
btw, this is unreal + its sources
never seen someone successfully build to mac from windows who knows if they ever fixed it
You need a mac to build to mac proper
So i would need to run all this on a vm
using GH actions you might be able to
nah, just the prod build
actions support unity?
That's what i meant for building
I would worry about this stuff later..
yep
learn the editor first lol
and i will prob get rid of Unreal now that i saw the full size XD
Relearn you mean
136Gb on disk
Didn't really have the chance to learn unity too much because my old laptop is bad
Wait i have unreal..
that was unreal + the sources
How big is it??
Well that explains where a big chunk of my storage went
btw next time this goes in #💻┃unity-talk
this is a coding channel
Ok
I'll just add it anyway
The only things i really need atm is android and ios build support
Hello! I need big help with my code. I made it that when a player is near a ledge the off balance animation plays but since I could still move around and stuff the player could move a bit while still playing the animations I tried snapping the player when its not moving to the corner but couldnt get it to work. can someone help! :(
I can send the code if u want the one with the snap and without
well thats the least you should be doing. we can't just guess around
every system is specific
you're probably using a ground check that doesn't make sense for your character
what's the intended behavior anyways
fair 😅
private RaycastHit2D GetIsGrounded()
{
return Physics2D.Raycast(transform.position, Vector2.down, PlayerHalfHeight + 0.2f, LayerMask.GetMask("Ground"));
}
private void CheckGroundAndEdges()
{
Vector2 basePosition = (Vector2)transform.position + Vector2.down * PlayerHalfHeight;
Vector2 center = basePosition;
float facing = facingRight ? 1f : -1f;
Vector2 front = basePosition + Vector2.right * facing * edgeOffset;
Vector2 back = basePosition - Vector2.right * facing * edgeOffset;
bool centerHit = Physics2D.Raycast(center, Vector2.down, groundRayLength, LayerMask.GetMask("Ground"));
bool frontHit = Physics2D.Raycast(front, Vector2.down, groundRayLength, LayerMask.GetMask("Ground"));
bool backHit = Physics2D.Raycast(back, Vector2.down, groundRayLength, LayerMask.GetMask("Ground"));
Debug.DrawRay(center, Vector2.down * groundRayLength, centerHit ? Color.green : Color.red);
Debug.DrawRay(front, Vector2.down * groundRayLength, frontHit ? Color.green : Color.red);
Debug.DrawRay(back, Vector2.down * groundRayLength, backHit ? Color.green : Color.red);
isGrounded = centerHit;
isNearEdgeFront = centerHit && !frontHit;
isNearEdgeBack = centerHit && !backHit;
anim.SetBool("isGrounded", isGrounded);
anim.SetBool("isNearEdgeFront", isNearEdgeFront);
anim.SetBool("isNearEdgeBack", isNearEdgeBack);
}
void HandleFlip()
{
if (rb.linearVelocity.x > 0.1f && !facingRight)
{
Flip();
}
else if (rb.linearVelocity.x < -0.1f && facingRight)
{
Flip();
}
}
so you want to just interrupt the nearEdge animation thing when moving away from ledge ?
Implementations of Func and generics
yeah! Its just so that when the player is near the ledge it snaps there so that the foor is on the corner
Then I can just walk off the ledge if I want to
you have code that snaps it there or you mean thats what you want to do
I tried making a code that does that but it didn't work I even asked chatgpt for help but that was no use XD I'll send it over
private void HandleEdgeSnap()
{
if (!isGrounded || rb.linearVelocity.y > 0f) return;
float snapAmount = 0.05f;
float moveDir = moveInput;
if (isNearEdgeFront)
{
if ((facingRight && moveDir <= 0) || (!facingRight && moveDir >= 0))
{
transform.position += new Vector3(facingRight ? -snapAmount : snapAmount, 0f, 0f);
}
}
if (isNearEdgeBack)
{
if ((facingRight && moveDir >= 0) || (!facingRight && moveDir <= 0))
{
transform.position += new Vector3(facingRight ? snapAmount : -snapAmount, 0f, 0f);
}
}
}
if you gonna modify positioning make sure you do so on the rigidbody itself not the transform btw.
not saying it will solve how broken it is now but it keeps things consistent accurate in terms of physics.
yeah , what exact behavior you want? why did you want to snap it?
so that the foot is always on the edge and not offset
I need it to snap under the foot but not that much that the left raycast touches the floor
Since there a gap between them if I move a little I want it to snap back to the ledge but still have the ability to walk off the edge
maybe get the raycast hit point ? might be better than guessing offsets
hmm the games I seen only add the behavior to the animation but it breaks the animation when you move, the snapping thing idk that might mess with gameplay too much no?
Yeah i understand
Leaving the feature out might make the game smoother
Alright yeah I'll trap that then
I wanted to do something like in rayman origins
have an example vid?
yeah this is just an animation tbh, no need for snapping
hello, im having a problem with my magnet object, everytime i attract an object it doesent stay in the magnet and floats around, how do i fix that?
well, the magnet is not strong enough then
add more force the closer an object gets
it's like real life
i use joints
when i attract an object, i create a joint
fixed joint
i would not use a joint
but move the object as a child of the magnet
and disable the object rigidbody
and then enable the rigidbody again later when detaching
i tried that and its too rigid and ugly, and then it will trapass walls and have problems
well, fixed joint does basically the same thing i think
no it doesent
it doesent trapass walls
yep, it basically is
then keep its rigidbody
and it won't trespass walls
if you code the magnet correctly
when i first implemented my magnet it was parent of the player, it had collider and rigidbody, it still trapassed walls
Alright I'll see what I can do then. Thanks for the help guys!
well, how are you rotating the magnet?
by just setting its rotation?
do you want me to share the code? But idk how to
well, that would help
send it via pastebin
so i can see how you assign to the joint
whats that
why did you send a .txt...
i did paste in pastebin and download
yeah that's so wrong...
you had to publish the pastebin and send the link
why all of these here tho..
just set them to public
no its better to be private
yes it is. there's no reason to make something public unless other objects need access to them. serializing them just exposes them to the inspector to be editable, making them public exposes them to anything with a reference to the object and can therefore be changed any time at runtime
one thing, did you check if the target RB is actually getting set in the joint?
i dont get it sorry
wdym
via the inspector during runtime
did you actually check if there is a joint and if the joint has the correct values set?
there is no joint in the object i want to attract, since i build it in code
yes there isnt
the magnet has a target joint
that script is assigned to the magnet i think
also, you are just creating a new joint in the magnet
for each object
so don't look at the one you already have
but check if a second one gets added to the magnet
with the right values
no it doesent
well, there's your problem
Nvm I'm back. I'm going to have to change colliders and ground checks because using raycast really isn't working :P
also, you are never setting grabJoint to null (tho i think Destroy might do that)
add a check if the first if is actually running
like a Debug.Log
it runs
but it never creates a second joint, hmm
do you use the joint you already have in the magnet btw?
sorry i meant to say it doesent run
oh
then check why
and
it is buggy
the second else will always run after the first run
causing some problems
!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.
how do i find out the problem tho
if (distance < distanceToBlock)
{
if (grabJoint == null) {
grabJoint = gameObject.AddComponent<FixedJoint2D>();
grabJoint.connectedBody = attractedObject;
grabJoint.breakForce = Mathf.Infinity;
}
}
else
{
attractedObject.AddForce(direction * attractForce);
}
edit the if to this first of all

