#💻┃code-beginner
1 messages · Page 179 of 1
how about you share what you actually need instead of us interviewing you for fragments of info
There are a lot of tutorials on how to add a ragdoll to a character on youtube
I need help with a 2D collider bug i'm running into. I have a weapon that's supposed to go back and forth between a goblin and its target dwarf, and it checks onCollisionEnter2D to know when to go back to the goblin
the problem is that it uses movetowards to go towards the dwarf
and so if it gets to the center of the dwarf, sometimes the collision doesn't register and it just stays there
and if I go into the editor and manually move it out of the hitbox it works fine again
but it seems like if it's already inside the hitbox it won't register the collision
I don't get it
can you please link an easy one
both the dwarf and the weapon have rigidbodies with continuous collision detection
Most are easy for basic ragdolls. Literally just search "Unity ragdoll" and there will be plenty of ones that walk through all the steps.
why is my character falling through the map? i know im missing something.. i have a character controller and rigidbody, do i still need a capsule collider?
yes
Real life simulation isnt even possible to suggest, last i checked there are none that really try to even do this. This is a very advanced topic that engineers still struggle with. For a simple ragdoll in a game, there is the ragdoll wizard. Some simple tutorials are easy to find on google, you just use configurable joints and set the rotation constraints. use the hips as the center of mass where you would add force/set velocity
okay, i added it back. how is the character controller used with the new input system? i cant find out what to look for
thanks for telling me
You shouldn't be mixing Rigidbody and CharacterController. Pick one
okay, ill try character controller? idk which is better for this situation, or easier to code
Input system is for gathering input. CharacterController moves with the Move function
both are hard
@wintry quarry please check your DMs
oh god, ive already done like 2 hours of reading in unity trying to understand the input system and some other things
The new input system was certainly an undertaking. Maybe try some youtube tutorials on it
responding to your deleted message. if you are too lazy to even google how to setup a ragdoll then you 100% arent gonna do anything past opening the project. People in here arent gonna waste their time, just start doing it yourself.
does anyone have any idea why 2d collision just doesn't happen sometimes?
i got the input system working, and reading values, it all works correctly, but now im not sure how i should move my character
is it related to my use of movetowards()?
Depends on context.
this is the context
i just found out about the character controller, and copied code and it worked but i wanted to understand it, so i restarted, but now im stuck on movement after reading input
If you're moving with the Transform component, it would be teleporting and not moving with physics.
i have my input system reading Move (callback context) as my OnMove function, but how do i use the character controller to move it?
then why would it work fine most of the time?
Undefine behavior relative to the physics system.
It'd try to displace overlapping solid colliders.
ok, so I should use rigidbody.movePosition instead?
Are you moving it in FixedUpdate? Is the object moving super fast? There's many a things it could be
Rigidbody forces or manipulating velocity where the physics system would handle movement.
Or kinematic and do a bunch of stuff yourself.
wait is that a no
cause doesn't moveposition manipulate velocity?
or do you think it'll cause the exact same problem
Only if it's not applicable:
Moves the kinematic Rigidbody towards position.
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
A yes and no answer wasn't well suited for the question.
Moveposition is generally for kinematic rigidbodies.
Which in this case might be exactly what you want, if it isn't already set to that
kinematic is for when you don't want physics effects like gravity, momentum, and drag, right?
Yeah
Also, physics based movement should be in FixedUpdate, not Update
gotcha
hmm, turning the rigidbody to kinematic disabled collision. do I have to switch everything to trigger?
You use the values passed to the OnMove method from the input system to move your object
You need to decide how you're going to move your object: rigidbody force, rigidbody velocity, character controller, etc., then look at tutorials for that movement . . .
okay, ill look into character controller, i tried some code i found and kind of understood and it threw some codes. so at least now i have a direction. thankyou
I'm trying to get my projectiles to delete themselves when they collide with the environment but it doesn't seem to be working.
See the Physics Messages troubleshooting steps that are pinned to this channel
Thank you sir
Sorry i dont really know if this makes sense or is just jibberish but can anyone tell me how I can inherit data from an abstract scriptable object to another scriptable object while also having an abstract class using the data from the abstract scriptable object?
I mean something like:
abstract class Item : ScriptableObject and then class Weapon : Item while using the data from the abstract class Item in the abstract class ItemObject:MonoBehaviour ?
What's the exact issue?
Not being able to use the inspector to reference? Pretty sure interfaces and abstract classes are not serialized in the Unity Editor.
This should use a normal Lerp, or a Angle one?
I want to lerp the lookAt value, just to be clear
could probably use that instead
ah. may need to use lookrotation with it
right, I think you'd use lookrotation to get a rotation with the forward direction
woohoo i did it, and i know what i did too! lol good feeling
Can anyone here point me in the right direction for 2D procedural generated maps?
Like this???
Im working on a 2D rogue like game and im trying to generate random maps using pre-exsiting prefabs
step is in degrees per second
This is going in Update, it is meant to correct slightly the trayectory of proyectile to do sorta of an autoaim
I am using it right?
you'd want to use deltatime
Not sure that's needed, I don't it to rotate instantly towards the direction, I want it to correct the direction sligthly each frame
Using deltaTime wouldn't make the Lerp almost instant?
it's a speed and usually any speed you'd going to be normalizing
But like, if I am not wrong, if this is in Update, only the first frame of the transition would be called, and the it will set its rotation to the start of a new one once it is called, moving a bit closer to the target each frame but never truly doing perfect aim
I am rigth about that?
Any class derived from Item will have its fields, if accessible. You need to reference a Weapon SO by dragging it in a variable slot from the ItemObject class . . .
it rotates at a speed, if you don't do it by deltatime then it's going to be instant
Also, now that I am at it
My proyectile is basically a fancy cilynder rotated 90 degrees on the X, can I like, make that transform its new default and make those 90 degrees 0 or do I have to use a Empty for that?
if you have a prefab with rotational values, I'd use a empty to wrap it
I kinda want to avoid using much parenting cause it affects perfomance and things like proyectiles are intended to be kinda numerous u know?
But if there is no other way....
private void Shoot()
{
readyToShoot = false;
GameObject bullet = Instantiate(bulletPrefab, shootingPoint.position, Quaternion.identity);
bullet.GetComponent<BulletScript>().SetStats(statsScript.damage);
bullet.transform.right = transform.right;
Debug.Log("LOL");
Invoke("ResetShootingCD", shootingCD);
Debug.Log("Wtf");
}
void ResetShootingCD()
{
Debug.Log("Reset");
readyToShoot = true;
}
Lol WTF why does this not work?
When it spawns in it shoots once and then it stops and when I set readyToShoot to true once manually it goes on working normally
I wouldn't worry about parenting. Deal with performance issues when you get them
I parent and reparent things with reckless abandon 👌
I have an offtopic question when I seen this video, since I've watched it its been bugging me trying to figure out how that sphere on the ground works.
at first i thought it was a raycast, but its not centered so i thought it could be a raycast thats just offset from the center of the camera but then I noticed that it sticks to the edge when you walk towards it.. I've been racking my brain and I just don't know.. LOL could you explain how that is functioning soo my brain can stop trying to figure it out
wouldnt usually recommend using Invoke, but as for your question, depends on what shootingCD is set to, and what the code is doing that calls these methods
fun fact, you can instantiate the bullet as a BulletScript and that way u dont need to use a GetComponent after you instantiate it
bullet.SetStats();```
is there a utube vid about using the new input system to look around in a 3d scene? alot that im finding use the old input system
first person
i want to use my mouse to look around in a scene, but also be able to use a controller etc
ty 😄
Is this object ever disabled or destroyed? That will cancel any pending invokes. Also instead of logging random words, try logging useful variables like shootingCD or readyToShoot
Hey, I am a pretty new coder with little experience. I was hoping for someone to point me in the direction to have a player stick with a moving platform, while having their full range of motion. I have tried many attempts, mostly with making the player a child of the moving platform, but to no avail. Below are the tutorials I used. Thank you for any input you could give, it would be appreciated.
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
In this part, we will create moving platforms that can transport our player and learn about Time.deltaTime.
Github repository:
https://github.com/codinginflow/3DUnityBeginner
🎓 Learn how to build a 2D game in Unity (beginner): https://www.youtube.com/playlist?list=PLrnPJCHvNZuCVTz6lvhR81nnaf1a-b67U
🎓 Learn how to build a 3...
moving platforms are usuallly a pain to figure out
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
maybe check out this asset, and see how it handles it.. (kinematic rigidbodies imo, handle moving platforms the best)
Thanks for the input, although im trying to stay away form asset packs, cuz its a competition
Although I will look at it
you know u can study other assets right?
just look at how they did it.. maybe theres something in there that can help.. like i said, its usually difficult to get to work correctly anyway.. you'll just have to tinker and trying out things until something fits ur needs
well, as a beginner ur best solution is going to be to use a CC and parent it.. or use a Rigidbody controller
Moving with a platform is typically done by applying the platform movement to the character in addition to any movement the character has itself.
The details depend on your character controller implementation.
^ that too.. u can use a collision trigger or ground check (raycast) to know ur standing on it.. and then add the velocity of the platform to the vector you use to move the player
on top of the input ur already giving it..
hey guys i had a quick question to ask and was wndering if you guys could help
wanted to make slime enemy that jumps towards ours castle which is the grey box as seen in this picture and i know how do points to jump at. i was just wondering how would i code it to go in the castles direction?ike towrds the castle?
but in jump opoints?
like what math would i do to go towards the castle but create jumpoints to head their in the direction of the castle?
public class SlimeEnemy : MonoBehaviour
{
public int Damage;
public bool IsPlayerAttacker;
public bool IsCastleAttacker;
GameObject Target;
public Vector2 TargetJumpPoint;
public float JumpSpeed;
public float TimeBtwnJumps;
public float MaxTimeBtwnJumps;
float randX;
float randY;
public float MinrandX;
public float MinrandY;
public float MaxrandX;
public float MaxrandY;
void Start()
{
if (IsCastleAttacker)
{
Target = GameObject.FindGameObjectWithTag("Castle");
}
if (IsPlayerAttacker)
{
Target = GameObject.FindGameObjectWithTag("Player");
}
}
// Update is called once per frame
void Update()
{
TimeBtwnJumps -= Time.deltaTime;
if(TimeBtwnJumps <= 0f)
{
Jump();
TimeBtwnJumps = MaxTimeBtwnJumps;
}
transform.position = Vector3.MoveTowards(transform.position, TargetJumpPoint, JumpSpeed * Time.deltaTime);
}
void Jump()
{
randX = Random.Range(MinrandX, MaxrandX);
randY = Random.Range(MinrandY, MaxrandY);
TargetJumpPoint = new Vector2(transform.position.x + randX, transform.position.y + randY);
}
}```
heres code
also one other thingi wanted to ask you was lets say i wanted multiple types of slime eneimes but with diffrent behavoir would you reccomend putting it all in 1 scruipt or have diffrent scripts for each type?
I had ChatGPT write this, any reason why it wouldn't work?
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
public Vector3 moveDirection = Vector3.right; // Change this to the desired movement direction
public float moveSpeed = 5f;
private void Update()
{
MovePlatform();
}
private void MovePlatform()
{
transform.Translate(moveDirection * moveSpeed * Time.deltaTime);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
// Apply the platform's velocity to the player
Rigidbody playerRb = collision.gameObject.GetComponent<Rigidbody>();
if (playerRb != null)
{
playerRb.velocity = moveDirection * moveSpeed;
}
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
// You can add additional logic here if needed
}
}
}
yes, cause GPT wrote it
well, theres lots of reasons it may not work..
does one of the player or the platform have a rigidbody (it cant detect collisions w/o it)
does the player have a rigidbody if it doesn't playerRb.velocity can't work, b/c thats a rigidbody function..
its using tags to know whats the player.. did you set up the tag "Player" and assign it on ur player object?
... etc
ya, chatgpt can write functioning code (in small cases) but it usually isn't going to work w/o doing the setup that the script needs to function.
Ok. I think I can accomplish the setup fine, Ill get back to you guys tomorrow if I have question cuz its late. Thanks for the help!
might as well ask chatgpt how to set it up as well.. since it gave u the code.. it'll know how the setup should be
hey guys if you have a sec could you plz look at my question above if anyone has a second to spare
Anyone know why I get this issue inconsistently from my gun's script:
No, because you haven't shared anything
to get the direction towards the target u just subtract its position from the target position.
direction = target.position - this.position;
that'd be one piece to ur puzzle
u could also get the distance and divide that by how many ever jumps u want to make, and then that'd give u the distance of each jump.
for the actual jump, not sure how you could go about that.. maybe some parabola mathematics
no thats not really needed
parabola?
not sure how ur game's gonna function w/ the jumps and all.. but think about all thats gonna need to happen, and just start 1 thing and add onto it
surley there a simpler way
there are many ways.. for 1 u could just add an upwards force + gravity..
u wouldnt have any fine control over where it lands.. it'd be trial and error with different values, depending on teh speed its moving laterally.. (left and right)
if u wanted to add just the right amount of force to land in a specific location.. yea, it'd be a bit of math.. taking in the velocity ur already moving.. the distance you want to travel, then the gravity's pull, the force needed to overcome it long enough to land in a specific point..
i see
is there a way to use the "Look" Action and Delta [Pointer] in the Input Actions as camera/player rotation?
i cant find any videos/documentation on it
most are using old input system, or using an Action Map from scratch and using MouseX and MouseY, but ive already somehow implemented a way to move both up and down without splitting it up into two different actions
yea im using the default scheme when you create an action in the inspector
it only has Delta [Pointer] and gives mouse input when its moved
it just seems weird id have to change the action from Look - using joysticks and mouse, to having to basically use the old method inside the new method
why? would u do that? the purpose of the input system is to be able to easily use all types of controls
https://www.youtube.com/watch?v=lclDl-NGUMg&ab_channel=SpeedTutor heres a robust tutorial that walks thru all kinds of scenarios w/ the new system
In this Unity tutorial, we'll dive into the flexible and intuitive New Input System, perfect for enhancing your game's user interactions. We'll start with installing the system and setting up your first action map. I'll guide you through scripting a manager script and creating your own 3D and 2D character controllers, complete with practical exa...
im talkin about when you create an action map, and it gives the defaults, couldnt I use the Delta [Pointer] instead of going through all the mouse X and mouse Y stuff?
ya, im aware of what ur talking about.. heres a snapshot of that tutorial i just sent
okay ill watch that one then 😮
theres timestamps in the description. could help u skim thru it to find whats relevant to u
i must become the ultimate input manager guru now
ill invent an entire game engine system in spite of solving this problem
i, myself, am gonna end up watching it one day just for some context, as I have hardly used the new input system, and i need to start since im working on a game i plan on being friendly w/ mobile and gamepads
yea i have realized learning it now that movement is much simpler this way. I actually just read the unity docs over the subject until i needed some examples, then i watched some utube tutorials
nothing wrong with have a good input manager.. you could probably re-use it over and over if u set up a good one
if I just kept watching tutorials i wouldve been so confused still
yea but i dont know what im doing yet, so i gota know how the babies are made first
ya, watching videos are super beneficial when u actually get hands on.. and use the stuff ur trying to learn about
good thing its geared for Beginner
noooo hes not using the same method I am when dealing with the input system lolll
hes going more through code, I went with a different method
maybe try #🖱️┃input-system they'll be more people familiar with the ins and outs of the system.
I'm having issues with multi-animation for a jumping/falling animation mix. If anyone could dm and help me out that would be awesome. Thanks!
People are not going to DM you, also not a coding question
You can explain and show your issue in #🏃┃animation and anyone who wants/can help, will
No stress, I've never had success asking for help in large discords over a public chatroom. If anyone does DM, I would be thankful. If it's not allowed to ask for help in that manner then feel free to take it down.
Just ask your question.
yeah unfortunately security's very tight around here when it comes to asking questions properly
just present your problem, in its actual code form, make sure its not a basic syntax error or a question that's simple enough to google beforehand, and then pray for a response
So i finally got something to get my player to rotate with the mouse input horizontally, but the problem is that when I press W to move forward, its not using the rotation of the camera to change where forward is
public void Look(InputAction.CallbackContext context)
{
deltaPoint = context.ReadValue<Vector2>();
float mouseXRotation = deltaPoint.x * mouseSens;
firstPersonController.transform.Rotate(0, mouseXRotation, 0);
Debug.Log("looking around");
}
What is the move forward code?
public void Update()
{
playerController.Move(direction * moveSpeed * Time.deltaTime);
}
public void OnMove(InputAction.CallbackContext context)
{
// read the value for the "move" action each event call
moveAmount = context.ReadValue<Vector2>();
// the x and y inputs read from the Input Action are converted into a Vector3
// to move forward and backwards, not up and down.
direction = new Vector3(moveAmount.x, 0f, moveAmount.y);
// Checks if the player is moving and changes the bool "isWalking" accordingly
if (moveAmount.x > 0.01f || moveAmount.x < -0.01f || moveAmount.y > 0.01f || moveAmount.y < -0.01f)
{
playerAnimations.SetBool("isWalking", true);
}
else if (moveAmount.x == 0 && moveAmount.y == 0)
{
playerAnimations.SetBool("isWalking", false);
}
}
i am using the new input system and a character controller, I finally got movement down, but now i cant seem to rotate the player like an fps shooter
Not sure where OnMove is being called, but if you're rotating the player can't you just use tranform.forward?
where would i use transform.forward? and also wouldnt that be weird to implement into the character controller? idk, its all still fresh and new to me, but im kind of getting the hang of it
Ah, I'm a rigidbody boy. I don't have any experience with the cc. But transform.forward is a direction
idk why I cant just rotate the player and not have global movement
yea im trying to get used to the new input system to get some level of consistency
Hi. I have a question: Let's assume that I have several variables with 1 data type. I need to write them both in an array (floats[]) or separately (float Standard, float Run, etc.), despite the fact that these variables will be asked in other scripts. How will it be better and more professional?
Why would you add them to an array?
Well, somehow I don't want to have a lot of public fields. You can create an array and hide it sometime. I don't know how to explain it.
You just want to collapse them in the inspector?
Let's say I have 5 floats separate and 1 floats[]. Which option is better?
You don't want to convert multiple floats (that stores unrelated seperate values) in an array because it removes the readability of your code
What if you accidentally remove an element or change their position
Imagine you have 50 different floats in your game and you convert them all to an array, you'll never know which float is for what purpose.
That's why always use separate fields unless all the elements in array are doing one purpose only
Depends on use case
In short, is it better separately?
What are you intending to store?
Well, the data type is float and int, which will be used in another script and changed
That doesn't tell me what you intend to store
I don't understand what you mean about storing
I have 2 floats one is for SpeedOfCar second is for DamagePerBullet
I wouldn't store them in in an array of float as Array[0] = speed Array[1] = damage
Because both of them are used for vastly different purposes
But if I had to store speed of all the cars in my game I could store them in an array as they all represent same type of float
Does that make sense? With that being said what are you trying to store?
Make a struct or class
Player's speed: walking, running, squatting.
Could make a struct or class as praetor suggested for all different states of player's movement but if don't want to do that I would store these values seperately for readability purposes
Good. Thanks
how can i get my model not to rotate upwards or downwards with the mouse?
public void Look(InputAction.CallbackContext context)
{
deltaPoint = context.ReadValue<Vector2>();
transform.Rotate(0, deltaPoint.x * mouseSens, 0);
Debug.Log("looking around");
xRotation -= deltaPoint.y;
xRotation = Mathf.Clamp(xRotation, -xClamp, xClamp);
Vector3 targetRotation = transform.eulerAngles;
targetRotation.x = xRotation;
mainCamera.eulerAngles = targetRotation;
}
im about to just say screw it and use the controller asset plugin
doesnt look like this should be affecting the x or z rotation at all. Unless you've assigned the wrong object to mainCamera
Maybe you have other code that is rotating the player. Also you can avoid this entirely by just using cinemachine
oh plz how do i use cinemachine with it? i thought about it but i thought it was a stretch
use cinemachine for the camera, itll handle the rotations. Then i just rotate my player based on where the camera is currently looking
i want to make my first game with somewhat optimized inputs, and the new input system, character controller, and new terms in scripts is killin me grandpa
ooo what kind of camera? free cam?
whatever camera you need, i assume this is first person?
ytea
should be able to find exactly what you need for first person camera using cinemachine on 
theres also an issue where he does an animation and you basically watch the back of his head. Could i parent the camera to that object? i tried but it didnt work
you can go as far as having the camera not render the player entirely. Not sure what effect you want but i 100% wouldnt parent the camera to the head
cinemachine has that script for you
time to start googlin
it is a complete plug and play solution, there is very rarely functionality that you need to add to it
at least in the simple cases
ok so i learned the difference between = and == just now
its pretty cool and/or handy
i use it mostly in idle and walking animations
== is conditional
ayee
what?
lol nothin
New to programming, ran into this error, anyone have any ideas, I've tried googling, but I'm stumped.
I would guess that you aren't intended to be interacting with InternalDirtyFlags (it is internal to BezierUtils)
Im wondering if it has to do updating my project from 2020 to 2023, Im also reading it could be something with libraries but Im not ssure.
Thanks for the link, Im digging through it now.
👍
It's my only error remaining.
it's possible that it was accessible before and they decided it shouldn't be but normally i'd expect unity to catch that as part of the migration
well you can always go to that line and see what it's doing, probably there is a 'new' way and it just needs a slight edit
{```
it looks like the error might be in a plugin though, in which case you might just need to update the plugin? did tou do that first?
That was the line in question, my first guesss was to change it to public, but that didn't really effect much.
Looking into it now.
that would be much preferable to editing a third party module yourself
My question is: Is there a difference between performance if in place: Massive.Should Length be used as a number? Of course, it will be more convenient to use .Length, but doesn't the system count the size of the array, thereby consuming resources? For better performance, you need to use .Length or number or is there no difference?
i am not able to figure this cinemachine out. any good vids using the new input system?
no difference
Ok. Thanks
hello, I'm trying to change the color of an image when it is clicked. it should toggle between a red and orange color so I defined the colors
private Color orangeAudioButton = new Color(255f, 88f, 0f);
private Color redAudioButton = new Color(185f, 40f, 31f);
and when I try to change the color with audioImage.color = redAudioButton;
the color chart indicates wrong rgb values and the image stays white when it should be red. when it should be orange it is yellow.
I'm confused as to what is happening. the rgb values i took straight from the color property on the image.
buttons have a preset way of making them change colors when you click them
iirc Color takes normalized values so if you want to pass in 0-255 range values, use Color32
whats iirc
you can make these [SerializeField] then assign them in inspector. Will save you the trouble of defining them manually. Do that or divide your values by 255
thanks, I used color32 and that works
that's a great suggestion, I'll start doing colors in the inspector from here on instead of defining them 👍
if i remember correctly
im not entirely sure as I got that part of the code from a yt video but as I understand it, it sends out a raycast and a spherecast from the cameras position. it then checks if there is a raycast hit and if there is not, it checks if there is a spherecast hit. If both of them fail, its a miss and the gameobject (the red sphere) is deactivated. If either hit, the gameobject is activated at the hit location. The raycast takes precedence over the spherecast, regarding the position of the activated gameobject
How do paste sites work btw? should I save it then put it here in the discord channel?
send the link maybe?
Im trying to make a droppable item but I have this error and I dont understand the error, if I have to provide extra information please tell me
Hi, been having a bit of a weird issue that I haven't been able to solve for around an hour. It is most likely a simple fix but I'm not sure.
Trying to get a character controller crouch working for a first person game, following this tutorial https://www.youtube.com/watch?v=rJqP5EesxLk&list=PLGUw8UNswJEOv8c5ZcoHarbON6mIEUFBC
Using his code at around 21:13 for crouching, my character collider keeps "jittering" upon raising the height.
I have heard that I'm supposed to modify the "center" of the collider to offset it, but that just makes the game object clip through the floor. then bounce immediately back up instead of slowly raising the height. I used this stack exchange post for that: https://gamedev.stackexchange.com/questions/159781/changing-charactercontrollers-height-causes-jittering-issue-in-unity
Is there some universal fix that I'm missing for this? Thanks.
The first video in a series where we are creating a First Person game!
In this video we look at setting up our characters movement.
I've setup a Discord!!! and I would love to have you help me start up a friendly community where we can all help each other grow as game developers!
Discord invite link:
https://discord.gg/xgKpxhEyzZ
Can't wait t...
You'll have to show the full error message
What is Collectableitem?
Method parameters are type name. You only have type
public void method(int){
}
ohh, thanks nitku
If the editor didn't underline that error then configure it: !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
• Other/None
Oh yeah now it shows the errors, thats very cool thanks
Does anyone else have the problem where you cant drag the stuff in the scene samples? Im new to unty so i dont know if its my fault
Hello, so I have two gameobjects that both get destroyed when they come in contact. I would like for this to happen only after a key is pressed. This is my attempt, but it's not working as expected. What could be the problem? Or how should I best approach this?
public class DetectCollision2 : MonoBehaviour
{
public static int feed = 0;
private bool buttonpressed = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
buttonpressed = true;
}
}
void OnTriggerEnter(Collider other)
{
if(buttonpressed)
{
Destroy(gameObject);
Destroy(other.gameObject);
Debug.Log("Score:" + (feed++));
}
else
{
Debug.Log("Not Ok");
}
}
}
How you should post !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.
What're you expecting?
Paste in the format above but also try to add more meaningful debugs. Like debug the name of the object hit. Your code also doesnt actually check what its hitting. Itll destroy when it hits anything
As is, if the button was ever pressed once and collision occurred anytime thereafter, it would destroy the two objects.
{
Vector2 inputVector = new Vector2(0,0);
if (Input.GetKey(KeyCode.W)){
inputVector.y = +1;
}
if (Input.GetKey(KeyCode.S)){
inputVector.y = -1;
}
if (Input.GetKey(KeyCode.A)){
inputVector.x = -1;
}
if (Input.GetKey(KeyCode.D)){
inputVector.x = +1;
}
inputVector = inputVector.normalized;
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
transform.position += moveDir * 7 * Time.deltaTime;
}
}```
IDK what ive done wrong
Cool feature
How do you know something's gone wrong?
when i save and go to unity there is an error
And what would that be?
That would be an error. Meaning something to fix
It is back ticks, not quotes. In response to the deleted message
'''
public class DetectCollision2 : MonoBehaviour
{
public static int feed = 0;
private bool buttonpressed = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
buttonpressed = true;
}
}
void OnTriggerEnter(Collider other)
{
if(buttonpressed)
{
Destroy(gameObject);
Destroy(other.gameObject);
Debug.Log("Score:" + (feed++));
}
else
{
Debug.Log("Not Ok");
}
}
}
'''
Also I dont really need to see the code again. We've commented on it already above. If you change it then paste using the format the bot tells you
i had already been to that
Then what's your problem
It explains the issue
still the same issue
What don't you understand about the solutions
i removed the things i didnt need
So, why does the error mention two using statements
i do not know
Because the objects are destroyed when they collide, I would like to add another condition to trigger the gameobjects being destroyed. So the goal would be to destroy the gameobjects if they collide and a button was pressed.
public class DetectCollision2 : MonoBehaviour
{
public static int feed = 0;
private bool buttonpressed = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
buttonpressed = true;
}
}
void OnTriggerEnter(Collider other)
{
if(buttonpressed)
{
Destroy(gameObject);
Destroy(other.gameObject);
Debug.Log("Score:" + (feed++));
}
else
{
Debug.Log("Not Ok");
}
}
}
Well this code should do exactly that. You havent said really what the problem is. The sentence above really doesnt make sense other than "destroy 2 objects only if a button is pressed before"
The problem is sometimes the objects are destroyed and sometimes they are not destroyed.
inside your trigger check that other == "what ever is surposed to destroy it"
You also probably want to check the pressed state not the down state of the key, which you also would not have to store in a variable. Unless you want this button‘s effect to stay on forever
How do I do that?
The objects are destroyed fine, when I remove the button key operation. But it starts behaving wierdly when I add that button operation.
Hellooo everybody
Thanks, but I would like to achieve it by simply pressing the button not holding it down.
void OnTriggerEnter(Collider other)
{
if(!other.CompareTag("Player")) return;
GameController.Instance.Score++;
Destroy(gameObject);
}```
Why this not working? I have rigidbody and 2d box collider on it
I'm trying to write some script so that I can space out my enemies punches. They should be able to throw a punch every second. This is my code. For some reason when I change the values in the IEnumerator, it does change anything and I can't figure out why?
This is a video to show you what I mean. You can see the Float value for the reload timer on the right
Go through the physics messages troubleshooting link pinned to this channel
I mean its not getting a call even. Maybe I wrote it wrong?
Corutines can start multiple times. Maybe that happens?
Are you starting a coroutine every frame 
Go through the resource and find out
I wasn't planning to
Hmmm how can I avoid that happening?
You can save it and check if it exists
Well, you have it in Update, so is something preventing that in your code?
How?
I dont think so. Everything in my screenshot is my code
private Coroutine _coroutine;
If(_coroutine!=null) return;
In the corutne at end just set it to null
Like this only 1 corutine will exist
I have this bool which is what I'm using to determine if the player is in front of the enemy.
Is it possible to get a bool value from the Overlap method?
But not how I've done it here
But like as a value. I don't know if I'm explaining it correctly
is there a way for the first person camera to be connected to part of the mesh so when the animation bends over the camera follows the head instead of staying put
is it possible to make a sprite only collide with 1 different specific sprite, but be able to pass through other sprites?
use tags
how would i use tags here
or even terrain
Or you could use layers
ohh right
Then when you write the collision code, make it check what layer the colliding object is on
ok thx
I'm not sure I understand how to make this work
You make the corutine variable at top of the class
It exists just to hold it
Or you can just make a bool variable
Like "CorutineExists"
Set it to true when its made, then to false inside the corutine when it finishes
I still don't understand. I'm making a bool at the top of my script and setting it to true, then making it go false at the bottom of my Coroutine
But it doesn't do anything
Pass your code here from update and corutine
How do I color a drawing when The player selects the place he wants to color by tapping the screen. It should paint it up with the currently equiped color. I am currenly using 'UnityEngine.InputSystem.EnhancedTouch' To gather touch info
You mean you want me to type my code here?
Im going crazy or why its not working?
I checked everything and layers and fisics are correcly setup. I havent changed anything and it worked in previus project of mine
void OnTriggerEnter(Collider other)
{
if(!other.CompareTag("Player")) return;
GameController.Instance.Score++;
Destroy(gameObject);
}```
This is just not getting called at all
Yes Ill add to it what I mean
Should I make the drawing cut up in pieces (like hand a separate image form leg etc) or a whole drawing (Every part is one image)
//private bool CoroutineExists = true;
private void Update()
{
if (EnemyCanCheck)
{
if (IsPlayerInFront())
{
//Debug.Log("Player Hit");
EnemyCanCheck= false;
Invoke("WaitToCheck", 10f);
fistReload = 0f;
StartCoroutine(FistReloadTimer());
}
}
}
private void WaitToCheck()
{
EnemyCanCheck= true;
}
private bool IsPlayerInFront()
{
// Checks if player is in front of the enemy, if so, enemy can punch.
return Physics2D.OverlapCircle(PlayerCheck.position, 0.2f, PlayerLayer);
}
IEnumerator FistReloadTimer()
{
// Loops until Reload bar is full
while (fistReload < 1f)
{
// Increment reload bar by 0.01
fistReload += 0.1f;
// Wait for 1 second before repeat loop
yield return new WaitForSeconds(1f);
//transform.DOLocalMoveX(transform.position.x + 1f, punchDuration).SetLoops(1, LoopType.Restart);
//CoroutineExists = false;
Debug.Log("Punch");
}
}
}```
OnTriggerEnter2D
I cant even find documentation online
void OnTriggerEnter2D(Collider other)
{
if(!other.CompareTag("Player")) return;
GameController.Instance.Score++;
Destroy(gameObject);
}```
Gues what? Still not called.
wrong signature
so where is your rigidbody2d?
In player
2D!
I installed an addon for visual studio thats supposed to help with autocompletion but it broke yestarday.
I need exorcist
addon ?
you need to learn how to google
I mean I google, it finds something unreleated
cos your not using it correctly
Omg it worked
is there a reason parenting the camera to a part of the player isnt following the mesh during the animation?
How do I color a drawing when The player selects the place he wants to color by tapping the screen. It should paint it up with the currently equiped color. I am currenly using 'UnityEngine.InputSystem.EnhancedTouch' To gather touch info
not without context, it could be a script for all we kno
When I stop the game I have this errors?
This object is from previous scene with donotdeleteonload
Wth
i shall show ya
Why am I blocked
where
read the error, it tells you whats wrong
What did I do
I dont have OnDestroy anywhere
you have OnDisable
how do I speak to moderators, I think My posts gets censored
you're probably talking about the Regex
it says OnDisable, read the error messages
I dont think Im that blind but it sais onDestroy
screenshot
line above it
Oh did on destroy run before on disable and caused object to get spawned?
that is asking a question. one of the potential causes of the error
a Period is not a complete sentence
Should I change OnDisable to OnDistroy then?
show OnDisable on PlayerController
makes sense
You might be asking why Im always referencing it
Culling.
Because for some reason its not working other way
wdym the other way
Setting GameCotroller.Instance.PlayerControls to a local variable
and linking it that way
uhh what is htat
Supposedly it should work but it doesnt
OnEnabled and OnDisabled are not Unity methods
not acording to this #💻┃code-beginner message
You can set what your camera sees and not through the inspector
but couldnt i just move the camera with the head? it would add to the realism to bend over
A cheap solution but works is to make the torso a separate layer from the head
or do i have to make an animation for the camera
But if your game is purely first-person there's really no need for a character model
its all seperate layers, even the hair. but putting it as a child under it doesnt change anything to putting it under the first person controller empty
So make your camera cull the head layer
Again, of you're making a purely first-person game I don't get why you need stuff like hair or a head
Show the camera inspector
well yea but the arms
the arms would still move forward and do things, i need the camera to act like a head basically
i would still want the arms in the view, and soon change the view to 3d if it can be implemented
Set the near clipping plane to the lowest (0.01) and get rid of the layers you don't want to see through the "culling mask" dropdown
Such as the head
It won't get rid of the actual game object, the camera just won't see it
If you don't see the objects you don't want to see through the drop down, assign a layer for it and select it in the dropdown
@vale karma can you answer this please too
Because I don't get why you need hair
If you strive for realism in a first-person game, I'd get why you would keep the torso
But not the head or hair
it came with the model on mixamo
and also i want the player to be able to play in 3rd person too
But the model has separate parts, no?
ehhh, the body is pretty much everything, then theres hair and clothes
lol check it out
If you want to change perspectives I think you need 2 cameras, one for the first person POV and the other for the Third-person
But handle that later
Did you do this yet?
@vale karma
Why is the camera behind the player?? 💀
loll the animation steps forward, thats what im tryin to fix
i want the camera to be fixed to the head during the animation
Make it follow the model?
how? i got it parented under it alrady
You have the hair parented
yea, its parented to the hair lol
Is there anything that is fixed to the head?
the ! is before other not player
the body is the entire body, head hands, feet
its not cut up into parts
the hair is tho :d
The body is clearly split up into multiple childed elements
wdym?
if (!other)
yea but even parenting to one of those elements doesnt change the position of it during the animation
what with if other
do if(other.CompareTag(!"player'')
Hi, its possible to define an object inside a script in a prefab??
public GameObject Obj1;
Thats wrong...
i tried
is that supposed to be C#?
!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.
i was just trying something i didnt know if it would work
it wont even compile
well
what were you trying?
i dont know
There are many ways to handle and FPS camera controller dude. But if your animation detaches from the camera for some reason or the transform of the model isn't following the animation bounds then there's no easy way to fix this
i admitted my mistake alright
hey, i want to make an option to toggle between normal crouching (you crouch while holding ctrl) and toggle crouching but it doesn't work, it's only normal crouching
~~https://hastebin.com/share/xadegatexi.csharp~~
@cunning rapids i even tried a script to follow the object with
gameObject.transform.position = hair.transform.position;
hair 😄
but yea i might have to table it or something, and no it wasnt called hair haha i just called it that so he would understand
Again, if the physical player model doesn't change its bounds, despite it playing the animation, there's no easy way to fix this
When your character leans forward, does the position of the "hair" game object change with it accordingly?
If my parent class is calling a method on its update and I change the method on the child, does the parent call the new modified method or the initial one?
do you have the camera or the character parented?
How to change sizes of 3d plane object in 2d?
with this script enabled, no
place the camera as a child on the character
why do you have a 3d plane in 2d
cause mesh only thing that accepts materials
it doesnt follow the head :/
ah ok
Use textures
make the character the parent
Can anyone help me on this, i am not sure whats happening, but i want to add a sound when i turn on and off the flashlight and its not working, and have that error
can you send a screenie of the hierarchy
ah you forgot 1f after playsound
just being parented to the part i want it to follow exactly
If i recall correctly it needs SoundLine and volume
this is with a script on the camera. all it does tho is keep the camera still the entire time
I've been trying to find a good way to store dialogue text efficiently, without these weird ui extensions. Is it really good practice to have all my dialogue loaded from start, if i had a ton of text(ScriptableObkect)?
apply the camrea to the prefab
or
unpackage your character
im not finding where to do that in the hierarchy
is it possible to see where a raycast goes in the scene?
right click character go to prefab and press unpack
Any good way to make a ai agnet, STRAFE(walk to the left and right) so it gains sight of a game object?
The only thing i dont know how to do is the algorithm that will gave me a position to set the agents destination to.
Can anyone help me why moveSpeed doesnt show in the script in unity?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeMoves : MonoBehaviour
{
public moveSpeed = 5;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = transform.position + (Vector2.left * moveSpeed);
}
}
i made it public
why does it not show
!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.
what
make it a float
OMG I FIXED IT
ill show ya
i litterally posted it as a code
You need to post large blocks of code on one if these websites
You arent on a phone screen
doesnt matter this is annoying af to see on phone
transform.position = new Vector2(transform.position.x - (moveSpeed * Time.deltaTime), transform.position.y);
And cs public float moveSpeed = 5f;
what does the f stand for?
You have to specify it's a float and also make a NEW Vector2 for the movement
float
You have to specify that the number is in fact, a float
yea thanks
Np
check the inspector. make sure moveSpeed is indedd 5
but when i have
(moveSpeed * Time.deltaTime)
how will i be able to configurate it when i have movespeed = 5f; above?
i want it in unity to configurate it
right here
save after you fixed your compile error
is it still possible even tho it says Time.deltaTime?
You need deltaTime if you want consitency across diff fps
oh yea
it works now
thanks
i just thought deltaTime couldnt be configurated in unity
mb
you can add multipliers but you don't directly change it as its tied to the fps so it fluctuates
(its time between last frame and current frame)
You cant put headers with { get; set; } stuff?
Like if do I have to tell the method to override the previous one or...?
unity doesn't serialize properties
field isn't a prop
you would need to apply the field serialize attribute to your property
whats on the table?
yeah you can do [field:SerializeField, Header("CoolBeans")] @fervent abyss
i designed a 3d printer in Blender. I got one sittin on my desk so i just kinda winged it
im gonna make it move and actually print stuff, and be able to repair etc, its gonna be a struggle but a good idea
Now its displaying only playerHead variable and others not
that is a very cool idea
yea im really good with printers, and i have alot of good ideas that sound realistic enough to pulloff ingame
you only applied the corect atribute to one property
for props you need [field:SerializeField]
Hey guys, I'm having a weird bahavour in the TMPro, if I change the text from the inspector its normal, but if I change it from the script it has the data but it dosn't show!, I'm just using a script to fix the arabic letter and return it to me to use it
how is text declared in your script?
I'm just taking it from a scriptable object and pass it to the function
i asked how is it DECLARED
As a sring sorry
no, the text object
TextMeshProUGUI
change it to TMP_Text
it's the same
Did you try logging the return from the Fix method?
It's shown in the inspector here
can we see your code
that does not show EXACTLY what is being returned
why is your unity green
environmentally friendly Unity theme?
😂😂 I change the run color to know if it's on or not
good practice, too many people make changes in play mode and then lose them because they 'forgot'
This is what is eexcpected
Use the Gizmos to know the colliders locations and check if there is a collider in the way
At a guess, it doesn't look like your text area is big enough to contain the text. Do you have wrapping turned on?
How
I used Auto size and it's the same
!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.
https://gdl.space/ovayequjun.cs why do my pins get stuck? The pin movement script is attached
can you copy the generated text and paste it into the inspector outside of play mode
in the scene menu click on the arrow next to icon and check if the colliders is checked, then run the game, return to the scene menu and see all the colliders
thanks
outside the play mode it worked
but anything i put in play mode does'nt show even the english letters
obvious question. Errors in console?
!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.
jsut this warning
I think when the warning shows the TMP stop responing
should not do, error yes, warning no
can you screenshot your hierarchy again, in play mode but without having text selected
and then the complete inspector of text
Can anyone help me on this, i am not sure whats happening, but i want to add a sound when i turn on and off the flashlight and its not working, and have that error
Weren’t you here already?
Ok
your gameobject doesn't have the sound source component might be the reason
how i do that sry?
Click the light
Inspector> Add component> Audio source
your script is trying to access the component that's not present )
No problem )
also expand the Audio Source and uncheck the "play on awake". Just to make sure it doesn't click everytime you launch the scene ) this might be annoying
for the future you can also try asking chaatgpt. Basically you copypaste the code, if it's not too big, and then ask why are you getting XXX error (copypaste). Chatgpt is quite helpful and knows unity quite well.
Sorry, I am completely out of ideas, it does not seem to be a code problem so perhaps someone in #📲┃ui-ux can help
ty for the advice
chatgpt is always in my browser open. Helped me a couple dozens of times already 😉
ok, thx u for your effort 💙
Hi.
Good afternoon.
How should I make a quest active after some dialogues are done or an object is found?
How should I code for them.?
Care to explain further?
I want make a quest get active when my player dialogues are done. Or when it's start talking to a npc or when a special object is found.
When I tell an object to rotate or move forwards, what is the object actually considerign forwards?
Like what is the orientation they consider to be the front one?
I have made a dialogue system
Hi
Im trying to await and I get an error
public async Task LeaveRoom(){
var result = await runner.Shutdown(true, ShutdownReason.Ok, false);
}
so shutdown returns Task void, what kind of result were you expecting?
Oh lmao
Guys is it normal for a collider that is going REALLY fast (like 50 units) to only work if it's continuous and not discrete
Sounds like events could help you here, you can fire an event when dialogue is finished or an item is found/picked up, etc then you can have specific quests subscribe to those events, or have some kind of "quest manager" start the quests based on those events and maybe other details like relevant parts about the item collected, or NPC, player level, etc
Help please
Can you explain more please?
How should I code for it?
yes, it is
I believe so, the physics engine updates at a fixed rate (same rate as FixedUpdate is called), so if something with physics is moving too fast, its possible it can move between these frames and miss collision events, you may want to confirm with the docs, but using "continuous" will essentially check the last few frames instead of the current one to try and account for what would otherwise be potentially missed physics checks
It's weird tho. My bullet is continuous and it only collides with a rigidbody if it's "continuous dynammic"
Even if both are continuous it's noticeably inconsistent
See?
You could use a global event system or a publisher-subscriber pattern, or if you have a direct reference to your NPC/dialogue manager/special item, then that script can contain the event, for example when a item is picked up, you can call something like GlobalEventManager.OnItemCollected?.Invoke(item); which might be a static System.Action<Item> type, you can then have your quest manager subscribe to GlobalEventManager.OnItemCollected += LocalFunc; (and if you subscribe to things its always a good idea to also make sure you have a time to unsubscribe, such as in OnDestroy or OnDisable, etc) - that "LocalFunc" would have to match the event type, so in this example private void LocalFunc(Item thingCollected) {}, you can do whatever checks needed to know its a "special item" and then fire a quest - similarly for a dialogue ending, heres a tutorial I found useful on publisher-subscriber pattern but any event-based variant might work well too: https://medium.com/@kunaltandon.kt/implementing-the-publish-subscribe-pattern-in-unity-knowledge-scoops-60ca0ac29884
The publish-subscribe pattern is a messaging pattern. It consists of a message publisher which publishes a message. There exist…
@fierce shuttle
Oh thank you!
I try to make it! 😘🌹🌹🌹🌹🌹🌹🌹
Ah, I may have been thinking of how "interpolate" works when I was describing earlier, though if continuous dynammic works for you, why not use that? It might be good to look at the docs for how the different collision detections work, my description was off memory: https://docs.unity3d.com/ScriptReference/Rigidbody-collisionDetectionMode.html
and
https://docs.unity3d.com/ScriptReference/Rigidbody-interpolation.html
Isn't it very inefficient to use continuous dynamic? In the past, when I made tiny FPS projects, even discrete worked fine
use what you need to use
you always need to do more calculations if the velocity is much greater in distance than the area of the collider in its path
It takes more performance, but you need to if your objects are moving that fast. You can use that or raycast instead . . .
pretty neat visual representation
"Use Continuous on physics bodies that only collide with stationary static colliders"
📃 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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Here
This is the script for my shotgun
you're gonna want to double check that link
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Goddamnit
Sorry about that
Yeah, so reading the representation and looking at your video. You're shooting a rigidbody with a rigidbody which says to use continuous dynamic
if you're shooting static colliders like walls only, then you can just use continuous
also note that the expected speed of the projectile will play a factor in which collision detection mode you'll need to use too. a very fast projectile using discrete may be too fast to register some collisions
"Sweep-based CCD can have a significant impact on performance, especially when widely used in a project. If a large number of high-speed objects with sweep-based CCD are in close proximity, the CCD overhead increases quickly because the physics engine
has to perform more sweeps, and more CCD sub-steps."
I'm shooting a rigidbody AT a rigidbody that needs continuous dynamic
Could consider using your own raycast detection too, but I'm not too sure how well you can blend it with rb
would probably be fine if you aren't needing collisional points
Is it a significant performance issue? What if I have a bunch of enemy colliders in one area?
The problem is that eventually I'd have to polish up the game and add stuff like enemies
Witht heir own AI and scripts
At a large scale
I can't imagine that's very good for your project
I also have a script for the bullet
using UnityEngine;
public class Bullet : MonoBehaviour
{
// Specify the tags that should be excluded from collisions
private string[] excludedTags = {"Player", "Weapon"};
private void OnCollisionEnter(Collision collision)
{
foreach (string tag in excludedTags)
{
if (collision.gameObject.CompareTag(tag))
{
Physics.IgnoreCollision(collision.collider, GetComponent<Collider>());
return;
}
}
}
}
Simply for ignoring collision of the weapon and player
I'd expected some middle ground implementation like I suggested, but it does seem like there's situations where you don't want to be using it but there's no other options
"middle ground implementation "
Elaborate
i did ^^^^
Oh
For both objects too
i can almost guarantee it isn't actually at its old speed
Makes sense
actually, if bullets cant collide with each other, you can just disable that on the matrix and it may not calculate them
would make sense
It looks good enough for me
Instead of using an array of tags and ignoring the collision, use the collision layer matrix to place the bullets on a separate collision layer from the player and weapons and make sure their collision layers are unchecked to collide . . .
Using layers instead of tags?
I saw an example script using a "bitwise left shift operation" (whatever the hell that is)
Something implemented like this?
using UnityEngine;
public class Bullet : MonoBehaviour
{
public LayerMask bulletCollisionLayer;
private void OnCollisionEnter(Collision collision)
{
if ((bulletCollisionLayer & (1 << collision.gameObject.layer)) != 0)
{
Physics.IgnoreCollision(collision.collider, GetComponent<Collider>());
}
}
}
Problem is I have no idea how this script works or how to implement it
Specifically this line:
if ((bulletCollisionLayer & (1 << collision.gameObject.layer)) != 0)```
please actually take some time to read the link
The rest is pretty intuitive
Sure
https://unity.huh.how/bitmasks#bitmasks-and-layermasks has an explanation of what this line is doing.
specifically, https://unity.huh.how/bitmasks#checking-if-a-mask
it is also entirely unnecessary when using layers to filter unwanted collisions
ah, I missed your point (:
right: you should just use layer-based collision so that you aren't having to filter out layers in the first place
This method is assuming that any layer can collide with us, so it manually checks if we hit something on the right layer.
You should just prevent unwanted collisions from happening in the first place in the physics settings.
and you don't even have to have entire layers dedicated to not colliding with other layers. in recent unity versions you can exclude layers on a per-collider basis now right in the inspector
I rarely check layers in my collision and trigger methods. I just use TryGetComponent to look for the component I expect to find on an object
If I understood correctly, you can shift an active bit through a list of 8 bits (1 byte) using the >> operator?
there is no "list" here
1 << x produces a number that has a single 1 bit set at position x
1 << 0 is 1
1 << 1 is 2
1 << 2 is 4
etc.
0001
0010
0100
This is necessary if you want to test if a layer is contained in a layer mask.
But, again, you can sidestep that entirely.
public enum Days : byte
It specifically set the index to have 8 digits due to it being a byte (which is equal to 8 bits)
oh, yes, then the enum values are 1-byte integers
Understood
the same premise holds; it's just shorter than the usual 4-byte integer
so ```cs
private enum Bits : byte
{
Example = 1 >> 3
}
Should return 00010000?
this doesn't return anything
How do i make it so the ball flies away i tried just changeing the scale of the schield to push it away but it doesnt work
this declares a new type called Bits with a single value named Example
I know I mean the value of "Example"
the numeric value of Example is zero
beacuse 1 >> 3 is a right shift by 3 bits
you probably meant 1 << 3, which is 8
add force to it. right now it appears to just be depenetrating
Wait wait I'm getting a bit lost, sorry about that
How is shifting the active bit 3 positions over will equate to 8?
0x08
i like how they have seemingly dropped their initial issue which is actually unrelated to bit shifting in favor of figuring out how bit shifting works
Read about binary numbers
I know how binary numbers work
right-left, base 2
Pretty easy
Yeah I see that now
1 in binary is 0000_0001
Left shift by 3 is simply 0000_1000 which is 8
So max amount of layers is 32 or 64?
32
Well who knows why would you ever need 32 layers so that should be enough
yeah i kind of hate how rendering layers and physics layers are the same layers in unity
Does rigidbody follow similar rules of physics as irl?
that's the rough idea
Well in that case it's easy to calculate the velocity of an object and adjust it accordingly
what are you trying to do here
Nothing, I'm just asking why is there a gaurantee that the speed isn't the same if you can easily calculate it?
because you got different results
measure the velocity and find out what's actually happening
it doesn't matter how sound your reasoning is if the outcome is different
otherwise I wouldn't need to test any of the code I write (:
Yeah I know, but with a little bit of physics knowledge you can pretty much gaurantee the same result in-game
this is not code related
I'm too lazy to adjust my values accordingly since I don't really need to change the current speed of my bullet gameobject, but it's very much possible to do so if you're that picky
Not talking about you specifically just saying in general
I just thought that boxfriend implied that you can't just change the values and test for the same speed unless I'm just stupid
boxfriend said he thinks the speed is different
because you got a different outcome
that's the point
Which it is, not denying that
Anyway it's not really that important
it's not that this guaranteed in all situations in all possible multiverses
it's just probably true here
Fair
Why cant I add sprites into animation?
Hello, I have come from Godot to Unity and wish to learn any Godot equivalence in Unity.
And one of them is what is the equivalence of (Godot) Node.get_parent() in unity?
This isn't a code question.
You need to select an object in your scene that has the animator assigned.
transform.parent
I've never use Godot, but you probably want transform.parent
Oh I got it now
In Unity, transform is where you get the hierarchy (parent/children) and position/rotation/scale.
oh, can I call a method of a parent via transform.parent?
I read it as pepe
📃 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://hatebin.com/lefzljzvay
i get following error
why does highestpoint not work
you have it defined somewhere already
it tells you that
its not that its not working, it that it already was defined somewhere
ctrl+f
just rename it into something else
if u need local one
You have it defined somewhere at start of the class
paste your entire code
You can call methods that exist in the Transform class from the parent, since transform.parent would also return a Transform type, from that, if you know the class/type your looking for, you can call GetComponent<Type>() to access public methods, for example transform.parent.GetComponent<Rigidbody>().velocity
Hum, I forgot to clarify that Godot's get_parent() is not the parent the class has inherited.
For example I have a class Player and a class Weapon.
Player has a attribute Weapon but Weapon doesn't have an attribute Player
Thus, I have :
public class Player
{
Weapon weapon = new Weapon();
...
}
public class Weapon
{
Player player = get_parent();
...
}
So is transform.parents equivalent to get_parent()?
no its not
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using UnityEngine;
using static UnityEngine.RuleTile.TilingRuleOutput;
public class PipeSpawner : MonoBehaviour
{
public GameObject pipe;
public float spawnRate;
public float timer = 0;
public float heightOffset = 10;
public float heightOffset = 10;
// Start is called before the first frame update
void Start()
{
spawnPipe();
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer = timer + Time.deltaTime;
}
else
{
spawnPipe();
timer = 0;
}
}
void spawnPipe()
{
float lowPoint = transform.position.y - heightOffset;
float highpoint= transform.position.y + heightOffset;
Instantiate(pipe,new Vector3(transform.position.x, Random.Range (lowPoint, highPoint), 0), transform.rotation);
}
}
here if your not on phone
You have two variables named the same thing
There’s two in the top both named heightOffset
oh yea#
literally at start
lol
wait
1 sec
im dumb
yea got it
some are spawning off field
how do i fix that
wdym spawning off field?
Adjust the offset values, make them smaller
what heights?
The code that you made
Make height offset smaller
these ones
the lines
for my window
i have both on 10
rn
and then people get stuck in walls for some reason
@vast saffron are you following a tutorial or making this yourself?
So can I access to public methods of a custom class that I created?
For example :
public class Player : MonoBehaviour
{
Weapon weapon;
int TimeLeft ;
// Constructor
public Player()
{
weapon = new Weapon();
}
// Methods
public void WeaponFinishedHisAnimation()
{
TimeLeft = 1;
}
public start()
{
AddChild(weapon);
}
public Update()
{
TimeLeft --;
if(TimeLeft<= 0)
{
weapon.Attack();
}
}
}
public class Weapon
{
public void Attack()
{
...
transform.parent.GetComponent<Player>().WeaponFinishedHisAnimation();
}
}
Does Weapon's method Attack() access succesfully his parent (Player) and call its method?
a tutorial but im not trying to copy everything
trying to help myself
so i learn from it you know
Nice
thanks
If weapon is a child of player, yes
Can someon please tell where the mistake is if it is in the code?
Ah yes, how do I add a attributes as a Child?
(How do I add weapon as a child of player)
start by configuring your !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
• Other/None
Hm? What do you mean “attributes”?
Just drag weapon into player in the hierarchy
Oh wait
I see the issue
I meant field, sorry.
that is a field (class-level variable)
I am adding a shake effect to the screen when the player takes damage, to do this at the end of the shake I reset the position of the canvas panel to its initial one, but this causes that if the screen size is changed the position of the UI doesn't adapt, how can I deal with this?
Not exactly - while Player can call weapon.Attack() because its a public function and Player has a reference to an instance of the Weapon class, if the Weapon was a MonoBehaviour and a child of Player, then that would work, there is also transform.GetComponentInParent<Type>() - though in most cases, you would pass whatever data Weapon would need from Player, rather than have Weapon try to access Player directly, or store a reference to Player so you wouldnt need a GetComponent call - you also wouldnt need to use a constructor with a MonoBeheaviour class, since you can use Start or Awake to act like paramaterless constructors, but for the case of your question, your Attack function is technically possible just maybe not a typical setup, and would also have to be a Monobehaviour attached to an object as a child, otherwise that code could not work as a non-mono class has no "transform" at that point
Well, the thing is the weapon script can’t be a child of the player script, the weapon GameObject can be a child of the player GameObject.
Like, who does the automatic scale works for a canvas?
Might want to do a null check else it should work if the parent was not null and if the parent had a Player component.
Trying to update my HP's slider, but for some reason it isn't working
So if my weapon script is attached to a GameObject Weapon
ANd my player script is attached to a GameObject Player
Does that mean that, if the GameObject Weapon is a Child a GameObject Player in the Hierarchy,
Then I can access to the Player's public fields/methods via transform.parent ?
Yes
What do you mean by, isn't working?
Only issue is, according to this code, weapon doesn’t extend from MonoBehavior
I'd debug log right before you set the slider. I suspect it works up to there but the slider is a smaller range than the health so it looks unchanged
Meaning weapon can’t be attached to a GameObject
I also would use an image with fill instead of a slider as you don't want people dragging it up and down with their thumb
When I call the SetHP method from another class (in the OnTriggerEnter method), the value of the slider doesn't change (according to the functionality of the SetHP method in the BossProfile class)
alr
Btw you should not use constructors with MonoBehaviour classes (or other Unity object classes like ScriptableObject).
You can do initialization in Awake instead.
I wanted to do as much abstract classes for my game 😦
It really hinders me if I can't add a child in script or need to have a gameobject in order to access the parents.
Now that I know, can I create an abstract GameObject, so I can give him an abstract class and then define its BoxCollider or Geogemetric form later ?
The main goal right now is just making sure the outrigger was called, the value was correctly calculated, and the value was submitted. Doing that debug log or a breakpoint proves all of those are OK and that the problem is the slider itself
the slider can be set as non-interactable if that's what you mean
Not really. You can use it, but it's meant for user input, so it carries a lot of baggage. Where a health bar, you can just use an image set to horizontal fill. It is much better optimized and less prone to issues.
Does the trigger occur? (does it log)
Is the damage calculated correct? (not zero)
the damage is also calculated correctly
Are there any errors?
so I think the issue is the method itself
nope
If it doesn't crash at the last line, my guess is it's the wrong boss entity
Was the result the expected value?
Can you verify these with logs?
I tested that a class cannot have more than 2 inheritance.
So how can I construct a class which inherit an abstract itself inherited by MonoBehaviour class?
For example, how can I remplace the constructor by Awake in this case :
public abstract class Entity : MonoBehaviour
{
public Stats Stats;
// Constructor ------------------------
protected Entity(Stat BaseHP,Stat strength,Stat defense,Stat moveSpeed,Stat attackSpeedMultiplier,Stat critChance,Stat critMultiplier)
{
Stats = new Stats(BaseHP, strength, defense,moveSpeed, attackSpeedMultiplier, critChance, critMultiplier);
}
}
public class Player : Entity
{
// Constructors ----------------------------------------------------------------
public Stella():
base
(
new Stat(StatTypes.Hp, 100),
new Stat(StatTypes.Strength,1),
new Stat(StatTypes.Defense,1),
new Stat(StatTypes.MoveSpeed,500),
new Stat(StatTypes.AttackSpeedMultiplier,1),
new Stat(StatTypes.CritChance,1),
new Stat(StatTypes.CritMultiplier,1.5f)
)
{}
// Methods ----------------------------------------------------------------
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Stat is a class who doesn't have MonoBehaviour
instead of using a constructor just make Awake virtual and override it in the derived class then call base.Awake in the overridden method
I just found out that the damage that is calculated IS 0
Putting constructors on MonoBehaviour inheriting classes do not work properly and should not be used.
Unity will fail to instantiate the component properly when it's attached to an object
So a good tip for future references is to simply not make any assumptions. Good job 
yea 😓
im gonna remember that
Quick question about unity, when I attatch a script to an object, am i making an instance of that script?
Like if I have a script called Movement and I attatch it to an object, am I basically saying new Movement()
MonoBehaviours are created and 'attached' with the same function which is AddComponent
So should I do something like this ?
public abstract class Entity : MonoBehaviour
{
public Stats Stats;
public virtual void Awake()
{
Stats = null;
}
}
public class Stella : Entity
{
// Start is called before the first frame update
public override void Awake()
{
Stats = new Stats
(
new Stat(StatTypes.Hp, 100),
new Stat(StatTypes.Strength,1),
new Stat(StatTypes.Defense,1),
new Stat(StatTypes.MoveSpeed,500),
new Stat(StatTypes.AttackSpeedMultiplier,1),
new Stat(StatTypes.CritChance,1),
new Stat(StatTypes.CritMultiplier,1.5f)
);
}
}
@thorn holly Unity does call new Movement somewhere when that happens, but you should let unity do that
yes
thank you
Got it, thanks
can some one teach me
you will not find anyone willing to privately tutor you for free here. you would be better off going through some structure courses like the ones pinned in this channel and on the unity !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Learn c#, do unity learn, learn how to use google
Hello I'm new and a beginner here so apologies. I'm struggling with a 2d game. Basically I want to zoom in and zoom out of an image on click. Is it possible with a box collider? Or should I create cameras. (I know it makes no sense)
What are you struggling with, getting the click input or making the camera zoom in?
wdym with a box collider? 🤔 how would that be relevant? or are you referring to detecting clicks on the object?
If you mean like a tutor, you gotta pay someone to teach you. But if you just want help or solutions or questions then you're more than welcome to ask here :)
Can a class without GameObject ( inheritng MonoBehaviour) access to the function void FixedUpdate() ?
Here I wish to have a dictionary of buffs that update the Buff Timer of each buff at each FixedUpdate
public class Buffs : MonoBehaviour
{
public Dictionary<StatTypes,System.Collections.Generic.List<Buff>> Dict {get;private set;}
public Buffs()
{
Dict = new Dictionary<StatTypes, System.Collections.Generic.List<Buff>>
{
{StatTypes.Hp,new System.Collections.Generic.List<Buff>()},
{StatTypes.Strength,new System.Collections.Generic.List<Buff>()},
{StatTypes.Defense,new System.Collections.Generic.List<Buff>()},
{StatTypes.MoveSpeed,new System.Collections.Generic.List<Buff>()},
{StatTypes.AttackSpeedMultiplier,new System.Collections.Generic.List<Buff>()},
{StatTypes.CritChance,new System.Collections.Generic.List<Buff>()},
{StatTypes.CritMultiplier,new System.Collections.Generic.List<Buff>()},
};
}
private void UpdateBuffs()
{
foreach (var type in Dict.Keys)
{
System.Collections.Generic.List<int> RemoveIs = new System.Collections.Generic.List<int>();
System.Collections.Generic.List<Buff> buffs = Dict[type];
for(int i = 0 ; i<buffs.Count;i++)
{
Buff buff = buffs[i];
buff.Decount();
if(buff.TimeLeft<=0)
{
buff = null;
RemoveIs.Add(i);
}
}
int acc = 0;
foreach ( int i in RemoveIs)
{
Dict[type].RemoveAt(i-acc);
acc +=1;
}
}
}
void FixedUpdate()
{
UpdateBuffs();
}
}
!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.
Dude
in order to be valid, your Buffs class will have to be attached to a gameobject. it will not receive any unity messages like Awake, FixedUpdate, etc without being attached to a gameobject
thank you
if you do not want it to be attached to a gameobject then do not inherit from MonoBehaviour and do not expect unity messages to work without some other object calling them manually
so I can't implement a sort of Timer without the class having a MonoBehaviour?
I tried a tutorial where they used a gameobject (added component as a box collider and a script ) And as soon as they clicked anywhere in that area. They could zoom in. (Which didn't work for me at all when clicked)
it sounds like you missed part of the setup
Thanks !
can someon tell me whats wrong? i can't find the mistake
I see
you still need to configure your !IDE like you were told last time you posted this. it is a requirement to have configured tools in order to get help here
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
• Other/None
i did what this IDE Configuration told me to do
screenshot your entire IDE to show that it has been configured
In this video we setup Vs code for Unity game development. We will install VS code and then install the necessary packages and extensions so that we can get intelliscence and code completion as well for C# and Unity game development. Hope you like this video
============================= Follow me on =============================
Instagram : h...
considering they are using visual studio and not vs code, this video is not relevant
how do i replace my player prefab model with all my scripts and animations carrying over?
Isn't it simpler for VS? Just download the SDK and there's already a Unity preset for VS
yes it is very easy to configure visual studio. it's also a lot less likely to just randomly break unlike vs code which seems to just stop working for no reason whatsoever
Elaborate
A prefab sits in the assets folder
Eh. I mean It takes like 10 minutes to configure VSC and it's lightweight
Potato Potatoh
Both have their advantages
sure, and it will just randomly stop working correctly too. much much more frequently than visual studio would
Where did Alino go
Didn't happen to me in a while
what does it matter if it's lightweight? You open it when you get up in the morning and you close it just before going to bed at night
yes, visual studio's advantages are being a fully featured IDE right out of the box with just a couple steps to configure and it will stay configured and the configuration steps are not dependent on the unity version.
vs code's current extensions for unity integration require 2021+ to work otherwise you have to go and install a million different extensions for some basic features.
also what steve said.
I got a low-end PC so lightweight works well for me. But yeah I agree that VS is better due to it being a fully-fletched IDE. Just saying that both have their quirks
You can have 1 Mono call functions for other instances, for example:
public class SomeManager : MonoBehaviour
{
public List<SomeThing> instances = new();
void Start()
{
for(...) {instances[i].Init(this);}
}
void Update()
{
for(...) {if(instances[i].isOn) {instances[i].Execute();}}
}
}
public class SomeThing
{
public bool isOn;
SomeManager parent;
public void Init(SomeManager boss)
{
parent = boss;
}
public void Execute() {}
}
In this case "some thing" could be a buff or whatever, and "some manager" is calling its "execute" in the mono Update, and initializing it in the mono Start, not the only way, but one way if I understand your concern