#💻┃code-beginner
1 messages · Page 366 of 1
I think it has already been explained before, I'm just trying to give them some examples
oh, i missed that part then . . .
can i disable my game collision to object by using
public extern void set_isKinematic(bool value);
What
I don't think there is a built-in method for this. You can store the previous position of the GameObject and calculate the difference between the current one, which, if isn't zero, can be used to calculate the force applied
you can obtain the speed of the GameObject by recording its previous and current position . . .
Where did you get this random piece of code
Spot on!! Thank you very much!
damn, too slow . . .
If you mean something about the rigidbody there was a function if for example you have a grab system and you punch it into the ground to detect how many force was being used
from class RigidBody
i am noob
What are you trying to do? There isnt really a way to detect individual forces applied to the rigidbody. Youd need to make your own script which takes in these forces applied maybe.
Unless your just talking about collision forces, which is provided through the unity messages
you can create a method that will set the rigidbody to kinematic . . .
You can just rigidbody.isKinematic = true or so
and will destroy collision?
The trouble with that was it would move forward in the "scene" regardless of how much I moved the camera angle, where as I want "walk forward" to relate to how the camera is facing - but I don't want the camera to move on Y unless the character is jumping etc... What Bawsi said was the problem, I forgot to add Space.World, now the line ignores the Y change
No
It makes the rigidbody kinematic
Certain collisions still happen
Thanks for clarifying this
ok ty bro
ty bro
If you really meant what i said earlier, (since you never answered) this may help https://docs.unity3d.com/ScriptReference/Collision.html (the part of relative velocity)
Basically, making the Rigidbody kinematic still calls OnTriggerEnter, assuming the method is in the class, which Rigidbody we're talking about, in certain circumstances. Of course, it doesn't call OnCollisionEnter
What does it mean?
in a unity game only using fields
buzzwords
you know worldtoscreenpoint?
frick my IDE in visual studio broke again, it doesn't show errors neither suggestions
what could i do?
And why have you removed your previous message just to write the same thing using 3 different ones?
Yes, I would assume
i tought u woudnt respond
studio or vscode ?
Studio
Have I exceeded your expectations this time then?
you tried regen project files ?
worldtoscreenpoint = transforming a world position into the camera 2d position
i did
can you show the solution explorer
Maybe go through the ide configuration again. Did it break for every script, like you close VS, open a script through unity and it doesnt have highlighting?
Yes, it transforms the world position to the screen one, which is in pixels
wdym with Solution Explorer?
Yeah
yep there is another way u could do this using 4x4 Matrix
inside Visual Studio, the solution explorer tab/window
my question is how can i get the matrix
Is it specifically world-to-screen matrix are you looking for?
Generally for transforms you'd use https://docs.unity3d.com/ScriptReference/Transform-worldToLocalMatrix.html
i want to transform a world position into a screen pos (Vector3 to be specifical) using worldtolocalmatrix
nvm fixed, seems that i need to reload project files more than one time sometimes
ty tho
is there is a way i can get this by fields?
That's what this method does
yep but i can get this through fields?
What does it mean?
[SerializeField]
That is an attribute to serialize a field
That does not explain what you are asking though
What is "this" and what are you trying to "get"?
You can of course make a Transform typed field if you want
Transform myTransform
no how can i get in a random game
That is even more vague.
like is there any universal method?
To transform the world to the screen point? Camera.WorldToScreenPoint()
how to find a game gameplaymodule class?
nope bro
Gameplaymodule !?
i am trying to learn unity
okay, i know fully get it, thank u very much :>
maybe i am to noob to ask correctly
You should ask what you're actually trying to do gameplay wise. Not code wise
So does it work now?
Are you asking how to reference a component?
https://unity.huh.how/references
yep
ty
Hold on. So, this whole thing with matrix was to reference a component?
no i had other question b ru h
but i am too nob
what is the property bounds in class Collider do?
Stores the bounds of the Collider
nice ty
So confusing
Well the name literally tells you this
Raycast in class Physics is used for what bro?
To create the raycasts
can my scroll view be able to switch between different content? like have 2 different content objects and whichever is enabled is the one that scrolls
it won't let me scroll the 2nd content when active
under the Viewport
what are raycast used for
To detect the collisions
Querying an area for colliders
it can detect when a player is attacked?
Yes
ty
Is the attacker has a collider
I mean, if your attack relies on a raycast. Otherwise no
Also, why would you even detect an attack on the player if you have the data of the Enemies
It won't tell you that the enemy wants to attack you. Just that an enemy is there
if i destroy my raycast i destroy my game physics?
Yeah, exactly. You'll have to reinstall Unity after that
You don't destroy raycasts.
It is merely a query. It asks if something is there. Either yes or no
If I destroy my question I destroy whole discord? 🤔
No, this is mid
That is a ray
Not a raycast. You can use the ray for the raycast
how can i make it better
yes bro i am tying to learn the insides before making code for my game
Don't create a useless struct?
You should do !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
oh so should i make parameters without the struct
Yep - transform.Translate(new Vector3(Camera.main.transform.forward.x, 0f, Camera.main.transform.forward.z) * panSpeed * Time.deltaTime, Space.World);
What parameters?
Did you looj at the docs?
You can use the ray, or plug in values directly
oh right
i am bad at reading doc
Replies too
Ray ray;
ray = new Ray(cam.transform.position,cam.transform.forward);```
ray already made for ya, just fill it in and use it
they are both vector3?
yes
oh ok
Yeah, you can manage this by accessing the content variable via script
I highly doubt there're any components for this
Additionaly, you usually wouldn't need this. Simply let the content be the same, and instead change the items inside of it
This way, the content just shows the enabled items, which prevents you from changing the view's contents
what is freezerotation in class RigidBody used for?
To freeze the rotation
It is literally self-explainable by its name
The rotation gets freezed and is not changed
freezes the local rotation of the rb
so you cant rotate ur camera?
world rotation if its a root gameobject
Are you looking through the class and just becoming curious about every single property?
Why does your camera have a rigid body
it doesnt my bad
You cannot change the specific rotation axis of the certain Rigidbody. As previously mentioned, you should consider reading, first, the variables' names, second, docs for the desired variable
Did you look at the docs. You are required to do some research before asking questions here
#📖┃code-of-conduct
Also, i really do suggest just going through !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
sorry i will go read
How do I get this to work?
I'm still confused what you are trying to do with item
Make it an actual statement
chestloot is a List so use an indexer
You aren't actually DOING anything there
What are you actually intending to do with item
Hey im new here and im wondering where can i request or get help to specific problems?
learn to use lists
In whichever channel is close enough to your problem
Hi ! I don't understand my error :
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List1[T] inEdges, System.Collections.Generic.List1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <0e6f69b30d82405f98d87804eacb548a>:0)
Can you help me with this ?
Unity internal error, won't affect any builds, you can ignore it
If you're getting this error often, reopen unity and or reset layouts
how can i rotate the transform.up 90º to the left or right?
transform.Rotate(0, 0, 90);``` for example
or:
transform.up = Quaternion.Euler(0, 0, 90) * transform.up;```
"left or right" are not really good ways to describe rotation though
A better way would be "clockwise around the z axis" or something
i´ll take this one since im scared of quaternions
true
this one would be clockwise right?
clockwise around the object's local z axis
Hey, just switched around the responsibility so its the damage dealer making the enemy take damage instead of the enemy damaging itself from the damage dealers collider. The issue still appears to persist, however.
its triggerentering multiple hitboxes and damaging the victim for every hitbox it gets hit by
Did you add any other logic? A hashset storing the rigidbody for example should suffice. You check the attached rb, if it's already in the hashset then dont do damage again
whats a hashset?
and no i just switched around the fields basically lmao
Google will explain it more clearly than I can, it's just a collection of objects at the end of the day. You can also use a list too
but what if i want to damage the same guy twice in seperate damage instances?
that won't do anything at all!
then you need to track two separate instances of damage
i switched the responsibility is what i meant to say
stop and think about what's going on here -- if you don't remember what has already happened during this attack, then you will always get multiple hits
because how are you supposed to know if you've already hit the enemy or not?
2 different instances would store different collections of stuff they damaged. If you are pooling objects, then clear their list or hashset when you want a 2nd damage tick
im not pooling objects, this is for a fighting game
Could someone help me with a Unity build problem?
i think i've got an idea
hopefully that idea is "track which hurtboxes you've already hit per-attack" :p
i dont see how this will fix it, though. if i it the arm and the head with one hit, it should only damage the player once. if the attacker is moving and more colliders are hit while the attack is active, then wouldnt that break your logic or am i misreading it?
Each attack should track which hurtboxes it has hit.
It should only cause damage if it:
- has never hit a hurtbox yet
- hits a hurtbox that's better than the previous hurtboxes (if you have that kind of thing, at least)
Well the idea applies to stuff like damaging areas too where you want to deal damage to every single thing inside some area over time.
I don't see how moving and hitting more colliders would cause a problem here.
hold on i have an idea, let me cook real quick
Each attack instance (e.g. each swing in a combo) tracks the hurtboxes it has seen
that's it
okay i think i got it
(and pooling the hash sets would be reasonable!)
what is pooling again sorry?
in fact, UnityEngine.Pool.HashSetPool<Hurtbox>.Get() is right there (:
instead of allocating a new object and then throwing it out (so that the garbage collector has to eat it), you re-use the same object over and over
var hurtboxSet = UnityEngine.Pool.HashSetPool<Hurtbox>.Get();
// sometime later...
UnityEngine.Pool.HashSetPool<Hurtbox>.Release(hurtboxSet);
If the objects themselves are pooled, I think this is pretty much the same since the instance at the same time would make a new hashset
Oh yeah, that's also reasonable
I do that in my AI planner system
i see. i think the main issue is that im not spawning hitboxes in, I'm animating a box collider that is attached to the player
it pools the PlannerState objects, which contain a big pile of hurtboxes
this is irrelevant
we're talking about individual attacks here
i don't think we're on the same page here...
I think you just need to start implementing the code where an attack tracks what it hit, and then itll become clear what you actually need to do
or rather remove whats in it
okay, thank you
to clarify here...
if you allocate a new hash set every time you attack, you don't have to clear it at all
you throw out the attack object and it gets garbage collected at some point
you never see the hash set again
you could set the variable holding the hashset to null, but that would change nothing
if you pool your attack objects, then you must clean up the object before you re-use it
part of this would be clearing the hash set with the Clear method
Setting the variable to null would defeat half of the point of pooling, since you'd have to then allocate a brand-new hash set
Clearing a list/hashset/dictionary does not make it give up the memory it's using. When you fill the collection back up again, it won't have to ask for more memory
That's the big win that pooling gives you
My AI planning system uses and modifies tons of hash sets, but it generates very little garbage
everything is getting re-used
can i ask what you define as an attack in this case?
i just wanna make sure im getting everything crystal clear
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
If your character has a three-jab move, that's three separate attacks
Each jab can cause damage.
and each jab does not care if the previous jab happened to hit something
https://gdl.space/ronobahuyu.cs, https://gdl.space/yidajikufu.cs does someone know why when i shoot my bullets go up even if i point left?
An attack should probably correspond to a single animation being played.
but you could totally have a single big swing that can hit over and over
I haven't played Smash in a while, but doesn't Roy's Up+B hit enemies many times?
That would be many separate attacks going off very quickly
each one with its own hitboxes
im pretty sure smash like spawns hitboxes in world space
from what i've read in the wiki
sure
each attack creates a set of hitboxes, and if those overlap an enemy's hurtbox, the attack connects
Hello, I'm having a problem, today i made a build of my game but then it suddenly had a like dark gray screen, i'm not able to interact with the game but i hear the background music and only that. Sometimes it flashes up and i can see the game for half a second before it disapears once more. I looked around the Unity forums but non of their solutions seemed to fix mine. It has only being doing this since today. Yesterday everything was working perfectly fine.
I'm on Editor version 2020.3.29f1 if it helps
Please @ me if you found a solution or want to help!
Thanks
yeah, thats how my thing worked too. i think i sorted out the issue now though
i did what you guys said, every time the hitbox is active, if it hits a collider it adds the root player's character script to this hashset. if it hits something and the same root object is in that hashset, it ignores it. when the hitbox collider is disabled, it clears the hashest.
idk if this is the right way
the main issue is avoided, that being repeat damage instances
but i feel like projectiles and stuff are going to be a whole other beast
that's fine as long as you don't want to have different kinds of hurtboxes
different kinds in what sense? if you mean like vulnerable hurtboxes or whatever i dont plan on doing that
wouldnt make sense for my game i think
if (!hitCharacters.Add(_hitCharacter))
{
print("Already hit this player!");
return;
}
``` this is the base of the logic
you might want to have a hurtbox on a character's limb that isn't as important as the center of their body
ah yeah, no i dont have that planned to do
if (!hitCollider.enabled)
{
hitCharacters.Clear();
}
this runs in update
i feel like there is a smarter way to do that
I am open to suggestions
how can I not get bulldozed by the enemies if Im staying still and how can I not get slowed or stuck in them when I got the min amount of speed to be able to run them over
!code
the code that disables the collider should directly communicate with the script to tell it to clear
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
or an event that gets invoked
the animator disables the collider.
i could use an animator event but
that would mean going through like 120 differrent moves and switching them all out
and i dont wanna do that so
why does the animator affect your collider
the animator animates the shape of the hitbox collider
yeah
uh, idk then tbh. but i can say there should be a cleaner solution
if anyone got knowledge on this and could help me please
ight so
basically a car drifting, when it has a certain amount of speed it should run through enemies else it would get damaged leading to death(not introduced yet) and when the car stays still it can get moved around by the enemies, instead I want the car to remain still and the enemies to just basically circle it round
@buoyant knot
Disable the collision between the car and the enemies according to the certain speed
Using Physics.IgnoreCollision
Ignoring the collision when the player is not moving can be valid if you ensure the enemies don't get thru it
what do I add inside the parentheses
So you ignore it when
- The player is not moving
- The player's speed is high enough
And don't ignore when - The player is moving at a normal speed
Which ones?
this one
i would not do this
i would either change the layer or settings on the collider
Have you opened the docs?
or enable a separate trigger collider with the given settings
Can you help me with an error in a code that I don't know what it is?
Why?
eg, have a trigger collider for the hitbox, and a trigger collider for your hurtbox. Then in FixedUpdate, based on speed, enable one and disable the other
Why would you make the enemies, in their case, get thru each other?
https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
Ignore collision ignores collisions between a specific pair of colliders
Yeah, that's why use IgnoreLayerCollision
Ignore the collision between the Enemy and Player layers
you didn’t use ignore layer collision
I forgot to mention it
you said IgnoreCollision
Yes, I was about to say it when writing this message
@ember gate use layers
and you don’t need IgnoreLayerCollision either. that is a bad idea
This is much more efficient than ignoring the collision between the player and every enemy
IgnoreLayerCollision changes the rules for how ALL colliders interact with each other
what he/she wants is to change the rules for that specific player object
which is simplest by either changing it to a different layer
OR have 2 hitboxes of different layers and settings, and enable only one. I would only do that if the settings are wildly different and specific
If, for some reason, there is no wish to use IgnoreLayerCollision
you don’t need to use that
just change the layer of the one object you want to change
I got confused so my car is on the Player layer and the enemies are on the Enemy layer
do I change the car layer?
yes
like make a layer that is SolidIgnoreEnemy, and a layer that is Player
or just change the settings of the car’s collider
I don't see why you would have a 2nd layer if you can simply ignore the collision between the existing ones
You have to provide the error to receive help
this is a layermask of layer overrides. Whatever your layer is, you will additionally receive forces from whatever is here
and reverse for forceSendLayers
@static dune dont ask to ask, just ask
how come it keeps giving me errors for line 27 whenever the ray isn't over the object
you can also have a separate trigger hitbox to allow your player to destroy or be damaged by enemies
The code does not store/save the scene, what is wrong
So you're saying that IgnoreLayerCollision doesn't simply change a single boolean for the collision between two layers? Instead, you would like to simply change the layers.
What error?
IgnoreLayerCollision changes the rules for the whole goddamn world
which is not what we want
object reference not set to an object
b/c there isn't a hit or a collider to check the tag on..
so when u try to access hit theres nothing there
What kind of "goddamn world" are we currently talking about?
You should check if RaycastHit is valid

