#💻┃code-beginner

1 messages · Page 699 of 1

naive plank
#

Yeah, I ment explicitly for singletons

rich adder
#

are you like doing all this last minute 🤔

inland gazelle
#

Made the script a component of an object, then passed in the object and grabbed the component

rich adder
#

so in the inspector ?

inland gazelle
inland gazelle
#

She's fine now dw

rich adder
#

ohh alr.. teacher didn't want to give you extension time ?

naive plank
#

Let's see if it works now:)

rough granite
inland gazelle
naive plank
#

+1 Last minute is the way

inland gazelle
#

IM SORRYYYY lfmao

naive plank
#

All my courses so far are 2 months, I do everything the last 2 weeks lol

frigid sequoia
#

Can I not like, do this on the editor? Do I have to make a script for that?

naive plank
#

you can

#

Let me check my script quickly

rough granite
#

had a coworker complain to me cause i called my classes scripts 😅

naive plank
frigid sequoia
#

Like, the whole point is, I wanna keep it simple, not use a script, that's why I am using the legacy animation on these and not an animator lol

naive plank
#

ow wait

#

Im not sure then, im sorry

sour fulcrum
#

its almost giving nigel thornberry 😄

rich adder
drowsy flare
inland gazelle
#

OK LAST QUESTION FOR ME YALL

#

so i have it such that the pause menu is an additive scene

#

is that the best idea? who knows but not important

#

I have the system like this, where theres a variable set to 0 at the top

#

that way you cant spam pause and create a million pause menus

#

but now, when I unpause and puase normally, the pause menu does not show up again

rough granite
#

you load a scene for when pausing? odd

inland gazelle
#

correct

#

but rn it gets the job done

#

is there anything that would cuase this behavior?

#

this is the pause trigger

#

its also where i stop time

rough granite
inland gazelle
#

I pause and resume, everytihng is fine

#

but when i puase a second time, the pause menu never shows up

#

though time does freeze

rough granite
#

not sure i don't use scenes for my pause menu also isnt common to do it this way

frigid sequoia
#

Are u like.... loading the pause menu as an additive scene???

inland gazelle
#

yes

frigid sequoia
#

Why???

inland gazelle
#

cause i dont have time for a better solution rn

frigid sequoia
#

That's like way more complex than it needs to

frigid sequoia
rough granite
frigid sequoia
#

Just pack the scene that is the menu into a gameObject, place it on the main scene and toggle the object on and off when pausing and resuming

inland gazelle
#

yup, thanks for the advice!

#

got it in after a bandaid fix

#

dang grandma tripping like 3 days ago 😭

#

/j to be clear

crimson sluice
#

I wrote the code gay instead of say

livid mirage
#

hello everyone, is this where i ask for help?

sharp solar
#

yes

livid mirage
#

ok i'm new to unity. i have an issue with player movement, i have two scripts controlling 1) Basic Movement left and right 2) Jumping. How do i get the movements to be able to be pressed together? example press "D" and "Space" together

sharp solar
#

show code snippet

#

sorry

naive pawn
naive pawn
glossy carbon
#

Hello everyone, how are you all

livid mirage
#

sorry if i dont respond after this, im gonna be out for a bit but ill check suggestions when i come back. Thanks alot 😄

eternal falconBOT
naive pawn
#

your movement script is resetting y velocity to 0
your jump script is resetting x velocity to 0
change both to only modify the dimension they actually care about

glossy carbon
#

Can i ask a question in here ? its about the camera following the sprite

sharp solar
sharp solar
#

just add current vertical velocity to your move script and current horizontal velocity to your jump script

naive pawn
#

!screenshot

#

ah, which command is it...

#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

glossy carbon
#

I'm stuck with getting my camera to follow the sprite without turning, I moved the camera out so its not a child of the sprite and added a script i found on google but when i add the sprite to the script the camera background covers everything in the scene with the background colour

naive pawn
#

is the camera perhaps getting flung off the map

naive pawn
glossy carbon
#

Sorry im very new and dont know what the code command is

naive pawn
sharp solar
glossy carbon
#

O i thought screen shots were ok

north kiln
#

Also, just use cinemachine, it's worth learning as in most cases you'll end up making your camera logic more complicated in the future anyway

naive pawn
north kiln
naive pawn
#

if you have nothing of value to add you're free to leave, quartz

glossy carbon
#

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform Player;
    public Vector3 Offset;

    void LateUpdate()
    {
        if (Player != null)
            transform.position = Player.position + Offset;
    }
}

naive pawn
#

thank you

#

couldn't this logic in particular just be having the camera as a child of the player? or are you planning to add more logic in the future?

glossy carbon
#

truthfully im not sure

naive pawn
#

what about the second question

glossy carbon
#

im trying to jsut get my sprite to turn without the camera turning as a input movement

naive pawn
#

what do you mean by turn?

sharp solar
#

what have you set offset as

glossy carbon
naive pawn
#

is that supposed to be a gif, or...?

glossy carbon
#

so at the moment the camera changes direction but the spaceship always points upwards

#

screen shot of the game

naive pawn
#

ok, so you didn't actually answer my question

glossy carbon
#

so you cna see the stars moving underneath the sprite but the sprite never turns

sharp solar
#

youre sure camera isnt a child of the sprite?

glossy carbon
naive pawn
#

so your player is rotating on z?

glossy carbon
#

I did the new movement in unity (atleast the tutorial said it was new )

naive pawn
#

you are not answering my question

sharp solar
#

just to be sure you havent got the movement script attached to the background right?

naive pawn
#

how are you turning the player

#

this is unrelated to input

glossy carbon
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class NewBehaviourScript : MonoBehaviour
{
    [SerializeField]
    private float _speed;
    
    [SerializeField]
    private float _rotationSpeed;

    private Rigidbody2D _rigidbody;
    private Vector2 _movementInput;
    private Vector2 _smoothedMovementInput;
    private Vector2 _movementInputSmoothVelocity;

    private void Awake()
    {
        _rigidbody = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        SetPlayerVelocity();
        RotateInDirectionOfInput();
    }

    private void SetPlayerVelocity()
    {
        _smoothedMovementInput = Vector2.SmoothDamp(
            _smoothedMovementInput,
            _movementInput,
            ref _movementInputSmoothVelocity,
            0.1f);

        _rigidbody.velocity = _smoothedMovementInput * _speed;
    }

    private void RotateInDirectionOfInput() 
    {
        if (_movementInput != Vector2.zero) {

            Quaternion targetRotation = Quaternion.LookRotation(transform.forward, _smoothedMovementInput);
            Quaternion rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, _rotationSpeed * Time.deltaTime);

            _rigidbody.MoveRotation(rotation);
        }
    }

    private void OnMove(InputValue inputValue)
    {
        _movementInput = inputValue.Get<Vector2>();
    }
}


naive pawn
#

and this is on the player, correct?

glossy carbon
#

yes sir

sharp solar
#

check

glossy carbon
#

Im sorry for not knowing all the answers

#

I started yesterday

#

Im a massive NOOB

sharp solar
#

that is why youre here

north kiln
# glossy carbon

The offset is set to 0, so your camera will be directly on top of the player?

sharp solar
#

wouldnt be a very good code beginner channel if you werent welcome

sharp solar
naive pawn
#

oh yeah you do need a z offset, usually -10

#

cameras render what's in front

glossy carbon
#

I can change the offset but i was doing a topdown not a isometrical view , does that matter?

naive pawn
#

no

#

this is just how far the camera is from the plane of the world

sharp solar
#

set it to 0, 0, -10 see what happens

naive pawn
#

you're working in 2d, so you'll be using X and Y and ignoring Z
what x/y represent is dependant on the perspective, but it'll still be x/y

glossy carbon
#

You legends

#

that worked first time Woop Woop

#

Thank you

#

really apprciate that

sharp solar
#

does anyone know why that worked 😭

#

z issue fixes rotation issue

naive pawn
#

z issue fixes rendering issue, not rotation

north kiln
#

[when adding] the script the camera background covers everything in the scene with the background colour

#

Rotation was never the issue

sharp solar
#

mb

#

i was thinking of this

glossy carbon
#

I took a moment to think about this and i understand now the problem

#

I needed to back teh camera up above my scene so it could see it

#

Thats right ?

sharp solar
#

yes

glossy carbon
sharp solar
#

as vertx and Chris said camera only sees whats infront of it

glossy carbon
#

awesome i understand NICE

#

Thanks again

#

on to making a mini map now

#

lol

thick saddle
#

Hey in my top-down game I'm trying to make it so when I hit this enemy it goes in the direction the player is facing (the player is facing the mouse btw). The first method is for when it bounces off of walls which works and the second one is when it gets hit which doesn't work, it usally makes the enemy's velocity slow waaay down. Any help is appreciated

