#πŸ’»β”ƒcode-beginner

1 messages Β· Page 752 of 1

naive pawn
#

what's the type of dialogueText?

teal viper
#

That would imply that your ide is not configured correctly.

naive pawn
#

ah wait missed some context

sharp ridge
naive pawn
#

yeah sounds like a missing configuration thing

#

try regenerating project files, perhaps

sharp ridge
#

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

naive pawn
#

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

sharp ridge
naive pawn
#

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?

sharp ridge
#

Nope, i always close beforehand

naive pawn
#

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

sharp ridge
naive pawn
#

it's a button in the external tools page in preferences iirc

#

might be in project settings. probably not?

sharp ridge
#

Okay I will check it

teal viper
#

In preferences

sharp ridge
grave frost
#

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.

naive pawn
#

it's not just the library that should be ignored

sharp ridge
#

Didn't know this was a thing

#

Thats so nice

naive pawn
#

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

sharp ridge
#

I will have it in mind for the next project I work on thanks!

grave frost
sonic dome
#

i cant find the error script

#

why is this happening

floral garden
#

as said, go in edit and search the missing script on all gameobject

sonic dome
#

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

urban iron
# sonic dome why does this happen

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

sonic dome
#

i just used a coroutine until it wasnt null then used it

#

seems to work

urban iron
#

Oh ok

sonic dome
#

how do i istall this?

naive pawn
graceful fractal
#

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?

hallow acorn
grand snow
slender nymph
graceful fractal
#

That is...

#

fuck, why didn't I think of that

#

thank you

sour fulcrum
#

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

graceful fractal
sour fulcrum
#

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

graceful fractal
#

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.

sour fulcrum
#

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 πŸ˜„

graceful fractal
#

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?

grand snow
#

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

sour fulcrum
#

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 πŸ™‚

graceful fractal
#

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

naive pawn
#

they're all more work, really

#

if you overuse them, sure, it can cause issues

#

but that's true for anything

graceful fractal
#

that is true

iron mango
#

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?

fast relic
grand snow
#

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

shadow iron
#

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)

iron mango
#

What type of collider are you adding?

shadow iron
#

mesh collider, and the convex is set to false

iron mango
#

And like are you only adding that to the parent only?

shadow iron
#

I think maybe its cuz its too big? if so how do I make it do it in sections or smth

shadow iron
iron mango
#

Show hierarchy

fast relic
shadow iron
shadow iron
#

everything other then the sphere object is otherstuff thats unimportant rlly

iron mango
#

I forgot this was programming..

feral moon
sour fulcrum
#

that is a lot of commenting

#

and a lot of this. πŸ€”

feral moon
#

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)); }

sonic dome
#
        foreach (Transform child in parent.transform)
        {
            Destroy(child.gameObject);
        }
#

is this how i delete all the children of a parent?

naive pawn
#

sure, that works

languid pagoda
red igloo
#

Like this? || sorry for the late reply xd||

naive pawn
#

sure

#

you might be detecting the ground right after you jump, depending on how large the radius and distance are

earnest oak
#

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?

red igloo
naive pawn
naive pawn
languid pagoda
#

interesting

red igloo
hard tapir
#

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

rocky canyon
#

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

hard tapir
#

so I need to set it at the stat and then Instantiate(newShield, ......)?

