#💻┃code-beginner
1 messages · Page 617 of 1
the player
Ok so another GameObject
1sec
show us the collider configuration
you would have to explain what the player is and how it is configured and how it moves
and how you configured the MeshCollider as well
basically show us the two objects you're expecting to collide
inspector
this kind of screenshot isn't that useful
on gimme a min i'll
show the whole editor including the inspector
it also seems like that thing has at least 3 different colliders
ok, i want to add to my enemy collider the cover his body without blocking the "empty" spaces under it, if i use mesh collider the player can go through the enemy and if i use box collider im blocking those "empty" areas
ok major issue here
you're using a CharacterController
CharacterControlller cannot use any additional/extra colliders
you get the capsule that is the CC, and that's it
if you want a differently shaped collider you generally will want to use a Rigidbody-based controller or roll your own kinematic controller.
the cc is on the player, i want the shaped collider on the enemy
im using that Capsule Collider for trigger
So i was having a issue with unity detecting a controller when nothing was connected but it did print out and empty string. so i added this script to it so if its empty assume its not a connected controller. it works bt just wanted to check if it would stop 3rd part controllers or the code is no good. https://paste.ofcode.org/teXjuThBxP2gPv8RH7RigA
https://docs.unity3d.com/6000.0/Documentation/Manual/ios-detect-game-controllers.html this is the one i modified as it would show somthing is connect but empty
i'm sorry but i told you the purpose
to see keep the player fixed to the ground and rotate him acording to the surface of the ground
Yeah, but it's casting where the player currently is, and then you move them
wouldn't it make more sense to raycast where they're going to be and then setting the rotation and position there?
Well
i'm trying to keep the player fixated to the ground and not fall, and the ground is a cillindar and i need the player to be able to go 180 around it
how would u add a collider to a line renderer
You'd take the current position, add the forward and horizontal offsets, then raycast down. If it doesn't hit anything, you're on an edge and cancel the movement. If it does, move the player to that location and modify their rotation to the normal
so, move the player first. Then cast the ray and fix the player to the surface ?
Compute where the player would be if they were on a flat surface, raycast down from there, and if it hits, move the player there
that's the ground
a cilinder
and it gotta go around it
yes I am aware
have you tried googling for this?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/LineRenderer.BakeMesh.html
So, i move the player in the first half of the code, then i adjust the rotaiton and the position of the player based on the surface ?
You compute where the player would be if the movement were on a flat surface, then raycast down from that position. If it hits something, you move the player to the location and normal of the hit point
let me try and i'll get back to you
when i press the delete key assets dont remove from the scene does anybody know why that is
Is it possible to hide vertices that are weighted to a certain bone?
float vertical = Input.GetAxis("Vertical") * walkigSpeed * Time.deltaTime;
transform.position += new Vector3(horizontal , 0, vertical);
Ray ray = new Ray(transform.position, -transform.up);
if(Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, treeLayer))
{
if(hit.collider == null)
{
}
}```am i on the right path ?
right click make sure ur shortcut is indeed, Del
Compute, then raycast, then move
a shader possibly?
no clue just a guess
And make sure you use the object's local down vector, not world down
so i put the raycast first ?
Calculate where the player would be, raycast from there, in the player's down direction
Then see if it hits
hi
i'm confused on the calculate the player's position
should i put it on a vector ?
Current position plus some offset
However much you want to move by
I need some help with my hands to work in FPS Game, i have a script https://paste.mod.gg/jbqhcvlzzsoz/0 which basically makes the hands 2 bone ik constraint locked on to a grip of a weapon they pick up, although it seems to get attached, the IK doesnt work. sorry if its the wrong channel, i couldnt see any animation help
A tool for sharing your source code with the world!
but i awlays should hit would't it ?
Unless you're walking off the flat edge
there are no flast edges
ok, i can't find a solution
can't really wrap my head around it
i tried to do in the way you told and didn't quite get the result
float vertical = Input.GetAxis("Vertical") * walkingSpeed * Time.deltaTime;
movementPos = new Vector3(horizontal, 0, vertical);
Ray ray = new Ray(transform.position, -transform.up);
if(Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, treeLayer))
{
if(hit.collider != null)
{
fixedPos += transform.position + movementPos + hit.point;
transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
}
}
transform.position += fixedPos;```
that's with what i came int
You're still raycasting from the object's current position, and with world down
Do you understand the parameters you are passing to Ray
So, quick question: When you're not holding any directions, what do you expect movementPos would be?
if i'm not holding any direction it would be 0, 0, 0 right ?
so it's basically not hiting anything
Correct. Do you want your ray to start at approximately 0,0,0?
nope, i want it to start at the current position of the player
so i should insert the current position of the player at the start ?
So you probably want to not use the raw input vector as the origin of your ray.
Perhaps you should be adding some sort of offset to the player's position to get the origin
like this ?
There you go. Now use the object's local down vector (or negative up, I suppose) instead of Vector3.down
the entire fixedPos computation makes no sense
That also doesn't make sense
Think through the numbers
hit.point is the world position the line hits an object
so i should get the direction of it ?
or should i add it to the movementPos instead ?
Sorry, I scrolled up and saw that your conversation goes on for a while. What is this supposed to be doing?
When all is said and done, where do you want the player to end up
What is a value in code that represents a world position that would be on the ground?
Maybe somewhere that hits a collider of a solid object?
i think it's hit.point in this context
So you probably want to move the player there
Adding a position to a position is not a good idea
Work through the numbers. They actually have meaning
It's rapidly going towards infinity
What is the value of MovementPos? What happens when you add the world position of the target location to it?
If I'm at "100 miles north of Scranton" and I add "101 miles north of Scranton" then how far away would I be from Scranton?
at the start the movementPos is the position of the player
and the ray is drawn from there
Yes, and then what happens when you add the world position you want to go to, to the world position of the player
IT DOUBLES
and it causes not the movement i want
didn't quite got the result i was hoping for
it should be able to move around the cilinder
and not go throught it
im trying to add a collider to my line renderer and it wont work
you can't add a collider to a line renderer "just like that". you would need to make a custom script that keeps it aligned with the line, if the collider is on the same gameobject, you'll have trouble achieving that,.
You're going to have to be more specific
so i have a script that makes a line renderer create segements betweena start and end point and i want to add a collider to the rope
i tried to add a mesh collider to it and it didnt do anything
I noticed that once your raycast finds a hit, you check to see if a collider exists. Under what condition does your raycast find a target, but there is no collider?
Pretty sure you were linked to the function you'd need to use to add a mesh collider to a line renderer
did you use it
!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/, https://scriptbin.xyz/
📃 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'm trying to have a enemy be able to rotate towards the player but since I don't lock the rotation it ends up falling over. Is there a way to have it rotate but be able to stand straight up without it falling over
Yes I know I need to remove some stuff from my code btw
Probably, the problem is that the rigidbody is allowed to fall over in the physics simulation, which has nothing to do with your script.
I know and that's what I want. I want to know if there a way to make so the rotation doesn't do that
Check the rigidbody component and restrict it from freely rotating on any axis you don't want.
The rotation allows the character to move around when shot. Is there a way I can leave it?
You want it to be able to fall over on some axes when shot, but you don't want to normally allow movement on those axes when not shot?
Is there a way to active and deactive those axis?
Well, you have some options depending on what you need:
- Restrict rotations until the unit is shot -> like a ragdoll on death
- Don't restrict anything, but have a script "correct" the object to a more upright position each frame, to simulate a "standing up" force.
If you want the object to tilt over a bit under some circomstances, you'll have to add a force to move it upright so your bullets have something to fight against.
Well I want them to fly back each time they are shot. So maybe it deactives on shot, they get flung back but then get quick put back up. In which the axis are enbale again?
You could do that. You'll have to handle enabling and disabling rotation restrictions on the rigidbody in your code.
just wanted to ask if i was doing this code right because my high school mind is melting rn trying to understand raycasts lmao
what im trying to do is to make a raycast that goes diagonally down to see if theres a gap
and if the raycast doesnt hit anything then just jump
but my brain doesn't want to brain and refuses to understand how all these raycast functions work
First parameter, origin. Second parameter, direction. Returns a RaycastHit2D
there is no z direction in 2D.
but im not sure how to make it a certain direction so i just guessed with the Vector3(0, 0, 135)
so that direction makes no sense
Mhm, I am now just trying to think on how to have it so after a certain time on the ground, it'll active the restrication back on
yeah alr lol
did you learn vectors
You would pass in the direction you want
i just started learning about unity so maybe idk
Right now, this is 135 units into the Z direction, which, since it's a direction means it's length will be treated as 1, so it's 0, 0, 1
which is into the screen
vectors are a math concept
oh
yeah i thought itd work because when you rotate a 2d object u rotate it by its Z axis
but ig not
Yes, you rotate it around the Z axis. Imagine a line going straight into the screen, then spinning it like a foosball bar
that makes your 2D object spin
ohhhh
so how do i change the direction of the raycast
im trying my best to understand this youtube video but im still not 100% sure about what im doing
Again, first parameter origin. Second parameter direction.
Line starts at transform.position and goes to the right
Yeah, this part of your implementation depends on your specific needs.
im not sure what kind of thing id have to type for that tho
You'd type in your origin, then your direction
cuz i want it to be diagonal
Diagonal in which directions
right down
So make a vector that is right and down in equal amounts
so like 1, 1?