naive pawn
eternal falconBOT
thick saddle
#

in the class

frail hawk
#

this is the declaration, where do you set it?

thick saddle
#
private void LateUpdate()
{
    transform.rotation = Quaternion.identity;
    rb1 = GetComponent<Rigidbody2D>();
    if ( rb1 != null )
    {
        lastVelocity = rb1.linearVelocity;
    }
}
naive pawn
#

🤨 where is TakeDamage called from? specifically via what message

#

also you should cache or serialize the rigidbody instead of getting it every update

thick saddle
#
public class Weapon : MonoBehaviour
{
    public float damage = 1;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        NormalEnemy enemy = collision.GetComponent<NormalEnemy>();
        if (enemy != null )
        {
            enemy.TakeDamage(damage);
            
        }
    }
}
naive pawn
#

(and there you should use TryGetComponent, but we can worry about that later)

#

wouldn't you want to set lastVelocity in FixedUpdate so it syncs with the loop cycle where the trigger happens

frail hawk
#

can you Debug.Log the mousePosition please? how does it look like, you are using a Vector2

thick saddle
#

bc the camera follows the player and it was a different value after moving

frail hawk
#

yeah ScreentoWorldPoint is a Vector3 in world space

thick saddle
frail hawk
#

you can but you need to also define the z axis , maybe manually

thick saddle
sour fulcrum
#

it is but only with 2 values

frail hawk
#

yeah this

thick saddle
#

am I misunderstanding this then?

sour fulcrum
#

its stored as a vector3 but only the x and y have anything afaik

frail hawk
#

yeah z is unassigned

thick saddle
#

is that a problem? I'm not rly messing with the z axis

#

do I need to set it to 0 or something to fix it?

frail hawk
#

scroll up and see what i said

#
  Vector3 mousePos = Input.mousePosition;
  mousePos.z = Camera.main.nearClipPlane // or some hardcoded value as you wish;
  Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePos);
  Debug.Log(worldPosition);```

this will give you proper values, first you assign the mousePos than you feed that into the ScreenToWorldPoint
thick saddle
#

thank you 🫡

raw tulip
#

I imported the first person and third person starter assets, how can I make it such that I keep the armature but have an fps cam and third person cam?

#

I have a script that switches between the cameras, but everytime I try making an fps camera a child of the armature head bone, the movement and looking around gets very wonky

#

Or is there a way I can duplicate the third person camera put it in front of the head and have it look and move like a fps?

frail hawk
#

create an empty gameobject at very top of the player hierarchy and attach the cam to this gameobject

raw tulip
frail hawk
#

yes

raw tulip
#

So duplicate it yeah?

frail hawk
#

you can duplicate camera there is no problem, at runtime you can just disbale and enable them

frail hawk
#

i have no clue which one you want to duplicate, it is your game

raw tulip
frail hawk
#

looks like you are using cinemachine

raw tulip
frail hawk
unborn veldt
#

Hi! I'm coding an UI bar for entities that looks at the camera. Currently I did everything but I can't get it perfectly horizontal in respect to the camera

#

That's a screen. Full health bar, correctly facing the camera, but not horizontal

#

!code

eternal falconBOT
unborn veldt
#
void Update()
    {
        if (showCooldown > 0)
        {
            healthBar.SetAmount((entity.health / entity.maxHealth) * 100);
            healthBarObject.transform.position = healthBarPosition.position;
            healthBarObject.transform.LookAt(
                healthBarObject.transform.position +
                (healthBarObject.transform.position - playerCamera.transform.position)
            );
            showCooldown -= Time.deltaTime;
            if (showCooldown <= 0)
            {
                healthBarObject.SetActive(false);
            }
        }
    }

That's the code I'm using to rotate it towards the camera.

#

(only the LookAt row actually).. How can I fix that?

gaunt raptor
#

Quick question how you make a boss fight in 2d side scroll game like blasphemous or somthing like in cuphead

cosmic dagger
frosty hound
unborn veldt
#

the health bar is an object spawned in the world. I used this approach because using an UI element would require instantiating the health bar in the main player canvas, which is not easy to reference

sour fulcrum
#

Anything is easy to reference, you might just be missing some knowledge in your toolkit 😄

naive pawn
cosmic dagger
naive pawn
#

so you get ui in the world

unborn veldt
sour fulcrum
naive pawn
#

hold on i think im missing context

cosmic dagger
#

I spawn all my enemy health bars in their own canvas so I can hide them, if necessary . . .

unborn veldt
#

like this

sour fulcrum
#

clicked that embed and got ai keanu reeves ad im gonna kill myself

hexed terrace
#

You can use more than one canvas

unborn veldt
cosmic dagger
# unborn veldt 3d

You should be using 2d instead. When an enemy is spawned, instantiate a UI health bar and pass it the enemy information . . .

naive pawn
sour fulcrum
unborn veldt
# sour fulcrum this tutorial is for a 2d game where there's no rotational depth, its not direct...

well another one (https://www.youtube.com/watch?v=cUQVLgohAjY) does the same, and it doesn't align the health bars

Learn how to make Health Bars that stay above the heads of units in World Space!
A common need in games is to show Health Bars over some enemy or unit. In this tutorial we'll take a look at one way to achieve that in a way that enables us to retain the benefits of sliced and filled Sprites.

I also discuss some of the "gotchas" that you may enc...

▶ Play video
#

as you can see from the thumbnails

sour fulcrum
#

yeah?

naive pawn
cosmic dagger
naive pawn
#

that doesn't tell me anything new

unborn veldt
#

yeah what do you mean by "using 2d"

naive pawn
#

this is all in a 3d world, no?

unborn veldt
#

how am I supposed to just "use 2d" in a 3d world

sour fulcrum
#

i mean it was a response to you suggesting a world space camera

naive pawn
#

using 2d would not make them face the camera, they would face the XY plane

sour fulcrum
#

i said 2d when i should have said screen space

#

been a long day, apologies

unborn veldt
#

the object has a canvas, it doesn't seem like it's doing anythig. As far as I understand, it's because the object with the canvas is still in 3D

#

it's making me render image components, but definitely not fixing the problem

naive pawn
grand snow
#

its not a great idea perf wise to have many world space canvases for some health bars btw

unborn veldt
#

...isn't there a way to just rotate the already existing bar correctly?

naive pawn
#

hm, why not? isn't the cost of a canvas from dirtying/rerendering them?
so having it all in a single canvas would make any health change/position change dirty the whole thing, no?

unborn veldt
#

everything works flawless but a single rotation

unborn veldt
#

yea but I have no clue how to do it ahaha

grand snow
#

yes and we cannot benefit from things like gpu instancing as they are all difference meshes

sour fulcrum
naive pawn
grand snow
#

better if they are all the same mesh + shader doing the health bar for batching benefits

unborn veldt
grand snow
#

tl;dr many canvases for a health bar in world bad

sour fulcrum
#

no batches?

cosmic dagger
unborn veldt
grand snow
#

If its done in screen space UI it means you have to update their positions yourself (world > screen) but its cheaper perf wise

unborn veldt
#

@naive pawn how do I do what you said? It seems like nothing I do is working

sour fulcrum
#

Like instead of talking to unity ui just drawing to screen yourself

naive pawn
# unborn veldt yea but I have no clue how to do it ahaha

im not sure if there's a more direct way to do this, but here's one way (should work afaik, but untested)
do WorldToViewportPoint on the transform position
set depth to 0 on the result
do ViewportToWorldPoint on that
look at the result point

grand snow
unborn veldt
#

Like that?

#

it's not working

naive pawn
#

damn.

#

how isn't it working though

unborn veldt
#

The bar is tilted as before (I forgot to invert the camera position so it's actually backwards, that's why it's grey)

#

ehhh I'm just gonna go with the boring and problematic UI solution if I can't tilt that bar, at this point it's easier to do that..

naive pawn
grand snow
#

a canvas component can be used inside a root canvas to have smaller groups that can cause redraws
canvas graphic drawing uses batching so many health bars using the same textures/material should get batched together
this is why many single world space canvases in scene is shit

naive pawn
#

ah, i wasn't really familiar with batching

grand snow
#

Unity themselves recommend not having 1 canvas with everything in it and using canvases within to split up things

naive pawn
#

so separate canvases are much worse if they have the same assets, because that means batching doesn't happen?

#

does that also apply with 2 canvases that don't use the same assets?

cosmic dagger
#

I thought it was normal to use multiple canvases and keep the ones that constantly update in their own to separate from static UI . . .

grand snow
grand snow
#

frame debugger will answer these questions anyway, i know it will batch within a canvas (e.g. 20 images using the same spritesheet/sprite with similar draw order)

naive pawn
#

ah i think i misphrased my question

#

i mean between these 4 scenarios:
A1: 2 canvases both using asset X
A2: a single canvas having 2 instances of asset X
B1: 2 canvases, one using asset X, the other using asset Y
B2: a single canvas with asset X and Y

if both X and Y dirty the canvas, batching makes a difference between A1 and A2, but not between B1 and B2, right?

#

or i guess, batching will apply to A2 but not B2?

grand snow
#

I think only A2 will batch

naive pawn
#

well, that was a lot of words for a simple answer
i really need to get better at phrasing my questions lmao

grand snow
#

its a bit confusing. I just checked something in what im working on rn and 3 world space canvases with the same content are not batched but is in a "render sub batch" group

#

doesnt behave like when multiple graphics are batched in 1 draw call

raw tulip
#
using Mono.Cecil;
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    [SerializeField] private float AnimBlendSpeed = 8.9f;
    private Rigidbody _playerRigidbody;
    private InputManager _inputManager;
    private Animator _animator;
    private bool _hasAnimator;
    private int _xVelHash;
    private int _yVelHash;


    private const float _walkSpeed = 2f;
    private const float _runSpeed = 6f;
    private Vector2 _currentVelocity;



    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        _hasAnimator = TryGetComponent<Animator>(out _animator);
        _playerRigidbody = GetComponent<Rigidbody>();
        _inputManager = GetComponent<InputManager>();

        _xVelHash = Animator.StringToHash("X_Velocity");
        _yVelHash = Animator.StringToHash("Y_Velocity");


    }

    private void FixedUpdate()
    {
        Move();
    }


    private void Move()
        {
            if(!_hasAnimator) return;

            float targetSpeed = _inputManager.Run ? _runSpeed : _walkSpeed;
            if(_inputManager.Move ==Vector2.zero) targetSpeed = 0;

                
            _currentVelocity.x = Mathf.Lerp(_currentVelocity.x, _inputManager.Move.x * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);
            _currentVelocity.y =  Mathf.Lerp(_currentVelocity.y, _inputManager.Move.y * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);

            var xVelDifference = _currentVelocity.x - _playerRigidbody.linearVelocity.x;
            var zVelDifference = _currentVelocity.y - _playerRigidbody.linearVelocity.z;

            _playerRigidbody.AddForce(transform.TransformVector(new Vector3(xVelDifference, 0 , zVelDifference)), ForceMode.VelocityChange);
            


            _animator.SetFloat(_xVelHash , _currentVelocity.x);
            _animator.SetFloat(_yVelHash, _currentVelocity.y);
        }

}
#

Does anyone know why when my character moves he slides around and the proper animations don't play?

wintry quarry
raw tulip
wintry quarry
#

that's step one

rough granite
wintry quarry
raw tulip
#

What's the superior alternative?

wintry quarry
#

it's not about alternatives

#

it's about what you are actually trying to achieve

rough granite
wintry quarry
#

If you want direct analog control without extra "acceleration", you shouldn't be using anything - just feed the input directly into the velocity (with some scaling factor)

rocky canyon
# raw tulip What's the superior alternative?

lerps and slerps are still solid
but you learn other things like SmoothDamp, MoveTowards, etc
all kinda have their own use-cases

and then theres Tweening Libraries (DoTween, LeanTween, PrimeTween etc)
may want to look into those at some point

rocky canyon
#

tweens can use "curves" and they have built-in functions for almost everything related to unity
positioning, rotations, scaling, UI positioning, single values, colors, rigidbodies, and the list goes on

#

i used to animate everything.. like a door that opened -> animation, a ui panel that faded in and out -> animation.. it wasn't until i was told to be cautious about animating my UI that i discovered it.. and for simple animations theres no better alternative imo

barren pilot
#

How/where can I store changing data?
Context: I am creating a game involving autobattle heroes. Each hero will have items equipped. Each item will have mods that can be changed through crafting. I am thinking of storing mod information as scriptableobjects, as mod information shouldn't change. I am a bit stumped on how to store the item information, as the mods on an item can change through crafting (e.g., rerolling a mod value within a mod-defined range).
I am hesitant to use monobehaviour because the items aren't really interacting with things in the game - they're more like data containers that are themselves stored in the hero they're equipped to or the master inventory.
But i am also hesitant to use scriptableobjects, which according to what i've seen online, are static, so shouldn't be able to store changing data.

frail hawk
#

a json file or xml would do it too

barren pilot
#

Will the plain c# class need to be instantiated on a gameobject each time I generate a new item? or can i simply generate a new Item and store it like a variable in a hero/inventory?

cosmic quail
#

or hero class

barren pilot
# frail hawk a json file or xml would do it too

I feel this would be inefficient especially because of crafting during runtime - i envision changing the item multiple times a second during crafting, wouldnt it be inefficient to store it as a file? i would probably store it as json at the end of session

keen cradle
#

in short
First time I visited ECS

namespace Game.Player { 
    unsafe partial struct PlayerMoveSystem : ISystem {
        void OnUpdate(ref SystemState state) { 
            foreach ((RefRW<LocalTransform> transform, RefRO<PlayerData> data, RefRO<PhysicsCollider> collider) in SystemAPI.Query<RefRW<LocalTransform>, RefRO<PlayerData>, RefRO<PhysicsCollider>>()) {
                float3 moveDirection = new float3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
                moveDirection *= Input.GetKey(KeyCode.LeftShift) ? data.ValueRO.RunSpeed : data.ValueRO.Speed;
                moveDirection *= SystemAPI.Time.DeltaTime;

                if (math.lengthsq(moveDirection) < 0.0001f) {
                    continue;
                }

                //moveDirection = transform.ValueRO.TransformDirection(moveDirection);

                PhysicsWorld physics = SystemAPI.GetSingleton<PhysicsWorldSingleton>().PhysicsWorld;


                ColliderCastInput input = new ColliderCastInput {
                    Collider = collider.ValueRO.ColliderPtr,
                    Orientation = transform.ValueRO.Rotation,
                    Start = transform.ValueRO.Position,
                    End = transform.ValueRO.Position + moveDirection
                };
                if (physics.CastCollider(input, out ColliderCastHit hit)) {
                    float3 normal = hit.SurfaceNormal;
                    float3 remainingMove = moveDirection;

                    float3 slide = math.normalize(math.projectsafe(remainingMove, math.cross(normal, math.up())));
                    transform.ValueRW = transform.ValueRO.Translate(slide * math.length(remainingMove) * (1f - hit.Fraction));
                    Debug.Log($"collision");
                } else {
                    transform.ValueRW = transform.ValueRO.Translate(moveDirection);
                }
            }
        }
    }
}```
Why the hell does the player yeet into the void when pressing A or D?
slender nymph
red igloo
#