rocky canyon
#
{newShield = instantiate;}```
naive pawn
rocky canyon
#

ya, that ^

#

but the variable outside the functions.. like u do any other variable

rocky canyon
#

πŸ‘

hard tapir
#

what does this line mean?:
{GameObject newShield = instantiate;}

naive pawn
rocky canyon
#

GameObject newSheild; {newShield = instantiate;} just shorthand showing that the variable isn't within the {}s

rocky canyon
#

^ yea

naive pawn
#

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

rocky canyon
#

good luck πŸ€

hard tapir
#

much appreciated

next birch
#

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

red igloo
naive pawn
#

that is exactly what i said

#

also what nav said

red igloo
#

how can I fix it? shall I add a small delay after jump before allowing isGrounded to become true again.

naive pawn
#

sure, or make the ground check more accurate

rocky canyon
#
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

iron mango
#

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

cosmic dagger
#

you mean intersect?

iron mango
#

yes

#

sorry

keen dew
iron mango
keen dew
#

You can't use Collider.bounds, no

hard tapir
slender nymph
#

!code

radiant voidBOT
iron mango
keen dew
#

That's why I linked it, yes

hard tapir
#

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;
        }
 
    }
}
vital otter
#

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.

hard tapir
#

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?

vital otter
#

show the code

hard tapir
#

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;
        }
 
    }
}
vital otter
#

well... im not sure. Maybe newShield is getting either reassigned or its not properly assigned?

naive pawn
#

sheildOn == false could just be !sheildOn btw

keen dew
#

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

vital otter
#

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.

slender nymph
#

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

vital otter
#

useful though

hard tapir
#

ive been trying for like an hour

vital otter
#

maybe a discord bot to edit messages could do that?
I heard that format can have coloured text?

hard tapir
slender nymph
#

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

vital otter
slender nymph
#

whoops there goes the context that was included with the code

vital otter
#

it could add all context before and after. Maybe it repastes the message and in a code block it formats it.

slender nymph
#

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

naive pawn
#

but yeah, context gone

vital otter
#

does anyone know how to make smooth movement?

naive pawn
#

that's quite a vague question

slender nymph
#

there are plenty of ways, and a lot of it depends on context

vital otter
#

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

slender nymph
#

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

vital otter
slender nymph
#

good thing google exists so you can find out!

vital otter
#

so is smoothTime the acceleration or the inverse of the acceleration?

slender nymph
#

what does the documentation say

vital otter
#

smoothTime Approximately the time it will take to reach the target. A smaller value will reach the target faster.

#

but what does it mean?

edgy sinew
#

It means, lower values reach the target faster. That's it

slender nymph
vital otter
#

i could try using it
but if its completely broken well... yeah

slender nymph
#

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

vital otter
#

so what part of smoothdamp controls the acceleration?

rich adder
vital otter
#

and how do i fit the acceleration variable into it?

rich adder
#

You pass it in

naive pawn
#

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

edgy sinew
vital otter
#

which means faster acceleration?

naive pawn
#

you shouldn't be caring about acceleration with smoothdamp

slender nymph
#

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

naive pawn
#

though, the acceleration isn't constant

vital otter
#

wow, the velocity is approaching zero really quickly
not a good look imo

naive pawn
#

i'd guess the velocity follows a parabola

#

so the acceleration would be linear

#

jerk would be constant

vital otter
#

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);```
thorn holly
#

lol

naive pawn
#

yeah

hallow acorn
winged ridge
hallow acorn
winged ridge
#

How big are your chunks

hallow acorn
#

32 units on x and z

winged ridge
#

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

languid pagoda
#

do asset bundles have to be created in by the project they''re loaded in?

hallow acorn
#

what do i have to offst it doesnt make sense in my head

winged ridge
# hallow acorn 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

hallow acorn
edgy sinew
#

⭐ 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)

winged ridge
slender nymph
winged ridge
# hallow acorn wdym?

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)

edgy sinew
naive pawn
slender nymph
edgy sinew
#

But, it seems to feel fine with Slerp πŸ€·β€β™‚οΈ can't really tell if it's better or worse than Lerp

naive pawn
#

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

edgy sinew
#

I see. But ... "Most games" use _ ?

naive pawn
#

I've switched my camera follow to use Vector.Slerp
are you referring to rotation or position here?

naive pawn
edgy sinew
edgy sinew
naive pawn
#

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

slender nymph
edgy sinew
naive pawn
#

that is the answer

edgy sinew
#

In a "you already know the answer bro" kinda way sadok

slender nymph
naive pawn
#

..because we just told you?

edgy sinew
#

I meant, thanks for confirming guys. I had a feeling Slerp wasn't right for position smoothing

naive pawn
#

if you're asking for confirmation, say so

edgy sinew
naive pawn
#

it just looked like you were asking the same question without applying any of the info we just gave

slender nymph
edgy sinew
naive pawn
#

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

calm agate
#

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

slender nymph
#

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

radiant voidBOT
calm agate
#

cost

slender nymph
#