we want to change the rules for the one object interacting with everything else
how should I do that
Return value of Raycast
just check if hit is not null
so you should change the settings on the collider
either changing its layer or its layer overrides
then any changes solely apply to that one thing
So why is IgnoreLayerCollision not valid for that? Does it somehow rewrite the whole physics system or what?
what if he/she later has a second object in the same layer?
you are now changing the rules for it, for no reason
like if you add a second car or whatever
Why would they have a 2nd object in the Player layer?
because you have no clue what features they might add a year from now
but by using IgnoreLayerCollision, yoh are changing static variables that apply to everything
idk why it gives an error
So what if they have another layers depending on the collision with the Player layer?
Because it isn’t a static field. It is a field of an object that is a collider2D
so you get a ref for the collider2D of the car, and then say myCar.forceReceiveLayers = whatever
^ u don't call AddForce on a Rigidbody.. you call it on an instance of a Rigidbody.. Rigidbody is the class for all rigidbodies.. same thing here
Collider2D thisCollider;
thisCollider. dadada```
= the layer I want to swap to right?
layer overrides affect how forces get calculated, or contacts get generated (which affects calling OnCollision/Trigger calls)
it would be a whole layer mask
and that layer mask should have the relevant bit for the layer to receive forces from turned to 1
and 0 for layers where you don’t
So basically a method marked static is for general Rigidbodies, and non-static methods are used for the specific ones, which references are being used for its call @ember gate
making a layer mask from layers is a really important part of working with the unity physics system
like if your layer mask says to interact with layers 2, 5, 6. Then in binary that is 000…001100100
i think Unity has methods to do the conversion
important class for working with physics
static methods/fields belong to the definition of the class, and not to any one instance
wheres the OP?
probably writing code
nah i mean the post
So what error is thrown?
im confused on what even he's trying to do.. i just stepped in
this
thankyou
the goal
trying to process all the messages while reading the doc and writing code aswell
ahh ok i see
note that layer mask and layers are not the same
The code doesn't store the scene,
When I want to check if the code works, there is no saved one
a layer mask is a bitmask. it is a number where each digit in binary corresponds to a specific layer being “on” in that number
so layer mask 5 means YES to layers 0 and 2, because 5 = 000…00101 in binary
oh ok I understood I think
i assign layers in an exposed variable for my layermasks..
im really bad at all that bitshifting stuff
in the context of a contactfilter2D, this would be like one number that tells you all the layers you can touch when you raycast
it hurts my brain :d
in the context of forcesendlayers, it’s all the layers to which a collider can send forces
same for forceReceiveLayers
the LayerMask docs tell you what methods that class has
Does manually dragging components into variables rather using GetComponent optimise the game, and would it actually help with loading times to do that when possible?
any getcomponent u get rid of the better ur performance is
but theres nothing wrong with using them for initialization (1 - time use)
like in Start() or Awake()
u can use getcomponent to cache ur variable.. and then accesss that cached variable..
not the getcomponent call each time
https://openupm.com/packages/net.tnrd.layertagsgenerator/
This is a useful plugin for working with layers. It autogenerates a class with public constants with useful names for each layer. Because unity was too lazy to do something sensical for that.
very handy!
i'm using it
it makes a class called Layers where you can use Layers.PLAYER to get the layer number of player. And Layers.PLAYER_MASK to automatically get the number corresponding to a layer mask of just the player
Installed it now aswell
Yes I understand, was wondering if having like 500 game objects all of which do this in Awake would slow down the initial load time
and thus you can do Layers.FLORP_MASK | Layers.BLORP_MASK!
[SerializedField] private Rigidbody myRB; --> assign it via inspector
private Rigidbody myRB;
myRB = GetComponent<Rigidbody>();```
Does it have something to do with you just getting the ^2 object from the Stack, which, if there are < 2 scenes saved, is null?
i wonder if that compiles down to a constant. C# isn't nearly as aggressive as C++ can be about such things
500 of em would be noticeable.. but Initialization stuff.. like the beginning of the game.. ususally has a loading screen.. (fading from black)
so you can do LayerMask playerAndEnemy = Layers.PLAYER_MASK | Layers.ENEMY_MASK;
and that is a layer mask that includes player and enemy
Don't ever mix your Florp mask with your Blorp Mask. You'll intransilate the floobmapper.
that can give ur game time to load up correctly..
what I do not get is idk what should the forceReceiveLayers equal to @buoyant knot
The future is now, old man
True, thanks for the help. I guess I should manually drag the variables in when I can for initialisation then
when you don’t want to receive force from enemies, then I would just set the relevant enemy bit to zero, so you still collide with terrain
God I hope some generative AI picks this up
I did that but it shows me this
yup, the only time u should be worried about using GetComponent is for things that u Instantitate into the game at Runtime.. or references from the scene that a prefab needs.. that can only be asssigned after initiation
everything else can be assigned via the inspector
eg myCar.forceReceiveLayers &= ~ Layers.ENEMY_MASK;
~ is the bitwise NOT, which flips all 1 and 0
I guess that’s where object pooling comes in clutch
it needs to be the specific collider2D instance
or wait u meant Collider2D as a general thing instead of it I should put my car
ye I got it now
yes
So why aren't you using it?
Colider2D.forceRecieveLayers is the name of the property (as it is defined), which is not static, and you can only use on instances
so if Layers.ENEMY_MASK has only the enemy bit set to 1, then ~ (that) is all bits are 1 except the enemy layer bit
&= takes each individual bit, and ANDs it. So if every bit on the right hand side is 1, then & makes the result the same as the left hand side. But since the enemy bit is 0, that AND forces just the enemy bit to be 0.
I don't think this is what you mean
idk im sorry im stupid I haven't coded in unity for a long time
you need a layermask
0 is not a layermask
you have to explicitly cast it to a LayerMask
because unity is too dumb to figure that out by itself
does your IDE at least acknowledge that property?
it should automatically find the right property in like a dropdown list
what is the error
which version of unity are you on
i think thats 2022 property
force overrides were added later
DAMN
yeah. it’s semi recent
2021.3.19f1
DAMN XD
Unity 6 is about to be out lol at very least use lts 2022
layer overrides make life vastly easier
does the game change a lot if I change the version?
I mean its not much to it anyways
nothing would change much code wise (would make sure third party tools / assets are compatible)
always make a git commit before doing such drastic change
its not drastic I got 5 objects on the screen and 5 scripts
basically the UI changes around.. some things get deprecated / or their names changes the very most
then ur fine
thats not LTS
or unity6 6000.0.4f1
just back up the project
btw https://www.youtube.com/watch?v=5IxUElilf2M something you should have
https://git-fork.com/ my obligated Github Desktop alternative plug
fork is good client but might be too overwhelming for beginner
true.. the revert changes and check-outs and stuff might be a bit much
for ur basic push/pull stuff its pretty much the same
the documentation could be better tho 😢
i get help from my friends that use it when I get stuck 😅
doing that tutorial rn
if its too overwhelming.. u can always duplicate ur projects folder and zip it up as a backup
but learning how to use version control is a must eventually
valid , I just wouldn't include Library folder unless you want to wait long xD
but then u have to wait to rebuild. its a double edge sword 😛
true.. thats a good general point
the Library folder is included in the gitignore.. b/c its HUGE and Unity rebuilds it automatically when u open a new project..
soo if u want to u can delete it completely.. wont hurt anything.. and when u put ur project up on version control it gets excluded automatically (if ur gitignore is correct)
yeah, this is just for the sake of making a local backup
damn it took me so long
hi could someone help me figure this out? im trying to make a wizard shoot a fireball in a 3d topdown game but i cannot get my head wrapped around what im supposed to do
anyways imma go to sleep too exhausted to process all the stuff that were received by my brain, good night
most of the things ive found are about shooting towards like a point, but i just want it to move in the direction that the mouse was at
Are you following a tutorial or something? What part is getting you confused?
im not following a tutorial, ive been looking at ways that other people have done it and cant seem to get it to work for me
In this case - you'll want to just convert your mouse position to a world space position. I recommend using Plane.Raycast. You can find a code example for that here https://unity.huh.how/screentoworldpoint#alternate-methods
Then you can shoot your fireball int he direction towards that world space point
oh okay, thank you :)
Hi! I have a small generated dungeon and got some performance issues with the amount of objects increasing. Can you give any links on how to improve and optimise procedural generation in Unity. Thanks in advance!
You'd have to use the profiler and see what part of your code is causing problems
optimization goes like this:
- Use the profiler to identify bottlenecks
- Think about how to optimize those parts
- Do the optimization
- Go back to the beginning
If you have no clue where to look, you can use Deep Profile to see every single function call. This slows things down a lot and unfairly punishes small functions (since each function takes longer to run).
you can then add your own profiler markers to areas of interest
moduleMarker.Begin();
foreach (var moduleList in moduleTypeMap.Values)
{
foreach (var module in moduleList)
{
if (module.Tickable)
{
module.ModuleInfo.Marker.Begin();
module.Tick();
module.ModuleInfo.Marker.End();
}
}
}
moduleMarker.End();
...maybe like this!
Thanks guys, I'll try to locate the bottleneck
Are these advice for finding issues in my own code or can i use it for analysing frame render?
I thought of some articles about runtime light or culling, as far as I know they don't work out of the box
Can someone please tell me what in this is making my player slow fall (I am new to bolt)
yep the whole ass thing is what's doing it
you're explicitly setting your Rigidbody velocity to 0
On the y axis
C# code equivalent of what you're doing:
rb.velocity = new Vector3(something, 0, something);```
You need to put in the rigidbody's exisitng y velocity in for y instead of 0
it seems to have worked!! thank you so much, i've been trying to figure this out for hours lol
Would there be any way possible to make land like this from Sonic with decorations on top procedurally generated?
SpriteShape for the ground: https://docs.unity3d.com/Packages/com.unity.2d.spriteshape@3.0/manual/index.html
procedural generation for the decorations would just involve either sampling the sprite shape, or doing raycasts along the top surface randomly
Alright, thanks!
I already tried to add a Rigidbody Get Velocity --> Vector 3 Get Y --> Y of the vector 3 create but the player would only fall normaly if I pressed a key to move the player.
Oh wait, I meant it as in the land is procedurally generated randomly. I think I already got collision on the ground, but I haven't opened this project or used Unity in a while, would I still need the SpriteShape?
yes, that's what Praetor was describing
using SpriteShape to make ground that goes up and down (and generally has randomly-generated shapes)
Oh alright, sorry.
Hello, I want to get some advice for my enemy spawn method.
I have EnemyAvailableList with 10 game objects(the enemy), which will spawn 3 each time(set active), when no game object is available, all 10 are active, and will instantiate a new enemy, will not Destroy() this instantiate object when killed by user, instead add it to the list for later use. And I believe they will get cleaned up automatically when switching scene or exiting the game.
do you see any issues that could caused by this method and impact the game?
You put things in the wrong place then
hey, im a new scripter and this code doesnt act as i intend it to.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovmentScript : MonoBehaviour
{
public float movementSpeed = 15f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
if (Input.GetKeyDown(KeyCode.S))
{
transform.Translate(Vector3.back * movementSpeed * Time.deltaTime);
}
if (Input.GetKeyDown(KeyCode.A))
{
transform.Translate(Vector3.left * movementSpeed * Time.deltaTime);
}
if (Input.GetKeyDown(KeyCode.D))
{
transform.Translate(Vector3.right * movementSpeed * Time.deltaTime);
}
}
}
the problem is that i have to keep pressing the key repeatedly for it to move
when I want it to move smoothly while holding down the intended key
Take a look at this:
https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
That method only returns true the frame you start pressing that designated key
You are most likely looking for https://docs.unity3d.com/ScriptReference/Input.GetKey.html
what you describe sounds like Object Pooling
or are you talking about like enemy waves ?
Ah yes, this has fixed my issue, cheers.
Sort of like pooling + instantiate when needed more enemy. So like when increase game difficulty will require to spawn more enemies and the pool might not have that many objects to use
your pooling system can auto-add more to the pool if empty and you need more . . .
that's what i did . . .
then you can remove the added instances back to the normal count when the current active instances hit below a threshold . . .
Im tryina make a custom cursor and also lock and hide the system cursor, but for some reason its telling me that i cant do that anymore. Underlines with red and says "does not contain a definition for lockmode/visible" since when has this changed and whats the new way?
Did you name your own class Cursor? It might be picking up that one instead of Unity's
Ahhh sheit, definitely that, thanks lot
im new to C# and dont know how to program pls help
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
start with the pathways
i realise this might sound like a stupid question, but does LateUpdate always run after update?
LateUpdate is called once per frame, after Update has finished. Any calculations performed in Update will have completed when LateUpdate begins. A common use for LateUpdate would be a following third-person camera. If you make your character move and turn inside Update, you can perform all camera movement and rotation calculations in LateUpdate. This will ensure that the character has moved completely before the camera tracks its position.
Yeah, that’s the point. To ensure other Updates are all done.
its literally in the name 😛
If I am making a survivale game, should I make every breakable item an scriptable object?
scriptable objects should just be container of data they cannot be gameobjects
should I contain the data of each item?
what could be a way of facing these breakable objects I get resources from
well make it a prefab but the data itself can be SO
or an array of SOs and maybe randomize it
okay, thanks!
I would make a MonoBehaviour called Breakable, and then when doing damage, do
objectIAttack.TryGetComponent(out Breakable breakable) {
breakable.GetResources();
}
The breakable component could certainly have its resource data be an SO
Okay, thanks a lot
Ill start with the collectable resources
the SO can also contain an array of resource prefabs and then pick from there etc
It looks correct maybe im wrong?
Is it okay if all of my pickable items are enums in order to be displaced in the inventory?
they could but, just have to keep modifying the enum each time you add one
is there a better way to make this inventory?
SO + Poco is usually how I do it
Hey, Im making a multiplayer(Mirror for multiplayer) fps and I'm using animation rigging. Im assigning the target for "Two bone IK constraint" through code when the player is spawned. But when that happens the actual movement for the arms (that have the TB Ik constraint) doesnt happen. But if the target is assigned before starting playing it works. Does this have anything to do with Mirror or am I making a mistake?
This is how I assign it.
RightIKBone.data.target = weaponComponent.RightHandIK.transform;
LeftIKBone.data.target = weaponComponent.LeftHandIK.transform;
What is Poco?
like a Plain Old Clr/Class Object
in other words a regular class or even a struct
thats where my Mutable data goes
Okay, I think I get it, I´ll try that
the SO has the base stats, then create the plain object. that I can change damage and whatever on it
but what if the object is an apple?
what about it?
if you mean separating between consumable and whatever, that can be an enum for sure
how many types of resource can really exist, they are usually already defined ahead of time
depends what you're going for , now you're getting into a very complex topic
U usually use modularity though
Abstractions are delicate
oh okay, maybe Im going too far for my knowledge
start with simple items, and simple things like enum sure
Only abstract when absolutely necessary otherwise you are just adding unnecessary complexities and making it harder for yourself to debug at least from my experiences
multiple enums per object doesnt hurt if it makes it easier for you
ie
Consumable vs
Stackable non Stackable
etc.
Okay, thanks for your help
why cant i drag the audiosource to the audiosource var?
you cant drag scene objects inside a prefab
in what way can i do it then?
put audio source on shotgun
np.
its good a idea what ur going for but sometimes its better to Keep it Simple stupid
you would use an Audio manager which would have a static Instance, that would be easy access to play sound on an external component
or the component can be passed if its instantiated
noted
is it better to use the "Invoke Unity Events" option in while using Unity´s new Input System?
it depends how you want to interact with your input. use the unity events or the c# events . . .
Whatever works the best for you and your systems ^
Okay, thanks!
I do prefer the events (either c# or Unity) over messages. You can subscribe many different methods to each event, and the name is mandated to be On[ActionName] like sendmessage
ive been pursuaded to think SendMessage as being bad
not sure why i feel that way lol
What is this holy
what
That’s because the SendMessage method on MB is inefficient and uses reflection. I don’t think it’s related to the one used in new input system though
I think it's one of the last options on the component
How can I freeze ONLY my player once the inventory menu is shown on screen?
Have a bool that you check before moving your player
not working
If you say so
I freezed the constraints of RigidBody
that's not enough context. we have no idea how you implemented it . . .
that'll work too but still need a conditional, like a bool or to check if the menu is active or not
The player continued moving even when the conditional (freeze) was set to true
however i think I partially solved it by freezing the constraints of the player´s rigidBody
was the conditional freeze supposed to stop the player from moving?
yes, if the conditional was active, rigidbody.velocity was set to Vector2.zero
I also tryed it with the vector I was using as movementVector
that's an important detail to provide. we don't know how you tried to stop the player from moving . . .
so it never stops. it just keeps on moving?
I managed that with a UIManager that unchecks the player movement script and the player input script
yes, in one direction
but I managed to more or less solve the problem (i think) by freezing all constraints in RigidBody
You can't put it in before normalizing etc
It needs to go in at the end
how do i take a random position of a axis of a plane? for example if i have a plane and i want to get a random position in the bounds of its x
If it is a root object, or its parents are scaled at 1, then RandomRange the x scale
ye but what do i put for min tho
Then just add that to the position - x scale / 2
Zero
oh
Plane as in linear algebra doesn’t have ‘bounds’
If Plane is just your game object then random range sure
is it okay to create scripts just to organize variables for a specific object/task?
I don't want my main script to end up being a monster script with everything in it, but it feels a little awkward to use obj.GetComponent<Script>().variable when I could probably just declare the variable in my main script
ie. im wondering what the best practice is
single responsibility principle (SRP) . . .
you shouldn't need to call getcomponent more than 1nce unless u have to either..
cache it and use that instead
each class has one responsibility, not multiple . . .
kk yeah I'll just stick with what I have then
is it normal for a decent sized game to have quite a few scripts
is this a real question?
Very vague
Sure 🤷♂️
yeah there isn't a "guage" for normality..
is it better to minimize scripts or just not worry
you got as many scripts as you need, doesn't matter
You’d need to define “normal” “decent size” “quite a few”
I feel like you have asked this quite a few times, or at least variations of it.
The answer given has usually been to split responsibilities
i'd think so to but this one i don't think so that i can remember
but i'm also very dumb
Don't worry about the number of scripts
minimize scripts? you're never going to have too many scripts. there is no way to define, "decent sized game," or "quite a few," scripts . . .
gotcha
i basically live on this discord sometimes so
yeah i'll do that thx - thought it wouldn't work but I confused myself over the value vs. reference stuff
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Brackeys and Code Monkey
hey ehh,How to do the Cursor lock in unity?
you tried looking on google
alr,I'll try
its like the first result lol
Bruhh,its kinda ez af lol
Hey guys
Can you learn coding in unity on the unity learn hub
Like the language for unity projects , what we use
i want a place to store certain functions (abilities) so that with some parameters i can call them from anywhere (eg. player script or enemy script). how do i go about doing this?
i want to be able to call Abilities.Explode() or similar from both player script and enemy script. there's a lot of way to do this, but what is ideal? (to keep things organised and not run into a plethora of future problems)
the learn website?
abstract class or interface, if you arent already using it. Abilities implement whatever they want, not specifically an explode method but like an activate ability method and one derived class may do an explosion during this.
i mean to code in unity
Yes, you can learn it on unity learn. But it's also advised to learn it outside unity context before that.
hey! im trying to add a Animation for UI image, how can i achieve that? couldnt find a proper topic on the internet. Thanks !!!
The same way as any other object: animation/animator or code
If you want a tiling/repeating texture, is having a shader/script to change the tiling of the material a must? It feels so common a usecase that there must be a way builtin
i builded my game and now the character moves slower than in the one i open with the unity hub, is it something that i can change via code?
I need a enemy follow player script
hi guys I have a question! How do I access an enum from a scriptable object class to another script using monobehaviour?
ok never mind i just wont use enums at all 
Enums are useful for many cases. What do you mean by accessing the enum? Is it a public variable on the ScriptableObject of a specific enum type?
So, this is the definition of your ScriptableObject class. Do you have any asset of this class? (I'm not sure how familiar are you with SOs)
Do you mean the actual asset (data container)?
should i use raycast or physics2d.overlapcircle for my groundcheck?
Same as any other type/variable(depending on what you mean) defined in an SO.
Up to you. Both have ups and downs.
what are the ups and downs exactly? and also are there any other methods besides the two i just mentioned?
Raycast:
- would not detect colliders that it starts in
- only checks a ray, so you character would not be grounded when standing a bit below the edge
- would require some specific logic for deciding if you're grounded. For example, checking the distance of the hit.
Overlap: - Would still detect collision even if you're at the very edge
- would require some logic to not become grounded when colliding with a wall
There are probably more things that I can't come up with right now.
As for other methods, you could also just use the collider collision events.
Yes. Because as @teal viper says, once you have the asset referenced in your MonoBehaviour, you can access the variable just like any other.
I just read somewhere that unity serializes enums using their integer value so if I added more to the list it can cause problems. I'm just going to make the scriptable object reference to another scriptable object
OnCollisionEnter & OnCollisionExit:
- Is more precise
- You don't have to adjust the sizes and radiuses like with
RaycastsandOverlaps - Non-straight surfaces don't matter and are calculated properly
Adding values to a list only causes problems if you add the new values before the old ones. Because obviously now the numbers mean something else.
But if you keep adding new ones at the end, it never breaks.
Obviously it also means you can't remove old values.
But that doesn't mean you shouldn't use enums!
That is true, however if I was on a team and they changed it without knowing and commited the change im gonna- 
oh i see.. thank you then!
really? i never saw someone use oncollisionenter for a groundcheck
ill be sure to try it
i appreciate the help 👍
True, but that is down to communication and ownership.
Don't see why one wouldn't use it
I don't think there are more precise options
I mean, these are all obvious properties stemming from the fact that one is ray and another is an overlap circle.
The best way is to try and see for yourself what fits your project.
If you need to simply calculate whether the player is on the ground, regardless of its shape, use OnCollisionEnter & Exit
It's going to detect whether the colliders touch, which is appropriate for the majority of cases
im making a 2d platformer similiar to celeste for context
so i need it to be extra precise
Then use OnCollisionEnter2D & OnCollisionExit2D
Of course, it can be achievable with Raycasts and SphereCasts, but it doesn't make sense if you already have an option, which calculates collisions for you
There are issues with collision messages as well. There's no perfect solution. You need to test and see for yourself.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://gdl.space/qematavoku.cpp
Why OnRoomListUpdate is not called?
Because there is nothing in that code that calls it
In Photon, it should calls itself
then I suggest you ask in the Photon server
the main reason why an overriden method would not be called is because the calling method has not/could not cast the class correctly
Hello everyone,
I have a python script and I want to use it with a cs script ( I already looked on internet but I can't find any answer). Do you know how to do it ?
https://gdl.space/epopugoniz.cs
https://gdl.space/guqamulamu.py
I have also this error :
See "Script Serialization" page in the Unity Manual for further details.
Save.persistence.ConnectionManager..cctor () (at Assets/Script/Save/persistence/ConnectionManager.cs:9)
Rethrow as TypeInitializationException: The type initializer for 'Save.persistence.ConnectionManager' threw an exception.
Save.dao.ExecutionDao..ctor () (at Assets/Script/Save/dao/ExecutionDao.cs:17)
Save.service.ExecutionService..ctor () (at Assets/Script/Save/service/ExecutionService.cs:9)
Donneesentrees..ctor () (at Assets/Script/IA/Donneesentrees.cs:14)
Follow the stack trace backwards. It gives you all the information you need to find the error
Another reason not to use public fields thoughtlessly
Or at all
why can i use a character class as a boolean?
Does it inherit from MonoBehaviour?
Unity allows MB's to be implicitly cast into booleans
It's basically the same as if(player == null) return;
Well not just MonoBehaviours, but all UnityEngine.Objects really
it does
i didnt know that, cool
it's an implicit operator
Explicit casting is just (bool)variable
sometimes it says u cant do that thoug
Yep. You need to define the custom conversion operator.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators
An explicit operator allows you to do an explicit conversion, but it won't permit an implicit conversion
on second thought, let's not go to Camelot
it is a silly place.
Pretty sure you can define custom asignment operators in C#
A fellow python (not the language) fan, I see
Hmmm... Looking at the docs, it seems like you can't
You are limited to the unary, arithmetic, and comparison operators
(and a few unay operators aren't permitted)
Yeah pretty sure the best you can do is implicit casts for weird assignments
what's interesting is that there are true and false operators
you're allowed to return false from both of them at the same time
true, false, file_not_found
Why is Spawn = True in this code: https://pastecode.io/s/09qwryx7 https://pastecode.io/s/z4i3hhyd https://pastecode.io/s/nwottz8w (This will be the last time I ask, I promise).
I'm not sure if this is the place to ask questions, and if it's not please let me know.
I'm trying to use the line renderer but it's only moving in the y direction even if I enter a value for the x-axis.
I'll check back on this in a few minutes
I bet something is rotated by 90 degrees
How / where can I check?
Why isn't anyone responding to this?
Create a line renderer with no parent. Make sure its rotation in the inspector is [0,0,0]
also ensure that your camera is facing in the +Z direction. Setting your Scene View to 2D mode will do this
@swift crag
Respond
turns out the x-scale was set to 0 -_- thank you for you help it's appreciated
Please don't bother people. Consider maybe those who are experienced enough are not in the headspace to deal with another long discussion over messy code. You can be patient and wait.
I dont even know anymore
Sorry mate didn't know I was getting a paycheck from you
You can't put a yield return in a method that returns void
you need a coroutine
Use a coroutine
Or keep a running timer and do some math
I see
i dont know if you can use threading... but that would not be a good idea to do so
Like this?
yes
You can't run unityengine functions outside of the main thread, which means for this case you couldn't use it for Instantiating
Your coroutine currently does nothing
its half way there
Lol
You do nothing, wait one second, do more nothing, then exit
yes....
you need to instantiate it inside the coroutine
okay
im not used to C#. How do I make it so the other class knows that the class its referring to exists in a different folder
Public?
they are public classes
So just put the GetKeydown code inside I Enumerator?
Character doesnt know those other classes exist
The folders don't matter unless you have assembly definitions in them. Are you using assembly definitions?
public class Script1 : MonoBehaviour
{
private Manager manager => GetComponent<Manager>();
private void Update()
{
if(manager.b != null)
{
mananager.b.Func();
}
}
}
using UnityEngine;
public class Script2 : MonoBehaviour
{
private Manager manager => GetComponent<Manager>();
private B b;
private void Awake()
{
b = manager.Resolve<B>();
}
private void Update()
{
if(b != null)
{
b.Func();
}
}
}
using UnityEngine;
public class Manager: MonoBehaviour
{
public B b;
}``` Which script will be better for performance? Script 1 or 2?
I am not familiar with C# so I'll try looking up assembly definitions
They are not that difficult 🙂
ok
Do you have any files with the extension .asmdef in your code folders
No. Not yet
show us the Stats.cs file
also, has Unity tried to reload since you created those files?
it needs to see them so that it can update your .csproj files (which your code editor uses to know what files to look at)
this is what solved it lol
thanks for this
didnt expect it to work like that
I have Unity set to only manually reload, so I have to tab over and cmd-R it after creating new files
If you open the Assembly-CSharp csproj file, you'll see a big list of every single script file
VSCode reads that to learn what is and is not part of your project
whats the best way to create smooth, 2d platformer movement in unity?
should i use rigidbody.addforce or transform.translate?
Of those two options, your only option is the rigidbody.
why
what are the pros and cons
Because translating doesn't respect physics, and presumably you'd want things to collide.
oh yeah, i didnt think of that..
But if you do choose to use non physics, you'll have to use raycasts and do your own calculations.
well are there any other good options? like character controller 2d over rigidbody2d
There is no CC for 2D built in
can i use the 3d one
So really, it is the rigidbody method if you don't want to get an asset of the store
okay then thanks
Sure, as long as the rest of your world is using 3D colliders.
I'm trying to add 2 to a Button event OnClick but for some reason it will add just one event, any reason why?
button.onClick.AddListener(() => { elevatorManager.floors[index].spawnPoint.gameObject.SetActive(true); });```
It should add both
What makes you think it's only adding one?
Because I've tested it 😅
How
did you add log statements? Use a debugger?
print 1st listener and 2nd listener for them and check out
You need to add logs or use the debugger
As you can see it adds just the trigger ¯_(ツ)_/¯
that's the only real way to test it
AddListener adds nothing to the inspector
those are for persistent listeners only
Also, you can write an inline lambda without { }
Use logs or the debugger to actually test this
Oh I see ... nice...
AddListener is not persistent. It disappears after exiting the game. The Inspector listeners don't
Why did you share three entire scripts? Share just the relevant one or at least tell us where the code you're worried about is.
But my recommendation is to add logs around...
Indeed Debug.Log("Destination is " + level); still the best friend ever 😁
Thank's you all guys 🍻
// MonoBehaviour
print($"Destination is: {level}");
I still prefer + 😅
should i use a circle or box collider for my groundcheck?
Log 4 values with words and punctuation between and tell us if you feel the same
maybe because C=64 basic, or because I'm coming from Visual Basic... 🤭
with 4 value I will use a lot of + signs 😅
But you're right, I'll force my self to evolve even more 😉
https://pastebin.com/QAL5tUGE what can i improve with this script?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
String interpolation is usually better for performance but yeah why would it matter in a debug log that is temporary
but to improve is important, and I should use it also in ingame string instead of plus sign
- Assign
Rigidbody2DinAwake, not in theInspector
private Rigidbody2D _rigidbody;
private void Awake() => _rigidbody = GetComponent<Rigidbody2D>();
- You can keep the ordinate the same by multiplying the abscissa by
Vector2.right
Vector2 movement = movementX * Vector2.right;
- Create a method to not repeat the same thing, and make sure the layer is checked using your already created
LayerMask groundLayer
private void OnCollisionEnter2D(Collision2D collision) => SetGrounded(collision, true);
private void OnCollisionExit2D(Collision2D collision) => SetGrounded(collision, false);
private void SetGrounded(Collision2D collision, bool value)
{
if (collision.layer == groundLayer)
isGrounded = value;
}
- Make sure the region is ended outside of the
OnJumpmethod
private void OnJump(InputValue inputValue)
{
// ...
}
#endregion
I answered you in the other channel before you removed it
Usually i let my IDE convert it to an interpolated string at that point
but I'm lazy AF 😂
oh thank you, ill check that now
VSCode doesnt like to show intellisense properly inside interp strings
i didnt know i could check layers in collisionenter and exit
thank you
Note that I have used the previous version of the script, which you then have removed
i put the collisionenter and collisionexit in a seperate script onto a gameobject on the players feet with a box collider so it acts as a groundcheck
Great idea
wait how do i make my player movement more snappy? when i use rigidbody.addforce it makes the player slide like its on ice
should i use a physics material and add friction or something?
Yeah, that can definitely help
Without friction, you are basically on an even slippier substance than ice. Some absolutely frictionless material
nvm, physics material doesnt do it
even at max friction theres still sliding
which ruins the whole point of my snappy 2d platformer experience
Is there a material on both objects? Did you set the friction mode to max or is it still average?
its on max
and yes its on both objects
Ah ok. Well, addforce is certainly going to cause SOME sliding, unless you combine it will velocity setting when you have no input
quick question, is it more expensive or taxing to pull functions or variable from other scripts?
You'd need to profile it. Other than that, stick with what's readable and possibly follow the SOLID principles.
reading a field from an object is trivial
If it's a DateTime value, then you can call .ToString() on it and pass a custom format string to that method.
Do note that by default, date formatting is localized, which means it's adapated depending on the language of the system your app is installed on.
So a user living in the US will not see the same thing as a user living in Germany, for example
(default ToString() without any custom formatting applied)
what does this mean? theres no stack trace
Seems like a coroutine failed to resume after a yield. First time I see that one though
Maybe the object with the coroutine was destroyed but Unity still got a reference to it, somehow?
I was working on a scriptable object to hold my Operation data for game scenes. I wanted to add a variable for the scene this operation is in but for some reason it is not showing in the inspector?
Called as public Scene OperationScene;
https://gdl.space/edimeyogeh.cs
Scene represents a loaded scene and is editor-only, so you can't serialize it.
Scenes are not serializable. You'll need another way to reference a scene, by name or build index for example
there's this lil guy
I use something I copy-pasted from the unity forums several years ago, as god intended
thx!
(I mixed this up with SceneAsset; that is editor-only)
I cant find a proper step by step on that page. How do I import it into my scriptable Object
using Udar.SceneManager; nvm found it. Finally showeed in my VSC list
add a SceneField field to your class
Why isnt the boost working
First of all, are you getting the log in the console?
Do you get your log whenever you press space
Second of all, is the speed boost value in the inspector the same as expected (40 in this case I presume)
Yes
Why cant i hold
Third of all, this boost is active for one frame, so the deltaTime is small, thus the boost is small
Because you aren't checking for a hold. You're checking for a press
So i take away Down?
Yes
shouldnt it say something else though? nothings been destroyed
From what I could see on the forums is that it can happen when you use StopCoroutine() to stop a coroutine that was started on another object. The error seems harmless though
its not harmless in my case, as it seems to make my character freeze in place.
eg.
Coroutine c = obj.StartCoroutine(M()); // coroutine is started on 'obj'
StopCoroutine(c); // attempt to stop the coroutine on 'this', but it was started on 'obj'
obj.StopCoroutine(c); // correct
oh i seeeeeee
wait that makes sense now
cus the issue as from an explosion
that destroys itself
that makes much more sense
i thought startcoroutine did that impliocitly
public Coroutine CurrentStun
{
set
{
if (currentStun != null)
{
StopCoroutine(currentStun);
}
currentStun = value;
}
}
[SerializeReference] private Coroutine currentStun;
is this a good way to do this?
Why do you need serialize reference on Coroutine?
Just so I could see if the coroutine was actually setting properly or not
But basically I only want one stun coroutine happening at a time
So when it gets set, it turns off the old one if there is any
You could use logging for that. Also Coroutine should be stopped by the script that started it
So it doesn’t make much sense that it is set by public property
Better way is having StartStun() method or something
And manage coroutine internally
Makes sense, but do you think this method is robust enough? I just did this now but I still appear to be getting coroutine continue failure errors
Error looks like there is issue with the coroutine
Logic inside the coroutine.
from the unity documentation "OnDestroy occurs when a Scene or game ends." if I have a listener, and I want to remove it in OnDestroy, but the game crashes, or is forced to terminate, what happens to this listener? does it still exist?
that memory will get cleaned up by the OS
When the game crashes the process is stopped abruptly. It's the same as graceful shutdowns, the memory is freed and can be repurposed to other processes
If the game crashes nothing in your application will exist anymore
I want the player too go in the direction and not too the cursor : (
void Jump()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (mousePosition - transform.position).normalized;
float appliedForce = Mathf.Lerp(minJumpForce, maxJumpForce, Mathf.Clamp01(holdTime / maxHoldTime));
rb.AddForce(direction * appliedForce, ForceMode2D.Impulse);
}
well, you told the player to move towards the cursor...
yeah
What is the purpose of normalizing a vector?
a normalized vector has a length of 1
because i dont know how too make go in the direction
this is important any time you need a direction
you wouldn't want to move faster if the mouse was further away
what is "the direction"?
i have no idea what you actually want to do
So i want too make that the player jumps in the direction of the cursor and the longer the mouse button is hold down the player jumps wider (like golf or jumpking)
but you said you don't want that
I want the player too go in the direction and not too the cursor : (
I said i want that two times now
Making a "unit" vector that length is consistent
In other words removing the size while keeping the direction
I want the player too go in the direction
So i want too make that the player jumps in the direction of the cursor
This makes no sense. You said you want it to go in the direction of the cursor. That's what your code does. But then you said you don't want it to go in the direction of the cursor.
You're going to need to show me a video of the problem if you can't explain it.
what does Quaternion.Euler do and mean?
did you read the documentation?
That means creating Quaternion from Euler angles
uhh no, ill check it out right now
you should consider doing that (:
What's an instance when you wouldn't want to normalize a vector?
any time you care about both direction and magnitude