I am making checkpoint system where the player enters the checkpoint trigger it should save the players position to the spawn point and the kill player collider should teleport the player to the spawn point. I have 2 scripts one will handle saving the players position to the spawn point and the other will teleport the player to the spawnpoint

red igloo
#

right now if I enter the checkpoint trigger it will teleport the player to the spawn point which I want but I only want it to teleport when I hit kill player collider

cosmic dagger
#

Basically, you only want to store the spawn point position when you reach the checkpoint, then use that position to set the player there when they respawn . . .

red igloo
cosmic dagger
red igloo
# cosmic dagger Yep . . .

so in the other script thats attached to the kill player collider should I do
_player.positon = currentCheckPoint.position

#

when I try to reference the currentCheckPoint.position it doesn't recognise it.

grand snow
#

If you have many Checkpoints this wont really do anything useful
It should be that the checkpoint script updates something on Player so it knows what the latest checkpoint is

#

then on death it can check if its not null and move position to the checkpoint pos

red igloo
grand snow
#

yea i said the same thing?

grand snow
# red igloo how should I do it? Imm gonna be having more checkpoints later on

the checkpoint script should do something like:

[SerializeField]
int order;

private void OnTriggerEnter(Collider other)
{
    if (other.TryGetComponent(out var player))
    {
        if (player.checkpoint == null || player.checkpoint.order < order)
        {
            player.checkpoint = this;
        }
    }
}

then in your player script on death you can do transform.position = checkpoint.transform.position; (if not null)

grand snow
#

yea. Ideally it would be done via a function on TeleportPlayer but looks good

red igloo
#

I just tried it and it doesn't work

grand snow
#

er actually your second picture shows a logic problem

#

the "checkpoint reference" should be stored on the player object

#

the death area trigger can tell the player to move to the last checkpoint

red igloo
grand snow
#

up to you. If you have a main "Player" script to handle stuff like this it can go in there:

void UpdateCheckpoint(Checkpoint newCheckpoint);
void RespawnAtCheckpoint();
red igloo
grand snow
#

no its just an example of the functions you could make 😐

red igloo
rough granite
#