why not look and find out?

errant knot
#

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

stray fog
#

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

Gist

GitHub Gist: instantly share code, notes, and snippets.

#

The camera is a child of head bone yes

earnest oak
#

why is my cinemachine camera y axes looping

rocky canyon
#

what do you mean by looping? what components are u using?

solar hill
#

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

rocky canyon
#

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"

rich adder
earnest oak
#

yes

#

like when moving camera y axes up up i go to the bottom rig

rich adder
#

unless its code related then share that

desert temple
#

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.");
            }
        }
    }
}```
stray fog
desert temple
#

Everything tells me it should work, but it isn't.

stray fog
solar hill
#

if so thats normally you just need to clamp the look.

violet shoal
#

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

solar hill
#

you can just tell us whats wrong

#

so we can help you

violet shoal
#

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

solar hill
#

ok we are going to need a bit more context, send us the script youre having the issue with

radiant voidBOT
violet shoal
#

'''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

solar hill
#

please look at the bot message

#

i sent it for a reason...

violet shoal
#
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());
            }
        }
        
    }
    
}

solar hill
#

those arent hyphens

#

okay so whats not working here?

#

which part in particular

violet shoal
solar hill
#

okay disregard that, tell me what part of the update isnt running at all?

violet shoal
solar hill
#

ok now its inside an if statement, have you debugged and ensured that your player, animation and rb isnt null?

sour fulcrum
solar hill
#

also i dont think its good to have a return if statement that early inside your update function...

violet shoal
solar hill
#

im not talking about errors

solar hill
#

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

violet shoal
solar hill
#

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

languid pagoda
solar hill
#

also perfect grammar and em dashes in comment blocks

#

typically indicates its code written by ai

rich adder
#

fixing broken ai code should not part of this channel

violet shoal
sour fulcrum
violet shoal
solar hill
#

we werent talking about you

solar hill
#

especially when you have a lot of if statements.

violet shoal
#

im questioning everything atp

solar hill
winged ridge
solar hill
#

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.

violet shoal
solar hill
#

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

winged ridge
#

or use a this.gameObject

solar hill
#

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.

solar hill
#

i think i need to be more confident in my coding skills lol

violet shoal
#

thank u so fucking much i was gonna cry very soon

ancient lotus
#

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

radiant voidBOT
rich adder
#

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"

ancient lotus
#

is it supposed to look like this on vs?

ancient lotus
#

Yeah I assumed as much

rich adder
#

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

ancient lotus
#

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

rough granite
#

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

winged ridge
#

Make a script that you can run from in editor to reset them all

cosmic dagger
rich adder
rough granite
rich adder
#

if you want mutable data that resets make a poco

rough granite
rough granite
rich adder
#

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

stray fog
#

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

rough granite
rich adder
sour fulcrum
# rough granite well i dont plan to redo all this again :/

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)

rich adder
rough granite
rough granite
sour fulcrum
#

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

rich adder
#

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

rough granite
sour fulcrum
rich adder
#

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

sour fulcrum
#

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

rich adder
#

ya TIL

rough granite
sour fulcrum
#

Thats not how you would use prefabs is it

rough granite
rich adder
rich adder
rough granite
sour fulcrum
fierce shuttle
sour fulcrum
#

making an instance of that so doesn’t magically replace any reference to the template with that instance

rough granite
rich adder
#

wait SOs have "Start" ?

fierce shuttle
#

They have "OnEnable"

sour fulcrum
#

the class using it, not the class itself

rich adder
#

ohh right thought they were doing it in the so itself

sour fulcrum
#

Though ScriptableObject.Awake and .OnEnable is a cursed rabbit hole

rich adder
#

yea

sour fulcrum
#

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

sour fulcrum
#

No, why?

languid pagoda
#

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

grand snow
#

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

sour fulcrum
#

I don’t ever intend to use il2cpp when I can make that choice for modding benefits so not sure

grand snow
#

well you can use mono for platforms that allow it

teal viper
# languid pagoda Because for whatever reason which is beyond my knowlege il2cpp generates signifi...

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.

hallow bobcat
#

guys its been 9 years

languid pagoda
hallow bobcat
#

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 😒

rich adder
#

this is a code channel..

hallow bobcat
#

oh yea

#

I like C#

rich adder
#

cool.

#

if you want casual chit chat use

#

!cs

radiant voidBOT
rich adder
#

this isnt place

hallow bobcat
teal viper
rich adder
languid pagoda
# teal viper This is kinda backwards thinking. You should worry about performance first, rath...

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));
    }
}
teal viper
#

You're not comparing apples to apples here. You should compare the IL code to C++.

grand snow
#

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

languid pagoda
grand snow
teal viper
#

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.

chrome pond
#

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

sour fulcrum
chrome pond
feral moon
sour fulcrum
feral moon
sour fulcrum
#

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

chrome pond
thorn holly
#

cause youll know whats going on in the code yk

rugged beacon
#

for highlight object is it usually add/remove mesh material, change mesh material shader or swap mesh material?

tough lagoon
#

Especially in the vr space

willow iron
#

is SceneManager.LoadSceneAsync still a thing? its in the docuimentation but its not recognized by unity, even when using UnityEngine.SceneManagment

tough lagoon
#

Yeah that isnt going anywhere anytime soon

feral moon
thorn holly
thorn holly
winged ridge
feral moon
thorn holly
#

I meant the issue that made you give up on making your own code and turn to ai

winged ridge
thorn holly
feral moon
feral moon
winged ridge
thorn holly
#

That was ai generated right?

feral moon
thorn holly
feral moon
#

how do you know what it is?

thorn holly
feral moon
feral moon
sour fulcrum
feral moon
thorn holly
sour fulcrum
feral moon
thorn holly
sour fulcrum
#

(I don’t think a package developer has been mentioned before has it)

feral moon
#

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

feral moon
narrow pulsar
#

is application.quit typically what ppl use to quit their games

#

cuz im testing it in editor

winged ridge
#

Okay so you're not the main developer, we got somewhere. Okay so in principle look at Vectors, transform and coroutines

narrow pulsar
#

im not sure if its actually quitting

sour fulcrum
narrow pulsar
#

cuz it still acts as if the games being played

winged ridge
#

But it only works once built

feral moon
winged ridge
thorn holly
sour fulcrum
ivory bobcat
thorn holly
#

You can’t go off of packages and ai alone

radiant voidBOT
thorn holly
#

There’s some great resources for learning unity here

feral moon
thorn holly
feral moon
narrow pulsar
#

AI is buns i agree

#

learned codependancy

sour fulcrum
thorn holly
thorn holly
feral moon
# thorn holly There’s some great resources for learning unity here

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

thorn holly
#

<@&502884371011731486>

feral moon
thorn holly
feral moon
winged ridge
#

Not the place and discussion to have here

thorn holly
#

And neither is anyone else

thorn holly
#

Just keep building your skill level and you’ll get there eventually

willow iron
#

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?

winged ridge
#

Is ("Die") your scene name?

#

And if so, is it added to your build list

willow iron
winged ridge
#

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);
    }
sour fulcrum
#

~~Unsafe use of that fader reference ~~

winged ridge
#

not the point, but Fader is static, and the whole thing is an object thats not destroyed

willow iron
#

started digging a little deeper, neither LoadSceneAsync nor GetActiveScene are recognized

winged ridge
#

im in 6.1...unless they changed that in 6.2?

willow iron
#

the exact error message in unity is
Assets/SceneManager.cs(7,24): error CS0117: 'SceneManager' does not contain a definition for 'LoadSceneAsync'

winged ridge
#

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

willow iron
winged ridge
#

ah dont worry, we have all been there

loud remnant
#

what is harder to code
unturned like inventory system
project zomboid like inventory system

jolly cloud
#

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.

teal viper
mint flicker
#

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

fierce shuttle
# loud remnant what is harder to code unturned like inventory system project zomboid like inven...

"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

fierce shuttle
# mint flicker hey can anyone recommend a good unity 2D enemy tutorial i need one that allows t...

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)

mint flicker
#

ohh will do

fierce shuttle
teal viper
#

"Both hard". Here, 2 words.

loud quest
#

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?

regal isle
#

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

regal isle
#

thank you

grand snow
#

You can add an event subscription to On Click there or do it in code

safe root
#

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.

grand snow
scarlet pasture
#

hey do this Discord have a "collaboration" channel, i want devolop a smallGame with somone. i didnt finde the Cannel so i asked here

radiant voidBOT
# wintry quarry !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**

scarlet pasture
#

Thank u!

safe root
grand snow
#

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

safe root
grand snow
#

!code sharing time then

radiant voidBOT
safe root
grand snow
#

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?

safe root
#

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

grand snow
#

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?

safe root
grand snow
#

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;

safe root
safe root
grand snow
#

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.

earnest oak
#

how do i switch my game from urp to built in rendering i used to be able to do it but it changed

rocky canyon
earnest oak
#

thanks alot that was my problem only changed it in Graphics settings

rocky canyon
#

URP not doing it for ya?

earnest oak
#

nah man not really has some bugs and overall for a retro style im more happy with built in

rocky canyon
#

probably builds better/ easier to run on all kinds of hardware too

earnest oak
#

yea and vertex shaders are better on built in do you use urp or built in

rocky canyon
#

i've swapped to URP for a while now..

#

working on swapping to the new input system next..

#

gotta stay ahead of the times πŸ€“

earnest oak
#

yea

rocky canyon
#

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

hot wadi
#

When should I use Addressables to load a scene?

rocky canyon
#

until they actually KO the entire Built-in pipeline

#

then i guess we're all moving to render pipelines 🀣

earnest oak
#

yea 🀣

#

till then ill be safe tho

rocky canyon
edgy cloak
#

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

rocky canyon
#

you'll have to elaborate a bit

edgy cloak
#

but would it really become outdated in 2 years?

#

uh-

rocky canyon
#

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

edgy cloak
#

i dont even understand what that means....

rocky canyon
#

u dont understand what no means?

edgy cloak
#

i meant the rb velocity thing

rocky canyon
#

the rest really isn't important

edgy cloak
#

i see

rocky canyon
#

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

edgy cloak
#

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

rocky canyon
#

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

edgy cloak
#

i was following along with the tutorial, just about 1 for 1???

rocky canyon
#

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..

edgy cloak
#

this is what its showing for me.

rocky canyon
#

did u drag that from the Scene?

#

or the Project Window?

edgy cloak
#

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?

wintry quarry
edgy cloak
#

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 πŸ’€

wintry quarry
#

Maybe it's not a good tutorial then

manic hatch
#

hello

#

i have issue

rocky canyon
#

and wont make the mistake of dragging the script into the slot and not the gameobject...

#

ur dragging the wrong thing into the slot..

edgy cloak
#

i now feel incredibly dumb.

rocky canyon
#

πŸ—’οΈ 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 πŸ˜‰ )

rocky canyon
#

even I made that mistake πŸ˜…

edgy cloak
#

makes me wonder why its like this tho tbh

rocky canyon
#

but now u know πŸ™‚

edgy cloak
#

until i inevitably forget because goldfish memory

rocky canyon
#

b/c the script has to be in the scene (to function)

edgy cloak
#

ah

rocky canyon
#

unless its a Static script or something (but you'll learn about that later on)

wintry quarry
rocky canyon
#

^ OOP bb 🀀

#

object based..

rocky canyon
manic hatch
#

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

rocky canyon
#

good luck.. don't pull ur hair out.. keep calm and carry on πŸ€ͺ

wintry quarry
thorn holly
rocky canyon
#

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

naive pawn
#

heh, don't jinx it

rocky canyon
#

i wish unity had a primitive wheel ..
could make the process much more intuitive..

hot wadi
edgy cloak
#

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?

thorn holly
edgy cloak
#

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

thorn holly
edgy cloak
#

yes

rocky canyon
# hot wadi So to my understanding, if I include all my scenes in build, it will increase th...

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.
scarlet pasture
#

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.).

thorn holly
# edgy cloak yes

So in your script you can say something like

TMP_text tmp = tmpObject.GetComponent<TMP_text>();
tmp.text = β€œwhatever you want”;
rocky canyon
# edgy cloak yes
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());```
edgy cloak
#