yippe
Figure out which directions are which
yep
1,-1
x 1 to make it go forwards
-1 y to go down
is this raycast hit check correct though?
that correctly checks if anything was hit by the raycast yes.
oh sorry
how do i check if it didnt
it's the opposite yeah
Inverted. Checks if nothing was hit
you have it right
oh okay phew
I missed the !
okay ty a lot for the help lol
gonna check and pray this works lmao
i just realized i was using AddForceX not Y 💀
I didn't even realize they have AddForceX and Y now
lol
back in my day we had to craft our own Vector2s
anyways i think i did something wrong because its not really jumping over the gap
well if that screenshot from the vidfeo is any indication you seem to be doing this only in Start
which doesn't make a whole lot of sense
im doing it in void update
Woah. I'm not sure if I like knowing that those exist... I wonder if they just wrap creating new vectors anyway.
should ideally be FixedUpdate for doing physics
alright
that's absolutely what they do yes
changed update to fixedupdate and it kinda funked out the movement so i think im gonna leave the original movement code in update
yeah the raycast isnt doing anything and idk why
put in a debug.log if it doesnt hit anything
and even when its falling into the void it doesnt do anything
it's cnot clear what the scene actually looks like and what's going on
also how the object is moving in the first place
whyyy
What it looks like atm
which object am I supposed to be looking at?
The red thing
trying to make it follow the player
and also jump over ledges
you're not adding enough force to make it fly
asked abt how to make that work yesterday and they said use raycasts to check
it's also not clear what the rest of the code making it move does, which is impoirtant
and what did you assign to JumpForce in the inspector?
idk if i should add comments
500
and is JUMP printing? How many times it it printing?
I think it's very likely your raycast is simply hitting the enemy itself
since you're not using a layermask or anything
i just wanted to check if it wasnt hitting anything
right and?
yk that would explain it
Did it print or not
it didnt lol
how do layer masks work lol
yk i can prolly google it lol
public LayerMask myLayermask;
then set it up in the inspector
and use it in the raycast (in the correct place)
it will decide which layers are considered for the raycast
anything NOT in the layermask will be ignored entirely.
where is the correct place?
alr
o its right after distance
so just RaycastHit2D raycastHit2D = Physics2D.Raycast(transform.position, new Vector2(1, -1), 2, myLayermask);
yeah
alr
ohhh
so if i use the layer ground in myLayerMask
will it only try to detect that layer
then the raycast will only see things with the ground layer
and then ignore the enemy since its a different layer??
yes
okay lol
it works now thanks a lot!
i now understand raycasts in 2d yippee
very cool
i can use this in future projects ig
500 jump strength was a bit much 💀
After some new ground checks + checks to see if you’re being chased it will now jump across ledges very cool
prolly gonna make 3 basic enemy types for my first level which 1: dont jump + dont chase, 2: chase but no jump, and 3: jump + chase
I have two scripts, one for my pause screen and one for my player movement. However, I cant seem to figure out how to reference the pause system in my player movement script. I have two Pastebins so you all can see my current code:
PauseSystem.cs - https://pastebin.com/btZyZNeX
playerMovement.cs - https://pastebin.com/NzqN7jV9
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
A lot of people have their pause feature in a GameManager that uses a “Singleton” pattern
[SerializeField] PauseSystem myPauseSystem; //assign in inspector
if(myPauseSystem.isPaused){
//example
}```
Choose the best way to reference other variables.
tysm!
So I have problem with this code and having the enemy shooting away from the player not to mention not looking in the right direction either. I'm not sure why this is happening, I know i'm missing something just what is it?
Double check that the gun placement is actually pointing in the forward direction
How do I know which is forward?
that too.. to me it looks like its transform.right axis is facing the cam
unity is a Z forward engine.
blue = Z
Then it was facing backwards then and now it facing forwards
make a sphere mesh, child it to the character, and change the position to z = 1
as long as u have Local selected, youll be able to just kno
I got it now, it was just facing the wrong direction
So I have this problem with the bullet from the weapon just going through the enemy for a few bullets before fixing itself. Is it a setting that could be causing this?
@safe root Hey! So I started scripting about 2 days ago, sorry I can't help you but I pinged you since your the most recent online, is there a chance you know how to make other objects connect to another object? Like I make a script in another game object and I want the script to say "Make the door play this open animation"?
rigidbody has a few settings for detection directly on the body so play around with those
Alright thanks 😄
You can call a bool from that script make it true. Then call that into the other script which will set it to work
Bad at explaining, but if you can show me the script I can show it better
Ohh, alright thanks! I Just don't fully understand lol
These ones?
no more like I spawn in a new gameobject, and theres another gameobject that can be anywhere like "mushroom" in a platformer game 2K miles away, I can make like "if the player presses f then the mushroom will die" even if it wasnt in the mushroom game object, it was in an empty one
I was talking to the other dude about my problem
also , reason I'm going here not tutorials I came across a tutorial that said "If you try to learn programming through tutorials, it will pass right over your head."
He said "Learn the absoulute basics then try to make a game with those."
So maybe you can try smth like that too! Maybe.
If you want
tutorials are fine
All depends how you lean
there's so many things about game dev you're not going to naturally figure it out that easily
I learn best by trying, see if I can search up the problem and fix it. If not ask more experted people
WHY CANT I SAY HM, its banned?!?!!
I guess so
Have fun
Ik how to make a player move and how to collision with other objects now, so I just need to google up a little things on google for mechanics and I should be able to 😄
u too
okay guys maybe I was wrong
tutorials are great for absolute beginners who do not yet know how unity works and what it's features are
once you're familiar with unity and it's basic features, you learn best by trying things yourself
that can be in the form of fully watching a tutorial, then trying to replicate it by yourself and look things up when you don't remember
but if you just blindly copy/paste from tutorials while doing stuff, you'll never actually learn how any of it works, or at least MUCH slower than if you would try to do it yourself
Does anyone got a image or sort for having a enemy move away from the player? Cause for some reason the enemy would just teleport to a fixed distant
It's because you're setting its position to a fixed distance (or actually a direction which doesn't make much sense)
Try rb.MovePosition(transform.position + oppositeDirection.normalized * Speed * Time.deltaTime);
That works but the moment feels a bit glitchy. Sometime freaking out for no reason
Make sure you call the function in FixedUpdate
I have two problems now, the enemy is very glitchy and the enemy will just go straight through the floor
Let me do that
Thank you, that fixed both problems
Hello I’m new to making worlds, I need help to get beer pong to work and pool tables
I was wonder if someone here could help me edit some pool tables and beer pong
If it's not a coding related question (this is #💻┃code-beginner ), I suggest checking out #🔎┃find-a-channel to see if you can't find one better suited for your question ✨
Alright 🤯 I have the following set up:
Weapon inherits from EquippableItem, which inherits from Item
WeaponSO inherits from EquippableItemSO, which inherits from ItemSO
Item has a reference to it's ItemSO
How do I turn that reference into a WeaponSO on Weapon?
public WeaponSO weaponSO => itemSO as WeaponSO;?
hey, for NPCs do i make a script for every npc or one script for all?
usually you'd make one script for each type of NPC
not each individual NPC
'type' like merchents, blacksmiths, etc..?
yeah exactly
so if i have npcs that only talks i can make 1 script and use if (or switch ) for text
keep in mind 1 script != 1 usage of that script
sounds like a good use-case for polymorphism
feel free to ask questions if you get stuck
Folks I want to make an auto-saving system, When Player unlocks a gameobject (Unlocking here means it sets the inactive gameobject as active) with some action , how do I collect and save the unlocked gameobjects and store them?
You usually don't save/store gameObjects. Instead give them IDs and save/load the IDs instead. When the IDs are loaded, activate the corresponding objects
what should be the ID? Like integers?
Anything you want. Usually an integer(or several), but can also be a string.
I already have enums for the unlockables, can i use them instead
Sure
Okay thanks for the idea!
Hi, i have a question about the Liskov substitution principle, I think the doc I m reading is misleading me.
A code must be bulletproof from using base class instead of subclass, or from using subclass instead of base class, in the first place ? Or it doesnt matter and your app must work with any class in a derived class tree
it means that ur superclass is such that any kind of subclass which inherits from it works so perfect that it doesnt damage the code functionality, the purpose of that superclass remains intact
Its like you have 4 children, but those 4 children are damn good that they can replace you without affecting your purpose and work
Basically if someone looks at one of your children, they think its you
I ask the question, the doc might be wrong, because it states that "derived class must be substitutable for their base class" but you add functionnality in your subclass, by using parent class you easily get a NonImplementedException
Or am i wrong
This means that if you have code that works with the base class, it should also work if you replace it with any of its derived classes.
What you say makes sense, subclasses must achieve everthing that parent class does
Is it not the contrary ? I mean, what the doc states
If using a subclass instead of the base class causes unexpected behavior, you are violating LSP.
If a base class method is overridden in a way that breaks expectations, LSP is also violated
That I understood
It says unnecessary complexity right?
Or the 1st line you're reffering?
Yes, first sentence
Its given correct
What Im saying and whats written both are the same thing
If my code uses a super rare tropical fish for something, it should be able to consider using a fish in the exact same spot in the logic ?
- A base class should always be usable instead of a subclass? (Incorrect interpretation)
- A subclass should always be usable instead of a base class? (Correct interpretation)
Ok
I think you got confused in this
I read A base class should always be usable instead of a subclass
But it doesnt make sense
I understand A subclass should always be usable instead of a base class
So it is me not understanding english properly
probably lol
User error as always
Thank you
Np
Guys please help 😦 I just spent like 50 mins on different tutorials finding a gun script that shoots bullets (ik in the script it doesnt tell the gun to shoot bullets, the problem is the gun isnt doing what IT IS supposed to do, go to cursor rotation)
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
oh I thought !code did the notepad thing but better /:
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
E HOW I MAKE DYNO BOT STOP
ok good I js gotta reply to ppl ig anyways pls scroll up I need help 😦
The bot stops when you stop feeding it commands
It also gave good advice on sharing the code because your current code is not being formatted
well okay, uploading it to scriptbin so other ppl can help then ig
Im so confused I havent gotten any sleep 😭
Im just trying to make "super mega kewl platformer top down slime color battle gun omega"
Tried to make a gun that rotated around the player based on the direction of cursor, but terribly failed...
You aren't going to receive help if you don't share the code properly
Again, please use a paste site or proper code blocks so the code is formatted correctly 🫴 #💻┃code-beginner message
It's the little things that greatly help a question
Did you read the bot message?
here goes another 2 hour of tutorials
paste code into it, save. share the link. super easy
The bot message is formatted in a way even a 5 year old can understand it
Use Scriptbin to share your code with others quickly and easily.
Tried to make a gun that rotated around the player based on the direction of cursor, but terribly failed...
oh, that was easy
First off, there's a much easier way to get the main camera. All you have to do is Camera.main
it would also be good for you to record a video to show what is happening - "terribly failed" isn't very descriptive of the issue
oh sorry, issue is the gun isnt actually rotating, its sticking with the player but it isn't actually doing what It's supposed to, also thx camera.main might fix it.
I only have 2 days of experience
i've added EquipmentHolder to a prefab, but when i try to reach the Equipment within the EquipmentHolder im getting null
private void DropItem()
{
Equipments weapon = Equipments.Weapons[Random.Range(0, 6)];
Equipment equipment = new Equipment(weapon.EquipmentID, weapon.EquipmentType, weapon.EquipmentImage, weapon.EquipmentName, weapon.EquipmentBaseAttack, weapon.EquipmentBaseDefense, weapon.EquipmentBaseHP, weapon.EquipmentBaseMP, weapon.EquipmentEffects, 0, false);
GameObject weaponPrefab = Resources.Load<GameObject>("Prefabs/Weapons/" + weapon.EquipmentID);
SphereCollider sphereCollider = weaponPrefab.AddComponent<SphereCollider>();
sphereCollider.radius = 2f;
sphereCollider.isTrigger = true;
EquipmentHolder holder = weaponPrefab.AddComponent<EquipmentHolder>();
holder.Equipment = equipment;
Quaternion rotation = Quaternion.Euler(0, 0, 90);
weaponPrefab.tag = "Drop";
Instantiate(weaponPrefab, transform.position, rotation);
}
private void PickupItem()
{
if (droppedItem != null)
{
EquipmentHolder equipmentHolder = droppedItem.GetComponent<EquipmentHolder>();
AddEquipmentToInventory(equipmentHolder.Equipment);
Destroy(droppedItem);
screenText.text = "";
droppedItem = null;
}
}
which line is null
Equipment is the null
AddEquipmentToInventory(equipmentHolder.Equipment);
lol
at this point, .Equipment is null.. have you checked the inspector at this point (at runtime) and confirmed it's assigned?
also add a debug log above it to see..
Debug.Log($"equipment is null: {equipmentHolder.Equipment == null}", equipmentHolder.gameObject);
AddEquipmentToInven...```
the EquipmentHolder is assigned,
that log will be clickable and ping the gameobjec it's talking about
this does not show that Equipment is assgiend. What you have there is just the class itself
You click that, and it'll ping the EquipmentHolder.cs file in the project window
1 sec checking
that public field is not visible in the inspector screenshot
i think because its a class
Equipment is a class?
a script(object)
script/class same thing - interchangable, I'm just trying to confirm by "its a class" You mean 'Equipment'
yes
if it's not a MonoBehaviour, put the serializeable attribude above the class declaration
[System.Serializable]
public class Equipment {}```
this will allow it to show in the inspector
there you go, it's not assigned like you think it is
It's called an attribute. This particular attribute does this ☝️
there's more to serialization.. which may be a factor here
I'm not sure if it being non-serialized would mean it wouldn't copy over when you Instantiate from the code built prefab
How can I write code in Unity to trigger when an object touches a second object?
Typically with OnCollisionEnter or OnTriggerEnter, or the 2D version of those
Is it right?
What's happens when you test it?
No error but dont work
OK, that's a start. Do any of the objects have colliders?
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
Ckeck this out: Collider interactions, and look at OnCollision events link . . .
ok thanks
Depending on an object's name is not very robust. Usually instantiated objects have a "(Clone)" added to the name anyway so it wouldn't work with those
It's better to check if the collided object has a certain Component or Tag
TryGetComponent and CompareTag
Are tags / component checks faster or slower than strings
tags are strings
I want to create a rope between two characters that can increase & decrease it's length. I used HingeJoints2D.
If I spawn in new Rope Parts, they get hooked to the next joint, but they rotation is completely off.
So the Rope sticks together, but doesn't look like a rope anymore.
Do I missing something here?
How to spawn the RopeParts with the right rotation.
Everything falls apart as soon as I start moving
public class RopeManager : MonoBehaviour
{
public RopePart[] ropeParts;
public RopePart ropePrefab;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab)){
AddRopePart();
}
}
public void AddRopePart() {
HingeJoint2D ropeMiddleJoint = ropeParts[(int)ropeParts.Length/2].GetComponent<HingeJoint2D>();
RopePart newRopePart = Instantiate(ropePrefab,ropeMiddleJoint.GetComponent<RopePart>().NextSpawnPoint.position, Quaternion.identity,gameObject.transform);
HingeJoint2D newHinge = newRopePart.GetComponent<HingeJoint2D>();
newHinge.connectedBody = ropeMiddleJoint.connectedBody;
ropeMiddleJoint.connectedBody = newRopePart.GetComponent<Rigidbody2D>();
}
}
right sorry, should have been specific, as apposed to object variables
Having a public object variable string is essentially identical to using tags?
no
there is no short/simple answer here to "faster or slower"
it depends
using tags can mean a bunch of different things
We need an !itdepends command in here
hey guys, idk i made a 3d model from blender and then export it to glb. i wanna put it to kotlin using sceneview. my 3d model doesn't load but others do? why is that
Nah, it would make the bot show this
Also got it in the C# server
well there is the taghandle thing in unity6
What should i google if i want to create a dynamic area in between other gameobjects. Like a lasso, how to check was inside ?
create a poly-line from the lasso's path, check self intersection of that poly-line, then triangulate the enclosed path-cycles, check whether any object is inside any of the triangles . It gets more complicated if the enclosed area is concave or the path can cross multiple times. (algorithms via google)
i wish i had a better way to ask this, but why does this not work??
Thank you! i will look into that!
transform not Transform
Transform is a class, which does not have a static function localRotation.
transform is a field, which is a reference to an instance of type Transform, which does have a non-static function localRotation
that doesn’t fix anything
show your current code and error
did you look at the link? is it even a monobehaviour?
i’m sorry i’m extremely new to coding i don’t understand what that means
It most certainly does. It might expose a new error now that it can actually compile this one
So what is the error currently
this
Okay so your script is not a MonoBehaviour. If you created it in Unity you would have had to manually remove the : MonoBehaviour , so, don't do that.
Leave that there, it's important
have you done any C# course? If not, it might speed you along tremendously doing one. https://dotnet.microsoft.com/en-us/learn/csharp
i never removed any mono behavior thing?
Maybe show the full !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/, https://scriptbin.xyz/
📃 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.
`using UnityEngine;
public class MouseMovmentScript
{
public float mouseSensitivity = 100f;
float xRotation = 0f;
float yRotation = 0f;
public float topClamp = 90f;
public float bottomClamp = 90f;
void Start()
{
//Locking the cursor to the middle of the screen while making it invisible
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
//Mouse inputs
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
yRotation -= mouseX;
xRotation = Mathf.Clamp(xRotation, topClamp, bottomClamp);
transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
}
}`
Yeah, so you removed the : MonoBehaviour that unity puts in a class by default. Don't do that.
Create a new empty script and compare what is there with what you have here
And see the difference
i guess i did, i don’t even remember deleting it lol
when i do it’s just
{
}
Then somehow you've deleted your script templates. I don't even know where to find them so I have no idea how you deleted them
You're creating these scripts in Unity, right?
i literally have no idea how that would of ever happened
yes
https://github.com/brihernandez/MouseFlight
Litterally the flight sim installed from github gives this stupid jitteryness. I implemented this same flight sim into my game and its very much the same structure and stuff and yet the jitter problem is still there. it kind of started after I reloaded the prject.
i like just clicked on “create empty c# script”
Well that would be why it's an empty C# script. Create a MonoBehaviour instead
ooohh
sorry i’m new to unity
i’m level designer so i’m used to opening a program and already having everything done for you lol
if that makes sense
It does, but you've somehow gone out of your way to pick the option where it isn't
I don't even know where the "empty C# script" option is, I can't even find it on my end
this is what it looks like for me
maybe my version is different for some reason or whatever
Notice how MonoBehaviour Script is separate from that and still an option
Taught me something new. Didn't even see that was a thing xD
as i said, i'm new, i saw "C#" and it was thing i recognized so i picked that one
I have the same options, but they're custom editor scripts I created. Kind of cool if they do that by default now . . .
I always choose the Empty C# Scipt now, all that's missing is : MonoBehaviour and comes with no extra fluff that gets deleted anyway
it's new in Unity 6
Ah, that'd make sense. I haven't upgraded this project to 6 yet
Hello, are there any common reasons for builds to show up as viruses for other people when they download it?
i've been building for a while and suddenly without changing anything, when i send my build to others their browsers detect it as a virus and block the download
configure 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
• :question: Other/None
it'll highlight errors
how?
see the bot message
Not sure what that has to do with what you were asked to do
sorry wrong channel lol
which link should I click?
Which one do you have
I have unity and atom for script
Then you should switch to an actual IDE, pick one that's actually on the list and follow the instructions for that one
okay, thanks !
Hello, i have a problem with the player stopping half way the cilinder while i need it to be able to go 180 around it and i don't have any idea why it happends
The raycast will stop hitting the cilinder at some point
even if it's close to it
i debuged the ray and it's always pointing downwards
youve got Private void which should be private void
I have a Prefab gameobject attached to a canvas. It has a script that is supposed to write "OnPointerDown" in the debug console. However, the gameobject does not register when I press it. The prefab is an empty gameobject with text and a sprite attached as children. It still does not register when I attach the script to the sprite child instead. What am I doing wrong?
The canvas is set to screen space - camera, and the camera has a physics 2D raycaster.
your object doesn't have a Graphic component
there's nothing to raycast against.
I'm not quite getting the desired behavior for my player rotation handling near the bottom of this script. The debug console still shows some residual player rotation for a short while even when there is no player input. I'd like their currentSteerAmount to drop to zero when there is no input. I'm doing this so holding a turn in one direction has ramp up but then if for whatever reason you turn the other way it feels more responsive.
https://hastebin.com/share/xamugokitu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it needs an Image or something
Let me know if I can clarify better.
Input.GetAxis has some built in "smoothing" behavior
use GetAxisRaw if you don't want that
Thanks for the response! But there is still no debug message even when I attach the script to the sprite child of the prefab gameobject. The child has a Sprite Renderer component.
BLESS YOU
does your canvas have a GraphicRaycaster?
Is the event system all in order?
Yes it does, and as far as I can tell, the event system is in order.
wait sorry
why does your UI object have SpriteRenderer
that's not correct
UI should be using the Image component
SpriteRenderer is not a Graphic
and it's not for UI
Omg marry me! Thank you so much, I have been scratching my head for the last 90 minutes
Why have I been looking at this for a while and have the feeling I can simplify it but I can't tell how?
else if? assuming isCombatTimeRunning cant change in that method call
I would change the second if to an else if, but otherwise, without refactoring other thing, you're very fine like that
else if (isDead) yep
Either if it's dead or the time is paused the Update should stop
So I don't think I can use the else if
do you mean that both conditions you showed could happen at the same time ?
The entity could be dead and the time could be paused at the same time, yeah
of course you can. the only difference in logic is if the case i mentioned above
"isCombatTimeRunning cant change in that method call"
It's Update
doesnt matter, thats not what im referring to
im following a crappy bird tutorial, for some reason, when i build the game, the UI gets misplaced (top left score gets cut), inside unity I have these scaling settings and from the "game screen", the game looks alright in all resolutions, what could be wrong and how do i fix it?
im brand new to unity
no I meant, if combat time is running AND if the character is dead, do you want to runskilltimer THEN stop update ?
If so, two ifs are fine, otherwise use else if
Yeah, I want to
ok then your code is fine
This is like league where your skills still count their cd timer while you are dead
If u didn't touch anything, u probably have the anchors right but have the text on the default mode of line up to the left, make it centered
your code doesn't do that 😅
If time is running, the cooldown will be decrease, otherwise or if the character is dead, it will stop being decreased
But to come back to your first issue : no you can't simplify it right now. best you could do is create a function to get the result of combattimerunnin || isDead, but it would serve basically no purpose
if your logic is 5 lines long and works as intended, you're very good to go
No, it will be decreased anyways, the stopUpdate check happens later on in the line
hmm im gonna try to figure it out from the docs since im not understanding, i'll be back if i dont get out of it
Basically is to stop the Update of the subclass
I should have definitely given a whole different script for when a character is dead I think
context: object pool. want to give the pooled objects a timeout. Better to use coroutine or just a timed invoke? (there can be 100+ in the pool)
Yes, have one person stand over the other's shoulder or use discord
otherwise - you should use git or other version control to collaborate
So now these values are how many pixels away from the center you want this to be
tyty
id avoid invoke as much as you can. you could use a coroutine or just manually keep track in update. it really doesnt matter which you do. I'd just try to make sure you aren't coding this per every class and maybe have this functionality in a base class
its a reusable class i made UnitPool, and it uses a queue of classes implementing IPoolable
i'm hesitant to make it kick off 100s of coroutines, but idk what kinda limits there are or how heavy that'd be
similar to other VC. You make change sets, commit them, then pull them from theo ther pc
the coroutines would just be waiting for (timeout) seconds and then force returning the object to it's owner ObjectPool
you could just start off by doing it in update. if this code is in one place, its quite literally 30 seconds to swap it from a coroutine to update
mostly just there as a precaution so nothing hangs outside of the pool forever
yeah true.
id only really worry if you were using Invoke. if you use update or a coroutine and have performance issues, those performance issues are due to the amount of (likely moving) objects. not because of some timer
aye
i highly suggest just looking into git rather than unity's version control. you dont need an integrated version control, and git is used in every other branch of computer science. it's way more useful if you were to learn it
I-m using deltTime, from the documentation I read that its the time from last frame. So in this case, would the position be independent from the frame rate? since faster frames mean smaller updates?
transform.position += Vector3.left * moveSpeed * Time.deltaTime;
However in practice, the speed dramatically jumps in the build
even the gravitational acceleration increases, which I have not coded myself but implemented with RigidBody2D, what could be wrong?
you would have to show your full code
this isn't enough context
yes Time.deltaTime is used to compensate for frame timing differences
it lets you convert a per-frame quantity to per-second
What's the best way to share the full file?
!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/, https://scriptbin.xyz/
📃 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 you wouldn't see the rigid body implementations etc?
Since that's done through the editor
would help if you could show more context
you can share that as well as screenshots
but if you're using a Rigidbody, that code is completely wrong
That's for the pipes sec
I'm gonna share
https://pastebin.com/XcUq8Lva this is bird code
https://pastebin.com/NXaZdfgM this is the pipe mover code
in image rigid body of bird
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
The issue: everything in the game seems to speed up, including the falling speed of the bird and the speed of the pipes
as I mentioned above, you are mixing up Rigidbody motion with directly modifying the Transform
you should pick one or the other, not both
doing both causes issues
I see, so tl dr I should never use Physics from the editor if im affecting movement in code?
no idea what you mean by "use physics from the editor"
if you're using a Rigidbody you should move the Rigidbody via appropriate physical methods in your code
you should not move the object via teh Transform
im slightly confused im not using transform for the bird
but for the pipes
the pipes are not rigid bodies
what was the issue again
everything speeds up randomly after build
also are you sure things are actually speeding up? Sometimes people perceive a speedup when the game resolution is larger
yes
show a video or something?
weirdly enough having amd in game overlay on top fixes the speed up
i will film with my phone, since the recording prevents the bug xd
if your game is actually haveing framerate issues, that can cause the simulation to slow down
if you are exceeding the max timestep
As you can see it randomly slows down to what should be the correct speed after the first death
And then speeds up again randomly
maybe your code is changing Time.timeScale somewhere?
what's in LogicScript
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Any other scripts in the project?
theres a pipe spawner and a collision detection for the score
can you show them?
pipe spawner https://pastebin.com/YcN2m5B4
collision https://pastebin.com/HwYVdU4L
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yeah i don't see anything in here that should do any of this
there are no other scripts
only thing I can think of is a framerate issue kicking us past the max timestep but that seems unlikely
or a hardware issue of some kind 😬
maybe some weird GPU setting or something
maybe
amd is famous for weird drivers
ok I found the issue
its this gpu setting
i can make a short video xd
I believe you
should i bug report this to unity or what?
yes
ok cool, i'll look into it tmr, gonna hit the bed soon
ty for the help
In theory it's an fps unlocker but prob does weird stuff behind the scenes
It's more of a v sync alternative. I guess I could see a path to delta time getting confused if Unity is trying to measure frame delivery, but it seems odd that it would end up being reported like this.
hi
Hey man. I need some help.
Don't ping people you're not in a conversation with
i am working on my own 2d game and want to do a really simple thing but cant figured it neither can chat
i have a gameobject (inside canvas and horizontal layout group) in it i have another game object (its child) which i want to place inside the bounds of its parent randomly. But i am just confusing myself with the coordinate system or idk, when i try to get the height of the parent i always get 100 or 0 both of which are wrong. I will greatly appreciate any help or advice how should i tackle this issue
thanks
You probably want sizeDelta
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RectTransform-sizeDelta.html
thanks will look at it
Vector2 parentSize = parentRect.sizeDelta;
Debug.Log(parentSize);
this will print: "(491.43, 0.00)" and parent height is clearly not 0 its just broken idk what to do man
Dont know how to fix this crap.
- https://screenshot.help/
- Find whatever broken script is still attached to an object and remove it
Show the inspector for the parentRect object
So, its height is driven by a layout group. When are you logging the height? You might be getting it before the layout has had time to resize it
its set before runtime
i fix it
And the layout group my re set it when you start up, it might be 0 on Awake until the layout group runs Start
but have no idea why did it work 😄
in the parent object of the parent i unchecked control child size height
Is it possible to write unit tests for Monobehavior scripts? I see there is some unity test framework but does it allow that?
You can unit test something in monobehavior sure
You still need a poco iirc
Poco class runs function in MB to unit test
hello, does camera.worldtoscreenpoint have a distance limit?
can someone help me fix this error if possible please
that's not quite how you create a new instance of an array
is this some homework or somethin cus those comments seem sus
Is this Unity related?
Assembly-CSharp
seems like it
also coupled with the fact that they can't use newer c# features
components of the player
everything was working properly until i merged it with the main branch
the animator probably
is moving the renderer into the ground
and/or one of your sprites pivots is just off
(which is the same thing)
do I have to fix the pivot points in the sprite editor manually for every sprite I used?
maybe? I don't know what your art pipeline is
normally it's a spritesheet that is aligned properly from the get go
tbh i don't know what to tell you since Im very new to 2d game dev but could you look at this and tell me what has happened?
is this what you mean by the rendering being moved when changing pivots?
I didn't say anything about changing pivots
YOu need to look at your sprites in the sprite editor
and make sure their pivots make sense
I just centered them all back to what they were originally
if i want to get the velocity of an object right before it collides with something, should i use the contact point with the GetPointVelocity function or will that return the velocity after the collision happened?
*the contact point of the thrown object
guys can a string be capitalized
no it's illegal if you use a capital letter the secret police will take you away
oh ok
Hello, I am making a underground 2d game. its essentially just a game where you are constantly digging down. I was wondering what is the best way to populate a tile map on level load? There are 3 ways of doing it that i thought of.
Generating the entire map, then only rendering what is near you.
Generating the entire map and just loading it all at once
Generating chunks as you get near them.
Im not sure what exactly is best practice, im basically brand new to game development ( i know the basics of unity and am very practiced in c# just never made a game). The tiles themselves are very simple and the only data they hold is their sprite then probably a indicator of what kind of resource they are (probably just held in the tile name). The levels themselves can be 1000x10,000 roughly if i had to guess, but i havent flushed that out so I cant say for sure.
any help/useful resources we be appreciated
Tilemap already handles the "rendering only what's near you" thing
you can start with #1 and switch to #3 later
thought so but again not super practiced so was just shooting from the hip
can someone help me with the bottom method
i dont remember how to have them add up every time
!code
(thanks for flashbang btw)
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 does "have them add up" mean
i have to return the sum of the entire array basically
by iterating through each number in it and adding them
so make a variable and add to it
but why is your return type int[]?
Don't you want to just return a single number?
whoops
int counter;
for(etc.
counter += number[i]
there is also just array.Sum()
or foreach (var num in array) sum += num;
ok i think this is more like what i learned
(true but given the type of code they are at probably better to do the more simple route for now)
im sure theres plenty of ways to write it though
true. its always good to learn how to do these without "special methods" first
fair. learning linq is a great way to get faster at coding for future reference
Plenty of tricks yeah. If your new doing it the more expicit cave-man style Praetor suggested will help you get more comfortable with the language
faster != always better
thats y i said future reference. good foundation is best
considering this is their homework, i doubt that their teacher wants them using linq just yet
lol
flex on em
just checking to see if this is a reasonable way to do this. Right now I have a gameobject with a script attached that on startup makes a tile map object and just loops through and places tiles. (ill make it threaded in the future with a task list).
could also have the tile map be separate and just pass that in via a serialized object. again not sure what is best practice
ill make it threaded in the future with a task list
you can't touch the unity api on other threads
good to know
I could make the array of objects with threads and pass them back into the tile array (in the case that the tiles were large objects)
in this case i wont worry about it though
just for clarification this means you jsut cant touch objects that appear in the editor with other threads correct?
that means that most of the unity api is not accessible off of the main thread
ok yeah so background processing is fine, just bring it back to main thread before you try to apply it. got it
If you use Awaitable you can switch up which thread it happens on
cool
oh my god
that did not format the way i thought it was going to
maybe this is better?
hello, i have these two classes that work together to move my character around in unity. it currently works as intended but i am following a tutorial and they dont really explain "why" it works.
I see that the Update() method happens every frame, which initializes inputVector with the GetMovementVectorNormalized() method every time Update() is called. It then gets a little fuzzy to me as I examine what happens inside of GetMovementVectorNormalized()
.
I see inside that GetMovementVectorNormalized() it initializes a Vector2 object called inputVector and then (somehow?) assigns the values of inputVectors y and x variables to key presses such as W,A,S,D with the if statement if (Input.GetKey(KeyCode.W) ).
My question is this: Does the line if (Input.GetKey(KeyCode.W)) automatically just wait for a keystroke to happen? If the Update() method is happening every frame, and if if (Input.GetKey(KeyCode.W)) is
getting ran every frame as well, why does it not break when I dont press a keystroke?
there we go, thank you!
I have always had a doubt in Unity. I come from Roblox Studio, and when we reference objects, we do: workspace.something.something, but in Unity, I do not know very well which is the correct way to reference GameObjects/Components, I usually do it by creating a field of the type of component I want to access, but in the case I do not know which component I want or I get it while the game is running (after a certain action for example), how would I do to reference an object correctly? Could someone help me with this? I'm kinda lost
I know about the GetComponent and GameObject.Find thingys, but i feel they are not the best way
It simply returns true on frames when it's pressed and false on other frames
It doesn't wait for anything
[SerializeField] when possible
GetComponent for runtime grabs
Find is the worst
What I mean is that if, for example, I have a script in another gameobject, and I want to get the player (that is, another gameobject), would I always need to create a field for that?
coming from Roblox Studio makes me very confused about this in Unity 💀 🙏
you guys are heroes, no idea why you help us for free like this but its so much appreciated
you create a field when you want to store the reference throughout
if you only need it once you dont need to make a field
depends how you want to grab the component, normally physics query, collision etc.
people who can help only got there by being helped 😄. It's also a good way to practice your own knowledge
its normal in the beginning no worries.
Check this also has some useful info for each
https://unity.huh.how/references
Choose the best way to reference other variables.
tysm 🙏
It's totally normal to be confused.
In the way c# is designed (and maybe how roblox does it?) all references need to be set in code because the language wasn't designed with some nice looking editor in mind. w/ Unity and the Unity Editor the ability to "expose" (via serializing) certain fields where we can drag and drop references ourselves is kind of black magic in regards to how the language works and is a nice and convenient luxury
fields are just a box/container for a value so you can either set what that value is via code or via the unity editor
yea, I started unity around 2 weeks ago, I'm really loving it, but i always wondered how people would do that, but I got a better idea now
is there any way i can zoom out on visual studios
so i can take a screenshot of my 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/, https://scriptbin.xyz/
📃 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.
oh okay thats pretty nifty
Also, while GameObject.Find is almost always gross, stuff like GetComponent, FindObjectsOfType and FindObjectsByTag all have completely acceptable usecases, but they do take "some" work that can almost always be avoided when using more than once by just saving the work that was done the first time. eg.
PlayerManager : MonoBehaviour
public void HealAllPlayers()
foreach (Player player in Object.FindObjectsOfType<Player>)
player.health = 100;
is bad because your doing the work of searching for all the players every time
PlayerManager : MonoBehaviour
List<Player> allPlayers;
private void Awake() //happens once when the PlayerManager initializes
allPlayers = Object.FindObjectsOfType<Player>().ToList();
public void HealAllPlayers()
foreach (Player player in allPlayers)
player.health = 100;
doing the work once and "caching" the results by storing them where they can be accessed later is better because then you only look for them once
gotcha, tysm
What’s going on here?
you have a component on a GameObject in your scene or in a prefab that is broken
i.e. it's a script that no longer exists or something
Ooh, how can this be fixed?
remove the broken components
thank you so much.
bump
You either:
- didn't enable interpolation on your Rigidbody
- Are moving your camera at the wrong cadence
- are breaking Rigidbody interpolation with some code that directly modfified the Transform
Well interpolation is on, should I give the 3 code files that control the planes?
maybe I should
!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/, https://scriptbin.xyz/
📃 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.
Sorry to do this to you guys but where should I start. I've been wanting to learn game development for a while and have tried several times but never had dedication to do it. I plan to learn C# then eventually move on to C++ but I just don't know where to begin. I've watched a few videos but ultimately none of them helped. I scrambled around Unity for 5 minutes yet I couldn't find where to begin and what to do, so is there some other game engine that supports C# that I can use?
planecontroller: https://paste.mod.gg/wblrwihcmgpa/0
Hud.cs
//
// Copyright (c) Brian Hernandez. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
//
using UnityEngine;
namespace MFlight.Demo
{
public class Hud : MonoBehaviour
{
[Header("Components")]
[SerializeField] private MouseFlightController mouseFlight = null;
[Header("HUD Elements")]
[SerializeField] private RectTransform boresight = null;
[SerializeField] private RectTransform mousePos = null;
private Camera playerCam = null;
private void Awake()
{
if (mouseFlight == null)
Debug.LogError(name + ": Hud - Mouse Flight Controller not assigned!");
playerCam = mouseFlight.GetComponentInChildren<Camera>();
if (playerCam == null)
Debug.LogError(name + ": Hud - No camera found on assigned Mouse Flight Controller!");
}
private void Update()
{
if (mouseFlight == null || playerCam == null)
return;
UpdateGraphics(mouseFlight);
}
private void UpdateGraphics(MouseFlightController controller)
{
if (boresight != null)
{
boresight.position = playerCam.WorldToScreenPoint(controller.BoresightPos);
boresight.gameObject.SetActive(boresight.position.z > 1f);
}
if (mousePos != null)
{
mousePos.position = playerCam.WorldToScreenPoint(controller.MouseAimPos);
mousePos.gameObject.SetActive(mousePos.position.z > 1f);
}
}
public void SetReferenceMouseFlight(MouseFlightController controller)
{
mouseFlight = controller;
}
}
}```
A tool for sharing your source code with the world!
main core
just start with c# basics, not sure if you're aware but you dont use c++ in unity. unity has its own learn course too
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Alright, thanks! And yeah, I'm aware that Unity doesnt support C++ :)
how does the camera work
Unity is the easiest one with the most documentation tbh
trying to use DG.Tweening to make a smooth hp decrease but sometimes when taking dm + dying to an enemy i get this error message
tried to fix it by making the HP script that used tweening a function
and then only updating it when taking damage
and even checking if the game object that its trying to change is null like the error says
Where/when are you destroying the image/object?
I'm assuming from the coroutine die cooldown
yeah
it reloads the level scene which is what is ig destroying the image/object
So.. which variable would they be referring to? It should be a reference to an image object
im guessing the healthbar
LoadScene and everything destroyed
yeah
Perhaps consider stopping the tween if possible before loading a new scene?
There's autokill option iirc
hm how would i stop the tween tho
o yeah lmao
SetLink
huh
The first few links on Google yield something similar to this: https://www.reddit.com/r/Unity3D/comments/1dooi5t/dotween_best_practice_for_killing_a_tweensequence/
autokill was something related to pooling, SetLink is probably what you finding
yeah im just trying to figure out how im supposed to use it by trying to find it in the documentation
yep figured out how to use .setlink and it worked thx a lot
Is a coroutine typically more or less efficient than setting up a simple timer to fire off
If there is a difference, it's negligible. Though, it depends on how you're using it.
Don't think of performance. Think of readability, extendability and debuggability.
Implementation can be adjusted later.
Alright thanks, I think I get too hung up on performance at such an early stage
Yeah those small things would only matter if you have like hundreds of instances running all at once
coroutines make a little amount of garbage, but there's always alternatives like pooling them, or using UniTask which have some similar features of pre-allocating them
and another alternative is just make a manager system where gameobjects can subscribe to
To answer your question typically yes a coroutine would be less efficient than a simple timer
hard to be super definitive without context, no?
So i'm having issues with one of my enemy dashes towards the player but when it does. It tilts a tad bit forwards and I belive that was causes that werid effect that sends my character flying. But I can't figure out what causing that
a coroutine is managed, work is being done for you, and it's more than you might do yourself if you made a barebones timer
hard to tell if it's more without context? surely in some scenarios it's worth considering the tradeoff of what that "barebones" timer would be (eg. having that update loop even running on that class)
I don’t rly have an poco tho
I only have mb classes
But I need to write unit tests it’s a requirement
I don't really need definitive responses just practical ones
If they're close enough to be irrelevant that's good news ahaha
(hence why i asked that :P)
Do you want it to stop tilting forward? Or is that intended?
Stop tilting forwards
It's tilting because its position is higher than the player's position, so it looks downwards
for some reason only my HP bar updating, im only able to set them
playerHP = playerMaxHP;
playerMP = playerMaxMP;
SetPlayerEXPToLevelUp();
playerHPBar.maxValue = playerMaxHP;
UpdatePlayerHPBar();
playerMPBar.maxValue = playerMaxMP;
UpdatePlayerMPBar();
playerEXPBar.maxValue = playerExpToLevelUp;
UpdatePlayerEXPBar();
public void UpdatePlayerHPBar()
{
playerHPBar.value = playerHP;
playerBarsTexts[0].text = playerMaxHP + "/" + playerHP;
}
public void UpdatePlayerMPBar()
{
playerMPBar.value = playerMP;
playerBarsTexts[1].text = playerMaxMP + "/" + playerMP;
}
public void UpdatePlayerEXPBar()
{
playerEXPBar.value = playerExp;
playerBarsTexts[2].text = playerExpToLevelUp + "/" + playerExp;
print("EXP:" + playerExpToLevelUp + "/:" + playerExp);
}
Add more logs.
And make sure you don't have errors in the console
Yeah, that makes a lot more sense. How would I have it look towards the player but not down at the player?
Try this to keep it level:
Vector3 flatPosition = new Vector3(transform.position.x, 0, transform.position.z);
Vector3 playerFlatPosition = new Vector3(player.transform.position.x, 0, player.transform.position.z);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(playerFlatPosition - flatPosition), rotationSpeed * Time.deltaTime);
Unrelated but see also https://unity.huh.how/lerp/wrong-lerp
What's this for?
You're doing Slerp wrong
Ah, I see. I'll to do study these then. Thank you
theres a camera rig that follows the object`s position. the camera rotates about the pivot(which is the plane) to look at mouse aim
spotlight.pointLightInnerAngle = 45f;
spotlight.pointLightOuterAngle = 45f;
why doesnt this change the Light2D spotlight angle? im positive the reference is valid
Are you on URP/HDRP?
URP
In HDRP at least you need to change it via the additive light data component instead
See if URP has a similiar component it adds to lights
Oh wait, you said Light2D
the component itself works, I just cant set the angle within a script, it just refuses to update
indeed
foreach (Skill skill in Skills[i])
{
GameObject skillObject = new GameObject();
skillObject.name = skill.skillName + " Skill";
Image skillImage = skillObject.AddComponent<Image>();
skillImage.sprite = skill.skillImage;
skillObject.GetComponent<RectTransform>().SetParent(skillsTabs[i].transform);
skillObject.SetActive(true);
skillObject.AddComponent<SkillHolder>().Skill = skill;
Button skillButton = skillObject.AddComponent<Button>();
skillButton.onClick.AddListener(() =>
{
selectedSkill = skillObject.GetComponent<SkillHolder>().Skill;
skillName.text = selectedSkill.skillName;
skillLevel.text = "Skill Level : " + selectedSkill.skillMaxLevel + "/" + selectedSkill.skillLevel;
skillDescription.text = selectedSkill.SkillDescription;
});
}
}
the images are too small, how to make them them fit
not really a code question? might want to make a horizontal layout group
ok thanx
i have just got some issues in c#. i want to make a simple script for a 3d object to move and i tried to make it in 2 hours and it dosent work😭 . can someone explain whats wrong?: transform.position += new Vector3(0, 0, 5f) * Time.deltaTime;
share your !code properly ( 👇 ) , and not just a single snippet like that
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
and maybe look at one of the thousands of tutorials for movement that are available online!
Not that I don't believe you but how do you figure that?
I guess just by coroutines being part of the whole unity cycle and therefore having a little overhead over simple "native" timers?
I would say that is actually better because a timer might need an additional thread or won't work directly in the same Unity "cycle"
I would not know though, I mostly ask because I am interested in what the better approach would be
Unity has to handle all those coroutines, even when coming from native IENumerable stuff, that might be the overhead. But as said, just guessing here with short reading about whats happening under the hood
I presume unity will check the yield each update anyway to see if its done so probably no better
Is there a way to serialize a Tuple?
To be more specific I want to assign a transform for each weapon item, which results in
Tuple<Transform[], Weapon[]> thing
Which does not get serialized
nah make your own class with these 2 fields and mark it as serializable
Use a struct or a class instead . . .
The goal is to assign a transform for each specific weapon and I want them to be a one-to-one relation instead of relying on array index
the problem is my Weapon is a scriptableObject and I'm not sure if private variables behave normally
I like using an index though since grabbing it from the collection is O1, it's easier and smaller to store an int . . .
well this will be arrays of references so such a benefit is minimal
offtopic it seems a little interesting that your weapons are paired with just regular transforms rather than a more direct way of correlating that data
i've just never seen something like that before
It's because I wanted the locations to not be linked directly to the weapon so I could swap the positions around without attaching the location to the SO
ah fair. i've usually done that by having some small component on the transform that communicates w/ whatever is managing this but i could totally see that approach
so you want to associate data with a weapon but not "attach" it to a weapon? wut
Always nice to hear other people's implementations :D thanks for sharing
the weapon are so assets so don't wanna retain any runtime data
put more elegantly than I could
Better to have some runtime object and keep the "weapon data" seperate
I do
but only using some index to link the data seems flimsy
or be even more cursed and start making self-referencing runtime sos
a prefab of a turret keeps both the transform positions of the weapons and the weapon's configurations(scriptableObject)
Like this
oh yeah the exact example i was thinking about when mentioning my approach previously was for a turret setup like this haha
yea id not do this but have a class/struct to hold this data
a serialized dictionary can also be nice for cleaning up the inspector for those
that's bsaically what I wanted to do with the Tuple!
Dictionary sounds much more expensive to initialize than a Tuple though
i haven't gotten further and/or paid enough to pay for all my various tech debt crimes so i can't confirm or deny that
I've had a great experience using ayellowpaper's SerializableDictionary project on the asset store though
It's basically the same. Your Tuple is similar to a Key/Value pair, which is what a dictionary uses . . .. . .
thanks
any android dev here? How can I disable these adaptive performence logs?
yup. You need that for test on MB
ye i got it figured out with a tutorial
i just had to create a shit ton of interfaces and wrappers
There is a layer called player. It's the player's layer. There is a layer called ground. It's a layer for the ground. I have items with colliders. I want this collider that the items have to act as a normal collider when it touches the ground. But when it touches the player, I want it to act as a trigger collider. I was thinking maybe to create an item layer and then have it ignore the player layer, but then that wouldn't even trigger the isTrigger collider. So what would be the best approach?
Basically, it can collide with the ground, it has gravity and once the gravity drags it down to to touch the ground, it stays there, but the player should be able to walk through the item, while still being able to detect its there.
How do i approach this?
Should be able to just make a child object with a trigger collider
Two colliders. Parent object on Item layer with solid collider. Make a child object that is not on the Item layer that has a trigger. Set Player and Item layers to ignore each other in physics settings.
so the item has its own layer which ignores collision with player laye,r but has a child that doesnt have the item layer, and that child has the trigger collider?
yes
Triggers are fine, but non-triggers would become composite
just to be clear when you mean ignore each other in physics settings you mean by utilizing layers, right? or it there some otherway that doesnt need the creation of a layer for this sole purpose?
Do note that this would necessitate a Rigidbody on your player character, since putting two rigidbodies on the same object is going to cause problems. But that's most likely the case already
Yes, in the layer settings. You can specify an individual pair of colliders to ignore each other in code, but doing that for every item would actually be fairly expensive, and if you can spare the layer you should do that instead
You can actually exclude colliders from the rb directly from the component if not the matrix setting
but probably worth it to do it globally if you've multiples
How do you trigger particle effects using animation animation events? I have a Slash effect prefab that I want to time to an attack animation, and I want to be able to set the location rotation and scale for each animation's slash effect
If you know how to add events, you make a script with methods specifically to be called by those events
Usually you can send in parameters with the events, so give it the position where it is in the animation, move the particle system there, then Play() the system
or, attach the system locally to the bone of where the particle system should be played and just Play() it
alright, thanks!
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class CombatUI : MonoBehaviour
{
public GameObject enemyUIPrefab;
public Camera mainCamera;
public Canvas canvas;
private Dictionary<GameObject, RectTransform> enemyUIMap = new Dictionary<GameObject, RectTransform>();
void Update()
{
GameObject[] allEnemies = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject enemy in allEnemies)
{
if (enemy == gameObject) continue;
if (!enemyUIMap.ContainsKey(enemy))
{
GameObject uiElementPrefab = Instantiate(enemyUIPrefab, canvas.transform);
Debug.Log($"Instantiated UI for {enemy.name}");
enemyUIMap[enemy] = uiElementPrefab.GetComponent<RectTransform>();
}
RectTransform enemyUI = enemyUIMap[enemy];
Vector3 screenPos = mainCamera.WorldToScreenPoint(enemy.transform.position);
if (screenPos.z > 0)
{
enemyUI.gameObject.SetActive(true);
enemyUI.position = screenPos;
Debug.Log("updated ui position");
}
else
{
enemyUI.gameObject.SetActive(false);
Debug.Log("UI is hidden");
}
}
List<GameObject> enemiesToRemove = new List<GameObject>();
foreach (var entry in enemyUIMap)
{
if (entry.Key == null)
{
enemiesToRemove.Add(entry.Key);
}
}
foreach (GameObject enemy in enemiesToRemove)
{
Destroy(enemyUIMap[enemy].gameObject);
enemyUIMap.Remove(enemy);
}
}
}
Above here, i have a script to display a crosshair over other players. However, when the players are too far away, it doesnt work?
I can't seem to find any issues
dont use the old Tuple, use ValueTuple instead.
you can do the same but much cooler like this :
(Transform[] transforms, Weapon[] weapons) thing = default;
but yeah they will never allow us to serialize Tupple/ValueTupple for a good reason
imagine if some dumbo coders do this
(int, float, (float, int, (string, string))) a;
now imagine how they'd serialize that 😂
How should character move within new input system? I've set invoke events in behavior and wrote this method:
private void OnMove(InputAction.CallbackContext ctx)
{
Vector2 _movement = ctx.ReadValue<Vector2>();
_characterController.Move(new Vector3(_movement.x, 0, _movement.y) * _speed * Time.deltaTime);
}
Character is moving by 1 value and only when I press (I'm using Value in action type but it works so idk)
As I've read it should be in Update but a couple of weeks ago when I started learning Unity it worked without it
I'm not full of confidence about the best solution in this situation
you want to only read values in OnMove
move the actual CC in update
make _movement not local
Is it possible to reference a specific file type in code? For example, I want a serializedfield variable that can hold OGG files
ogg are just AudioClip files
gotcha
is there a way I can see what data type these imported assets and stuff would be?
Unity doesn't deal in file types, they deal with Asset types. File types can tell Unity which kind of asset it is, but multiple file types can map to the same type of asset
For example, png and jpg both become Textures
gotcha, makes sense
(Or Sprites depending on your project settings)
Is there a way I can see what asset type something is in the editor? I have it selected but can't seem to see it in the inspector
ReadValue should be in update method?
No, Move should be in update
you'd click on it and see what the inspector says
actually disregard this, I see the asset type in the name in parentheses
hello. i'm trying to use a sprite sheet i bought on unity store. i have two problems, both of which are probably pretty simple
-
i've been using auto-trim to get the sprites out of it, but these sprites move around on the canvas when they "jump," and auto-trim effectively removes that. they are gridded. can i just specify math to place them?
-
i've been making animators by dragging things onto the scene, because i don't know what i'm doing. the problem is, this time that produces bad results, because i get the entire sheet, which contains multiple characters, in a single animator. is there a way for me to specify what sub-range to use?
i guess i could just cut the sprite sheet apart but these seem like things i ought to know either way
Thanks now I got it and it works well
Can I give coordinates after vector2?
You can search, "how to use a sprite sheet in unity," as there are tons of tutorials to help and give you insights on this topic. For help with animators, checkout #🏃┃animation
wat?
For example, let the ball jump 1 unit up and 1 unit to the left.
they are gridded.
then don't use autotrim
can i just specify math to place them?
yes, that's what the grid options are for
not a code question