I feel like you are way over complicating this

grand snow
# red igloo This is soo confusing if I were to put the functions in my script what would I s...
public class Checkpoint : MonoBehaviour
{
    public int order;

    private void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent(out var player))
        {
            player.UpdateCheckpoint(this);
        }
    }
}

public class Player : MonoBehaviour
{
    private Checkpoint checkpoint;

    public void UpdateCheckpoint(Checkpoint newCheckpoint)
    {
        if (checkpoint == null || checkpoint.order < newCheckpoint.order)
        {
            checkpoint = newCheckpoint;
        }
    }

    public void Respawn()
    {
        if (checkpoint != null)
        {
            transform.position = checkpoint.transform.position;
        }
    }
}

public class RespawnArea : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent(out var player))
        {
            player.Respawn();
        }
    }
}

have a complete example

#

plz try to understand the flow of logic as you seem to have a hard time understanding

rough granite
grand snow
#

its really not

rough granite
#

Meaning it's over complicated

grand snow
#

This is what I deem to be good design so you do you

rough granite
nova kite
#

how is TBOI's random generative rooms work? because it's not fully random so it's not picking from a pool of enemies but it's random enough to not be the same every time

grand snow
crystal rain
#

Does anyone know how to get past a hidden code system

timber tide
#

konami code

polar acorn
#

sudo rm -rf *

crystal rain
#

What?

polar acorn
#

Ask a stupid question get stupid answers

eternal needle
crystal rain
polar acorn
crystal rain
#

But it wasn’t really an answer

eternal needle
polar acorn
crystal rain
#

How was that not a question?

polar acorn
#

Provides zero information and is fundamentally unanswerable

crystal rain
#

You could have just asked for further explanation.

polar acorn
#

Nah this way's more fun

south nexus
#

hey im trying to make a top down rpg game and im pretty new to coding so ive mostly been following tutorials and stuff but im having issues on how to make enemys attack where the player is like for example playing the attack down or up animation depending on where the player is. is there any tutorials or information about this?

crystal rain
rich adder
#

there isn't going to always be a video for how to do this and that, it takes years of experience

eternal needle
crystal rain
south nexus
south nexus
crystal rain
#

I am decently new and I was wondering what coding software I should use

eternal needle
# south nexus well for example flipping the hitbox and playing different animations depending ...

i dont know what you mean with "depending if the player is up or down". up or down relative to what?
also you dont need to manually flip the hitbox. have it as a child of some object in your character and itll move around along with the animations.
Before you worry about doing this efficiently, first worry about doing it once. there isn't really a way to do animations more efficiently, at the end you're going to be interacting with the animator component anyways. You would typically just want to be interacting with it through one central script and thats fine enough

eternal falconBOT
crystal rain
#

Yes

#

I am on Mac so idk what to use

#

Because most of the systems are windows

rough granite
crystal rain
#

It says visual studio code not just visual studio

rough granite
#

What?

ivory bobcat
ivory bobcat
rough granite
# ivory bobcat <https://learn.microsoft.com/en-us/visualstudio/releases/2022/what-happened-to-v...

They can still install visual studio just it wont get updates https://learn.microsoft.com/en-gb/answers/questions/2236094/visual-studio-for-mac

Hello, Community, how are you? I would like to know. I've not long found out that Visual studio for mac has reached its end-of-life period. Is visual studio code exactly like the Original? I went through the old downloads & downloaded the 22 version

crystal rain
#

Thanks

raw tulip
#

When my rigidbody player steps on uneven terrain, say a slope, or jumps on a box, he starts rotating jitterely on his own in turn causing my camera to rotate. Anyone have any ideas? Does this sound familiar?

ivory bobcat
#

It doesn't sound like a beginner coding question

raw tulip
rich ice
eternal falconBOT
edgy pier
teal elk
#

How do I properly parent items to a player joint without a weird rotation and pivot point , so they tem can look proper with my animation

edgy pier
#

because if it's specifically this box, I'd say you need a box carrying animation.

raw tulip
edgy pier
raw tulip
edgy pier
teal elk
# edgy pier What is it exactly youre trying to achieve?

i have the animation. What I mean is when I parent it, I want it in a specific position, but I don't understand Unity transforms properly to position it the way I want. In the code, I'm setting the parent to my rig prop joint transformation, but the crate is under the floor when parented and with rotations.

edgy pier
#

so the box is being dragged through the ground

#

you can do SetParent(transform, false)

#

(you can overload the method, if you do not the worldPositionStays param is set to true)

livid canopy
#

guys i need help with a script that can move a car properly

#

where can i find one?

edgy pier
livid canopy
edgy pier
#

I bet you can find insane assets on the asset store that do that.

livid canopy
#

ok thanks for the info i have never searched in the asset store

wicked cairn
#

Any idea for VS ide resizing this area? it automatically went wide

nova kite
eternal needle
# nova kite Oh not every feature could be re coded in Unity?

im not sure how you got that from what I said. I meant that you're asking a unity server about how a very specific game writes its logic. It's incredibly unlikely that anyone here knows, and even if they do, this would be better in a forum/server dedicated to that game

edgy pier
#

ooooo you mean the binding of isaac.

sour fulcrum
# nova kite how is TBOI's random generative rooms work? because it's not fully random so it'...

bawsi is correct but here's a few general pointers on that kind of thing,

re: floor design i'd take a look at this https://youtu.be/Uqk5Zf0tw3o?t=97

for items, consumables, enemies etc. i'd assume they use spawn pools that consist of a list of weighted rarities

weighted rarity is a lottery esque random system where a given option has a amount of lottery tickets and the random selection is done by randomly picking one of those options

eg. lets say a given floor type had a enemy spawn pool of

CoolGuy1 | 4
CoolGuy27 | 4
MomsHand | 1
RarerCoolGuy4 | 1

the total spawn pool has 10 choices it could randomly pick from. Weighted rarity pools are used a lot in these kind of games because you don't neccarily need to adjust all the options values whenever you add or remove something, you just need to give whatever your adding a value thats relative to all the other values

dire agate
#

Can i update .assets files from previous game versions to current by myself?

grand snow
#

opening an old project in a new version will prompt to upgrade so its all done for you

quiet pilot
#

idk if this counts as coding but how would I actually make this show the texture?

#

I've tried it in both 2d and 3d

#

I'm trying to follow a tutorial (this is just an example they gave to start out with) but they don't explain this

wintry quarry
#

(in the top left)

quiet pilot
#

thank you so much that took way too long

#

I spent hours trying to figure it out before I remembered this server 😭

#

(I might be stupid)

nova kite
nova kite
sour fulcrum
#

Unity doesn't really offer any specific ways to help do that stuff

nova kite
nova kite
#

Well as long as it’s possible haha

sour fulcrum
#

Anything is possible 😄

eternal needle
nova kite
#

I did a prototype with spawn handling but it was a mess and got too laggy, not sure how games manage to have 100s of entities without lag, are there special mod tools for Unity you’d have to install for it?

sour fulcrum
#

your using the term mod in a way that probably gives that message a different meaning btw

sour fulcrum
#

if you get back into that "mess" feel free to ask about it when you have specifics to show

nova kite
nova kite
nova kite
sour fulcrum
nova kite
#

And it gets very laggy, I basically re created one of those fake ad games where you shoot hoards of enemies

sour fulcrum
#

Well in that example is it the spawning of the enemies that is laggy or what the enemies are doing once they are spawned? Both can be problems

nova kite
#

They are just walking forward but I assume because each has a movement script to find the player and move towards him maybe that causes the lag(?)

#

Because it runs hundreds of scripts

eternal needle
#

game obejcts wasnt meant to really handle 100s of characters with their own logic. there are optimizations you can try to make, possibly using jobs, though this isn't beginner territory at all

#

especially if this is mobile

nova kite
#

Ohh I see, so it’s more complicated Unity functionalities

sour fulcrum
# nova kite They are just walking forward but I assume because each has a movement script to...

Yeah so overall the problem is when you do things at scale, the cost of doing certain things is going to matter a lot more right. So there are many, many ways to improve this kind of thing that usually fall under

  1. Doing things less
    1.a. - Doing things less by caching values in order to avoid "expensive" code when you can
    1.b. - Doing things less in a literal sense, eg. if your enemies are constantly checking something (maybe a path to the player) don't do that every frame, do that every x frames or something
  2. Doing things faster - Just Unity/C# ways of doing the same thing in a more optimised way
  3. Doing more at the same time. - By default a majority of Unity code runs on a single cpu thread. You can kinda compare this to someone with 1 arm working a busy kitchen, at some point the bottleneck is just how much the chef can do. Using pretty advanced programming knowledge you can mess with stuff like burst, jobs and ecs in order to multithread your code in order to utilise many threads, but there's a lot of considerations on how to do that