like i want it to dynamically show the HP in the top left corner or smth with how it changes

rocky canyon
#

whenever u take damage or get health you
update the player's health variable.. and then Update the UI right afterwards

thorn holly
rocky canyon
#
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}";
    }
}```
rocky canyon
thorn holly
#

Fair enough

rocky canyon
#

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

edgy cloak
#

i feel like i just got smacked in the head by a brick while trying to understand this

rocky canyon
#

yea, i think u just need to Marinate in some fundamentals !learn

thorn holly
rocky canyon
#

u got this noodle. i'll be ur wingman

fast relic
#

I'll just be watching silently

thorn holly
rocky canyon
#

all gucci

slender nymph
rocky canyon
#

i was wondering

#

i just thought inline commands were broken

edgy cloak
#

kinda lacking on time to marinate in code knowledge sadly

hot wadi
thorn holly
#

So there’s basically 3 steps to changing the players health:

  1. setting the health variable
  2. Changing the text that displays the health
  3. Updating the UI so that we can see the text change
#

Does that make sense?

grand snow
regal isle
#

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.

thorn holly
regal isle
#

let's assume I already have a working C# script that does all the functionality

#

there is No Function there

thorn holly
slender nymph
thorn holly
#

Does that make sense?

regal isle
#

@edgy cloak low key competing with me here

#

for the same project

#

with the same YT tutorial video

#

🫑

edgy cloak
#

kekw

#

nah tutorials can just be applied in a lot of places

edgy cloak
rocky canyon
grand snow
#

Addressable scenes should act the same as normal scenes in terms of how they are opened

thorn holly
# edgy cloak i think so yes. though i wonder *where* to assign it

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

grand snow
#

But with addressables we can have direct asset reference or indirect meaning no asset dep is made

thorn holly
#

Does that make sense?

loud remnant
#

i love how my text editor automatically includes using statements

#

like i access text in textmeshpro then it adds it by itself

fast relic
#

i mean yeah that's something id expect of most ides

loud remnant
fast relic
#

-# also assembly references are a different thing

edgy cloak
loud remnant
loud remnant
#

kachow

fast relic
loud remnant
#

auto add using statements go brrrrrr

thorn holly
fast relic
loud remnant
regal isle
#

I think I finally got the hang of it how to map the buttons

#

thanks to all

fast relic
fast relic
loud remnant
hot wadi
rocky canyon
#

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

scarlet pasture
rocky canyon
#

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

scarlet pasture
#

for answering

scarlet pasture
# thorn holly That looks good to me

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!

grand snow
thorn holly
loud remnant
fast relic
fast relic
#

if you think about it

loud remnant
#

unity engine

hot wadi
fast relic
#

and that is the one you need

#

it's really not that hard

loud remnant
loud remnant
#

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

fast relic
loud remnant
#

definitely didnt crash out over player movement script

naive pawn
loud remnant
#

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 πŸ—£οΈ πŸ”₯

naive pawn
#

then sure, but you gotta move away from that mindset if you want to learn and progress to making more complex things

loud remnant
#

btw what game should i make cuz i have no idea

naive pawn
#

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

loud remnant
loud remnant
fast relic
loud remnant
grand snow
fast relic
loud remnant
#

NO

fast relic
#

you can even make your own

loud remnant
hot wadi
naive pawn
fast relic
#

using is for namespaces, not scripts

#

a namespace is a collection of scripts

loud remnant
naive pawn
#

a namespace is a collection of types, to be pedantic

#

you can have multiple namespaces in a single script

fast relic
loud remnant
#

english is my 2nd language

naive pawn
fast relic
#

ugh fine

naive pawn
#

could say namespaces hold classes/structs/interfaces/enums

fast relic
#

-# let my midnight brain be okay

loud remnant
#

they are speaking mozart

naive pawn
#

it's kinda disappointing unity treats component classes and scripts as synonyms tbh - so this isn't really your fault

fast relic
#

nah i know the difference im just sleepy

naive pawn
#

nah i mean in terms of like, ideal communication with beginners

loud remnant
tender mirage
#

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

naive pawn
#

inner classes can be private/protected/internal/etc, and that could make sense

rocky canyon
#

am i trippin? whats wrong

#

πŸ€”

naive pawn
#

(save and refresh first ofc)

rocky canyon
#

no oddly enough

naive pawn
#

sounds like either lagging lsp or non-configured

#

try restarting the lsp i suppose

rocky canyon
#

its yankin my chain this morning

rocky canyon
#

πŸ€¦β€β™‚οΈ πŸ€ͺ not a clue bro

slender nymph
#

just vs code doing vs code things

naive pawn
#

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...

rocky canyon
#

i think it may correspond to my internet connection πŸ‘€ altho thats just speculation

earnest oak
#

switching to built in is like one of the best choices ive made

edgy sinew
earnest oak
#

yes

slender nymph
#

well that's not code related

manic hatch
#

@rocky canyon Thank you T-T I did it!

#

it is working like intended!

polar dust
#

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

tender mirage
#

ahh

#

coding style

#

got it

polar dust
#

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

sullen epoch
#

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?

polar dust
#

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(){}
}```
hexed terrace
# tender mirage i always write private

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

