#π»βcode-beginner
1 messages Β· Page 752 of 1
That would imply that your ide is not configured correctly.
ah wait missed some context
TMP_Text
yeah sounds like a missing configuration thing
try regenerating project files, perhaps
Due to me working on GitHub in Unity 6 I have been deleting the library very frequently maybe that's what gave the problem? Like, I've been working on this project for like a week and a half and it never gave me the problem until today
huh? you shouldn't be resetting the library frequently
vcs doesn't change that
vcs shouldn't care about the library outright - it should be in the .gitignore
Oh true, fully forgot to do that
make sure you have the proper unity .gitignore set, and check if you've committed anything you shouldntve
have you been resetting the library while unity's still open?
Nope, i always close beforehand
alright, that's.. good, relatively
resetting the library is an editor debug kind of thing, definitely not something you'd be doing regularly
have you tried regenerating project files?
this is unrelated to the library, it is about the sln files i believe
Not sure what this means...
it's a button in the external tools page in preferences iirc
might be in project settings. probably not?
Okay I will check it
In preferences
Seems to have fixed the issue!! Thanks!! I will definetely add the library to .gitignore, no clue how I forgot about it
Sorry I didn't see this till now.
Repeatedly getting items from a dictionary who's key is System.Type. Happens a handful of times per second.
no, use the premade gitignore for unity projects
it's not just the library that should be ignored
add stuff like .DS_Store or *.thumb if needed, but this is the base you should use
there are a ton of premade .gitignores
there's a prompt to add one if you create a repo in github or github desktop, too
I will have it in mind for the next project I work on thanks!
You might also want to add lighting data to git ignore specifically, especially if your scenes are large. Do this BEFORE tracking the file if you chose to. (You might do this because you dont want to pay for LFS storage but your individual files are too large for git)
as said, go in edit and search the missing script on all gameobject
thanks
why does this happen
and yes i do init it
okay so its cuz it hasnt Instancitated yet
but how do i make sure it is and only then sub
I had error like this this friday i cleared it by making void public and calling it in the if statement in update maybe that could help
Oh ok
how do i istall this?
install the module from the unity hub
I would please ask for a bit of advice on how to do a system like this.
I am doing a simple system where I have a bunch of individual tiles that have there own functionality when the player steps on them.
The trigger isn't important here.
What I need help with is the following:
Each individual tile is intended to override this function and add their own functionality in them, however I would like the function to retain these If Statements (Yes, I will be converting it to a switch case soon).
Is there a way to only inject a line of code where that comment is?
instead of overriding the entire function?
can someone tell me why my chunks are spawning only somewhere old chunks already are and not where its empty? https://paste.ofcode.org/jt3MkVaAuZSQ4VnMshjHYd
easy, you keep this functionality in the base class and have another function that you overide that is called at this point.
Call some other method there that your tiles are expected to override instead
Just food for thought, might be worth considering if you want that tileIsTriggered event to fire after the inheriting call or not
you might want it before but worth double checking
How do you mean? May I kindly ask you to elaborate please.
I don't know the context surrounding your game but eg. if some outside party is listening to a specific tile's tileIsTriggered event, would you want that tiles OnPlayerTrigger() code to run before or after that outside party receives the event invoke
if the Tiles response to the player trigger happening potentially changes the state of the tile, you might want that to happen before outside parties recieve notice that something happened
I think I should name it better, but that even is simply there for all VFX systems that are attached to the tile to listen to and know when to play.
fair, though that could also lead to some good examples !
random example being like maybe it was a ground type tile, player walks in, some inherited logic causes it to change to a water type tile
perhaps the vfx code should be firing after that change
etc.
you know what your code needs to be doing though π
mhm, but I genuinely appreciate the advice
thank you
IF i may ask another thing, should I avoid using Coroutines or is it fine
Said VFX i have coded as this, and I am slightly bothered that I have a function that starts a coroutine.
I'm trying to think if there is not a way I can make the function work as an Async, but so far DOTween has not been co-operative in this regard
Is there a better way of doing this or is this fine?
coroutines or async will achieve the same goal so probably fine
unless you use async already i wouldnt start now as you will surely encounter problems
Plus your being a smarty pants and seperating the logic into a single function so not a huge pain to mess around with it later if you have to π
at my previous job, one of the senior devs told me to avoid using Coroutines because they create performance issues
ever since then I have been hesitant to use coroutines and I only discovered async recently, so I am not sure to what extent they are similiar
they're all more work, really
if you overuse them, sure, it can cause issues
but that's true for anything
that is true
you can use a sequence instead
I am instantiating Gameobjects with meshcolliders. Is there a way to check if the collider of object 2 overrides the collider of object 1 and then move object 2 away from object 1 untill their colliders don't overlap anymore?
you can get both of their bounding boxes with Collider.bounds and then check if they intersect with Bounds.Intersects
An easy way may be to use the collder extents and centers to then work out how far one or both should move to no longer touch
so I created like a "planet" (rlly rn just a big sphere) in blender with a relativly small tunnle in it, however when i try to add a collider to it in unity it doesnt add anything, how cna I fix this? (I can send the blender asset if its needed or rlly anything, also im not sure if this is the cforrect channel or not)
What type of collider are you adding?
mesh collider, and the convex is set to false
And like are you only adding that to the parent only?
I think maybe its cuz its too big? if so how do I make it do it in sections or smth
Im adding it only to the sphere object cuz blender added a camera and light source so I unpacked it and deleted the camera and light and then added that to the ssphere
Show hierarchy
-# why not just delete them in blender
cuz i forgot lol
this si the screen rn
everything other then the sphere object is otherstuff thats unimportant rlly
I have problems with climbing on objects
Here you can see that I stand for some time on one side, and then go to the other - he teleports to the previous side.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The main problem for me is here:
case ParkourType.LiftUp: if (percentageTime < ParkourMovement.parkourAnimationVitalPercentagePoint) { transform.position = Vector3.Lerp(startPosition, obstacleVitalHeightPoint, Mathf.InverseLerp(0, ParkourMovement.parkourAnimationVitalPercentagePoint, percentageTime)); } else { if (ParkourMovement.enableRootMotion == true && percentageTime >= ParkourMovement.enableRootMotionPercentage) this.ABCEntity.animator.applyRootMotion = true; else transform.position = Vector3.Lerp(obstacleVitalHeightPoint, obstacleHeightPoint, Mathf.InverseLerp(ParkourMovement.parkourAnimationVitalPercentagePoint, ParkourMovement.enableRootMotion ? ParkourMovement.enableRootMotionPercentage : 100, percentageTime)); }
foreach (Transform child in parent.transform)
{
Destroy(child.gameObject);
}
is this how i delete all the children of a parent?
sure, that works
that is 100% chatgpt code
Like this? || sorry for the late reply xd||
sure
you might be detecting the ground right after you jump, depending on how large the radius and distance are
This is what happens
hey yall does anyone know the game megabonk im a developer with years of expierence but i cant seem to get a similiar look anyone know how they achieve it?
Its not that large where it would cause that problem. Well in the console its telling me that hasJumped is false but when I jump it isn't true.
add a log for when you jump/set hasJumped true. see if there are "hasJumped false" logs after you jump
whys your unity blue
playmode tint is customizable
interesting
Its only true for a split second.
Edit β Preferences β Colors β under General Playmode Tint
I made a shield fall down, if a player touches it the shield spawns to them (ill make it the players child later) anyways I want to destroy the shield If I hit an enemy but It says that newShield doesnt exist in current context. I frankly have no clue how to fix this so help would be great! thanks
b/c you create it inside this function
you can't access it anywhere but that function. (local variable)
if u want to access it elsewhere make it a class variable instead
so I need to set it at the stat and then Instantiate(newShield, ......)?
{newShield = instantiate;}```
to be pedantic, within that scope rather than that function
got it
π
what does this line mean?:
{GameObject newShield = instantiate;}
wherever you have Type name, that is a declaration
a variable only exists within its declared scope - to simplify, basically {} creates a scope
GameObject newSheild; {newShield = instantiate;} just shorthand showing that the variable isn't within the {}s
ohh
^ yea
so if you want to access a variable in different scopes, the variable's declaration has to be higher than or equal to those scopes
ohh
ty u both!
good luck π
much appreciated
hi, i have a weird issue with my 3d animations:
i made a player model and imported it to my scene. to add animations later on, i exported them without the model but with the same armature. i made a player avatar from my model. everything worked fine. now i imported new animations with the same armature again. but for some reason, the new ones break the animator. unity somehow does not see the new ones as humanoid animations even tho i have the exact same import settings as on the other armature with previous animations
I think the issue might be my ground check triggering immediately after jumping, detecting the ground for 1-2 extra frames and resetting it right away.
how can I fix it? shall I add a small delay after jump before allowing isGrounded to become true again.
sure, or make the ground check more accurate
like a groundCheck buffer
if(hit) lastGroundTime = Time.time;
isGrounded = Time.time - lastGroundTime <= groundBuffer;```
may want consider making it a bit more robust..
like coyote time + jump buffering
would give a smoother feel and more stable/predictable jumps
Bounds: Center: (0.00, 0.00, 0.00), Extents: (0.00, 0.00, 0.00) | name: object(Clone)
SECOND Bounds: Center: (0.00, 1.98, -5.42), Extents: (0.00, 0.00, 0.00) | name: object(Clone)1
if (bounds.Intersects(boundsNew))
{
Debug.Log("NEW BOUNDS INTERSECTS WITH PREVIOUS ROOM");
}
I get this issue but maybe I am doing something wrong..
It doesn't log so meaning Unity is saying it doesn't intersect with the second room?
But they clearly override
Both have a mesh collider
you mean intersect?
It's clearly gone wrong if the extents are zero. You can't use that anyway to check if mesh colliders intersect. See e.g. https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
So I can't use that to check if mesh colliders intersect?
You can't use Collider.bounds, no
how do I send my code all pretty like that?
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
So I should use that instead?
That's why I linked it, yes
using UnityEngine;
public class playerDie : MonoBehaviour
{
GameObject newSheild;
[SerializeField] GameObject sheild;
public bool sheildOn = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Shield" && (sheildOn == false))
{
Destroy(other.gameObject);
GameObject newSheild = Instantiate(sheild, new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, - 1f), Quaternion.identity);
newSheild.transform.parent = gameObject.transform;
sheildOn = true;
}
if (other.gameObject.tag == "Enemy" && (sheildOn == false))
{
Destroy(gameObject);
}
if (other.gameObject.tag == "Enemy" && (sheildOn))
{
Destroy(newSheild);
Debug.Log("destroyed");
sheildOn = false;
}
}
}
im having so much trouble with making smooth movement, and i dont know if I should send what I want to do in this channel.
exscuse my messy code, but I have a shield that I have saved to the GameObject new shield, at the end of the script im trying to destory it but it wont work, any1 knows why?
show the code
using UnityEngine;
public class playerDie : MonoBehaviour
{
GameObject newSheild;
[SerializeField] GameObject sheild;
public bool sheildOn = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Shield" && (sheildOn == false))
{
Destroy(other.gameObject);
GameObject newSheild = Instantiate(sheild, new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, - 1f), Quaternion.identity);
newSheild.transform.parent = gameObject.transform;
sheildOn = true;
}
if (other.gameObject.tag == "Enemy" && (sheildOn == false))
{
Destroy(gameObject);
}
if (other.gameObject.tag == "Enemy" && (sheildOn))
{
Destroy(newSheild);
Debug.Log("destroyed");
sheildOn = false;
}
}
}
well... im not sure. Maybe newShield is getting either reassigned or its not properly assigned?
sheildOn == false could just be !sheildOn btw
You're making a new newSheild (sic) variable inside the OnCollisionEnter method. Remove the GameObject part from the start of the line to use the correct variable
wait is the player getting destroyed when you collide with an enemy?
oh i see
discord could do with some color in the code blocks.
discord only colors keywords, it isn't analyzing the code to provide syntax highlighting for specific types of tokens like an actual IDE would. that would just be silly tbh
useful though
omg ur a life saver
ive been trying for like an hour
maybe a discord bot to edit messages could do that?
I heard that format can have coloured text?
oh ty idrk the c# syntax just yet so this is very helpfull
a bot likely wouldn't be able to add color to code blocks because code blocks just print what is literally there and don't do extra formatting based on tags/markdown/etc
at best a bot could create an embed on its own messages that would have correct syntax highlighting for all tokens, but then the code would have to be posted more than once (since the bot is then reposting it) and it would just be clutter
but then it could delete the old message?
whoops there goes the context that was included with the code
it could add all context before and after. Maybe it repastes the message and in a code block it formats it.
whoops now you can't ping the user directly using the reply feature.
it's very unlikely that anything like what you are describing currently exists or even if it did it's unlikely to be added. if you want to make suggestions for things to be added to the server though, post it in #1161868835423526933
there is an ansi thing actually
but yeah, context gone
does anyone know how to make smooth movement?
that's quite a vague question
there are plenty of ways, and a lot of it depends on context
well, i want the player to follow the cursor on the x axis. It has to accelerate towards and decelerate before the target so it stop directly on top of it. It also needs to have a velocity so it has to slow down to change directions.
oh, and acceleration and moveSpeed are also needed
moveSpeed is the max speed of the player
It has to accelerate towards and decelerate before the target so it stop directly on top of it
sounds like you want a smooth damp
i have no idea how to use smoothdamp at all :/
good thing google exists so you can find out!
so is smoothTime the acceleration or the inverse of the acceleration?
what does the documentation say
smoothTime Approximately the time it will take to reach the target. A smaller value will reach the target faster.
but what does it mean?
Huge topic here yeah. Of course
It means, lower values reach the target faster. That's it
it means that "smoothTime" is approximately how long it will take to reach the target position
i could try using it
but if its completely broken well... yeah
well if it ends up completely broken, it will be entirely because of how you set up your code. and of course you won't know until you try it. so either go try it, or if you are expecting to be spoonfed the code here you can go somewhere else where that nonsense is tolerated
so what part of smoothdamp controls the acceleration?
that's literally part of development process
and how do i fit the acceleration variable into it?
You pass it in
you don't
you can't set the acceleration
you get high acceleration if you have move a large distance in a small amount of time
There's no "acceleration", in the sense that "increasing the acceleration makes it approach faster"
You set the "approach time" - obviously less time means faster approach
which means faster acceleration?
you shouldn't be caring about acceleration with smoothdamp
acceleration is the change in velocity divided by the change in time. use that knowledge to determine the acceleration based on the other factors you pass in, like the time and velocity
though, the acceleration isn't constant
wow, the velocity is approaching zero really quickly
not a good look imo
i'd guess the velocity follows a parabola
so the acceleration would be linear
jerk would be constant
itll have to do i guess
ill make the player rotate to match the direction
I've done the code
transform.rotation = Quaternion.Euler(0, 0, -velocity.x);```
yeah
can someone tell me why my chunks are spawning on each other and not where its empty? https://paste.ofcode.org/jt3MkVaAuZSQ4VnMshjHYd
Look at the last method, you tell it to spawn chunks on the position, but don't mention offsets
so + Math.FloorToInt(transform.position / width) essentially?
How big are your chunks
32 units on x and z
So you'd need to offset position based on this concept.
FloorToInt rounds a number to a integer value.
You'd want to set your offsets on xyz for spawning chunks at your width and height values
do asset bundles have to be created in by the project they''re loaded in?
i dont get it
what do i have to offst it doesnt make sense in my head
If we take a vector value of 0,0,0 and add an offset to the y by 1, it would be 0,1,0
Your code repeatedly spawns chunks at the same position which. You haven't got it calculating the offset and spawning a chunk there. As your doing X,0,Z for your values you'd want
X+offset,0,Z+offest
okay i got that but how do i get the offset?
β hi guys, is anyone familiar with when to use Vector.Slerp over Vector.Lerp ?
Context
I've switched my camera rotation smoothing to use Quaternion.Slerp instead of SmoothDamp-ing the targetYaw & targetPitch individually. Which feels, amazingly better
π€ Now, I've switched my camera follow to use Vector.Slerp and it feels... different.** Is that just, funky & wrong application of Vector3.Slerp?**
(inb4 WrongLerp, I'm using the 1 - Mathf.Exp trick from UnityHowHuh)
Generally, one way to do it is to take in your offset as a variable for your method. Or you could use your width and height variables
wdym?
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Vector3.Slerp.html
The difference between this and linear interpolation (aka, "lerp") is that the vectors are treated as directions rather than points in space.
At this moment if you are struggling to apply offset, I'd have a look into how vectors work and how the Instantiate works.
But to put a brief example
pos = new Vector3(X+offset, 0, z+offset) etc
It will set your position to the X value plus your offset, and your z plus your offset (if the offsets are equal you'll get diagonal placement)
Well yeah I read that. I figured I'd ask you guys for guidance, before I just A/B my entire game code to find out for myself.
slerp stands for spherical lerp. it follows an arc on the surface of an imaginary sphere, keeping the magnitude the same, as opposed to a straight line as lerp would
i know but what is offset
Yep. read that
do you think it makes more sense to treat the camera's position as a point in space or as a direction?
I'd think, a point in space. So, not a Slerp.
But, it seems to feel fine with Slerp π€·ββοΈ can't really tell if it's better or worse than Lerp
it's different. it has a different use
it's not better or worse in general
it might be better or worse for specific cases if you don't actually want the behavior that slerp gives
I see. But ... "Most games" use _ ?
I've switched my camera follow to use Vector.Slerp
are you referring to rotation or position here?
the correct one for each task
Position, rotation i switched to .Slerp instead of smoothing targetYaw and targetPitch individually (amazingly better)
That's what im trying to learn yes π€£ when to use which one
so does the camera position stay on the surface of an imaginary sphere centered on its parent's position?
no? then slerp is not what you want
we've already pointed out that lerp would be more appropriate for changing a position and slerp would be used for changing a direction. what more are you expecting here then?
I'm thankful!! I love the way we dance around the answer here.
that is the answer
In a "you already know the answer bro" kinda way 
you're the one dancing around the answers we've literally provided
..because we just told you?
I meant, thanks for confirming guys. I had a feeling Slerp wasn't right for position smoothing
if you're asking for confirmation, say so
Will do!! Copy that
it just looked like you were asking the same question without applying any of the info we just gave
in that case you should probably get your idioms straight, because to "dance around" something means to intentionally avoid it which was the opposite of what we were doing by providing you the information
Is that just, funky & wrong application of Vector3.Slerp?
kinda literally did ask for confirmation in initial post Ngl π€·ββοΈ
that's.. just a normal question
if your intent is that you have an assumption and you want to confirm it, you gotta make that clearer
we aren't psychic
Oh got it! my bad
yo im new to coding, like very new and im using unity, im trying to make a vr horror game, like big scaryn if you guys know that
and i need help lol, im hoprrible
i can pay if needed
there are beginner c# courses pinned in this channel that will teach you enough to know what you are doing. and the pathways on the unity learn site are a good place to learn the engine
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thanks! does it coast money
cost
why not look and find out?
You guys made this out like this is impossible
Value type = method(value type)
???
You can easily update the value of a value type variable by passing the variable by a method and assigning the result to itself, dont see what the problem is
As a noob coming here to see what advice you guys have, you guys way overcomplicated a simple topic
Hi,
I am implementing a full body controller and I'm nearly there. Right now having an issue where the camera is bobbing due to animation and tilting as the animation affects the head. How do I achieve a camera that is stable and moves smoothly with the head when I look down or up e.g.
https://gist.github.com/Alwandy/6583c0a3a4a8466a37341c6391d71c5b
The camera is a child of head bone yes
why is my cinemachine camera y axes looping
what do you mean by looping? what components are u using?
youre going to need some kind of view stabilization
or rather some kind of decoupled look implementation
in fact im pretty sure final ik has something that can let you accomplish this pretty easily
yup, i agree.. key is to decouple ur camera..
use the head to have a target for the camera to track in LateUpdate() or something...
Code -> rotates Camera or Camera Holder
Camera or Camera Holder -> tracks "Camera or Head Target"
looping?
you're gonna have to show the setup #π₯βcinemachine
unless its code related then share that
Odd question. I have several rotating objects in a scene, that can be rotated with a mouse. Each object has a circlecollider2d childed to them in an empty object. In the testing bar on the inspect, is a box collider2d that has a specific script on it, which checks to see if each circlecollider2d in question from each object, is present. From there, it is meant to activate the You Win panel, but unfortunately it is not doing that. Nor is it activating even the debugs put in to check.
Does anyone have any idea of what might be the issue?
using UnityEngine.UI;
public class TripleColliderTrigger2D : MonoBehaviour
{
[Header("Colliders to Check")]
[SerializeField] private Collider2D colliderA;
[SerializeField] private Collider2D colliderB;
[SerializeField] private Collider2D colliderC;
[Header("UI Panel to Activate")]
[SerializeField] private GameObject targetPanel;
private Collider2D thisCollider;
void Awake()
{
thisCollider = GetComponent<Collider2D>();
if (targetPanel != null)
targetPanel.SetActive(false); // Hide it at start
}
void Update()
{
if (thisCollider == null || colliderA == null || colliderB == null || colliderC == null)
return;
bool aTouch = thisCollider.IsTouching(colliderA);
bool bTouch = thisCollider.IsTouching(colliderB);
bool cTouch = thisCollider.IsTouching(colliderC);
if (aTouch && bTouch && cTouch)
{
if (targetPanel != null && !targetPanel.activeSelf)
{
targetPanel.SetActive(true);
Debug.Log(" All three colliders are touching οΏ½ panel activated!");
}
}
else
{
if (targetPanel != null && targetPanel.activeSelf)
{
targetPanel.SetActive(false);
Debug.Log(" Not all colliders touching οΏ½ panel deactivated.");
}
}
}
}```
oooh, I need to utilize LookAtIK more then, since it follows headTarget for its head / spine rotation
Everything tells me it should work, but it isn't.
So basically use the LookAtIK headtarget gotcha!
do you mean you can look all the way around?
if so thats normally you just need to clamp the look.
hey hey hey i just joined bcz i needed help on unity urgently for a game jam that i have to complete the game for today and ive run into an extremely weird issue and id really appreciate if someone can help me, i typically code myself and use tutorials but today i had to resort to AI to but ive been going in circles and ive gotten nowhere, is anyone available
im probably doing something stupid but i have been up for 2 days working on this as its my first game so bare w me at my noob-ness
ok so
my player transform isnt updating in the script
like i move my player around
and in my script in the update function, ive used my players transform to do other stuff
however after the game runs initially, the player transform never changes
even tho this is the update function
not start or awake
ok we are going to need a bit more context, send us the script youre having the issue with
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
'''cs
private void Update()
{
if (player == null || animator == null || rb == null) return;
playerPosition = player.transform.position - transform.position;
Debug.Log(playerPosition);
// Face the player
if (playerPosition.magnitude < 5f)
{
if (playerPosition.x > 0 && transform.localScale.x < 0)
{
facing = 1;
transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z);
}
else if (playerPosition.x < 0 && transform.localScale.x > 0)
{
facing = -1;
transform.localScale = new Vector3(-Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z);
}
// Check if player is within attack range
bool isInAttackRange = playerPosition.magnitude < 3f && Mathf.Abs(playerPosition.y) < 2f;
// Update attack animation state
if (isInAttackRange && Time.time >= lastAttackTime + attackCooldown)
{
if (!animator.GetBool("attack"))
{
rb.velocity = Vector2.zero;
animator.SetFloat("horizontal", 0);
animator.SetFloat("vertical", 0);
animator.SetBool("attack", true);
StartCoroutine(ManageAttackHitbox());
}
}
}
}
'''
ok that didnt work
wait
private void Update()
{
if (player == null || animator == null || rb == null) return;
playerPosition = player.transform.position - transform.position;
Debug.Log(playerPosition);
// Face the player
if (playerPosition.magnitude < 5f)
{
if (playerPosition.x > 0 && transform.localScale.x < 0)
{
facing = 1;
transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z);
}
else if (playerPosition.x < 0 && transform.localScale.x > 0)
{
facing = -1;
transform.localScale = new Vector3(-Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z);
}
// Check if player is within attack range
bool isInAttackRange = playerPosition.magnitude < 3f && Mathf.Abs(playerPosition.y) < 2f;
// Update attack animation state
if (isInAttackRange && Time.time >= lastAttackTime + attackCooldown)
{
if (!animator.GetBool("attack"))
{
rb.velocity = Vector2.zero;
animator.SetFloat("horizontal", 0);
animator.SetFloat("vertical", 0);
animator.SetBool("attack", true);
StartCoroutine(ManageAttackHitbox());
}
}
}
}
yeah i saw π i used the apostrophes or wtv they are but they didnt work so i copy pasted from the bot msg instead
okay disregard that, tell me what part of the update isnt running at all?
the player transform isnt updating so nothing else is running, the first lines where we calculate player position, no matter where i move it prints the same position every time in the console so i know its not updating every frame
ok now its inside an if statement, have you debugged and ensured that your player, animation and rb isnt null?
Kinda concerning that ai is using .this so much, I tend to only see that when decompiling compiled c# :/
also i dont think its good to have a return if statement that early inside your update function...
yes bcz when i move the enemy closer to the player manually, the other stuff that requires them to be close works, animations, rigidbody, etc, also no errors printed on console
im not talking about errors
Thatβs very common
actually you are right
idk why i said that lol
i guess i thought it was all one nested if statement?
its just a single check at the start of the update
ive tried without that as well, i first did it all mysellf, all these null checks were added by ai to debug when i finally gave up and asked it
but it might also be the problem here, make sure you add a debug line for that if statement to check on all 3 conditions
the sample code he provided probably had this. in it, it will follow your coding "style" but the fact nearly every line is commented is a dead giveaway
also perfect grammar and em dashes in comment blocks
typically indicates its code written by ai
fixing broken ai code should not part of this channel
except when i move the enemy close manually b4 running, everything works as intended but only with the transform at the beginning of the game
Might be nice in theory to force it to be a thread that must use a tag/label indicating that
yeah ik i mentioned that, ive been at this all day i gave up at some point and went to ai, it was no help either, then i came here
we werent talking about you
anyways i have no clue honestly, when something breaks for me like that i shower it in a shit ton of debug lines to see what stops where
especially when you have a lot of if statements.
i know for sure that the player transform isnt updating, what i dont know is why, it is supposed to update, right? when we move?
im questioning everything atp
maybe your player variable is being missassigned?
If your debug outputs player position that's a start
What's your scale got to do with it?
And have you tried getting the local position for your player rather than global, ie parent/child relation
oh yeah if your player is also a child of something im pretty sure its transforms wont change if you only move the parent.
nvm youre calling world position.
i assigned it the prefab in the inspector, is that ok? i redid it a few times too
its not a child of anything
wdym
im pretty sure thats your problem
assigning it from the prefab
i think π€
maybe just use a simple findgameobjectwithtag in the start function
and keep your player prefab in the scene
or use a this.gameObject
im pretty sure altough i could be wrong, since you are using the player prefab from the project as the reference youre never actually changing its transforms or anything as the player present in the scene itself is a seperate instance.
u were right
i think i need to be more confident in my coding skills lol
thank u so fucking much i was gonna cry very soon
Hi all, I just installed Unity, and I can't seem to get any code snippets and no keywords are highlighted or acknowledges at all by vs22, it is so weird, the unity workload is installed, I restarted my pc and all, and still the same
recheck all the steps in
!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
if you verified all those, you can try closing VS, regen project files then open script from unity again wait for VS to load
if its still not working, check Solution Explorer in VS. if the assembly / sln is not loaded , then you can right click it and do "Reload with Dependencies"
is it supposed to look like this on vs?
no
Yeah I assumed as much
its supposed to show the assembly
right click it and do Reload with Dependencies, if it doesn't let you , you probably missed a step somewhere
Oh now its fine
I see, I think it happened cause I didn't have the Unity workload installed the very first time I opened it in vs right?
Thank you sir
is there anyway to make my SOs not save when their data is changed in the project cause having to reset it all after a test is annoying
Make a script that you can run from in editor to reset them all
Uhh, this is what we were telling you to do. To give the method a return value . . .
thats why you dont normally use them as mutable data...
uh my bad
if you want mutable data that resets make a poco
well i dont plan to redo all this again :/
wait so people mainly just use them to read data?
yes mainly they are used as "Templates"
copy the values into another object like a POCO and you can modify as you heart desires
if you change 1 scriptable object data it changes it for any other instances using that SO
think of it as a static class almost
https://discordapp.com/channels/489222168727519232/497874004401586176/1429550409281699962
So back to this,
I did something like this in playerController
https://gist.github.com/Alwandy/ef4c75f438a63f862d1a55dca9263d51
in playerCamera
https://gist.github.com/Alwandy/230b36eb6f61bc6ef973aa68c45fa2ef
But yeah there's few issues now, feels very jittery and a spring effect movement on top of that the camera is not stabilizing.
Anchor is a child of head, while camera is just attached to player game object
oh im sure i can* do that :/
use links for code. we dont need giant wall of text π
In that case if you donβt want to juggle poco classes and/or a whole redesign there is the slightly unsuggested kinda suggested route of instantiating new scriptableobjects at runtime using a βtemplateβ one as reference eg.
SO myInstancedSo = SO.Instansiate(myTemplateSo)
why not ?
would i do this inside the SO or the class using it?
"can" miss type π€£
Could be either depending on context and preference, the idea here would be treating them like prefabs and making instances of them. Ideally you should use poco classes for this for various reasons but instancing soβs is a flawed yet viable route aswell
you can instantiate them as well sure, but depends on use cases it may or may not be the fit
know the options, limits and all that. make a formed decision
could you be kind enough to share how π
Instansiate is probably preferred since you can provide another scriptableobject for a full copy
oh wait you can do SO.Instantiate like IAmBatby said
Im used to Create Instance when I need to make custom objects in unity editor from files like CSVs :
force of habit
I spent like 8 months using create instance and manually copying over properties so my trauma makes me prone to correcting it
i did not know i could just instansiate
ya TIL
so just shove a vvv in the SO (SkillTree)?
public void Awake()
{
SkillTree Instance = SkillTree.Instantiate(this);
}
Thats not how you would use prefabs is it
no π
forgot that Instantiate comes from Object class and SOs are Object π
that should technically clone it no ?
it didn't work :/
Yeah but running that in the soβs awake does nothing
Oh wow, I always used a serializer to copy the data from a SO, but I normally set mine up with the poco as a property of the SO
making an instance of that so doesnβt magically replace any reference to the template with that instance
but shoving SkillTree = ScriptableObject.Instantiate(SkillTree); in the start of the class using it worked
i think?
wait SOs have "Start" ?
They have "OnEnable"
the class using it, not the class itself
ohh right thought they were doing it in the so itself
Though ScriptableObject.Awake and .OnEnable is a cursed rabbit hole
yea
I tend to maybe do something like this, but be warned this is very jank pseudo phone code
MySo : SO
MySo ReferenceSO get; private set;
bool IsInstance => ReferenceSO != null;
static MySo CreateInstance(MySo reference)
MySo instance = SO.Instansiate(reference)
instance.ReferenceSO = reference
return (instance)
then you can do just like
MySo instance = MySO.CreateInstance(mySoTemplate)
Having the reference that was used to make the instance accessible from the instance can be nice in situations where you need to compare them
Do you use il2cpp?
No, why?
Because for whatever reason which is beyond my knowlege il2cpp generates significantly more complex code due to the use of static variables, enough to potentially lead to a ton of overhead if your'e using static variables all over your game
you can read more about it here. https://www.jacksondunstan.com/articles/3916
I presume there are good reasons for this but it does look weird I admit
no 1 that is, no 2 seems weird a f
I donβt ever intend to use il2cpp when I can make that choice for modding benefits so not sure
well you can use mono for platforms that allow it
This is kinda backwards thinking.
You should worry about performance first, rather than C++ code complexity. C# would have a lot of overhead not visible in code, since it's managed jit language. Perhaps the c++ complexity is due to necessity to preserve similar functionality. And it might still be faster.
Sure, it might lose to code written in C++ from scratch, but that's not what you're comparing to here.
guys its been 9 years
The code its executing is complex enough that overusing statics all over your game could cause il2cpp to result in a net loss.
I've tried to use unity for 9 years and each year I just come back, try a unity tutorial and give up
I've tried it since I was 9 years old π’
this is a code channel..
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
this isnt place
mb I am in the wrong channel
Edit: found it
Is that based on benchmarks and tests, or just a guess? A lot of such code is easily optimized out by the compiler, so I really doubt C++ would lose.
again, this isnt a casual talk server no matter the channel
There is a do while loop that just hangs the main thread until the runtime is initialized everytime a method using a static variable is called. this isn''t just some trivial code executing going on.
{
// This macro expands to this:
// do {
// if((klass)->has_cctor && !(klass)->cctor_finished)
// il2cpp::vm::Runtime::ClassInit ((klass));
// } while (0)
// This happens every time you call the function
IL2CPP_RUNTIME_CLASS_INIT(CircleFunctions_t532702825_il2cpp_TypeInfo_var);
// Access Pi
float L_0 = ((CircleFunctions_t532702825_StaticFields*)CircleFunctions_t532702825_il2cpp_TypeInfo_var->static_fields)->get_Pi_0();
// Actually do the work
float L_1 = ___radius0;
float L_2 = ___radius0;
return ((float)((float)((float)((float)L_0*(float)L_1))*(float)L_2));
all of that just goes away when the variable isn't static
extern "C" float CircleFunctionsConst_Area_m2838794717 (Il2CppObject * __this /* static, unused */, float ___radius0, const MethodInfo* method)
{
{
float L_0 = ___radius0;
float L_1 = ___radius0;
return ((float)((float)((float)((float)(3.14f)*(float)L_0))*(float)L_1));
}
}
Yes, and what I'm telling you that C#(or rather IL) is very likely to have something similar.
You're not comparing apples to apples here. You should compare the IL code to C++.
I trust unity did a good enough job with il2cpp ill sleep at night
the generated cpp has to include what the CLR does so ofc it wont be as we expect
no ones saying they didn't what I am saying is if you plaster singletons all over your game like a lot of people here like to advise its coming with its impacts if you use il2cpp it may generate more overhead than you're realizing
I avoid them anyway (singletons) but we can use the profiler to detect such issues
It might generate more cpp overhead compared to a project written entirely in C++, that lacks C#/dotnet features. Not compared to the C# unity code.
how would i code a method to make a button that will just load the next scene in the build? and i mean like withut naming it, i just want it to go to whatever the next level is
More than youβre realising != enough to be problematic
thank you!
Somebody can help me about this?
Did AI assist with that code?
I tried through AI - it seems yes, but I would also like to contact here
Most people here are uncomfortable assisting with AI code because in theory the goal here is to assist people in making better code rather than just βfixingβ it
that's why I'm here
it worked great, thank you!
try coding it yourself, youll have an easier time debugging it
cause youll know whats going on in the code yk
for highlight object is it usually add/remove mesh material, change mesh material shader or swap mesh material?
Those are common solutions for sure.
Especially in the vr space
is SceneManager.LoadSceneAsync still a thing? its in the docuimentation but its not recognized by unity, even when using UnityEngine.SceneManagment
I use it
Yeah that isnt going anywhere anytime soon
so I'm here because I don't quite understand how to write it 0_o
Start simple, break down the climbing mechanic you want to make into smaller, specific steps
Do you think I didn't do this?
Well then what issue did you run into that made you turn to ai to write your code?
Less attitude, ask questions. You don't know how to write what exactly, guide me through your process
I think I showed it on video 0_ΠΎ
Except that code was ai generated
I meant the issue that made you give up on making your own code and turn to ai
Unless I'm mistaken, and correct me if I'm wrong their issue is part of lacking the understanding on the coding part. Which is okay, that's why we help
I know, Iβm trying to get them to write their own code instead of trying to debug the ai one
I have an object that I want to climb. if I stand next to him on one side for about 10 seconds and move to the other side, he will teleport me back to the other side
what code?
Okay and what is your current understanding of C#
The code you posted with the video
That was ai generated right?
wait, so you want to say that now AI is a useless waste of time, incapable of helping a person?
No, but itβs not very productive to use ai to generate your code because then you wonβt know how to debug it
how do you know what it is?
What what is?
what does this mean? I asked for help
How do you know that AI did this?
Itβs very obvious when ai code is used directly
not all
You literally said it was ai generated
Itβs more useless than helpful yeah, especially for beginners
if you ask AI, he can help. Well, speaking of methods, the package developer helped me with this
Then why are you asking here if your ai is supposedly going to fix it?
(I donβt think a package developer has been mentioned before has it)
Let me explain again: the code was originally made by the developer. I couldnβt find a solution to the problem and decided to turn to AI. he told me a way, but I'm not sure how correct it is, and that's why I'm here
what's the difference? the package that belongs to the developer can be remade
is application.quit typically what ppl use to quit their games
cuz im testing it in editor
Okay so you're not the main developer, we got somewhere. Okay so in principle look at Vectors, transform and coroutines
im not sure if its actually quitting
Context helps people understand the situation
cuz it still acts as if the games being played
It's what I use and so far no issue
But it only works once built
do you propose to stagnate and study c#? this is very unproductive from the point of view of creating a project. Why canβt you do and study?
You can, it's the best way to learn
Yes, Iβd think that learning the language a game engine uses is a good way to use said game engine
Like every single developer before the invention of generative ai yes
It likely isn't for the Editor. Pretty sure if you search for application quit in this channel you'll see what people have done as a work around for the editor.
You canβt go off of packages and ai alone
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thereβs some great resources for learning unity here
Amazing!
πgood luck with your learning!
Well then I propose to tell Elon Musk to fuck off and say that the AI is complete shit
as long as the quitting actually works im fine i just thought it didnt work cuz it was in editor
AI is buns i agree
learned codependancy
Yup, elon musk is a lying gross piece of garbage
Ai is a great tool, but not for making unity code
Anyway moral of the story is Iβd start by learning c# and the basics of unity first, then making smaller projects and working your way up
I just asked for help based on the code, because I know what the problem is in the code. But nevertheless, they just slipped me "!learn" so that I could go and study happy.
learning a language is a big time commitment. first we get junior, then senior, and so on (I donβt understand the hierarchy of programmers)
and now, after about 50-60 years, instead of finishing the project and asking for help from an auxiliary robot that was specially invented for consultations, we get a great programmer who certainly knows how to stop teleporting a character during parkour π«‘
God bless our programmers. there are so few of them, they are so missing... fuck your AI? YES! This is evil, this is a follower of heresy
<@&502884371011731486>
and for what then? Play role-playing games related to porn? Really?
Idk, but not unity code
You know what? it's a waste of time
Not the place and discussion to have here
Iβm not going to fix the ai code you donβt understand
And neither is anyone else
Not really, you can make games like flappy bird mere hours into learning unity
Just keep building your skill level and youβll get there eventually
anyway asking this again because that other guy drowned it out
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneManager : MonoBehaviour
{
public void Die()
{
SceneManager.LoadSceneAsync("Die");
}
}
for some reason, SceneManagement is "not required by the code" and LoadSceneAsync can not be resolved. weird since im only like 6 lines in. Any help here?
yup and yup, just double checked to make sure
okay just checking, I tend to prefer using int values and order everything manually than use string reference (personal preference), ill have a look at my code quickly and get back to you asap
Example snippet of code I have that uses loadsceneAsync
{
DontDestroyOnLoad(gameObject);
Fader fader = FindAnyObjectByType<Fader>();
yield return fader.FadeOut(3f);
yield return SceneManager.LoadSceneAsync(sceneBuildIndex, LoadSceneMode.Single);
yield return fader.FadeIn(2f);
GetCurrentScene();
Debug.Log(currentSceneIndex);
Destroy(gameObject);
}
~~Unsafe use of that fader reference ~~
not the point, but Fader is static, and the whole thing is an object thats not destroyed
started digging a little deeper, neither LoadSceneAsync nor GetActiveScene are recognized
im in 6.1...unless they changed that in 6.2?
the exact error message in unity is
Assets/SceneManager.cs(7,24): error CS0117: 'SceneManager' does not contain a definition for 'LoadSceneAsync'
ah thats why, you named your script SceneManager
Change its name to something like SceneLoader
i missed that originally, but yes SceneManager.LoadSceneAsync is a built in unity method

ah dont worry, we have all been there
what is harder to code
unturned like inventory system
project zomboid like inventory system
Hi, I have Two character prefab and in each character prefab, I have a rope attach point. what I want is make the rope with physics and connect these characters. Any one have idea for how to create a rope with physics.
By using joints. There are plenty of tutorials on this.
hey can anyone recommend a good unity 2D enemy tutorial i need one that allows the enemy to chase and then go back to patroling
"harder" would be dependent on your experience with the engine and your knowledge of C#, as well as the specific features of either system your trying to replicate - imo both are going to be difficult if you have never made a inventory system before, and both seem similar enough in design and function that it may be good to start with breaking down the parts of either system your trying to replicate then approach each of those parts
A common approach to this might be using a FSM (Finite State Machine), that can be applied to 2D as well, the FSM would let your enemy be in one specific state depending on conditions, and once in that state you can handle what the enemy should do - you could try searching up "unity c# fsm tutorial" and im sure youll find lots of playlists and blogs you can use as a reference (if you choose to take this approach)
ohh will do
i expected a 2 word answer
Fair enough, im not sure a 2 word answer would provide you much context to do anything with, but in short "both are hard"
"Both hard". Here, 2 words.
much bette
thank u
Hey everyone,
Iβm not very familiar with Unity and Iβm running into a problem when I launch my game. Normally, my mouse cursor should control the camera, but instead it stays outside the game window β like Iβm still in edit mode.
If anyone has any idea what might be causing this, feel free to DM me! I can share my screen if that helps.
Itβs a game my friends made in Unity, and I worked on some of the assets and integrated FMOD middleware. I wanted to get back into it, but right now I canβt even play. Any ideas?
could someone please show me a screenshot of the UI of Unity where to map the OnClickEvent() to the buttons?
I can code.
I don't know a single thing about Unity though...
and I'm learning off of YT like how coders learn coding from Hidnus YTs coding tutorials
and my patience is running out honestly
I'll figure it out eventually
but I'd appreciate help
thank you
You can add an event subscription to On Click there or do it in code
I need help with figuring out how to make my collider stop rotating on the Y axis to that it's fully level with the floor no matter where the player looks. I'm not sure what to look up to find video and was wondering can either teach or show me a good video.
you can freeze rotation on your rigidbody but this sounds like its a player controller.
But if you are rotating your player based on input then this wont help.
hey do this Discord have a "collaboration" channel, i want devolop a smallGame with somone. i didnt finde the Cannel so i asked here
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
β’ ** Collaboration & Jobs**
Thank u!
It's following the players camera , I just need it not to rotate on the Y-axis when it follows it cause I just need to orbit around the player with the camera is at fixed distants
can you share some screenshots or a screen recording of this behaviour?
It really sounds like your code that is causing this rotation because as I said, we can lock rotation on a rigidbody
I am but I am not using a ridge body for this as it's only needed to push stuff along
!code sharing time then
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
okay so you are copying the world Y rotation to some other transform
this should work fine for what you describe. Are you getting the rotation axis confused?
No, not no more. It was just a fixed that did a little second ago and I go them confused. it's just issue now where the box is going up above my head. and I want it to stay at the orbit away from the player. Not going above the head
yea i just dont understand what you want. A drawn picture or screenshot or something to illustrate would help
Is this some third person orbiting camera?
So instead of collider going above or below the player, I want to stay at fixed distant from the player like how it starts
Right so no rotation is needed but correct positioning.
Using the correct terms to describe an issue helps a lot.
You can position this object by projecting forward using the cameras forward vector.
e.g. boxTransform.position = camera.transform.position + camera.transform.forward * 2.5f;
My apologies, it was that at first but I found the fix and it was the problem you describe. I had gotten the axis mixed up, I should have made it clearer. This was the next problem after that and I was sure how to have it stay
When you say boxTransform.position, you mean the object itself right?
You box collider game object transform
The take away is that we can use the provided normalised forward vector to move an object to be a fixed distance in front of a Transform.
Thank you
how do i switch my game from urp to built in rendering i used to be able to do it but it changed
remove the URP Render Pipeline Asset from the projects "Graphics and Quality" settings.. and then manually change all the materials to use the "Standard" shader π«
thanks alot that was my problem only changed it in Graphics settings
URP not doing it for ya?
nah man not really has some bugs and overall for a retro style im more happy with built in
probably builds better/ easier to run on all kinds of hardware too
yea and vertex shaders are better on built in do you use urp or built in
i've swapped to URP for a while now..
working on swapping to the new input system next..
gotta stay ahead of the times π€
yea
nothing wrong with built-in tho
most of my simple examples and prototypes are built-in
no need for URP for something as simple as an example
When should I use Addressables to load a scene?
until they actually KO the entire Built-in pipeline
then i guess we're all moving to render pipelines π€£
when u need to optimize performance and memory by loading on demand... managing large number of scenes.. or enabling dynamic content updates
am i doing something wrong that the little scene transition isnt working?
im following a tutorial but something seems to be going wrong and stopping it from working
either that or its because the tutorial is outdated
you'll have to elaborate a bit
no.
10 yr old tutorials still work with the current code-base
the nly issue with old tutorials is menus moving around.. and specific functions being replaced.. like rb.velocity becoming rb.linearVelocity <- but even unity will take care of that kinda stuff when it compiles
i dont even understand what that means....
u dont understand what no means?
i meant the rb velocity thing
the rest really isn't important
i see
just gave an example of what types of things change..
you'll need to give more specifics.. tho... we cant really guess what the transition is. or even means
uh- anyways
https://youtu.be/DX7HyN7oJjE?t=229
im following this tutorial. Script is in the main camera (even though i dont understand why)
I have the canvas and a button to lead me to my script,
but with the on click stuff, the menu is a little different from what hte video shows
In this Unity tutorial we'll make a Main Menu.
How to make a PLAY button , OPTIONS button and QUIT button in Unity ?
π¨ Get Sprites: https://www.patreon.com/posts/sprite-bundle-2d-116754519?utm_medium=clipboard_copy&utm_source=copyLink&utm_campaign=postshare_creator&utm_content=join_link
π» Get Codes: https://www.patreon.com/posts/script-bu...
and why its not working
is it because ur dragging in the script into the button?
and not a gameobject with that script attached
^ those are two very different things.. and u the first doesn't work
i was following along with the tutorial, just about 1 for 1???
so u dragged the Main Camera (w/ the script) into the slot on the button?
if thats the case it should show any public methods in that script
if thats not the issue u need to specify..
this is what its showing for me.
where is TestGround?
did u drag that from the Scene?
or the Project Window?
a game object with the script attached.... do i need to make another game object for this?
.... the script is attached to my camera
do i have to drag my camera into the thing?
If you want to assign that function from the camera object, yea
no i dont know why its attached to the camera i just did what the tutorial did
......... the tutorial vid didnt explain this at all π
Maybe it's not a good tutorial then
its probably attached to the camera b/c the tutorial maker knows you'll have ur camera in the scene
and wont make the mistake of dragging the script into the slot and not the gameobject...
ur dragging the wrong thing into the slot..
i now feel incredibly dumb.
ποΈ when you drag the script from the project window it wont work..
you must drag a gameobject w/ the script already attached to it.. (maybe ur camera π )
nah bro.. this is a problem alot of beginners make..
even I made that mistake π
makes me wonder why its like this tho tbh
but now u know π
until i inevitably forget because goldfish memory
b/c the script has to be in the scene (to function)
ah
unless its a Static script or something (but you'll learn about that later on)
It's part of the basics of object oriented programming pretty much. You need an object on which to call the function
what was funny is when u sent the video it was timestamped exactly where it shows the guy drag in the Camera object π€£
Hello, Iβm a beginner. I saw a tutorial on YouTube and Iβm trying to use a car controller on a model, but I donβt know why the wheels pop out when I start driving. Iβve tried rotating the wheel hubs and fiddling with the colliders
good luck.. don't pull ur hair out.. keep calm and carry on π€ͺ
Looks like the 3D models for your wheels aren't oriented properly
It looks like the wheels are rotating along the wrong axis
Or that
@manic hatch check out #π»βcode-beginner message that second link... it's Unity's WheelCollider walk-thru/ tutorial
take ur time and check out the steps it takes..
compare to urs.. and also maybe check out the wheel's pivot/orientation in ur 3D software...
b/c its possible what Praet has said..
Wheel Colliders are a Pain in the Ass..
my least favorite Unity component ever
heh, don't jinx it
i wish unity had a primitive wheel ..
could make the process much more intuitive..
So to my understanding, if I include all my scenes in build, it will increase the build size and time
But how does that actually work? Does it create copies of referenced asset data in the scenes or something else?
got another bad tutorial that im gonna need some help on. Im followin this one for a basic HP system. Its got text on UI, but it doesnt show me how i get there.
So this will be my question. How do i get a number from a script and have it show as a text element on a canvas?
You can set the text directly from code by accessing the text component
meaning?
i dont know how to do a lot in unity cus im brute forcing this stuff for a tutorial and not giving myself time to learn or experiment
Ur using text mesh pro right
yes
build size = how big ur game file is..
load time = how long it takes to start or load a scene
Scenes in Build Settings:
- Included in the game file.
- Not loaded until you call them.
- Bigger build size, same startup speed.
Addressables: - Not included in the main game file.
- Downloaded or loaded only when needed.
- Smaller build, faster startup.
** Using too many Addressables can increase load when fetching them, so balance it β donβt make everything Addressable.
Hey guys!
I'm working on a 2D Metroidvania-style combat system and I want to make it modular and easy to extend.
Right now, my idea is:
β Play the attack animation (Light / Heavy)
β Use animation events or triggers to enable a hitbox
β Deal damage to the opponent when the hitbox overlaps
Do you think thatβs a good and scalable approach?
Or is there a better way to handle combat timing and damage in 2D (Unity)?
Iβm mainly looking for the best structure for modular attacks (so I can later add combos, cancels, etc.).
So in your script you can say something like
TMP_text tmp = tmpObject.GetComponent<TMP_text>();
tmp.text = βwhatever you wantβ;
using TMPro; // include the using statement for TextMeshPro
public class Boot : MonoBehaviour
{
public TMP_Text bootText; // assign in Inspector
public void SetBootText(string msg)
{
// set it's text property
bootText.text = msg;
}
}```
```cs
// if its something other than a String you need to convert it to a string when setting
SetBootText(score.ToString());```
what if i wanted it to be something dynamic like a health bar or smth?
it starts at 100 but gets either chipped down or increased from healing.
like i want it to dynamically show the HP in the top left corner or smth with how it changes
whenever u take damage or get health you
update the player's health variable.. and then Update the UI right afterwards
A good way to do this is by making a setter method for your player health
using TMPro;
using UnityEngine;
public class PlayerUI : MonoBehaviour
{
public TMP_Text hpText;
public int health = 100;
public void TakeDamage(int dmg)
{
health -= dmg; // update player
UpdateHPText(); // update screen
}
public void Heal(int amt)
{
health += amt; // update player
UpdateHPText(); // update screen
}
void UpdateHPText()
{
hpText.text = "HP: " + health.ToString(); // or
//hpText.text = "$HP: {health}";
}
}```
very true.. this guy is total beginner tho..
just making use of hard references for now
Fair enough
Later you can replace this with a proper health system that sends events to the UI instead of directly referencing it.
but just for kicks
public class PlayerUI : MonoBehaviour
{
public TMP_Text hpText; // assign in Inspector
private int _health = 100;
public int Health
{
get { return _health; } // read value
set // when value changes
{
_health = value;
UpdateHPText(); // update display
}
}
void UpdateHPText()
{
hpText.text = "HP: " + _health;
}
}``` this is what they're talkin about..
with code like this just by *setting* the `Health` variable it'll update the main variable.. and call `UpdateHPText()` at teh same time..
π is to only update the UI when it needs to be updated..
"sure you can have the UI updating every frame but its not very good structuring"
you'll only want to update it when it changes..
no reason to change 99 to 99 but there is a reason to change 99 to 98
may want to consider using a single script to update all your UI with different functions...
UIManager.UpdateHealth();
UIManager.UpdateShield();
UIManager.UpdateInventory(); so on and so on
i feel like i just got smacked in the head by a brick while trying to understand this
yea, i think u just need to Marinate in some fundamentals !learn
Ok we can take it slow then, do you understand how weβre changing the text?
u got this noodle. i'll be ur wingman
I'll just be watching silently
I have to go soon you might have to take over lol
all gucci
just FYI, the new bot only likes commands at the beginning of the message
i hardly understand code on a good day, ontop of that i more or less am doing a last minute assignment crunch for thursday
kinda lacking on time to marinate in code knowledge sadly
I found some document and it says this about direct references: "When your application runs on the target device, Unity loads the entire asset file into memory before loading a scene."
I suppose it means all the direct references will live in the memory when a scene is loaded, even if they are not instantiated?
Thatβs ok, like I said we can take it slow
So thereβs basically 3 steps to changing the players health:
- setting the health variable
- Changing the text that displays the health
- Updating the UI so that we can see the text change
Does that make sense?
Well everything in a scene will be created when the scene is loaded so makes total sense that all the required assets are loaded into memory.
Yes. Logic is simple enough.
let's assume this is my MainMenu Scene.
I wish to hook my On Click () event to the ImageStartButton which is an Image Object in the Canvas.
I added a child button Object to it on the right panel.
Ok so for the first step, the text mesh pro object has a component called TMP_text which has a text property that holds whatever the text displays
let's assume I already have a working C# script that does all the functionality
there is No Function there
What you want is to assign that text property to the players health
Events should have an appropriate Component instance assigned to their object field.
Does that make sense?
thanks
@edgy cloak low key competing with me here
for the same project
with the same YT tutorial video
π«‘
i think so yes. though i wonder where to assign it
?.
im not π― sure of anything more than what ive already said..
i just know the concept of Addressables.. i haven't ever actually used them unfortunately
Addressable scenes should act the same as normal scenes in terms of how they are opened
Perfect, so the way youβd do that is retrieving a reference to that TMP_text component, then assigning the text property. To do that, you can do something like this:
[SerializeField]
TMP_text healthText;
Then, you can assign the TMP_text component to healthText in the inspector so that healthText becomes a reference to that component
But with addressables we can have direct asset reference or indirect meaning no asset dep is made
Does that make sense?
i love how my text editor automatically includes using statements
like i access text in textmeshpro then it adds it by itself
i mean yeah that's something id expect of most ides
cuz yes i dont want to memorize all of the assembly references or what ever they are called
but also just make sure it doesn't add an incorrect using statement haha
-# also assembly references are a different thing
should i uh, should i be working along as you say this?
also should we be doing this in a thread to avoid message backlog?
if it does im bringing out my secret weapon (asking chatgpt what assembly reference im missing)
Yeah good idea
or you can just look at the using directive..
no im lazy
auto add using statements go brrrrrr
I do have to go though, @rocky canyon can you make the thread
it's literally easier than asking chatgpt to fix it
im also dumb
im not saying don't use auto add using statements im saying make sure they're the ones you want
yes yes
usually it's pretty easy to tell tbh
damn π
Yeah, I was looking for a way to dynamically update my assets seasonally. I'm afraid I would do something wrong so I force myself to understand it
ya, that does sound like a use-case tho
when i think addressables i instantly think DLC... and since my projects aren't actually that big i never had a need to figure them out
That looks good to me
Thanks bro
if its just seasonally tho.. and you know you're already planning on using seasonal stuff.. you could just include all the assets.. and have a flag that toggles between them depending on the date
for answering
yeah i will do it this way, i just wanted to make sure that my way would be okay. i thought about "maybe somone does know better and have some experiecne". but again Thank u!
Yea you will want to look at addressables then. I should warn you that asset bundles (and addressables) assets cannot ref things outside meaning you can get asset duplication. (e.g. addressable asset -> Resources is an invalid ref)
learn more: https://docs.unity3d.com/Packages/com.unity.addressables@2.7/manual/AddressableAssetsOverview.html
Well I donβt have the most experience but thatβs a pretty modular approach yeah
so lazy infact in my latest game i made the upgrade button functionality inside the spawn manager script instead of making a different script
like tell me, do you want Debug from UnityEngine or System.Diagnostics
i dont know
unity engine
I see. All dependencies must reside in a group in the bundle then?
yeah
and that is the one you need
it's really not that hard
.. sure? but why

i dont know
i mean
dont we have the mindset of
if it works dont touch it
and i really wanted to finish the project in 3 days
i had fun making it
i had fun coding too actually
sometimes but jd advise against it
definitely didnt crash out over player movement script
that is.. somewhat of a joke, man
maybe
project i was working on wasnt taken seriously
js a 3 day code and pray
somehow did workout
10 browser plays and 4 downloads on itch.io π£οΈ π₯
then sure, but you gotta move away from that mindset if you want to learn and progress to making more complex things
like i said
the project wasnt taken seriously
next project would be taken mindfully
btw what game should i make cuz i have no idea
i know what you said. i'm talking about your mindset in general.
sure, you completed the project
but you gotta learn from it too
if you keep that mindset, you won't be able to effectively be mindful in the next project
sure, don't touch it if you don't want to.
but at least think about it
only thing different from it and my 6 prototypes is the SceneManager method
which i did learn
and button functionality
i know
unity isnt my first game engine
maybe you can also learn about namespaces!
what
No they just need to be addressable too. If not the asset is automatically added to the same bundle. There are analysis tools in addressables to help find and solve this. Ask in #π¦βaddressables if you need help later.
-# namespaces are the thing you include in your using directives
NO
you can even make your own
lemme guess
smth like
using WeaponScript;
Oh right thanks. I didn't see that channel lol
you wouldn't be doing that to a script, no
well not really
using is for namespaces, not scripts
a namespace is a collection of scripts

a namespace is a collection of types, to be pedantic
you can have multiple namespaces in a single script
well yes but let's not say too many fancy words
yes please
english is my 2nd language
sure, but let's also not give misinformation
ugh fine
could say namespaces hold classes/structs/interfaces/enums
-# let my midnight brain be okay
they are speaking mozart
it's kinda disappointing unity treats component classes and scripts as synonyms tbh - so this isn't really your fault
nah i know the difference im just sleepy
nah i mean in terms of like, ideal communication with beginners
communication with noobs
just wanted to ask about this error. Writting a private or protected class is pointless right? especially with grabbers like monobehavior since nothing can have access to it
Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected
it's not pointless, it's invalid, in the case of top-level classes
inner classes can be private/protected/internal/etc, and that could make sense
is the error also shown in unity?
(save and refresh first ofc)
no oddly enough
ur a genius
π€¦ββοΈ π€ͺ not a clue bro
just vs code doing vs code things
hmm, can't seem to find the command for the .net lsp. i guess reloading the window would also work
there is a language server, another command references it...
i think it may correspond to my internet connection π altho thats just speculation
switching to built in is like one of the best choices ive made
built in? render pipeline?
yes
well that's not code related
for the most part, private is often redundant.
private float _foo;
float _bar;```
both properties are private
Im sure theres some situations where its important to write private, but its probably more down to a convention of some organisation where they want the code to have a specific style
i always write private
ahh
coding style
got it
It could be good to use private when youre starting out writing code, as youre explicitly telling future you that something is or isnt private. That way you cant read code and accidentally assume X is public
I have a question, in plain C# constructors inside of classes are important... what about MonoBehaviour? since unity handles creation of new instances of the class when its assigned to a gameobject do they still serve a purpose?
MonoBehaviour classes dont support constructors, but if you had the constructor in this class Foo, its redundant as it wont ever get called
public class Foo {
public Foo(){}
}```
I've been using Unity for ~12 yrs and still type private. From habbit, previous jobs and find it easier to read, no need to ever use that microbrainthought to work out something is private
MonoBehaviours cannot have constructors
Foo thing = new Foo();```Will produce an identical result whether you had a plain constructor or not
Well, to be more precise, they can have them, but calling them won't actually create anything since they can only exist on GameObjects
At times it can feel a little frustrating that you cant use a constructor with them
You can just create a function called something like Init() and call it after adding the component
Yeah thats what I typically do. But each time I think "man it would be convenient if I could just use a constructor"
Yeah i thought so, as the only documentation i could find was for C# base classes. Thanks for the clarification
just fyi, but neither of those are properties. they are both fields
dang it, I dont think I'll ever not get names of things correct π
for simplicity, ill just refer to everything as "stuff and things"
i know this didn't relate to me but is it too much to ask to explain the difference, ironically that very topical for me atm π
β hi all. Project runs better in Editor than exported MacOS .app? 
Nothing seems off in the Build settings. I have this code in Awake()
Screen.SetResolution(Display.main.systemWidth / 2, Display.main.systemHeight / 2, Screen.fullScreen, Screen.currentResolution.refreshRate);
Furthermore - in Editor game can run at 300-500 FPS uncapped, or VSync very stable (computer's fans don't turn on, no game lag either.)
fields are variables defined as part of the object. properties are syntactic sugar for get and set methods that look like variables
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
Is this because in editor your game window is small? Make a debug build and profile it!
Display.main.systemWidth / 2, Display.main.systemHeight / 2
I was running the game higher than this resolution, in Editor
then the profiler and frame debugger are next
I have been stuck on this for a while and can't seem to figure it out. If I want to make it so when you hold the space bar you jump higher and when you tap it the jump height is reduced to a certain value how would I do it? would I just make another if statement with wasreleasedthisframe instead and add >
rb.AddForce(Vector3.up * smallJumpHeight, ForceMode.Impulse); Any ideas?
I think beyond the initial "small jump" impulse, the 'added jump height by holding button longer' would not make sense with impulse π€
I'd think it's preferred to use ForceMode.Force which is applied steadily?
I made this same mistake in my first 2d platformer using the Impusle, I had to do all kinds of crazy math to do a second impulse in order to sort of cancel out the initial impulse to cut the jump height it was a headache so I think just adding a force is better.
Essentially you can just keep adding force, until some 'maximum jump height added' is reached (probably counting how many times the force is added in FixedUpdate)
Hey
Hey
using UnityEngine;
public class CombatSystem : MonoBehaviour
{
[Header("References")]
[SerializeField] private AnimationHandler animationHandlerScriptRef;
[SerializeField] private bool useAttackScript = true;
[Header("Light Attack Settings")]
[SerializeField] private Collider2D LightAttackTrigger;
[SerializeField] private KeyCode LightAttackKey = KeyCode.Mouse0;
[SerializeField] private float LightAttackCooldown = 1f;
private Coroutine LightAttackCoroutine = null;
[Header("Debug")]
[SerializeField] private bool isCurrentlyLightAttack = false;
void Awake()
{
if (animationHandlerScriptRef == null) animationHandlerScriptRef = this.GetComponentInChildren<AnimationHandler>();
}
void Update()
{
if (useAttackScript == false && animationHandlerScriptRef != null) return;
ReadAttackInputs();
if(isCurrentlyLightAttack && LightAttackCoroutine == null)
{
LightAttackCoroutine = StartCoroutine(LightAttackCooldown_Coroutine());
}
}
private void ReadAttackInputs()
{
if (isCurrentlyLightAttack == true) return;
if (Input.GetKeyDown(LightAttackKey))
{
isCurrentlyLightAttack = true;
Debug.Log("isCurrentlyLightAttack" + isCurrentlyLightAttack + "!");
//TO:DO Angirffs Animation abspielen.
}
}
private System.Collections.IEnumerator LightAttackCooldown_Coroutine()
{
yield return new WaitForSecondsRealtime(LightAttackCooldown);
isCurrentlyLightAttack = false;
LightAttackCoroutine = null;
}
}
``` I want to make my first Combat Script, i want to ask is this way i do Good? and i also want to use Combo Attacks, can i do
are u asking me?
somthing like is 85% of the Coroutine Cooldown Done and the play pressing the Button again do a antoher Attack?
yo thats actually really clean for a first combat script i like how you handled cooldowns and states pretty simple and solid if you wanna add combos you can just track combo steps and reset them after a short time like press timing based chaining its a good base to build on
It's gonna be much easier to do this with a state machine
what is that?
you could clean it up a bit by separating input and attack logic so the combat system only handles attacks and another script handles inputs tho
Save yourself now, your code is brutal to read currently bro
ahhh i saw that in a Unity forum
u right
i forget it
let him find out on his own
i mean what would be better? State Machine or Coded?
jk but i mean his script isnt awful
wait is Enum a State Machine?=
i used Enums for my Enemy
like Walking, Attack etc
Yeah. Hierarchical state machines are a little cooler, and take advantage of Polymorphism
Polymprphsim
how long of a dev are u
sorry if my english isnt that good
im not a dev, im just a hobby coder
oh alr
Hahaah look at my
im to bad to call myself Dev, i respectet that Title Extremly
thats crazy
nahh fr
so, what exactlly would u change on my Script?=
i coded Attack Scripts 2 or 3 time but im scared at Combos, i code evertyme (in the future) and saw that everthing messed up. I think i cant really handle the "Timers"
and Coding? like a along time but never really a lot
just maybe 1 week than a huge break and then again 3 Days
etc
With a state machine it looks something like this.
float timeInState;
void LightAttack_OnEnter() {
timeInState = 0.0f;
}
void LightAttack_EveryFrame() {
timeInState += Time.deltaTime;
// do whatever cool stuff you want
if (timeInState > 0.85f * timeLightAttack && comboButton.pressed)
{
// switch states
}
}
helllll hnahhhhh
this looks like hell
okay no its actually looking alr
so its better to use a Costum timer? and not Coroutines?
You can use either. I haven't heard that Coroutines have much advantage to manually keeping track of time.
@scarlet pasture the point is, every state has 4 important methods. And with that you can have more control over what exactly is happening in your game πΏ
OnEnter
OnExit
EveryFrame
HasNextState
Super easy to keep time, allow certain things to happen at certain times, prevent certain things from happening, etc.
Trust me it's really fun and pleasant. you won't miss hard-coded if/else logic
don't ask just to ask
always post the details up front when someone sees it they can answer
i have loop floor here
I will test it know, Iβm gonna rewrite this small code and use u method
but i am getting this line
men i will really apprecite it i like trying for hour to remove this line
I tried using forcemode.force but my player can barely jump.
last option was here
does the jump height value need to be much higher?
Just multiply the force until it starts to have an effect yeah
@edgy sinew 
This is not a "one person helps" server, you post your question and whoever knows will answer it. If it gets lost post again
are those 2 seperate sprites or just one big long one?
Are you using Pixel Perfect camera?
There's also some crazy '1 pixel padding' trick people are saying fixes this kind of issue.
ahh alr, it works now this is what I did β rb.AddForce(Vector3.up * jumpHeight * 2, ForceMode.Force);
how would I make it so when you tap the space bar the jump height is small? would the setup be the same for that?
one when i chnage the draw mode to tiled and the width this start showing the ground is loop
this is somthing else
check the sprite editor maybe you have an extra transparent line of pixels at the end or start?