nova kite
#

Ooo I see! Thank you both for all the information super useful!❤️

#

I’ll look into all the suggestions

#

I didn’t know it runs on only one thread, is there a way to utilize more?

sour fulcrum
#

with scary code like jobs as bawsi suggested, it's probably not going to be the first tool you bring out

nova kite
#

Ohh that’s what jobs do!

eternal needle
#

you're pretty limited to what you can do on other threads iirc

#

like i dont think you can access most of the unity api on another thread

sour fulcrum
#

hordes of enemies moving towards the player is something jobs can mess with pretty well though right?

nova kite
#

How do companies make AAA games on Unity with only one thread?😅

eternal needle
eternal needle
#

you'll see a lot of games really dont have that many enemies at once, for a reason

nova kite
#

Ohh right offloading

sour fulcrum
nova kite
#

Does it kill game objects when you offload areas?

#

And if so are you able to save their state so when you load them again they remain in that state?

sour fulcrum
#

theres no single answer for either question

#

thats up to you

nova kite
#

I see so that’s possible too,

#

Right everything is possible🤣

sour fulcrum
#

I have a UnityEvent esque class named ExtendedEvent that wraps an action and I want to make a kind of middleman class that allows strangers to listen and unlisten but not invoke, any suggestions on what to name this kinda class?

shell sorrel
#

expose only the interface that can sub to it

#

and only invoke on the concreate type

wintry quarry
shell sorrel
#

or just use C# events

sour fulcrum
# shell sorrel use a interface

Can't they choose to cast into the full thing though? I did see thats how ireadonlylist works though so i might be missing something

shell sorrel
wintry quarry
shell sorrel
#

it could be internal or private

#

also they prolly wont

#

so its fine

#

also C# events literally do this

#

just use them

sour fulcrum
#

if interfaces are the objective answer here i can live with that

shell sorrel
sour fulcrum
shell sorrel
#

no matter how you do it, people can still blow past any guard rails you put up

sour fulcrum
#

I'm very aware

shell sorrel
#

but you can expose something via interface even if its own protection level is lower

#

which would stop casting to it

#

still not going to stop meta programming stuff like reflection

sour fulcrum
#

Yeah

eternal needle
#

if you use an interface though, something will have to implement this interface along with the event. I don't really see the point of it. unless im misunderstanding they just want a class with a private unityevent inside, with an add and remove listener class. Though I dont see the point of this either

shell sorrel
#
public ITriggerable<Transform> OnTargetChanged => _onTargetChanged;
private readonly Triggerable<Transform> _onTargetChanged = new();
#

is how most would do it via interfaces

#

like mentioned depending on your needs the concrete type could be internal or private

#

but it only really effects ergonomics and intent of how its used, can smash through that with reflection easily

eternal needle
#

truthfully this just seems like a waste to do. you have to use this custom interface/class/whatever everytime instead of a unityevent just to protect yourself against calling Invoke on another object. If you were working with someone, you'd also have to convince them to remember this as well. Nothings stopping you from using a unityevent directly 3 months in the future because you forget about this class, and making this whole thing pointless

#

theres really no need to protect yourself from this, in the same way you dont need to protect yourself from the fact any code right now could call Application.Quit or Destroy every single object in your scene for fun

sour fulcrum
#

I hear you on concerns about it being a waste of time but i've used my one personally quite abit and im happy with it

#

we chilling

shell sorrel
#

am just confused by you saying security

sour fulcrum
#

(i was not the one who brought up the term security)

#

it's chill

shell sorrel
#

but yeah for custom implementations like what i showed a few nice things can be added in, like the one at work we have instead of unsubcribe methods you just returns a IDisposable on subscribe

#

which can be nice for only being subbed for a certain scope, or nice simple by just putting them all in a collection on sub, then disposing them all in this objects dispose method

sour fulcrum
#

dawg

shell sorrel
#

the downside to not using event is other people will likely not clue into there being a other implementation to use

sharp solar
#

that you want to be sure what can and cant be called or changed externally?

shell sorrel
#

the only non interface way i can think of is a little awkward as well since its just abusing closures and would involve making a method that returns both the thing to sub to and a method that invokes through it

wintry quarry
#

but anything like that is easy to get around if someone really wants to

#

I was basically wondering why the person cared if someone could cast the interface to a concrete type.

eternal needle
#

rather than a class inheriting from UnityEvent

shell sorrel
eternal needle
#

same, I got lost once really badly when my main menu was connected entirely via unity events and decided it was better to just do it through code

shell sorrel
#

to me its just overhead and they really only have benefits if you are using mb's or so's everywhere which is often not that case

median hatch
#

is unity down or am i tripping?

#

giving me internal server error

sharp solar
median hatch
#

yea wtf

median hatch
sharp solar
#

lucky im already in mine 😎

median hatch
#

hope yours isnt 15GB

#

asset store seems to be slow asf too

rough granite
median hatch
#

dont give a fuck if its big or not

sharp solar
#

lmaoo

rough granite
median hatch
#

pissy?

sharp solar
#

🗣️

median hatch
#

instead of giving proper info youre here having a dick contest

rough granite
sharp solar
#

yzaka u funny bro but people around here are very serious just dont get yourself kicked or nothing

median hatch
#

i've been here for a long time

#

i know how this works

rough granite
rough granite
sour fulcrum
#

your just getting the wrong vibe i think ngl

median hatch
#

idk some people are just eh

#

im getting this error when trying to sign in in unity hub

obtuse yoke
median hatch
#

wdym

#

are you getting the same thing?

sharp solar
#

nah they just agree that youre getting the error

obtuse yoke
rough granite
sour fulcrum
#