polar acorn
polar dust
#
Foo thing = new Foo();```Will produce an identical result whether you had a plain constructor or not
polar acorn
#

Well, to be more precise, they can have them, but calling them won't actually create anything since they can only exist on GameObjects

polar dust
#

At times it can feel a little frustrating that you cant use a constructor with them

polar acorn
#

You can just create a function called something like Init() and call it after adding the component

polar dust
#

Yeah thats what I typically do. But each time I think "man it would be convenient if I could just use a constructor"

sullen epoch
#

Yeah i thought so, as the only documentation i could find was for C# base classes. Thanks for the clarification

slender nymph
polar dust
#

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"

sullen epoch
#

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 πŸ˜…

edgy sinew
#

⭐ hi all. Project runs better in Editor than exported MacOS .app? notlikethis
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.)

slender nymph
grand snow
edgy sinew
grand snow
red igloo
#

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?

edgy sinew
wide aspen
#

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.

edgy sinew
earnest oak
#

wsp?

edgy sinew
#

Hey

scarlet pasture
#
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
earnest oak
#

are u asking me?

scarlet pasture
#

somthing like is 85% of the Coroutine Cooldown Done and the play pressing the Button again do a antoher Attack?

scarlet pasture
#

i need every help

earnest oak
#

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

edgy sinew
scarlet pasture
#

what is that?

edgy sinew
earnest oak
#

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

edgy sinew
#

Save yourself now, your code is brutal to read currently bro

scarlet pasture
#

u right

#

i forget it

earnest oak
#

let him find out on his own

scarlet pasture
#

i mean what would be better? State Machine or Coded?

earnest oak
#

jk but i mean his script isnt awful

scarlet pasture
#

wait is Enum a State Machine?=

#

i used Enums for my Enemy

#

like Walking, Attack etc

edgy sinew
#

Yeah. Hierarchical state machines are a little cooler, and take advantage of Polymorphism

scarlet pasture
#

Polymprphsim

earnest oak
#

sorry if my english isnt that good

scarlet pasture
earnest oak
#

oh alr

scarlet pasture
scarlet pasture
earnest oak
#

thats crazy

scarlet pasture
#

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

edgy sinew
scarlet pasture
#

helllll hnahhhhh

#

this looks like hell

#

okay no its actually looking alr

#

so its better to use a Costum timer? and not Coroutines?

edgy sinew
#

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

meager flume
#

hi can somone help me with somthing

#

i small issue but i am new i dont know

edgy sinew
meager flume
#

i have loop floor here

scarlet pasture
meager flume
#

but i am getting this line

meager flume
red igloo
meager flume
#

last option was here

red igloo
#

does the jump height value need to be much higher?

edgy sinew
meager flume
edgy sinew
wide aspen
edgy sinew
#

Are you using Pixel Perfect camera?
There's also some crazy '1 pixel padding' trick people are saying fixes this kind of issue.

red igloo
meager flume
#

one when i chnage the draw mode to tiled and the width this start showing the ground is loop

wide aspen
# meager flume

check the sprite editor maybe you have an extra transparent line of pixels at the end or start?