#💻┃code-beginner
1 messages · Page 780 of 1
why do i have a feeling that you need to learn the concept of oop.
what's wrong?
so what error do you still have?
whenever i get those errors, i just unsave the changes and they're fixed
i just have to not press the popup
but i was curious what that popup meant, since i always get it
what pop up?
Well if the script is doing what the name suggest, u will want to take a look at the event system
Its not
ah, probably unrelated.
yep
I just choose to ignore it and things are fine
Clicking yes is a grave mistake
clicking yes just normalizes your line endings
Does anyone know what resource I should be looking into to convert a large json string into a small hash looking string? Like how some idle games let you export the web save into a string that tends to be short, and then import that string to load your save? I'm trying to do that, but I'm not quite sure what I should be looking for.
encode then to base64?
Base64 would make the large string into an even larger string
You can implement a compression algorithm to reduce the size to maybe about half but I assume the exports you've seen are a custom format instead of compressed JSON
Ah, that would make sense. I tried messing around with some online string compression sites to test different compression methods, and all of them made the strings bigger, probably will just look into another way of doing so then, thank you.
You can try out TOON, its just json but cleaner and smaller , its built for LLM's to reduce tokens
Is this diacord server programme?
I don't know why am i come to this server without any experience
What?
Hi
yes this channel for code beginner, u can ask about u code in this channel
hey for my Visual Novel game, i made a new scene with two images, with a background image and the hex code is adjusted. One is like yellowish for a day theme, and one is like a dark blue for a night theme. Now i want to randomize it each time the player enters the scene to be either day or night, and depending on the time of day, they should say something different. so now i've managed to make the image backgrounds random, but the text is always the same. Can anyone take a look at my code and lemme know what i did wrong here?
Nevermind I figured it out...
Hey, can someone help me with playermovement? I tried using couple of scripts, and one ready asset, but when I tried using it it failed to work.
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
Talk is cheap, show the code errors
Did u move the script or delete it while in play mode?
make sure the script name and the class name match.
well, if you're below unity 6. you've conveniently cropped that out
Nope.
It is matched, I double checked
can you show them
Script, yes?
The name mismatch would cause a compile error
definitely not a compile error
maybe an error from unity? i don't remember, but either that or a warning
though, not on unity 6
Well we can’t be sure unless they provide the 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.
(but that's unnecessary here, just wanted to make sure the name was correct)
you haven't messed with the meta file, right?
is this happening to all your scripts or just this one?
Uhhh... And what is meta file?
To all scripts
it's a file with the .meta extension providing metadata for each asset
like for this script, there should be a PlayerMovement.cs.meta
(it won't show up in unity)
how'd you get the asset?
Asset store and rest of the scripts for walking from videos. I did exacly same thing as they but I had an error
I can even tell you which asset for walking I used
how did you import them
Assets > My Assets > And then import asset and that's all
It showed up in my assets, and I used script for walking from asset store
IEnumerator BulletInstantiate()
{
if (enemyCollision.EnemyList.Count != 0)
{
Transform bullet = Instantiate(prefabBullet, transformOfSpawnPoint.position, Quaternion.identity);
_BulletPool.Add(bullet);
}
yield return new WaitForSeconds(4);
}``` if i call this caroutine inside `update`, will it only be called once every 4 seconds?
When I'm creating script it shows up
no, it'll be called every Update
"if i do X, will it do Y" bro please
this shouldn't affect it
do you still get the issue if you just remove the component and readd it?
Yep, I even created new test project, same thing
That means u don’t have a class named PlayerControls anywhere
Coroutines are not meant to repeat tasks periodically. They are triggered once then stop until a certain condition is met, or spread the tasks in multiple frames.
The simplest solution is to have a timer variable to keep track of the cooldown, and update it every frame until u reset it
ya i figured it out just then, that's why i deleted it. although, now i am facing a completely different bug.
Coroutines are not meant to repeat tasks periodically.
they can do that though
im assuming the playercontrols class is supposed to be an input action wrapper class?
and that you probably dont have one generated
and if you do its probably not named that
will i be breaking anything if i am iterating through a list of transforms while i am destroying the elements inside it ? i have noticed locations after destroying become null
well.. destroying them doesn't remove them from the list
they become destroyed
that's what unity null is
are they managed by unity in a way such that they are removed when they turn null or something? or do i need to manually remove those indexes too...?
are they managed by unity in a way such that they are removed
no, that's literally just not possible
they become null objects in your list
it's why unity null exists to begin with
they aren't actually null
you do need to remove them, yes. the wrapper objects still exist
so after the whole process the list is gonna have null objects inside it, and i just check for all objects inside it which are null and remove them yeah?
or you could remove them as you iterate, which can work if you're iterating backwards for example
When you destroy them can you remove them?
won't work, that still breaks stuff?
i did think of it though
wait lemme think it through
Did I miss what you are trying to do
i guess i will need to add the enemies in reverse order and i think it works?
no clue what you're talking about
i have no context on what you're trying to achieve
the order they're added in probably won't have an effect
it will lemme explain
you also just.. don't need to iterate backwards, that's not the only way to achieve it
i have a tower, the tower sees objects, adds them onto List<Transform> EnemyList, another script shoots bullets from that tower. i have a reference to both lists, so, suppose i see two enemies so List<Transform> EnemyList has two enemy transforms at index 0 and 1. The first enemy was added first, and then the second enemy was added, so the first enemy is at index 0 and second at index 1. now i iterate through my _BulletPool and List<transforms> EnemyList. Guess what happens when i iterate backwards? i check the last index first ie index 1, so the first bullet moves towards the second enemy instead of the first.
where does iterating the enemies and destroying them come in
you shouldn't be destroying from the tower to begin with
not on the tower, i am doing it on a script attached to a bullet child gameobject of the tower
if (enemyCollision.EnemyList.Count != 0 && _BulletPool.Count != 0)
{
for(int i = 0; i < Mathf.Min(_BulletPool.Count, enemyCollision.EnemyList.Count); i++)
{
Transform bullet = _BulletPool[i];
Transform Target = enemyCollision.EnemyList[i];
Vector3 direction = (Target.position - bullet.position).normalized;
bullet.position += BulletSpd * direction * Time.deltaTime;
Debug.Log($"{Vector3.Distance(bullet.position, Target.position)}");
if (Vector3.Distance(bullet.position, Target.position) < BulletSpreadArea)
{
Debug.Log($"IN RANGE: {Vector3.Distance(bullet.position, Target.position)}");
Destroy(bullet.gameObject);
Destroy(Target.gameObject);
_BulletPool.RemoveAt(i);
}
}
}```
i don't see any list you'd be iterating to destroy
the bullet should manage its own destruction
the enemies should manage their own destruction
using collision checks or something then?
distance stuff also works. you just need each thing to worry about itself
but this is gonna work though.
what do you even mean by "bullet child gameobject"
is one bullet calculating stuff for every bullet?
in heirarchy, bullet is a child gameobject of its parent(tower)
each bullet?
U just have to worry about cleaning up the null ref in the towers’ EnemyList when the targets are destroyed
might seem dumb, you can iterate through those right?
this seems pretty overcomplicated
also pretty fragile
not rly? u just check their distances, if they are less than something, destroy em
each tower expects to manage the destruction of every enemy it's created a bullet for?
what happens if an enemy is in the range of multiple towers
the tower manages that when an enemy goes out of range
not that part - having these 2 lists, correlated by index, all managed via the tower
that's the part that's both overcomplicated and fragile
that was not the situation i mentioned
no i have two scripts, one for the tower, which adds on enemies on collision and when they exit collision. and another script for the ShootBullet which looks at that, and its own BulletPool which it manages and does this stuff.
...so you have even more stuff handling this...
and ShootBullet is for each tower
this is overcomplicated, yes.
O_O
"this isn't managed by the tower, this is just managed by ShootBullet which is part of the tower" bro please
i don't understand how it is complicated though...
this
that's just two lists...
are you aware of "single responsibility"
no
and you could have 1
you have them correlated by index
elaborate
The single-responsibility principle (SRP) is a computer programming principle that states that "A module should be responsible to one, and only one, actor." The term actor refers to a group (consisting of one or more stakeholders or users) that requires a change in the module.
Robert C. Martin, the originator of the term, expresses the principle...
there is no link between each bullet and each enemy.
basically, each entity should be responsible for itself
your tower should not be responsible for all its bullets if it doesn't have to
you could easily just make this a fire-and-forget system
the tower shoots a projectile at an enemy (or even just its position)
then the projectile has its own collision logic
Following ur idea, u will have to keep a reference of the parent towers on each bullet in order to access the EnemyList. Hundreds of bullets, each iterating through the list will cause performance issue, and the code itself is too tightly coupled to be maintained
then the enemy is responsible for destroying itself if it's been damaged enough
what you have here closes off the potential for making different damage or health values entirely
that's not what's happening here, but yes, the coupling is also a hazard for future pain
basically UDP
that's.. entirely irrelevant, but sure
UDP is fire-and-forget, not the other way around.
so i make a dictionary whose key are enemies and its elements are gonna be bullets? i have just one script which iterates through this dictionary and makes every bullet element of a enemy key fly towards it or something and if the bullet reaches a certain range, destroy the key(enemy) or something?
you don't need to save the bullets at all
then how do i manage the bullet's movement?
i did try to make a script for every bullet on instantiation, but i could not get it to work
the bullet manages itself
the tower just tells it where to go
that's the end of the responsibility for the tower
i will try it again then.
That makes me wonder: Is calling Update on hundreds of objects faster than updating each of them in a single Manager?
Tower:
serialized float cooldown
serialized int damage
serialized Bullet bulletPrefab
List<Enemy> enemies
OnTriggerEnter2D: if collider.TryGetComponent(Enemy): enemies.Add(enemy)
OnTriggerExit2D: if collider.TryGetComponent(Enemy): enemies.Remove(enemy)
float nextShot = 0
loop:
if Time.time > nextShot && enemies not empty:
target = enemies[0]
bullet = Instantiate(bulletPrefab, transform.position)
bullet.Initialize(target.position, damage)
nextShot = Time.time + cooldown
Bullet:
serialized float speed
serialized float lifetime
Vector2 target
float damage // could be serialized here instead of the tower
float expire
Initialize(Vector2 target, int damage):
this.target = target
this.damage = damage
expire = Time.time + lifetime
transform.up = target - transform.position
loop:
if Time.time >= expire:
Destroy(gameObject)
return
position += transform.up * speed // set rb velocity if using rb
// collision handled with an rb or something would be the easy and natural solution, otherwise
// - you could make it expire at the target position for a directed attack
// - you could only check collision with the initial target, but that would probably be jarring as it passes through other enemies
OnCollisionEnter2D:
if collider.TryGetComponent(Enemy):
enemy.Damage(damage)
Destroy(gameObject)
```this is really all you need at the bare minimum. damage could be serialized with the tower or the bullet, up to you.
with a pool, there's some more stuff to store and you'd grab from the pool/return to the pool instead of instantiating/destroying
this is both the tower and the bullet.
Calling Update() on 500 MonoBehaviours is like reloading an LMG every time you see an enemy
do you see what i mean about yours being overcomplicated
you can have fewer moving parts, less logic overall
Initialize(Vector2 target, int damage): this IS EXACTLY WHAT I WAS LOOKING FOR WTH
...were you not aware of this
look at my previous posts
i kid you not, i had been so troubled by the fact that i could not pass information along with the Instantiate() method which unity already comes with, that's why i reverted to the method i was tryna use
So so. I realize it depends on the number of objects
more methods is going to be more overhead, but it's gonna be on the order of.. probably nanoseconds, if we're talking just hundreds of objects
though there's probably a jump between native and IL code, so maybe 100's of nanoseconds
it all just shows as yellow i don't know what to do?
is that ui
not a code question, #💻┃unity-talk
ok
Well that’s good to know
only got one question, how would i change the script to make it such that, if the target is destroyed before the projectile reaches the target, it changes its target to the next one in the enemy list?
you want them to be homing?
i mean like...those bullets have no use otherwise right?
yeah, and then they'd expire. that's a pretty normal thing to happen in tower defense
homing is generally an additional attribute making stuff better
consider what the projectiles represent diegetically
but if they're homing, they'd usually be targetting stuff near the projectile, not near the tower
consider: if there's 2 enemies, one inside the tower range, one outside (but near the first one)
then the tower shoots at the first one, but it dies just before the projectile reaches it
what should happen?
as the code currently is, since the bullet uses the target's position to map out its trajectory, it's gonna return a nullref error cus the target its trying to reference has been destroyed
it homes in on the next enemy present in the list
closest based on where the projectile currently is, right?
yes
what if when the tower shoots the projectile, there's an enemy right beside the tower, such that it's initially closer to the projectile than the intended target?
then my priority is gonna be to fire it at the intended target rather than the closest one...
cool, so now we have a solid picture of how the projectile should act (there is another issue but we can get to that later)
only now, should you start thinking about how to implement that
oh
given this, now it's clear that the list of enemies the tower holds isn't relevant to this behavior at all (aside from setting the initial target)
kinda...but my mind is going on a tangent wherein, the bullet calculates the distance between itself and all the enemies in enemylist and then finds out the closest one and homes in on it 💀
is it bad that that's the first thing my mind goes to...
well, not bad, but you gotta realize that you're getting ahead of yourself
that'll come naturally when you get more experience - you can design the behavior and the implementation together
but right now, you don't have the experience and foresight to do that effectively, and you'll end up coding yourself into a corner
the intended behavior should come first
How do i build a NavMeshSurface at runtime?
like imagine this situation
yellow being the path, red being the enemies, green being the tower
orange being the targetted enemy, blue being the path of the projectile
imagine that orange enemy dies right before the projectile reaches it
intuitively, it should target the right enemy, right?
but using the tower's list of enemies, it'd go to the left enemy - or if that enemy wasn't there, the projectile just wouldn't find a next target
colourblind lol
ah fuck i forgot

ehhh well i think it should be easy enough to guess?
the gray circle represents the tower's range, the blob at the middle of that circle is the tower
the rest of the blobs are enemies
the flow for the bullet could go something like this (modified from above for brevity) (spoilered if you want to figure it out)
||```cs
Bullet:
Enemy target
Initialize(Enemy target, int damage):
this.target = target
this.damage = damage
expire = Time.time + lifetime
loop:
/* check expire /
if target:
transform.up = target - transform.position // set rb rotation if using rb
position += transform.up * speed // set rb velocity if using rb
else / logic to find target */
ohhhh, so it homes in on an enemy out of range
the other issue being the turning speed of the projectile, though it is viable to have infinite turn speed (especially if the projectile isn't directional)
I got a problem with my script, that when OnTriggerEnter is being called, I use Physics.Overlapshere and Everything in The Physics.Overlapsphere will get a rigidbody and and quick explosionpush.
but it doesnt do that instantly.
i think its Physics.Overlapsphere is getting called after one frame.
I dont want to change it to OnCollisionEnter becaue sometimes it is allowed to go through more objects for more realistic effects.
Here is the video and my Script: https://paste.mod.gg/eywsyhkefwgv/0
Note: please do not bully me just because my code is bad
A tool for sharing your source code with the world!
Why would the projectile change targets mid-flight. typically, the path would stay true (unless this specific projectile can update its target) . . .
we were talking about projectiles that can home in on targets, yes
doesn't homing projectiles stick to the main target?
well, even if you want to switch, you'd have to get a new list of enemies in range, then choose from those to avoid targeting any out-of-range . . .
physics messages happen after the physics tick, so the added force would be applied the following physics tick
https://docs.unity3d.com/6000.2/Documentation/Manual/execution-order.html
depends on the game design
that's what the entire convo was about, yes.
facts . . .
One (physics) frame is 0.02 seconds. I doubt you can tell the difference between the force being applied instantly vs. 0.02 seconds later.
so what does that mean?
the force from the explosion isn't applied instantly
ohhh.... i see. is there a way to use another method or can i change it in unity?
you could check for overlaps with FixedUpdate, which happens before the internal physics tick, but not sure it's worth it for 0.02 seconds as nitku mentioned
you can't change the event execution, no.
that would break a ton
you can set a bool to true in the trigger method, then call a method in Update or FixedUpdate that uses OverlapSphere . . .
what if i get the position from the gameobject using vector3 and then i call the physics?
this would still have a tick of latency
the Physics.OverlapSphere doesn't matter here, that one is instant
it's the OnTriggerEnter that is after the internal physics update
so if you want to change the behavior, you'd have to do it all in a different message
also, I would ensure the objects have a Rigidbody and DestroyOtherGameObjetcsOnHightSpeed component on them. Adding multiple components to multiple GameObjects can be costly . . .
ok so OnTriggerEnter is getting called after 0.02 seconds?
no
but yeah, does it really matter? the video you showed doesn't have any visible latency.
i don't see a problem with the interaction and the collision (i never thought there was one). what part are you worried about?
Realisticly it would first damage the roof than everything thats under the roof. i think imma just make the meteor slower
damage, as in physical or logically through code? what meteor?
i have posted a video
i saw the video. wait, there's a meteor, where?
is my meteor really that trash 😭
no i think its to fast for you
i saw a player, then a board flip and hit the building . . .
if u look at beginning, there was a fast flash and u dont see the meteor bc it is fast
where dafuq was that at? 😆
how did u manage to get the frame 😮
im a pro-buffer'er
just a quick hand i guess
here i made meteor slower
i managed to capture it
any quick fix out there for a mesh not showing up in the 'Main Preview' panel of Shader Graph? no default basic shape or custom mesh show up
this is the code channel, try #💻┃unity-talk or #1390346776804069396
hey, I had a merge conflict in git and one of the conflicts was one of Unity's meta files for a script. I'm a bit scared of those because I'm worried what happens if I have a "mismatch" between the changes I allow from the actual scripts (local version or remote version or a combination?) and the meta file hash or whatever it is. How does that even work?
a merge conflict in a meta file for a C# script is pretty weird. That generally means that both you and the remote branch created a script with the same name but one of you maybe deleted the script but kept and comitted the meta file.
The danger here would be if your script is in use in any scene or prefab, those components would become broken references if the file id changes
yeah, both me and the remote branch had an ICommand.cs file, and I wanted to replace the old one with mine
I would recommend taking the remote meta file
However for an interface
realistically it's not going to matter
in this case the script was not used in any scene or file, because it's a pretty new project.
because no prefab or scene will be referencing the interface
right
yeah it doesn't matter then
thanks for clearing that up, I'll be careful of that
I assume unity version control handles this better? I've never used it
i don't think UVC would handle this any better or worse than git
ah gotcha
!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.
ah gotcha
if you want to know the previous input, you'd just.. save the previous input
wdym by "get the last input"?
you already had it saved in a variable from what I saw
A tool for sharing your source code with the world!
right so what exactly is the question here?
😆 me confuse
like if I click d on wasd i face right thats what im trying to do
so your question is "how do i rotate my player to face the input direction"
i can do that all i need is the last input
transform.right = moveInput; pretty much
you already have it
moveInput
sorry i used a tutorial i did not now that was what it did
If you're doing tutorials the point is to try to understand the code
tutorials are not a recipe to build a game with
they're examples so you learn the concepts so you can build your own stuff with the understanding you gained
Hey, so im trying to learn unity and make something simple, im having an issue that im stuck on. So Im trying to get the direction that a collision occured between two players or a player and a stage part. The player part works fine, but the same code with the stage parts never triggers. Any help would be appreciated. I know this code is messy as well
Start debugging it
it could be a few issues.
your stage collisions may not trigger because the script is on the wrong object for example
the stage might lack a rb2D component
or youre using otherCollider incorrectly or youre trying to access a player component on a stage object that doesnt actually have one.
btw .otherCollider in Collision is, confusingly, your OWN collider
not the other object you collided with
var player = GetComponent<Player>();
print out which object you collided with, etc.
Certainly (contact.otherCollider.gameObject.CompareTag("Player")) is probably working becuase YOU are a player
the .gameObject you have is never needed btw
there's a few things that make this code pretty tedious
ok. I appreciate the help
would you recommend rewriting the whole section? Im assuming theres a better way to do it
work on fixing whats broken now first
then work on refactoring it in a more efficient way
as you learn more
ok. Thank you
so...i am encountering an issue where the ducks somehow start to rotate? might it be because they have rigidbodies attached to them and because of collisions with other rigidbodies, this issue is encountered?
if you think it is because they are colliding with other objects then constrain the rotation on the rigidbody
ok worked aight
@naive pawn it worked out. i now just need to figure out how to manage the homing mechanism
would you consider adding a bullet pool for every such tower?
if you are going to have a lot of towers creating and destroying bullets then you might want to have pooling
I would probably have a single pool shared by all towers to ensure that the projectiles get reused but also so that there aren't just a whole bunch of pools active at once
yeah not one per tower
oh, i was thinking along the lines of the latter
good point
in the case of towers that dont share bullets have them share their own pools with their respective different bullets
thats what i do in my game, each gun that has the same projectile type shares a pool
basically the amount of pools is equal to the amount of unique projectile types the player can have at any given time
which is never more than like 2 or 3
how do you set it up though, currently, this is a prefab of the tower
where would the script need to be on?
but i can have many instances of the same tower, how would they all share the same pool in that scenario?
pass a reference to the pool to whatever component actually uses it when that object is instantiated
https://unity.huh.how/references/prefabs-referencing-components
in this case it wouldn't be referencing a component per-se, but the concept is identical
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
ok, last question. where do i attach the script which has the pool in it. i sure can't add it on the tower
where ever makes the most sense, it can be its own gameobject
do you have some kind of game manager object?
oh, so like a different gameobject unrelated to it in the heirarchy?
yes
no singletons
i will use singletons later on in another project but i am too far deep in it to apply it in here atleast
just FYI, just because something has "Manager" in the name does not mean it needs to be a singleton.
but also the "GameManager" does not need the object pool used by the towers either
yeah a singleton is a class with exclusively one instance, not nescessarily one that appears just once in the scene
makes sense. you can manage other stuff insted of pool and stuff i guess
i personally handle my enemy pooling within my gameManager and i havent really had any trouble with it so far, but you can just set it up on a seperate game object
When you advance past the beginner stage then you should be able to judge better when and where an object pool should be stored and used
Ideally its whatever class is able to spawn and reclaim objects to return to the pool
i have a question. in scripts, we use the term GameObjects and in heirarchy, we use the term gameobjects too. don't people confuse them?
erm no?
what
GameObject only means one thing, An object in a scene OR a prefab
i mean like...i could just setup a parent class for every tower and everyenemy and attach a script to the parent which the children can reference
we can have many gameobjects in a scene. A prefab is a gameobject with many gameobject children
You need to ensure that all towers reference one single pool
that could be your game manager or a dedicated component
a prefab is a gameobject that's saved as an .asset file instead of inside a .unity file
prefab instances
ah i thought you meant the one you selected
then won't people confuse it with transform.gameObject?
note that this is really only a concept within the editor. the scene view (and inspector) shows that these objects originated from a prefab.
this wouldn't be the case in a build since the concept of a prefab doesn't really exist in a build
every entry here is a gameobject in the scene
the ones with a blue cube are also prefab instances (not prefabs, though when unambiguous, they might be referred to as prefabs)
they're the same thing
transform.gameObject is a property that refers to GameObject that the transform component is attached to. these are the things you see in the hierarchy
why would you confuse something with itself
//This is true!
bool isSame = gameObject == transform.gameObject;
ohh
Transform is a Component
MonoBehaviour (and your own component that derives from it) are also Components
Component.gameObject refers to the GO the component is attached to
the transform is attached to the same GO as the MB, so their gameObject fields refer to the same object
okie
What would be a good system of keeping flags of events in the game?
I've seen people say that too many Unity Events is not good, but I see people say that too many Updates are not good either
(As an example, I want to complete a mini game, and then a bridge appears)
But I don't want to hardwire the script so that the only thing it does is make a bridge appear
Is it conflicting with your development/game? This isn't like C++ where best practices are absolute must haves.
"not good" can be relative
Not really, but it might not be a good habit (not sure of course)
(refering to dalphat)
a foreach over an array is "not good" compared to a for loop in terms of perf but it literally just doesn't matter in 99.99% of cases
alr thanks
Hi! Anyone here think they could help me with Cinemachine scripting? I'm trying to figure out how to change the horizontal axis of a freelook camera through a script
uhh to be clear im giving that as an example, not saying your situation is the same
you haven't really given enough context to really say whether the "not good" parts are relevant in your case
in any case, you should figure out why they're apparently "not good" and consider whether those downsides are relevant to your usecase
As an example, I have a steppable platform which activates 3 other platforms as accessible. The platform uses this script
public class GenTrigger : MonoBehaviour
{
[Header("Events to run when the player enters")]
public UnityEvent onPlayerEnter;
[Header("Events to run when the player exits")]
public UnityEvent onPlayerExit;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Entered");
onPlayerEnter.Invoke();
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Exited");
onPlayerExit.Invoke();
}
}
}
This uses two Unity Events
I can use these to call any other method from other objects
yes this is good practice
I have been seeing people code and they get things auto filled for them like for example Destroy(); will just auto fill when they click tab even if not fully typed how can i get that?
i am new to the unity engine so if you ever see me ask dumb questions thats why
!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
You can set up the plugin for unity using these instructions ^
Alr thanks
No problem, dont worry about a question being silly or not, this community is here to help everyone. Configuring your IDE will significantly help you solve errors. Enjoy
quick question, if i wanted to instantiate a gameobject for every frame that the mouse is held down (using GetMouseButton(0)), do i have to multiply something in the code by Time.deltaTime so its not dependant on fps? when i use FixedUpdate() it works fine enough until i move my mouse even a little bit too fast, in which case the clones spawn super far apart and with way less than usual. ive read a couple forums that say mouse inputs are already safe from the fps stuff that Update() can be affected by but im just sorta lost. Here's the code im using for it if maybe im just missing something entirely:
{
Vector3 mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
mousePos.z = 0;
transform.position = mousePos;
if (Input.GetMouseButton(0) && touching)
{
cloner = Instantiate(cloned, mouser.position, mouser.rotation);
cloner.transform.parent = parent.transform;
ParticleSystem part = Instantiate(particle, mouser.position, mouser.rotation);
part.Play();
sketch.SetActive(true);
}
else
{
sketch.SetActive(false);
}
}
-# ignore the sketch and particle system stuff its unrelated to my issue
touching just ensures that i can only spawn the objects inside of a specific area which works fine enough (except when i get the issue of moving my mouse too fast, in which case theyll leave the area)
fixed update idea can work fine too and the idea is by using a rate of which you want to spawn them and over the distance from the previous point
otherwise if this is just rendering related and not tied to any gameplay logic then what you're doing seems fine assuming it isn't blowing up your frames
hi can explain to me why does my character stop falling if I hold w towards a side of a building
im using rigidbody character movement
If it helps, time.deltaTime is just the time (in seconds) between this frame and the last one. So if you move an object by a certain amount, say distance, multiplied by delta time, eg position += distance * time.deltaTime, if you replace time.deltaTime with 1 second, you'll find that position changes by 1 * distance every second, regardless of how many frames or how fast the framerate.
Friction.
At least assuming character controller respects it as rigidbodies do.
Try pushing an object against the wall in real life. It wouldn't fall for the same reason.
Delta is just a difference between two things
If the object only stops while you hold w into the wall, but if you let go and it doesn't have any horizontal velocity it falls, then you'll want to use a physics material to change the friction to 0 (and the friction combine mode to minimum as well).
The best way to make sure that u understand something is to try to explain it to someone else
hello guys i looked the whole internet for a way to implement 2d side scroller enemy i couldnt find a good tot so if any one have a good totorial or a way to imploment it please let me know
yes
and i want to make my own attacks not like sword slashes or smth like that
Hey does anyone know why my script isnt working? just trying to play a gun sound effect on left mouse click.
Can you send a screenshot of the gunFire component in the editor's inspector window?
when you say component do you just mean the text in the editor that says gunfire?
Components are these:
They're anything that goes on a gameobject
Somewhere an object called Gunfire has an Audio Source component
I can see it here
in the AudioSource attach a sound file you want to play
But that's just a reference to the component, I'd like to see the actual component
You should be able to double click on the reference to go to the component
this one?
Yup
its an empty object
Perhaps put a Debug.Log to check if the input is receiving
There's definitely an audio clip there, but make sure you can hear it in general, and also make sure your code to play the sound is triggering by putting a Debug.Log("(some message)") underneath the audio play. Then test it again and look to see if/how many times the Debug.Log message was triggered
audio definitly works, if i set it play on the instance beginning i can hear it.
I'm guessing it might be one of two things, but not 100% sure:
1st since you're using GetMouseButton, that triggers every frame that the mouse is down, which I think would be causing the clip to restart every frame until the mouse is released (should use GetMouseButtonDown if you're using the old input system)
2nd, you mentioned using a tutorial that might have been old. There's a possibility that the tutorial is using the old input system and your project is set up for the new input system. If that's the case there should be a couple of easy fixes.
Can you put a Debug.Log, then test again and show what happens in the console?
the tutorial is 12 months old
sorry im slow
A lot of stuff have happened in 12 months
That's not too old, I've been using tutorials 4-5years old
Do you know how to do that? (Use Debug.Log that is, and see its output to the console tab)
uhhh i am giving it a go
Also since the code is using GetMouseButton, I can guarantee that's part of the old input system
right, what should it be changed too?
oh sorry yeah saw the abvoe
If the input setting is wrong, Unity should give u a warning. It’s more likely the misuse of GetMouseButton
I changed it to GetMouseButtonDown but it i still cant hear anything
Did u put a debug log?
let me google how to do that real quick
There's a couple of options, it's not quite a single line of code change. Either you can switch the project to use the old system, which is easy but since I assume you're learning, it's not a good idea to learn something that's already being replaced. Alternatively you can find the new input system docs here: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.17/manual/index.html
and can search things like "unity new input system get mouse click" to find out how to use it
Do that and then come back, if it's the input system getmousebuttondown won't be the issue. Here's the debug.log docs:
https://docs.unity3d.com/ScriptReference/Debug.Log.html
ah these are good, thank you. probably going to go to bed soon and try again tomorrow but that new input system seems much simplier. correct me if im wrong but looks closer to an in game 'key binding' menu
Yeah basically, you set specific input actions in the editor then reference the whole action in code instead of the key. That way you can have one line of code that supports both keyboard or controller input, along with various other uses
Right, yeah ok sounds good, btw for someone whose a complete newbie would you have any tutorials you'd recommend for someone trying to make an fps? Im kind of hoping i can get away with mostly using animation to stick over my code to at least make it look ncie
Study C# and OOP before u take any Unity tutorial
I don't know how well you'll be able to replace code with animation, and while I don't exactly have tutorials, there are plenty of first person controller tutorials out there. If you want to make it multiplayer, "Unity Multiplayer Tutorial" will probably get you a lot of useful basic tutorials, but I can't say for sure based on what you want. However, multiplayer is something best set up in a new Unity project, so decide about that one quickly I guess.
Agreed, at least to some extent. There's a lot you can do with only the basics of C#, or basic knowledge of any other language that could translate a bit, but you'll definitely need to be able to read the docs for sure. In general figuring things out from the docs is much more useful for learning than tutorials imo
haha yeah nah its single player. like just a copy of fallout mechanically, speaking to npcs opening 'containers' and shooting at enemys
In that case there are a lot of good tutorials either on youtube or on various websites, though I don't have any off the top of my head. Just make sure when you follow a tutorial, you figure out what each step is doing.
yeah thats the plan basically, a lot of it (at least to me) seems like its just very basic coding and stuff thats very popular like inventory and containers there are 100s of tutorials. I essentially just want a vertical slice of good feeling movement and 1 weapon with all its animations and effects added and then just want to build from there
am I stupid or like why aren't these being affected by gravity?
I tried implementing gravity manually here --> https://paste.mod.gg/huxmgnplbqiz/0 but that didn't work either
A tool for sharing your source code with the world!
idfk if I'm just stupid or something
Read the warning
“In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour”
you can really just ignore that most of the time
Hello I'd like to make a game similar to FiveM's architecture, meaning that people can host their own server and add their own scripts: server and client included, but I don't know where to start.
Is it a FPS game?
If so, make singleplayer first. Multiplayer is a massive step up and not going to be fun for beginners.
First Person but not a shooter , a Roleplaying game
A school Rp
Oh dam But what I'm asking is, is it possible to do this with Unity or not? Just curious.
Definitely possible in unity, but as any engine… multiplayer at all is a very tough process. You’re going to want to fully complete a singleplayer game to become fluent in that first, multiplayer will be more than double that work
Do you have a first person and third person body/controller setup?
For first person you need animated arms for your screen, then a third person body for everyone else to see
You would use a networking system such as “Mirror” and likely a P2P setup
I haven't even started yet; the player controller isn't finished because I'm having trouble understanding Fish Networking This is apparently the best option for my project.
That’s incorrect and sounds like a personal opinion.
Fish networking structure is designed for optimal server setups on a dedicated host.
Mirror is already setup to work as P2P self host. Out of the box it’ll somewhat have a demo of that.
Fish net will have higher performance on dedicated servers. Where as mirror will have more options for self hosting
this why i choose Fish Networking bc The goal will be to allow people to host their server on their own machine (VPS, dedicated server or on local for testing ) with their scripts.
like fivem
Not like Minecraft servers?
I suppose it would work like fivem. If it’s working out for you stick with it lol
how big are individual servers going to be? like how many players do you think one could host maximum?
For my project, I'd like the server to be able to handle a maximum of 100 players, and more later on. There will also be a voice chat system; otherwise, there's no point in roleplaying.
Hi guys
Hi guys I am a beginner in c# coding nice to meet u all how do this server work pls
Hello! My team and I are working on a local multiplayer game where players can team up with up to 4 players using controllers.
We’re exploring ideas for situations where there aren’t enough controllers—for example, 3 players but only 2 controllers.
Is it possible to let two players use controllers while the third uses keyboard input? Would that setup work well in practice?
We’d love to hear your thoughts or suggestions.
definitely possible, yes
Surely your team are the only ones who could know if it would work well in your game
Can you use a keyboard and controllers in a game? Yes.
Figuring out which player is keyboard on a splitscreen game is tougher
this was the first idea
we thought about splitting the keyboard into 2 parts
but this idea can make the game harder so we want help with design
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
otherwise unless you got specific questions you're asking in the wrong place
Ok thx
What is standard practice when I have multiple scripts that their methods need to be updated? Just make a "UpdateInputs" method and put them all in that? Maybe with if else null checks?
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class Player : MonoBehaviour
{
[Header("References")]
[SerializeField] private CharacterController m_CharacterController;
[SerializeField] private Transform m_Camera;
public PlayerMovement m_PlayerMovement = new PlayerMovement();
public PlayerLook m_PlayerLook = new PlayerLook();
public CharacterController CharacterController => m_CharacterController;
private void Awake()
{
m_CharacterController = GetComponent<CharacterController>();
m_PlayerMovement.Initialize(m_CharacterController);
m_PlayerLook.Initialize(transform, m_Camera);
}
private void Update()
{
m_PlayerMovement.UpdateMovementInput();
m_PlayerMovement.UpdateMovement(transform);
m_PlayerLook.GetInput();
m_PlayerLook.Rotation(transform, m_Camera);
}
}
Like in a monobehaviour, you have them in Update
hi, not really how support servers like this work. just lurk around for issues you can help with
But since those scripts are basically SOLID principles, they don't derive from monobehavior since they are extensions
methods that are called each update?
Yes
extensions of what
player movement, player camera control, etc
basically extensions of a player monobehaviour class
so they're monobehaviors
Fantastic my dm
Are open for more details/ requirements
No
please do not solicit DMs
this is not a space for seeking commissions
They do not derive, instead, they are labeled with [System.Serializable] and they are variables in the main player script
initialized with new
...you just said they're extensions of a player monobehavior class...
what is the setup here
Look, I researched SOLID and they call them extensions
you mean this?
Objects or entities should be open for extension but closed for modification.
"extension" there is what inheritance is in OOP languages
Basically these (PlayerMovement.cs, PlayerLook.cs) are non-derivable classes that are labeled with cs [System.Serializable] and then they are brought in as variables in a monobehavior class, and their methods are used by said variable in the main script
exactly
ok, so there's just no extension here other than your component extending MonoBehaviour
Okay, I thought they used that term when I read SOLID
that term is used, you're misunderstanding what it's used for
My fault, again, I have trouble conveying thoughts, I apologize
it's also an OOP term, not specifically a SOLID term
Oh okay, well what you said earlier is what I meant
I just didn't know how to contain methods that need to be updated each frame in a way where my script doesn't look like spaghetti code
tbf, there is also an issue of terminology with "script" in unity
Okay, monobehaviour
"script" technically means the file itself, and it does not have a 1:1 correspondance with the types inside
but here "script" can also mean components
to make sure we're on the same page,
What is standard practice when I have multiple scripts that their methods need to be updated?
here you mean you have multiple non-component types that are used in a component, and they have a method that is supposed to be called every Update?
why not just make them components
how's it easier exactly
i don't see the benefit
ah well i guess there's a time dependency, is that what you're referring to
Because I can just make a non-derivable class, label in serializable, and then call it in my main monobehaviour, and boom they control input, etc
Yes
you could also make a monobehavior class, attach it to the same objetc, and boom that controls input
(also why not use structs, do you really need that to be a reference type)
Can I ask you a question? I PROMISE I'm not trying to sound mean, it might because again... I have trouble saying what I wanna say PRECISELY, but why does it feel like I'm being told to code a certain way?
if playermovement both controls its input and the output, and same for playerlook, there's no time dependence, actually
By time dependency, I thought you meant deadline, no?
no, i'll explain in a sec
that's on me, to be clear i'm not trying to convince you to write code my way, just trying to convince you to not write code like that, because afaict you're just creating more work for yourself
I really hope I didn't make you upset or anything I asked what I did. I spent all my life being misunderstood and because of that I take stuff a little too personal when people ask me to do things differently
i'm presenting an option that i think fits the scenario better and is easier to work with, to reason why your solution isn't needed - but you don't have to take my solution
That's kinda my job LMAO I'm a programmer
Not my JOB but just as inn I want to
by "time dependency" i mean like, if your Player script needs to use input, but it's being read in PlayerMovement, then PlayerMovement needs to get the input before Player can read it
but that's not what's happening here
Oh?
also, this is a pretty good read
https://xyproblem.info
Well, making components probably will be faster for prototyping small games, but when I get to making big games, I'll probably want to do what I'm doing now
why?
your actual problem (X) is trying to separate out the logic, making it more modular
your current attempt at a solution is using another layer of classes as members of the main component
-> that brings up an issue for updating those classes (Y)
i think a better solution to solve X would be to just use separate components
Well, because I've learned pretty much from seeing other people's code, and there's one person in particular who made a big game this way. Like yeah, he uses inheritance, but for his player and some others, he does use the "variable" scripts like I am
ok, and what benefit does that provide
And playing through the game, there's really no bugs
you can do that with any pattern
I don't know
and you can get bugs with any pattern
I mean he did say years ago, before he even came out that he was "killing himself" learning how to make this project, so could that be it?
you shouldn't follow practices blindly. if you see a new pattern or practice, you should find out why that's being done, and see if that applies to your situation
i honestly just don't see any benefit to doing this over just using separate components
making a big game and making good code are two different things
Well I think I know why. One is that he has systems, frameworks, that cross checks each other. Let's say he has an interaction system that checks stuff across scripts, can you do that with different components?
yes
Huh.
components are classes too
anything you can do with classes, you can do with components (aside from stuff related to the lifetime managed by unity)
So by that logic you don't need a local "player" script. You just need a component for movement, looking, etc
sure, that would decentralize the logic
and that is possible
but whether it's viable, depends on what you want to achieve overall
in a lot of cases, you do also want kind of a "mastermind" component to control the overall flow
maybe you can't move sometimes because you're in a cutscene or paused
if you had each component detect that separately, that'd be a lot of repetition
Well see, I'll be honest, I'm not into this whole "component" stuff, I was just afraid that if I didn't agree, I wouldn't get help
Yeah but I mean I was afraid that if I didn't denounce my way of working and conform to others', I wouldn't get help
That's my problem, even in IRL I'm a people pleaser, I'm so concerned people are gonna be p*ssed at me I don't even bother
im sure there was a reason the person you're referring to chose to use member objects instead of separate components
"personal preference" is a valid reason - and it is for you too
i'm just trying to provide solutions that will be easy to work with and maintain
and i think components would be easier to work with than member objects
but that doesn't mean you can only use components
Oh okay, do you think you can still help with my original question, or because you don't work that way you don't have an idea?
(also i'm working with this in mind)
does anyone know a quick solution for instantiating at a fixed interval regardless of fps? ive tried using fixedupdate but that makes the cloning process weird and somehow makes it slow when i move my mouse rapidly? (my mouse controls when to spawn), i can send relevant code if its needed but im just hoping for some general ‘instantiate at .3 seconds * time.deltatime’ or something lol
"unity update timer"
well, your original question was about standard practice.. i don't think there's a standard practice since this pattern isn't commonly used as far as i know (though, i don't have that much experience in the ecosystem.)
having a separate method for updating the modules could be viable if your Player has to do other stuff in Update, but if not, you could just do it all directly in Update.
another approach would be to have a uniform interface for the modules, and then you could have a collection to loop through to update all of them
some comments about the code, now that i'm reading it more closely
- seems like the
UpdateMovementInput()andUpdateMovement(transform)(and same for playerLook) should always come together - why not have a single method to do both? - i see you have an
Initializemethod used in Awake, why not use that to set thetransform/m_Cameraso you don't have to pass them inUpdateMovement/Rotation? - why is UpdateMovement using the transform if you have a CC? you shouldn't be modifying the transform's position, that'll be conflicting with what the CC is trying to do
Ah, okay. I get this. Thank you
I didn't know transform conflicted with my CC
looks like the same as this, but i dont think either of these will work since i need be instanciating ALOT in a short time frame
why wouldn't it
its a painting program type thing with pixels that follow your mouse when its pressed down
i dont know it just. Doesnt
have you tried it
yeah
ive got it set to 0.01f and its acting the same as 0.5f so i assume theres a limit
That's definitely doing painting wrong if you're instantiating objects for each pixel
it gets deleted at a set time its not gonna cause a performannce issue or anything
it will
But it sounds like it literally is already
it lasts for about 4 seconds total
? not really
ive got an fps counter
it doesnt get affected when i spam it like crazy
you're trying to instantiate objects at 100Hz
that's.. going to create a lot of objects for GC
that might be delving a little too deep i dont really know that kind of stuff
what else can i do?
then you aren't actually creating them all
if you do something at max once per cycle then it's going to be limited by deltaTime
that's what the inner while loop solves
googling "unity painting" gives a lot of results
oh i just realised you have while in here
doesnt that crash update?
or well . Crash unity
if you have an infinite loop, yes
weird
its crashed for me when there hasnt been one
ill try using that code and see if anything changes
a yield return is very important for coroutines
dont you usually make a coroutine with ienumerator?
Hey, I was just wondering whether I should use visual studio 2026 or 2022 for unity.
ah i just realized i had that template wrong....
yeah
both should work
Im just wondering if there are reasons whether 22 is better then 26 and whatnot
frankly i dont care about the performance because it doesnt seem to take a hit and its not a very big game at all anyway
i just need a quick bandaid fix
it should look like this
float elapsed = 0;
/* some update loop */ {
elapsed += Time.deltaTime;
while (elapsed >= timeInterval) {
/* do thing */
elapsed -= timeInterval;
}
}
```the "some update loop" can be:
- a unity message that is given continuously, in which `elapsed` would be a field.
- a coroutine, where `elapsed` would be a local, and the loop would be a `while (cond)` with a `yield return null;`
just try one and switch if it has issues
you aren't locked into your choice
L L
(- (
i dont understand that second part at all
which part exactly
after the code
it just needs to be something that keeps running over time
elapsed being a field ?
elapsed being a local ?
i just dont really get it its not clicking
do you know what fields and local variables are
fields no
fields are the variables that exist in a class or struct scope, for example
class X {
float t; // field of X
void Method() {
float x; // local variable inside Method
}
}
struct Y {
int v; // field of Y
}
go google "c# field" for a better explanation
alr preciate it
float elapsed = 0; // field
void Update() {
elapsed += Time.deltaTime;
while (elapsed >= timeInterval) {
/* do thing */
elapsed -= timeInterval;
}
}
``````cs
IEnumerator DoThing() {
float elapsed = 0;
while (true) {
elapsed += Time.deltaTime;
while (elapsed >= timeInterval) {
/* do thing */
elapsed -= timeInterval;
}
yield return null;
}
}
```here's examples of how to use the template
is invokerepeating fps dependant?
no
aaoigugfhhh this sucks
but you also just.. don't get any control with that
true
huh? fps independant is a good thing
does anybody use jetbrains
plenty
is it good
fucking called it
it's usable
it's good if you think it's good
try it and see for yourself
could i not just set it to only run when a bool is true (set when im holding my mouse down and false when im not)
wouldn't you just use the cancel thing for that
i think the second example here could work
let me try it
both could work
yeah i just dont understand the first one lol
it's the same thing just without a coroutine
that would be an infinite loop
this one is written to not be infinite
ill try it
that's not how code works, no
if you're getting freezing issues, then there's something not completing
shrug
wish me luck
this looks like it has the exact same issue with fixedupdate ,,,,,,,,,,,,,,
i dont think its an ‘issue’ though its just kinda how it works and im not sure if theres even a fix lol
when i move my mouse fast the clones spread out like crazy
if you're instantiating them all at the mouse position then it'll be limited by deltaTime
you'd have to interpolate between the previous mouse position and the current one
seems like more hassle than its worth
or you could draw a line between the previous mouse position and the current one instead of using pixels
i mean, the spacing out thing isn't really uncommon among poorly made versions
are they even on a grid
they dont need to be
that changes the constraints, it makes it easier
you can interpolate the mouse position
uh. i dont really know what youre saying anymore
oh this new code fucks with my other code somehow
fuck it all im just going back to fixedupdate 😭
way too much effort for qol
Why is there no C# script option
Is it MonoBehavior script or am I missing something
yes it is monobehavior found it
yeah it was renamed
For whatever reason i just cannot get my colliders to collide at all. i've used debugs, ive changed around triggers, i have both objects with colliders and rigid bodies... the bullets are just going striaght through the other asset.
how are you moving them
public class Asteroid : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("Asteroid trigger with: " + other.name + " (tag: " + other.tag + ")");
if (!other.CompareTag("Bullet"))
{
Destroy(other.gameObject); // bullet
Destroy(gameObject); // asteroid
}
}
}```
also you are specifically checking that the other object does not have the Bullet tag
[SerializeField] private Transform bulletSpawnPoint;
[SerializeField] private float bulletSpeed = 15f;
[SerializeField] private float burstShotInterval = 0.1f;
[SerializeField] private float singleShotCooldown = 0.25f;
private float nextSingleShotTime = 0f;```
{
if (bulletPrefab == null || bulletSpawnPoint == null)
return;
GameObject bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
Rigidbody2D bulletRb = bullet.GetComponent<Rigidbody2D>();
if (bulletRb != null)
{
if (pewAudioSource != null && pewClip != null)
pewAudioSource.PlayOneShot(pewClip);
Vector2 direction = (Vector2)transform.up;
bulletRb.linearVelocity = direction * bulletSpeed + rb.linearVelocity;
}
Destroy(bullet, 4f);
}```
i ensured that the proper tags were set
okay so does the bullet object have the Bullet tag then?
indeed
Great! That means it will not be destroyed by the OnTriggerEnter2D method you showed before. Just like I said.
i don't understand what is going on as i have played with triggers many times before. I've only run into this problem the first time i dealt with them.
if (!other.CompareTag("Bullet"))
what is the outcome of this if statement when other refers to a Bullet object?
U say u have played with triggers many times but u clearly don't understand how a simple bool return works
i fixed that part. but it still wont detect if the asteroid is it. i have it so two players with Player tags can shoot each other, but not themselves.
This does not seem to be a safe place to ask dumb questions when you put it like that 🙄
other.CompareTag(alienTag))
{
Destroy(other.gameObject); // destroy target
Destroy(gameObject); // destroy bullet
BasicExplosionAnimation();
}
if (other.CompareTag(playerTag))
{
// method to die and respawn
Destroy(gameObject);
}
}```
i have this script now attached to the bullet rather than the asteroid.
For what ever reason it just works now after remaking the asteroid asset. thanks for your help @slender nymph
!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.
MY ISSUE IS I HAD SIMULATED TURNED OFF IN THE inspector
just a quick question when i try VS2026 the intellisense doesnt work but when i install the 2022 from unity hub it works straight away. isnt 2026 intellisense fully compatible yet?
Did you follow the docs here?
!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
ill read thru it now but i dont see how 2022 works and 2026 wont but ty for the quick reply
2022 is installed through hub, 2026 you have to go thorugh the (Installed manually) part. You did that, yes?
thanks
It's not our fault that u ignored the hints we gave, especially when u claim to have experience with something
That's completely different from saying: "I don't understand what this if statement does"
It's unclear where your frustration is coming from as you seem to have very little patience for something you had little involvement with. My code is not the thing i was actually struggling with in the end. I made a typo in my code by accidentally removing my return in place for some brackets. You were not the one who pointed that out. So cheer up, have a cup of tea, friend. Life is too short to have frivolous gripes.
No, I was not frustrated. And I don't have to repeat what others have said. If there is an issue, it's better to focus on that issue and getting feedbacks before continuing debugging further.
I guess, we can just continue to help others from here. No need to dig further into someones reaction and expected behaviour.
Hi guys
How to use the newest cinemachine version
I'm kind of confused
I'm making a platformmer btw
as in, how to access it or how to utilize it?
Ultilizing
I want my camera to be a bit biased to wherever the player is looking
😭
have you tried googling for cinemachine guides/tutorials
isn't the core concept the same
and you can always just add the version to your search query
https://docs.unity3d.com/Packages/com.unity.cinemachine@3.1/manual/index.html
there are guides here too
Thanks man
Heyyy, i've got some file i'm generating on my app (csv files) and i would like to make a zip out of them, but everytime i try, i've got an "Permission denied" error, any idea why ?
(i'm already doing a lot of stuff with theses files so idk why this thing specifically is annoying)
Is that a code question?
Yep ! i'm just doing that
{
Debug.Log("Tentative de création de zip depuis : " + sourceDir + " vers : " + zipPath);
ZipFile.CreateFromDirectory(sourceDir, zipPath);
Debug.Log("Zip créé : " + zipPath);
}```
not really how support servers work, just lurk around and wait for questions to pop up
Alr
are you getting the error in the editor or in a build?
are you able to read other files from sourceDir or write other files where zipPath is?
Well the permissions are managed by a native api
You have to invoke the native api to give the user a prompt that asks him to provide this and this permission
Take a look around the google and you will find it really easy
This is a simple read and write permission
in the editor
and yes, in this directory, i create, i read, i do all the basic stuff
Ok so it’s not android?
the build will be for android, but i didnt try it yet
to be clear, you're getting an IOException?
oh, that's different (i misread what the exceptions meant)
UnauthorizedAccessException
destinationArchiveFileNamespecifies a directory.
-or-
The caller does not have the required permission to access the directory specified insourceDirectoryNameor the file specified indestinationArchiveFileName.
just to make sure - check that it's not the first situation
if you have a specific issue, you can ask about that
ZipRecordOnEndExperience(Application.persistentDataPath + "/uploaded/2025-09-16", Application.persistentDataPath);
i simplified to this
and i'm 100% sure i have the required permission since this .cs file is writing files on the same directory
ok so it's the first situation then
persistentDataPath is a directory
you're trying to write data into a directory
but the 2nd argument is where i want my zip to be right ? or i misunderstood ?
wait
i think i understand
you need place to be + filename
yes, as a file
it's where the file is at, not where the file is in
ahahaha my bad, it was such a basic thing i'm sorry
but thank's !
how could i missed that
Nobody starts an expert, no worries 😄
(that's where i got this)
that's the thing ;'( i'm not starting 😢
Oh you should see the stuff my colleagues with 20years of gamedev experience sometimes fail on 😄 and I'm not better with 7 years
you never really stop learning with this stuff
honestly in my experience, if someone claims to be an expert, they're either a god with a lot of dedication and experience, or they're overconfident
I think Chris here had one or two moments where he wouldve liked to curse at me with the dumb stuff I was writing here 😄
i have less experience than most people here tbh
i just have more free time to be active lmao
Yeah but a good eye for details that I tend to miss
"one or two" would be on the lower end for me.. i don't remember any instances like that with you lol. most of the negative experiences i remember are people consistently being confidently incorrect and arrogant/stubborn
if someone doesn't know something and they learn afterwards, that's a positive experience
Yeah you help too many people here to really remember it but I had my moments where I thought you might be angry at me xD
I've also been more active but thanks to those damn crunch times in our industry I cannot really do that atm
-# for example that one dude that was arguing for a good 3 hours against 5 people about how CC was supposed to be used
-# holy shit that convo was 3 hours...
ahh that's probably on me. i need to work on my communication lol. i tend to be pretty blunt and ive noticed that comes off as harsh when the situation is already tense
Nah I earned it in those situations, half reading the question and then blurting out non relevant stuff 😄
I wouldve said something if you were rude for no reason
why does it need to multiply with fixed delta time here? what it mean
Turns the number from units per frame to units per second. It lets you enter a per second value for m_EulerAngleVelocity
like just converting seconds to ms typa shi here?
then i suppose i can set a small speed instead and still make sense ?
To add to that: Your frame times are not consistent, neither on a device nor between devices
A device with 50 fps would move 5x the speed of a device with 10 fps,
So it behaves like:
50 x distance x 0.02 (Time.deltaTime) per second = 1x distance vs
10 x distance x 0.1 (Time.deltaTime) per second = 1x distance
no, converting x per second to x per frame (or in this case, x per physics tick)
not really
it could work (specifically in this case with the fixed time step), but it wouldn't make sense.
Not for fixed update, in this case it's purely just to make more convenient numbers
isnt even fixed update not guaranteed to run on timing? Especially with lags
@tranquil forge do you understand deltaTime in general? (is your question about it being fixedDeltaTime, or just the deltaTime in general)
why is the set (0,100,0 a per frame thing?
it won't actually run at a fixed interval, but it'll be simulated to a fixed interval. fixedDeltaTime will be consistent
i only knew multiply with delta time to make it not depend on frame rate
not sure what you mean by "set"
there's no set (noun) nor set (verb) here
the velocity set to 100 at start
fixedupdate is run many times, over time
you want to use a value of 100 per second, because that's easy to work with
but fixedupdate isn't running once per second
it's running faster than that, some x times per second
so 1/x gives you how many seconds each fixedupdate takes
that's fixedDeltaTime
but this is not the same as seconds and miliseconds conversion ?
it is not, no
see above ^
but fixeddelta time is set 0.02 right ? it is unchange ?
By curiosity, can we speak French in this community or not ?
you should not consider it as a constant
it's not guaranteed to be 0.02
it could be affected by physics settings and timescale
alr i think i get the gist, the fixed delta time here serve just a unit conversion
Hello
Think of it this way, if you had a value for m_EulerAngleVelocity of 0, 100, 0:
- Without FixedDeltaTime, it would rotate the object by 100 units every physics step, for a total of 5000 units per second
- With FixedDeltaTime, it would rotate the object by 2 units every physics step, for a total of 100 units per second
They're both constant based on frame rate because it's in FixedUpdate, so neither one is wrong, but it comes down to what unit you want to deal with in the inspector
just want to learn how to handle the basics of vectors, for moving things or moving the player
#💻┃code-beginner message
is he true tho
FixedUpdate runs independently of the framerate. It will double up or skip as necessary
yes, but it doesn't really change the answer
bet
so yes the timing may be different between the calls but it doesnt matter cause they equal out over time?
Trying to understand too 😄
Remember - Rendering happens based on your framerate, so even if the physics calculations happen independent of time, if your game lags, you might not see the results until the next render frame
he saying its really come down to what unit i want to works with, but sidia guy saying the difference might break thing
There's also a maximum delta time which Fixed Update will catch up with, after which it will skip updates. The default is 0.3333, so if you have a lag spike longer than that, Fixed Update will miss some frames.
but also, consider the things that would affect fixedDeltaTime
changing the tick rate would mean the speed changes
changing the timescale would mean the first situation doesn't get scaled, but the second situation does - either could be the intended outcome, but then what if you want to try switching?
if you use fixedDeltaTime, switching is just changing to fixedUnscaledDeltaTime
using deltatime just makes everything easier
There are valid reasons for changing the fixed timestep, possibly even at runtime, depending on which device is running, as a quality setting, etc. So you should still use delta time in Fixed Update.
You're already using delta time if you're using AddForce with the Force or Acceleration mode.
Let's say you have a game that runs at 60 frames per second consistently, with the default physics step of 0.2:
This means that a frame takes 0.0166 seconds, and FixedUpdate takes 0.02 seconds.
At frame one, you're doing both Update and FixedUpdate.
Frame two, 0.0166 seconds have passed, not enough for another FixedUpdate.
Frame three, 0.0332 seconds have passed, so it would run FixedUpdate, leaving you with 0.0132 "unaccounted" physics seconds
Frame four, another 0.0166 passes, putting you over the 0.02 budget again so another fixed update happens.
Now let's suppose you hit a loading zone that takes exactly one full second between frames four and five.
Your current time is at 1.0664 and you've done three fixed Updates, leaving 1.0064 seconds unaccounted for in physics time. This means that FixedUpdate will run fifty times right now. This "catches up" the physics engine with the game time. This means that any per-physics-step calculations like momentum do happen fifty times, each one doing the math as if they were exactly 0.2 seconds apart, and you see the result all at once when the render thread catches up after the load.
Oh yeah, so I did understand correctly just didnt think about that it will equal out and therefor prevent it from making speed framerate dependant, thanks for the writeup! 😄
if you don't have deltatime itll still be tickspeed dependant
Yes, you could change the Physics Time Step or the Time Scale, which would affect the value of FixedDeltaTime, so if you want a number to respond to those changes you should use it
Even if you weren’t frustrated, you came off that way. You were dismissive of my inquiry as you criticized my ‘lack of understanding’ rather than being helpful. You assumed I ignored the help I was given. You belittled me by suggesting a lack of ability than being helpful in any way. You criticized my technical skills, now I’m criticizing your communication skills.
This means that FixedUpdate will run fifty times right now.
That is, if you've increased the maximum allowed timestep. With the default 0.333, Fixed Update will run 16 times after the loading time and skip the rest. Rigidbodies will appear to slow down when this happens.
Actually, it probably won't run 16 times. It sounds like it will run however many updates it can fit within 0.3333 seconds. So if your physics update is light enough, it might be able to do 50.
whats make you want to specific set fixed step to 0.0139 percisely
That's 1 / 72 Hz. This is from a Quest project that runs at a locked 72 FPS.
you match it with update ?
i suppose make it smaller is better but larger is questionable
No, but that's a separate option.
If your physics update rate is lower than your rendering frame rate, you will see physics objects lagging every so often unless you enable interpolation on each and every rigidbody. For a VR project that needs to have a locked framerate and consistent frame times, it's better to match these.
Yeah, that setting is how long it takes to run the physics. If you do a ton in FixedUpdate it can actually slow down, but since it doesn't have to deal with the real heavy lifting like rendering, it's unlikely to run into that. I didn't bring up the possibility of how long FixedUpdate itself takes to run for the sake of making the math easier, but it is something to factor in
Hey I would have a question about movement. Lets say I have a "drone" hovering at a fixed altitude, I want to move that drone on two axis X/Z. I know I can use translate to move the drone, but what if I want to use addForce instead ? How do I make it ,ot fall with a rigidbody ?
There should be a checkbox to disable gravity on the rigidbody
If it's a Rigidbody2D it'll instead be a "Gravity scale" field you can set to 0
if it can be affected by other stuff, you could also freeze Y position or apply a restoring force to the specified Y level
If the a gameobject jumped to a ledge and had a box collider touch both the wall and ground they become grounded even though they are jumping. I tried using ignorelayercollision but idk if thats what I should be doing.
Does anyone know some potential solution to this?
depends on how you're doing the grounded check
you'd generally try to make it so the wall isn't considered
I tried to but when I airdash into the ledge Ill start running
Was using tags
and hoping to say that if I collide with the wall then grounded is false
but Im colliding with both the ground and the wall
when I airdash into the wall by itself then I never become grounded
is that not what you want
It is
The issue is when I airdash into the wall ledge Im also textnically touching the ground
at the top?
Yeah
how are you doing the grounded check
If my gameobject box collider is touching the stage box collider
On collision enter
tags
so you're grounded, if you're grounded isn't it correct?
couldnt you just make the ground above the ledge not reach the ledge
Anyone think they can help me? I'm trying to get access to a value in another component in a script
Show the code you tried so far and any errors or issues you ran into
Reference the other component, then you can get the value from it
https://unity.huh.how/references
Choose the best way to reference other variables.
let me get the errors real quick
!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.
What is InputAxisController in this script
A tool for sharing your source code with the world!
Its the component I'm trying to get a value from
Why did you write this line of code?
InputValue movementData = InputAxisController;```
It's nonsense
Its a value called LookOrbitX and I want to get the InputValue from within it
you're trying to shove a square peg in a round hole
So the variable is of type CinemachineInputAxisController. You are then trying to store it in a variable of type InputValue, those are different types
Its what I have left from tinkering with it and trying different things
there is no such thing
@pliant dome you basically have this, right?
Yeah sorta
Are you trying to just get mouse input?
yes
can't you just do this, basically
then why are you messing around with Cinemachine
You should be getting mouse input from the input system
ok but it doens't seem to recognize lookorbitx
I was worried about this becauce what happens if in theory you land on the tippy part of the wall on top?
= means "Assign to". It means you're putting a value in the box.
You've made a variable of type InputValue named movementData. The = would be telling it which InputValue you want that variable to hold. What you've done is instead tried to set it to InputAxisController, which is not an InputValue. You've essentially done int x = fish. They're not the same kind of data
You just constantly fall
What is lookOrbitX
I tried this earlier
Its in Driven Axises
the other option is not basing your check off of purely collisions
include positioning in that check
What do you want from it?
It's a category
which value do you want from that axis?
InputValue, I want mouse movements
you could add that in your existing check, or you could use something like a raycast or a trigger
input does not come from cinemachine
I'm not sure how to do that
The thing you're looking at is something that responds to input. It's not actually input
The lookOrbitX is something that reads from the given input value and does stuff in response to it
I wanted to make it so that if your colliding with both the wall and the ground at the same time then it always prioritizes you not being grounded
You want to read from the input system to get the mouse movement, which has nothing to do with the Cinemachine component
Time to start looking into that, instead of playing around with Cinemachine stuff
that simply does not make sense
Yeah Id imagine it be so
There are many ways to read input from the Input System:
https://learn.unity.com/project/using-the-input-system-in-unity
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Then what you need to do is keep track of both "is grounded" and "is toouching the wall" separately, then your code can do something like:
if (isGrounded && isTouchingWall) // touching both
else if (isGrounded) // touching only ground
else if (isTouchingWall) // touching only wall
else // touching neither```
i don't think that's applicable to their situation tbh
This wont be a concern as this is a platform fighter with no walls like that
I can't tell - seemed to me they want some special action when touching a wall that is mutually exclusive with being grounded
Ill try that