for anyone who helped me re: event stuff i went interface pilled eg.

    [System.Serializable]
    public class SelectableCollection<T> : ISelectableCollection<T>
    {
        private ExtendedEvent<T> onSelected = new ExtendedEvent<T>();
        private ExtendedEvent<T> onUnselected = new ExtendedEvent<T>();
        private ExtendedEvent<T,T> onSelectionChange = new ExtendedEvent<T,T>();

        public IListenOnlyEvent<T, T> OnSelectionChange => onSelectionChange;
        public IListenOnlyEvent<T> OnSelected => onSelected;
        public IListenOnlyEvent<T> OnUnselected => onUnselected;

im happy enough with this

median hatch
#

tried restarting pc but still the same

rich ice
obtuse yoke
median hatch
obtuse yoke
#

that's why im here, looking to see if i was alone.

#

The fact you are also getting it reassures me.. although i wonder if i caused it.

median hatch
#

yes it was definitely you

#

xD

obtuse yoke
#

its a possibility.

#

somewhere in multiple datacentres, servers are burning.

median hatch
#

engineers screaming your name

obtuse yoke
#

..i mean i blame them, they gave me the free 'credit' to spend

median hatch
#

guess it wasnt free after all

pallid heron
#

C# thing, not a unity problem, but I REALLY REALLY REALLY REALLY wish there was a way to say "All declarations between HERE and HERE have THIS set of attributes"

#

I just felt the need to complain about that

sour fulcrum
#

real

eternal needle
#

though yea that doesnt seem to apply much in your case

pallid heron
#

You are remembering correctly, I use that all the time.

wicked fiber
#

Is it possible to make my game object to only sense collision on the frame it was made?

rough granite
wicked fiber
#

the frame it was made

#

i wanna use the collider when its made and then use it for other purposes on other frames

#

just to specify

#

If it's not possible I can find another way, but it would be easier for a built in way

teal viper
#

If you really need to, you could store the frame number in awake, and then disable the collider in update on the next frame.

wicked fiber
#

Alr thanks

#

I honestly forgot about queries though

rough granite
#

surely you are in the wrong server

frosty hound
#

@humble rain There's no off topic here. Thanks.

humble rain
#

where do i ask that kind of question ?

frosty hound
#

Not in this server, that's for sure, being that it has nothing to do with Unity development.

humble rain
#

oh, i see

wicked plover
#

Hi
Anione can explain me how I can make move control for the player 2 in my scene with the new input system
I am creating a simple pong and I need to move the player 2 with your specific 2nd console gamepad
when I move the player 1 the player 2 is moving too

frigid sequoia
#

I am looking at the screen for a while trying to make a not shitty solution to this. So I have all those stats that can be added as stats from the gear and I want the UI to go over all of them and display a text showing those that are not 0, but I am not sure how to do that iteration/loop to check them all. Should I just manually go 1 by 1?

#

Or should I try to make them into a list somehow, even tho they are diferent data types?

teal viper
frigid sequoia
#

I kinda have that already, but I'd have to refactor all of the above???

night raptor
#

One could also use reflection, but I wouldn't generally suggest that for runtime code

frigid sequoia
#

Yeah, also thought of that, fast to code, but rather slow to run

frigid sequoia
#

This is gonna be update whenever a the selected inventory changes

eternal needle
teal viper
eternal needle
#

Whats in your Stats enum?

#

is it the same name as all those fields

frigid sequoia
#

I was not intending to iterate over those when I was making the stats tbh

#

Just to each value add the extra value from the modifiers

eternal needle
#

id consider even just having a Dictionary then of <Stats enum, float>

#

anything that wants to access a stat is forced to do so by its enum

#

all of those could be floats realistically

frigid sequoia
#

Pretty much any number I am using could be a float I guess

#

But I just went for the "this value can NEVER have decimals" route

night raptor
#

Unions maybe?

#

Wait are those not supported by C#?

eternal needle
frigid sequoia
eternal needle
#

the main thing I wonder is how you're using that StatAttribute in the first place

#

is there somewhere that uses a switch statement from enum and manually affects that class.health?

frigid sequoia
#

And it's not like a 1 to 1 conversion, some attributes don't even show on the "Stats" enum; since I need to use some "in-between values" on the stats to do the final calculations and all that do not show there cause they were intended mainly just to use for stats that are displayed

frigid sequoia
#

The GearManager takes that on a switch and converts it into the appropiate stat and adds it to the total

#

But the GearManager is indeed just having all stats on it straigh up

#

Having some stats locked into ints make it so even if I wanted to pass a float I could not, so it's kinda of a remainder here

eternal needle
frigid sequoia
eternal needle
#

the refactor would be easy if you had methods exposed to handle the logic you want. A TakeDamage method where GearManager handles subtracting from its own health would mean your entire change would be

// in gear manager
public void TakeDamage(float dmg)
{
  // health -= dmg;
  statsDictionary[Stats.Health] -= dmg;
}

but now if you move this health variable to a dictionary, a lot of other scripts are going to have errors

#

or even like a GetStat(Stats myStat) method would save from all other scripts referencing the actual floats

frigid sequoia
#

Well, the thing is like, health is not even a thing?? Like, health on the stats enum is basically refering to maxhealth, since health on itself is not a stat, really

#

The stats on the unit calls that "currenthealth" instead, and is not modified by any stat

eternal needle
#

then make it a value in the stats enum

frigid sequoia
#

So it's kinda convoluted to change

eternal needle
#

either way that doesnt really affect the concept here, refactoring would be easier if you dont directly reference the public variables. now that you consider putting them in a dictionary, everything breaks

#

if you really cant refactor it due to an absurd amount of changes, in your initial problem, id suggest write the code one by one because this wasn't designed to be iterated over

frigid sequoia
#

Yeah, like I think I would get more issues than solutions refactoring tbh

#

I am not even sure if it be technically better, maybe easier to code, but, would also make it kinda more complex and messy?

#

Like basically I think I would get like genuinely hundreds of errors changing how stats are referenced now lol

eternal needle
#

I feel like you could get away with some slight insanity here if you really wanted to refactor this. Like in GearManager (is this your stats class?), create the dictionary, then change currentHealth to be a property.
currentHealth => myDict[Stats.CurrentHealth];
then rename it using IDE to follow proper convention

frigid sequoia
#

Ah, well, no, GearManager just stores the stats comming from the gear rn

#

Then the class Stats, should handle them comming over to calculate the finals

eternal needle
#

i mean, what you're doing can work, but you already see that its not possible to iterate through

frigid sequoia
#

I also have a separate class that is basically a copy paste from stats that is BonusStats, that is basically any modifiers from stats that do not come from gear, I placed these appart so I could reset any bonus directly if needed

eternal needle
frigid sequoia
#

Honestly, the only real reason why I would prefer an iteration here is cause I want 1, to not show stats that are not being modified by gear (aka = 0), and 2, I want stats that are going into the negative to display after the ones in possitive, so just going 1 by 1 is kinda more messy than anything I was doing with those prior

eternal needle
#
    void OnTakeDamage(DamageDealt damageDealt)
    {
        float newHealth = damageDealt.postDamageHealth;
        float maxHealth = playerStats.GetCurrentStat(StatDefinition.MaxHealth);
        float percent = newHealth / maxHealth;

        ChangeImageFill(percent);
    }

the only thing that changes is that I call a method to get the stat I want, rather than directly referencing it. you could've also implemented it this way from the beginning where it goes through that switch statement you mentioned. So your code would be some stats.GetStat(enum). The refactor from a bunch of fields -> dictionary would only change the implementation of GetStat

#

you still could do what I said above to make refactoring easier by changing what currentHealth is, making it into a property. You wouldnt need to go into other classes to change it

frigid sequoia
#

So, I would add that into the stats enum?

#

Feels kinda weird, considering that should not actually show in many of the things that are using it

#

Like what, can I now add "current health" as a gear attribute?

eternal needle
#

well for currentHealth specifically thats up to you, idk what you intend to do there. I actually do have currentHealth in my dictionary of stats

#

for other variables like maxHealth, the same concept still applies

eternal needle
edgy pier
eternal needle
#

there are benefits though, like if we think of a "health potion" vs "mana potion". you wouldnt want separate code where both do the same logic, but are different methods because one needs to reference stats.currentHealth or stats.currentMana.
this could just be an enum exposed to the inspector and consolidated into one method

#

idk how i forgot to mention this. the main purpose for the dictionary is that you can "choose" a stat via the inspector, since enums are serialized. So if you had an object which buffed a stat, you just choose the enum in inspector, then pass that enum when interacting with the stats class

frigid sequoia
#

Makes sense but... I don't think it works on how I am doing things actually

#

Like for modifyig the stats, it would be useful to just select the stat as enum and add a value, but the managers need more data from that in most cases

#

Like for example, if it's a buff, it needs to know stuff like it's stackeable or how does it stacks, so it kinda needs to be of spefic class for that???

#

I think I could maybe refactor that too, if I try hard enough

#

Maybe I should???

#

Not sure

sour fulcrum
#

It's possible using scriptableobjects as kinda enums here might be a nice solution

#

depends on if that additional data is per gear type (enum option) or per usage of the enum

frigid sequoia
#

Currently not intend into making anything "usable" or "consumable"

#

Like at all

#

Could be cool, but no, I am trying to avoid that

sour fulcrum
#

you misunderstood what i meant by that

eternal needle
#

your buffs could stay exactly as they are

frigid sequoia
eternal needle
#

it shouldnt affect anything at all

frigid sequoia
eternal needle
#

infact if you do the cursed suggestion i said above of making all the current floats into properties, all the other code could stay the exact same

sour fulcrum
eternal needle
#

tbh i dont think scriptable objects solve anything here compared to enums

#

if there was some additional logic you needed to attach to this, then maybe, but that is also fine to just throw in a switch statement in the stats class.

frigid sequoia
frigid sequoia
eternal needle
# frigid sequoia A property like, an enum + value as you were saying?

i really dont like that im even suggesting this, but its purely to not break every other class. it would just be something like this

public class Stats 
{
  Dictionary<SomeEnum, float> myStats = new(); // plus logic to populate this dictionary
 
  public float currentHealth => myStats[SomeEnum.CurrentHealth]; // or => GetStat(SomeEnum.CurrentHealth)
  public float GetStat(SomeEnum myEnum)
  {
    return myStats[myEnum];
  }
}
#

also typed it on discord incase theres some error i dont see

#

then you could right click in IDE, rename currentHealth to CurrentHealth to follow convention for properties and itll update everything for you

frigid sequoia
#

So basically whenever I reference current health, it just gets me the value on the dictionary that is asocaited to the same enum and I can basically just get a stat with the method to do the same with any

#

I see, I see

#

I see what you meant now

#

Yeah, that sounds reasonable

eternal needle
#

tbh it's not even bad to do with properties here, but its just not what i'd do. you will have a lot of extra properties

#

because its not just currentHealth. it is everything that you showed in the initial screenshot

frigid sequoia
#

Yeah, there are a lot of little things than I am likely gonna miss and break everything lol

eternal needle
#

well with what im suggesting, you dont need to touch any other class yourself

#

everything is purely within this Stats class

#

currentHealth gets changed to a property so everything referencing it still works. Then IDE renames it for you

frigid sequoia
#

I am right now just considering how much better it would be going forward if I just do it that way, to see if it's worth the hassle

#

Mmmmm... not sure

vital vault
#

how can i change material properties from script

#

i want to change offset on unlit texture

eternal needle
eternal needle
vital vault
sour fulcrum
#

if you want to change it from a script

#

you need to change it from a script

eternal needle
eternal needle
rough sluice
#

Player is falling forward like a mannequin when I try to move it forward by pressing W but instead of moving in that direction player just falls in that direction? Is this due to I am using 3D box collider?:
Codes:

private Rigidbody player;

private void FixedUpdate()
{
    Vector2 moveInputs = mobileInputs.Player.Move.ReadValue<Vector2>();
    float speed = 5f;
    player.AddForce(new Vector3(moveInputs.x, 0, moveInputs.y) * speed, ForceMode.Force);
}
naive pawn
silk night
naive pawn
#

x and z, usually

atomic prairie
#

hey guys was messing with tilemaps and was wondering if it was a bad practice to put 2 tilemaps on the same "tile" or not?

#

was also trying to understand what this does, searched online but i still dont fully understand it

naive pawn
#
  • question doesn't really make sense
  • not a code question
atomic prairie
#

oops

naive pawn
#

ask in #🖼️┃2d-tools, and could you clarify what you mean
tiles go in tilemaps/tilesets/grids, not the other way around

atomic prairie
#

alright thanks

naive pawn
#

i'll answer the composite thing there too

restive sigil
#

Can anyone look at this?
I want the loop in AnimMain() to run forever, and after thats done, the next command is executed in AnimRoot() which called AnimMain(). both IEnumerators.
But currently, AnimMain() only runs once and nothing after that.

#

I pasted the script twice to put it in a window like this

naive pawn
#

!code

eternal falconBOT
restive sigil
#

so you cannot look at it that way at all...

#

let me correct it :3

#
using UnityEngine;
using System.Collections;
using JimmysUnityUtilities;

namespace NSMB.UI.MainMenu {
    public class MainMenuTitleAnim : MonoBehaviour {

        [SerializeField] private RectTransform titleMain, titleSub;
        [SerializeField] private UI.Elements.GIF titleGif;
        [SerializeField] private float latency = 0.00008f;
        private float temp = 0.0f;
        IEnumerator AnimMain() {
            while (true/*temp < 0.5f*/) {
                titleMain.SetPivotX(temp);
                float prevTemp = temp;

                temp += (latency* Time.deltaTime);

                Debug.Log($"VAL: {prevTemp}=>{temp}, {titleMain.pivot}");

                yield return null;
            }
            Debug.Log("Anim End?");
        }
        IEnumerator AnimSub() {
            titleSub.SetPivotY(-2f);

            yield return null;
        }
        IEnumerator AnimRoot() {
            temp = -3.0f;
            yield return StartCoroutine(AnimMain());

            yield return new WaitForSeconds(0.2f);

            yield return StartCoroutine(AnimSub());

            yield return null;
        }
        void Awake() {
            StartCoroutine(AnimRoot());
        }
    }
}
naive pawn
#

we can (on desktop), but it'd be better with the ideal method as given above

#

(the pastebin sites would be better for large blocks like this though fyi)

#

to run forever, and after thats done
how do you expect this to work, exactly?

#

if it runs forever, it's not gonna be done

restive sigil
#

Yeah see the commented out piece of code in the

#

actual loop

#

theres a condition

naive pawn
#

which... isn't being used

restive sigil
#

yep

#

it runs only once

#

and for debugging i put it forever

#

and still only once

naive pawn
#

ok so right now it should run forever, but it's only running once?

restive sigil
#

yep

naive pawn
#

so you're only getting the VAL: log once? or are you also seeing the Anim End? log?

restive sigil
#

nope

#

it is 3.0 => 2.99998 or something

naive pawn
#

what's telling you that it's running once, exactly

restive sigil
#

unity is compiling scripts

#

it was so much better when that happened in the background in 5.x...

#

(used that ver once)

#

VAL: -3=>-2,999998, (-3.00, 1.00)

sour fulcrum
#

That didn’t change

restive sigil
#

i remember that it didnt put a popup which blocked my path

#

whatever

naive pawn
restive sigil
#

the output.

#

its only printed once.

#

it should clearly repeat the loop

naive pawn
#

are you getting the Anim End log

restive sigil
#

again, nope

naive pawn
#

bruh i asked you 2 questions before and you said "nope" once LMAO

#

make sure you don't have collapse enabled in console

restive sigil
#

not enabled

#

and i know this because button isnt pressed.

naive pawn
#

any errors or anything else? have you tried putting logs at the start/end of the loop?

restive sigil
#

imma run this

#

right i had to go

#

imma run it..

#

For some reason i am only getting the VAL thing and none of the other prints, which makes no sense

runic lance
#

you're not getting "Alive" or "Done"?

restive sigil
#

nope

#

and unity also flags the yield return null in the loop as unreachable now

#

why would a debug log stop that iteration

runic lance
#

well, either you're not running the code you sent or you're filtering the debug logs somehow

restive sigil
solar hill
#

having issues with player collision, when i get close to other objects and tap a movement key the player character bounces off the other objects

#

but holding it down just has the player "phase through"

#

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
    public float speed = 5f;
    public Transform cameraRig;
    public float dashForce = 8f;
    public float dashDuration = 0.1f;
    public float dashCooldown = 3f;

    private Vector3 currentDirection;
    private bool isDashing = false;
    private float dashTimer = 0f;
    private float dashCooldownTimer = 0f;

    private Rigidbody rb;

    void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        HandleDash();
    }

    void FixedUpdate()
    {
        HandleMovement();
    }

    void HandleMovement()
    {
        if (isDashing) return;

        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        Vector3 inputDir = new Vector3(h, 0f, v).normalized;

        if (inputDir.sqrMagnitude > 0f)
        {
            Vector3 forward = cameraRig.forward;
            Vector3 right = cameraRig.right;
            forward.y = 0f;
            right.y = 0f;

            forward.Normalize();
            right.Normalize();

            currentDirection = (forward * v + right * h).normalized;

            Vector3 targetPosition = rb.position + currentDirection * speed * Time.fixedDeltaTime;
            rb.MovePosition(targetPosition);
        }
        else
        {
            currentDirection = Vector3.zero;
        }
    }

    void HandleDash()
    {
        if (dashCooldownTimer > 0f)
    }
}

#

this is my player gameobject set up

#

i have an additional gameobject for rendering a sprite and a camera as a child of this

#

the actual sprite is being billboarded so i assumed that might have something to do with it but apparently it does not

restive sigil
#

If anyone wants to do my question:

Alive
AnimRoot Start.
Anim Start.
ANIM VALUE: -3=>-2,999998, (-3.00, 1.00)
Done
is my output
(scroll up)

rough granite
solar hill
#

same thing

#

in fact i changed it initially from discrete to continous thinking it would solve it

#

the fact that you can sort of bounce off of the wall makes me think some kind of collission is happening

#

but for whatever reason continous movement seems to just disregard it allowing you to walk through

#

tried it on different kind of colliders as well and you can walk through pretty much anything no matter how big or small

rough granite
solar hill
#

hmmmm for some reason

#

changing interpolate from interpolate to none

#

makes it work 🤔

rough granite
#

Odd cause I've been told when watching videos that it just makes the movement visually smoother

solar hill
#

not just deltatime

solar hill
rough granite
restive sigil
naive pawn
#

also deltaTime is the same as fixedDeltaTime within FixedUpdate

wintry quarry
solar hill
#

So whats the better alternative

naive pawn
#

set velocity or add a force

wintry quarry
#

The easiest to work with will be setting the velocity

solar hill
#

Oh i see

#

Thanks !

eager spindle
#

Does c# have a dictionary that behaves like the one in c++?

wintry quarry
#

Not sure how the C++ one behaves exactly but they're pretty much the same in all languages

night raptor
#

If you have some specific difference in mind, please specify it, not all of us use c++

naive pawn
#

Dictionary in c# is a hashmap/dict/table, what unordered_map is in c++

#

structures in different languages will be implemented differently and will not act exactly the same

#

consider what functionality you actually need and go from there, instead of trying to find a direct equivalent from a structure in a different language

slender nymph
naive pawn
#

very few structures in c# will behave like c++ analogues because c# doesn't have copy constructors 😛

wintry quarry
#

I feel like we're getting ahead of ourselves

#

The basic contract here is key/value mapping presumably

eager spindle
#

its a little different, in c# you need to initialise the values before being able to use it.
in c#, you must call Add first before being able to use the values

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 30);
ages.Add("Bob", 24);

but in c++ you can just use it directly

map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 24;
rough granite
naive pawn
wintry quarry
wintry quarry
#

You can use the [] syntax in C# as well

eager spindle
#

My use case is a bit niche in that I want to

Dictionary<string, Action> actions = new();
actions["money"] += moneyAction;

But calling actions["money"] += moneyAction; calls NRE

naive pawn
#

does it? i would assume it says the entry doesn't exist instead of an NRE

eager spindle
#

Oop yep I meant the entry doesnt exist

naive pawn
#

but yes keying into a dict does not default-create the element like c++ does

eager spindle
#

I was thinking that in c++, it would instead treat actions["money"] as an empty Action that would just allow me to add to it

#

yea i wanted that default creation method

naive pawn
#

yeah c# just doesn't have that concept in general

wintry quarry
#

I mean, that's a pretty minor difference

naive pawn
#

(not really, it means upsert is given for free in c++)

eager spindle
#

I see, I'll find another way

wintry quarry
#

If statements exist.
TryGetValue exists

#

The difference here is really in the fact that Action is an object that needs to be created

#

If it was a struct it would be equally free

naive pawn
#

generally for [non-c++ language] you would check for existance and then choose to add or update, or default-create the entry and update

it's only c++ that has the default-init behavior afaik

naive pawn
wintry quarry
soft lotus
#

Im working on implement a save file system to my game, and i want each save file to be accompanied with a little screenshot of the game, for better readability. How can i take a screenshot & save it to file? Additionaly, i'd love for the screenshot to be in a different aspect ratio from the game itself (4:3, instead of the game's 16:9)

#

the save files themselves are .json

wintry quarry
naive pawn
soft lotus
restive sigil
#

not changed.

#

i gave up and put it in a messy update loop

naive pawn
#

which kinda sounds like it not being passed to StartCoroutine, but it is...

restive sigil
#

so yield just stops all coroutines smh

#

funnily i have a GIF script using ienums and they somehow work

naive pawn
#

well yes, but it's supposed to continue in the next frame in the case of yield return null

restive sigil
#

i made that before this tho

rich adder
restive sigil
#

and it loops if yields are removed from animroot

#

but it currently works with the update function either way

hot wadi
#

Should I use a Pool to reuse my bullets or should I just instantiate them when needed?

rich adder
craggy depot
#

Hey yall, so I’m new to unity, and am making a project for digital twins, I wanted to ask are there any good tutorials or materials I can refer to? I do use chatGPT, but after a point I’m not able to make it work

waxen glacier
#

How can I get the value of the angle between a Raycast and the normal of whatever it hits ?

waxen glacier
rich adder
waxen glacier
rich adder
waxen glacier
waxen glacier
#

I just had to quickly research how raycasts work cuz I couldnt get the "hit" variable to work

#

Ya learn somehting every day

scarlet skiff
#

whats the easier simplest way of making an on value changed for a bool? and getting the old value and the new value

waxen glacier
#

Another question, the blue box is the Ground Check, and I set it to turn off the gravity on the rigidbody if it's grounded, only problem is, when I jump on the cube's edge for example, the rigidbody still kinda bumps off and slides down. I want it to stay at the exact same height it's at when the gorund check first collides with the cube, I tried manually setting the downward velocity to zero if it's grounded and it didnt work, any ideas ?

naive pawn
#

no reason to provide the old value for a bool though lol

naive pawn
waxen glacier
naive pawn
#

yeah that would be due to the existing velocity

#

perhaps show !code

eternal falconBOT
naive pawn
#

why are you resetting the angular y velocity

#

that's how fast you're yawing

#

motion is linear velocity

waxen glacier
#

changed it but the problem persists

#

if i jump further on the cube and walk backwards until the Ground Check barely makes contact there's no problem, the capsule only slides down If jump on the cube's edge directly

#

let me take a screenshot to make it clearer

naive pawn
#

-# a literal edge case

crystal rain
#

how do you make your text small or big

waxen glacier
naive pawn
crystal rain
#

Discord 🤣

waxen glacier
#

As you can see the capsule still says at the same height if I jump correctly on the cube then slowly walk backwards, but if I jumped now from the position shown in the images, the capsule just bumps off the edge of the cube and falls , that's what I want to remove

crystal rain
naive pawn
#

it's extended markdown

# h1
## h2
### h3
normal
-# small
```the small version is a discord specific thing, and generic markdown goes to h6
#

you can google all this though

naive pawn
waxen glacier
crystal rain
#

Oh

#

Hahaha

waxen glacier
crystal rain
#

Are the objects frictionless

#

the player and block

waxen glacier
naive pawn
naive pawn
crystal rain
#

Can you turn off ground check? (I don’t use unity often I have only opened it once and understood nothing and was overwhelmed)

waxen glacier
waxen glacier
crystal rain
#

Maybe it is pulling it to the ground because it thinks it is hovering over the ground

#

And doesn’t like it and jerks it to the ground

waxen glacier
#

Managed to record it

#

Look at when i'm already standing on the edge of the cube and try to jump

naive pawn
crystal rain
#

Uh it was worth a try

naive pawn
#

snapping happens with depenetration

waxen glacier
crystal rain
naive pawn
# waxen glacier

this moment, right? where it's falling and the ground check kinda falls through the block a bit before the gravity disable kicks in

waxen glacier
naive pawn
#

i'd guess that's just gravity being faster than the physics tick rate, rather than any issue with your code

#

you could make it snap up to the surface, but that might be jarring

#

or i guess gradually move back up to the surface

#

but if you want that behavior, why not just use a boxcollider

crystal rain
#

Couldn’t you also just make a hit box for the player

naive pawn
#

there's already a hitbox, it's the green wireframe

crystal rain
#

Try making the hit box bigger than the little oval

waxen glacier
naive pawn
#

it'd just make the effect less

#

i get that you're trying to help, but if you have no idea how anything works, you just aren't really going to be able to help

naive pawn
crystal rain
naive pawn
#

no, it doesn't

crystal rain
#

Huh

naive pawn
naive pawn
# crystal rain Huh

the minecraft player's hitbox is a cuboid shape, that's why it doesn't slide. and minecraft doesn't have slopes.
the model protrudes out of the hitbox in some areas.

crystal rain
#

He doesn’t have slopes so I thought it would help I was not thinking in future

naive pawn
#

there's a slope check in the code

crystal rain
#

Oh i didn’t see that

naive pawn
#

nothing personal against you, but really - if you don't have the background knowledge to actually understand what's going on, your suggestions are just unnecessary noise

crystal rain
#

That was very personal against me

red igloo
crystal rain
rich ice
#

the point they're trying to make is still true. you haven't shown any signs of having knowledge related to unity, just general game dev. if you want to actually help here than understanding the engine is an entry level requirement

crystal rain
#

I don’t know where to start learning

waxen glacier
rich ice
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

crystal rain
#

That hasn’t helped me at all

naive pawn
naive pawn
waxen glacier
crystal rain
#

I can still present ideas that may end up being helpful

waxen glacier
#

is it basically the engine's physics acting before my code can disable gravity ?

naive pawn
naive pawn
# waxen glacier Mind re-explaining what that is ?

so basically how physics works is it's gonna step work out where stuff will be after velocity has been applied, then figure out what stuff is inside each other, and then try to make them not be inside each other

so gravity might make the player and the box intersect like this for a brief moment, then physics will figure out - hey, those 2 things collide, they shouldn't be in each other, and then it'll push the player out of the box (or vice versa, dependant on dynamic vs static and mass and stuff)

#

i guess what is happening here, is that due to the player being on the edge, it ends up looking like this - the physics system looks at this and thinks the easiest way to depenetrate is to make the player move out instead of up, which is technically correct, just not what you want

waxen glacier
naive pawn
#

(or the physics system just pushes them directly apart and that ends up being out. idk the specifics)

naive pawn
waxen glacier
#

i'll just duplicate my movement script and make the copy work as a CC so I can still go back to rigidbody if i mess anything up

naive pawn
#

seems like this is... not a particularly easy problem to solve with physics

#

imo this isn't too egregious and would be a lot of effort to switch to CC just for this change, but power to you if you decide to fix this

#

an alternative would be to i guess extend the ground check to snap to the ground better, but that might also be a lot of effort for not much gain

waxen glacier
naive pawn
waxen glacier
naive pawn
#

with the antigravity/velocity reset?

naive pawn
waxen glacier
naive pawn
#

buddy you are creating unnecessary noise that isn't helping

crystal rain
#

Ok and

waxen glacier
# crystal rain Can you stop hating

Bro I get you were trying to help but it's better for you to just admit you're in the wrong here, you were drowning out actual helpful messages with your ideas

naive pawn
naive pawn
crystal rain
#

It is not spamming

#

It is trying to help

waxen glacier
naive pawn
wintry quarry
waxen glacier
# crystal rain It is trying to help

You weren't really helpful tbh, throwing out random ideas doesn't really do much, @naive pawn could actually tell me what the problem is because he has enough knowledge on the matter, instead of arguing here you could've just followed along and learned something yourself

crystal rain
#

I have

naive pawn
# naive pawn snapping happens with depenetration

oh actually just realized, this doesn't happen with unity i don't think? at least with the 3d physics engine
there's a depenetration velocity, whereas source iirc does snapping - it tries to find an open space and teleports you there

physics2d doesn't have "depenetration velocity" so it might be snapping

soft lotus