#💻┃code-beginner

1 messages · Page 682 of 1

rocky canyon
#

something u could actual walk thru..

lapis parrot
#

oh

#

aghhh

#

still not working

naive pawn
#

make sure you also change the parameter to Collision2D

rocky canyon
#
using UnityEngine;

public class Enemy_Test : MonoBehaviour
{
    public int health = 100;

    void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("We collided with something.");

        if (collision.gameObject.CompareTag("Player"))
        {
            Debug.Log("We tested and collided with the player!");
            TakeDamage(10);
        }
    }

    public void TakeDamage(int damage)
    {
        health -= damage;
        Debug.Log("Damage taken: " + damage);
        if (health <= 0)
        {
            Destroy(gameObject);
        }
    }
}
lapis parrot
#

wait

rocky canyon
#

@lapis parrot ☝️

#

ez

robust kelp
#

i made one static class and unity is freaking out, ai says its a 'Unity parser bug'

lapis parrot
#

is that a script for a enemy to take damage or for it to deal damage

rocky canyon
#

since its on the enemy.. it detects contact with player..

#

and damages itself

#

simple mode: (1) script

lapis parrot
#

but you can use that to deal damage to the player, right

hallow rock
#

Where would i add a webhook here?

rocky canyon
lapis parrot
#

woohoo tysm

#

i understand

rocky canyon
#

the player would detect if it touched an enemy.. and damage itself..
or u can flop it out and have the enemy damage the player

lapis parrot
#

my code was just buns 😭

rocky canyon
#

ya, kept adding to it and adding to it..

#

u should try to keep it simple.. if u change out the way somethings happening.. remove the uncessary parts

#

it 'll get too cluttered to read/fix if u dont

naive pawn
hallow rock
naive pawn
lapis parrot
#

i thought it was simplest answer simplest solution

naive pawn
naive pawn
naive pawn
# hallow rock "setting"

you would just assign the webhook url in the inspector, presumably, since you've made it public

naive pawn
#

...is that the inspector?

rocky canyon
#

but yes u could do it it there.. but then that defeats the purpose of it being public

hallow rock
naive pawn
#

have you never set fields from the inspector before

rocky canyon
#

public field would keep it easy to change w/o loading up the solution but if u wanna keep it internal nothing wrng with assigning it in the class itself

hallow rock
#

@rocky canyon are you still awake

#

i get a compile error here

#

field is not classified or something

#

do i mind this?

lusty viper
#

I don't think the field keyword is used that way, unless it's a custom type you've defined

#

What's the type of discordWebhookURL supposed to be?

cosmic dagger
hallow rock
#

which sends like

#

thus'

#

a message

#

for a anticheat

#

field is here because

cosmic dagger
#

Is field a type?

lusty viper
#

Yeah but I mean that field in specific is going to have a type - whether it's a number or some text or a true/false

hallow rock
lusty viper
#

I'm guessing it's supposed to be a string then if it's a url

#

yeah

hallow rock
#

wait shoot

#

string

#

hold on people

cosmic dagger
#

Well, the name of the variable has "URL" in it, so I'd guess it's supposed to be a string . . .

#

This begs the question as to why you put the type as field?

hallow rock
hallow rock
#

@cosmic dagger

polar acorn
hallow rock
polar acorn
#

You've got the line public string discordWebhookURL; and then a random unattached string that cannot be

hallow rock
#

and thats all

polar acorn
#

It's like having a line that just says:

3;
#

That's not how C# works

hallow rock
#

heres the other lines

lusty viper
#

Yeah the semicolon means the line ends there - so basically the compiler is reading that you're saying
public string discordWebhookURL;
And then on a new line just you have that string "https...." sitting there, which is not valid

polar acorn
hallow rock
#

I see.

#

How do I fix this.

polar acorn
hallow rock
#

see im not the greatest at problem solving.

polar acorn
#

You have it right one line down

#

do that

hallow rock
#

listen, im very dumb at this crap, but its right here probably, or im going to cry in a corner.

#

😭

lusty viper
#

I'm confused what relation the screenshot you just sent has to the issue you were having before

polar acorn
#

What does this line have to do with anything

hallow rock
polar acorn
#

See how it does not have an error?

hallow rock
#

mhm.

polar acorn
#

Compare it with the line above, which does have an error

#

What difference do you see

hallow rock
#

the equals sign,

#

the semicolon at hte ends

#

etc

polar acorn
#

Cool you get it

lusty viper
#

It might be good to start from first principles - do you know what the equals sign is doing?

hallow rock
#

great its fixed, im just being dumb.

#

thank you.

#

peace.

lusty viper
#

(Cross-posting here bc it got buried in the other channel lol, hope that's allowed)

wintry quarry
# lusty viper

Approach 1 is what I would start with. To handle objects being destroyed - that can be done in two ways:

  1. Enemies fire an event when they die. When you add an enemy to your aggro range, you subscribe to the death event to remove the enemy from your list in case of death
  2. Each frame, or periodically, you check your list with == null which will return true for destroyed objects, or you have an isDead flag on the script which you check.
#

Approach 2 can also work. Just make sure you use one of the versions of OverlapCircleAll that takes a List so it doesn't allocate a new array each time

#

Also I would use a HashSet instead of a List for option 1

lusty viper
#

Ahh that's smart. Yeah I've already got a death event for entities so that would work perfectly

wintry quarry
#

just don't forget to also unsubscribe from the death event in the event handler 😛

lusty viper
#

So true!

eternal needle
#

alternatively you dont need to unsubscribe if you just set the delegate to null after invoking it

lusty viper
#

Does that have a big difference compared to unsubbing? Or is it just cause its shorter code lol

eternal needle
#

you just dont have to remember to unsubscribe, and it doesnt affect if someone else on the project also doesnt know about this and still tries to unsusbcribe somewhere

wintry quarry
#

My guess is it (setting to null) might be slightly faster but I doubt you would ever notice any performance difference.

eternal needle
#

i said it more cause it makes more sense logically. you invoke an event that only ever happen once per instance, everything gets notified, then you want everything to "forget" about this event

wintry quarry
#

(Assuming your enemies cannot die more than once)

eternal needle
#

unity does this with some editor event i forgot which exactly. something delay related

lusty viper
#

Tbh I'd rather not modify any state at runtime if it can be avoided

#

(Obviously you have to to some extent but yknow)

eternal needle
#

what do you consider state to be in this scenario? neither of the suggestions affect if your objects have or modify state

#

setting a delegate to null is the same outcome as everything unsubscribing

lusty viper
#

Oh, like if you're keeping a delegate field and you set it to null, that delegate would presumably be mutable state on the object

eternal needle
#

its mutable anyways, i think you have a misunderstanding of what state really is (or what we mean setting it to null)

lusty viper
#

Not if it's readonly right?

#

Or can you still set readonly fields to null?

eternal needle
#

why would you have a readonly event?

wintry quarry
#

I don't think readonly events work at all yeah

#

you have to rewrite the variable when you add a subscriber

lusty viper
#

Oh wait - when you say "set it to null", you're talking about the event?

#

I thought since you were referring to a delegate you were talking about the subscriber

wintry quarry
#

yeah the event

eternal needle
#

this is the first time ive heard of anyone not wanting to modify state in unity, so i assume you got this fear from another aspect of programming (web dev?). Every game object you have will have state, you modify its position

wintry quarry
#

OnDeath = null;

#

basically:

OnDeath?.Invoke();
OnDeath = null;```
eternal needle
#

the event is the delegate, event is the keyword used to restrict how a delegate can be used

#

so yea set the event to null

lusty viper
#

Okay yeah that makes more sense, didn't realize events were considered delegates (I'm thinking of UnityEvents specifically, never used regular c# events but maybe I should switch over)

wintry quarry
#

yep - event is a modifier for delegates

#

it means like "only the class that owns me can invoke me or assign me directly"

#

everyone else can only do += and -=

pallid nymph
#

I'd rather get used to unsubbing, tbh. Setting to null doesn't solve the problem when the listener "dies" first. (Although it may not be a possibility in this case.)

eternal needle
#

you arent restricted to only setting it to null. other entities can unsubscribe on death with no negative effect
the only thing this changes is entities dont need to unsubscribe when the event is invoked

pallid nymph
#

Why would they need to unsub in that case anyw... ah, because pooling? 🤔
I'd still go with the standard pattern and only deviate if performance requires it.

lusty viper
eternal needle
#

if you need to modify a value on an object, you are modifying state. this will happen throughout almost every feature in your game. it is not like there is an alternative to "not do it".
a lot of overengineered web dev things just dont apply here

lusty viper
#

There's often an option to not do it when it comes to internal state for a script, which is mostly what I'm talking about

wintry quarry
#

immutability and performance are often enemies

lusty viper
#

True, I'll have to reconsider if I run into performance issues. For now though it's pretty performant so I won't really optimize for that

eternal needle
lusty viper
#

Not really haha

#

When I say "state" I'm just referring to fields on an object that are not readonly, really. As an example, say I want a "fade" function on a script - I could store a stateful value like currentFade or something, and have it increment/decrement on every Update. Or like what I imagine most people would do, I could start a coroutine or async method to loop and fade asynchronously, not mutable fields needed

wintry quarry
#

Sure - just know that a coroutine is itself a state machine. The state is still there, it's just stored on a different object.

pallid nymph
#

I feel that's a bad example. Those are state and the worst kind - one that you don't control 😄

eternal needle
#

im aware what state is, but the assumption there that state doesnt exist because you use a coroutine is just not right. it still exists even though you dont see it, now its just in the coroutine

#

and you likely also will store the current coroutine incase you need to stop it. thus more state

wintry quarry
#

But i do get your point about not storing state on the MonoBehaviour in that case

#

in fact that coroutine case means the state is only stored when running it, otherwise not

pallid nymph
#

I think the main "no state" thing was their option 2 for the colliders - to do an overlap circle when they need then instead of storing state, which is indeed more stateless.

wintry quarry
#

yep

#

I think it exchanges memory and state handling for worse performance. Which might be a fine tradeoff

lusty viper
#

I mostly think about it from the perspective of how the code I'm writing is storing state, and even if I can isolate state interactions into one point of failure, that becomes way easier to check for bugs

#

Like, every script that doesn't define any new, mutable state, is a script that is a lot less prone to local bugs, in theory

wintry quarry
#

I don't think there's anything wrong with your philosophy

eternal needle
#

in some cases youd also want to consider managing it yourself because starting a coroutine does allocate memory. which ties into what Praetor just said above
Usually i design things around whats easiest to read and extend upon. Like sometimes a coroutine is just easier to use, sometimes update is easier. I never find logic so complex that id even begin to worry about state in the first place

wintry quarry
#

just be ready to profile and optimize where necessary

lusty viper
#

Yeah 100%, if/when I start to hit performance issues I'll definitely have to reevaluate, but hopefully then I can come at it from the perspective of optimizing the most costly parts of the code rather than generally making everything everywhere optimized for performance and sacrificing some of the other stuff I was talking about

brave robin
#

The only performance hit I ever noticed with coroutines was the 1 frame delay before they start. This won't affect framerate, but if coroutine yields on another coroutine which yields another etc. then you'll notice the delay build up

grand snow
#

is this still the case even if you do StartCoroutine(Thing());?

eternal needle
#

dont they run immediately until the first yield?

grand snow
#

I personally prefer async over coroutines but they do have their own issues

lusty viper
#

Yeah I've been using async more, used unity a good amount a few years ago and I just learned async exists in c# like 2 days ago haha

brave robin
# eternal needle dont they run immediately until the first yield?

Yes, but if you nest more than one with yield start Coroutine it creates noticeable delays if you have enough of them nested. I was building a turn based framework and in some spots I had a cascade of various coroutine listeners responding to events, and it built up a delay between the player choosing an action and it completing.

#

async and/or UniTask (which is async under the hood) are both good alternatives

grand snow
lusty viper
#

Me too!! Wait is UniTask not prefered anymore lol

grand snow
#

I think it is because Awaitable is missing some functions such as WhenAll

#

and UniTask has good extensions for Addressables

eternal needle
#

i wouldnt expect that behaviour to depend on how many you had nested either but idk i never really nest coroutines either.

brave robin
#

I have a very event heavy game, where everything sends out events before, during, and after completion, so that responders can interrupt, modify, or react to the action in question. All necessary to handle the conditional RPG logic

#

And since it's all turn based, everything waits its turn, and sometimes there's lots of nesting as a listener generates its own events if it's reacting

rocky canyon
#

turn based is already a flex.. i love a good turn-based game loop

eternal needle
#

i assume you were hitting a yield return null at one point unknowingly

brave robin
#

But this was half a year ago, so maybe I missed a detail in my explanation

eternal needle
pallid nymph
#

(I'm not sure what the exact implementation is though, so that's just a guess)

eternal needle
#

i would assume thats expected but yea a likely guess

rugged jackal
#
        {
            transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
        }
       if (transform.position.x > xRange)
        {
            transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
        }
            horizontalInput = Input.GetAxis("Horizontal");
            transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);```

When my character moves to the end of the range on the right, it stops and doesnt move any further, but when it moves to the end of the range on the left, it teleports to the end of the range on the right. I'm not sure what in this code is causing that
#

xRange is a float set to the value of 10

wintry quarry
#

seems pretty clear that's what this code will do

#

did you mean to put -xRange there in the Vector3 constructor?

rugged jackal
#

yes

wintry quarry
# rugged jackal yes

really you should just use clamp I'd say:

Vector3 pos = transform.position;
pos.x = Mathf.Clamp(pos.x, -xRange, xRange);
transform.position = pos;```
#

That can replace both of those if statements entirely

rugged jackal
#

i definitely do prefer single line code to if statements, they make more sense to me

#

im just not sure whats causing the if statements to loop when reaching the end of the -xRange side when I didnt use a loop statement anywhere..

#

thank you

wintry quarry
#

Also you should be doing the clamping AFTER you call Translate

rugged jackal
#

sorry im more used to writing python bash and posh

wintry quarry
#

there's certainly no looping happening in this code.

YOu might be getting confused because Update gets run every frame

#

Update is therefore, sort of implicitly in a loop

wintry quarry
#

this code simply doesn't have one

rugged jackal
#

thats why i was confused

wintry quarry
#

so I'm not sure what you mean when you say "the if statements loop"

rocky canyon
#

u may need an else - if statement instead of 2 ifs..

#

not sure thats an issue here or not

#

but the clamp is better potion

lusty viper
# wintry quarry ```cs if (transform.position.x < -xRange) { transform...

The issue is with these two lines that praetor pointed out - you're checking if the x position is less than -xRange, but then setting the x position to xRange, so you're presumably making a big jump from position.x near -xRange to xRange. It looks like it's looping cause you're setting the position to the right boundary xRange upon hitting the left boundary -xRange

wintry quarry
#

note this isn't a "loop" in the code, just a "loop" of the object's position.

#

Only one thing is happening each frame

rugged jackal
#

So the code is interpreting moving the object once it hits the less than value of -xRange then instead of stopping, the next statement is causing it to jump to the top of the greater than xRange in this case, once the character position value hits -10, it jumps to 10?

wintry quarry
#

yes, that's what your code says to do

#

so that's what happens

#

"if position is less than -10, set position to +10"

rugged jackal
#

Thank you for your help

#

the Clamp line works better and its easier for me to interpret

chrome shadow
#

im super confused if the code from the picture is using unity's new input system, because it looks super different from the input system tutorials i found on youtube, or is it just a newer version of the input system??? this code is from unity's third person starter asset package, and im using unity 6

teal viper
#

Also, there are many different ways to use the input system. I image subscribing some methods to the input events is one of them. The first 3 methods look like they might be doing just that.

chrome shadow
#

using UnityEngine;
using UnityEngine.InputSystem;

public class CharacterInput : MonoBehaviour
{
[Header("Character Input Values")]
public Vector2 move;
public Vector2 look;
public bool jump;
public bool sprint;

[Header("Movement Settings")]
public bool analogMovement;

[Header("Mouse Cursor Settings")]
public bool cursorLocked = true;
public bool cursorInputForLook = true;

#if ENABLE_INPUT_SYSTEM
public void OnMove(InputValue value)
{
MoveInput(value.Get<Vector2>());
}

public void OnLook(InputValue value)
{
    if (cursorInputForLook)
    {
        LookInput(value.Get<Vector2>());
    }
}

public void OnJump(InputValue value)
{
    JumpInput(value.isPressed);
}

public void OnSprint(InputValue value)
{
    SprintInput(value.isPressed);
}

#endif

public void MoveInput(Vector2 newMoveDirection)
{
    move = newMoveDirection;
}

public void LookInput(Vector2 newLookDirection)
{
    look = newLookDirection;
}

public void JumpInput(bool newJumpState)
{
    jump = newJumpState;
}

public void SprintInput(bool newSprintState)
{
    sprint = newSprintState;
}

private void OnApplicationFocus(bool hasFocus)
{
    SetCursorState(cursorLocked);
}

private void SetCursorState(bool newState)
{
    Cursor.lockState = newState ? CursorLockMode.Locked : CursorLockMode.None;
}

}

#

this is connected to the movement code

#

and it just references this code for anything input related

#

so is this code using the new input system?

#

or is there a new input system for unity 6

#

cus its kinda confusing

teal viper
#

Oh, I see they have 0 references. They are likely referenced in the inspector though.

#

Look around where this component is and see if there are any other components that might be referencing it and using these methods as callbacks.

chrome shadow
#

alr

#

is there a diff input system for unity 6?

naive pawn
#

no, it's just old system (input manager) and new system (input system)

#

the default was changed in unity 6

chrome shadow
#

so the input system from unity 6 is the same as ones from previous versions right?

naive pawn
#

yeah

crisp ingot
#

can anyone please help me with some code, im making my first ever game and am heavily stuck 😭

grand snow
#

Ask the question here and people can help...

chilly prism
#

why doesn't this destroy the bullet

crisp ingot
#

i am trying to walk up to a cube and press "f" for example and then i will teleport from one cube to the other.

chilly prism
#

but i cant refrence BulletIns if i put them in the update method

grand snow
chilly prism
grand snow
#

Create new bullet, add to list, loop over list in Update () to do your destroy check.

chilly prism
#

how do i create a new bullet

#

for i in list[] if i ...?

grand snow
chilly prism
grand snow
#

You need to re visit the basics of c#. You make a new instance of list (as a class member) and use .Add() later to insert a new element.

chilly prism
#

is there a different way to approach this other than lists

#

ok i added BulletIns to the list

#

so basically something like this?

chilly prism
modest dust
#

Define "doesn't work"

#

Also, you never remove the deleted bullets from the list

#

At least in the code fragment you shared

burnt vapor
eternal falconBOT
chilly prism
#

and it doesn't

chilly prism
#

when i play the game i get this error

burnt vapor
modest dust
#

I suppose it's the list

burnt vapor
#

Please provide the full error

chilly prism
#

in the unity console

modest dust
#

Which line. Everyone know that it's in the console

chilly prism
burnt vapor
#

You need to check what line this fails on. The error indicates this, including the faulthy file. From there it's clear what goes wrong

#

And what is line 30?

chilly prism
#

wait

modest dust
#

And which line is line 30, you cut it out of the screenshot.

burnt vapor
#

You left out the lines from your screen shot

chilly prism
modest dust
#

Yeah, the list

burnt vapor
#

Okay, so the list has never been created

#

If this is intentional, wrap it in a null check. If not, make the list

#

It would really help if you shared all your !code

chilly prism
eternal falconBOT
modest dust
#

A List is a reference type, you have to assign a value to it

burnt vapor
#

This is just the definition

chilly prism
modest dust
#

List<GameObject> BulletList = new();

chilly prism
#

oh ok

burnt vapor
chilly prism
#

it works now\

#

thx

#

it deletes the bullet when it's offscreen

#

Thanks

burnt vapor
#

If you do this, it will be clear what parts might be null in your code

chilly prism
#

yeah, i cant understand what this does exactly

burnt vapor
#

Hard to explain. You can find a .csproj in your current project which has this as well (and much more)

#

Basically you can't modify it because Unity keeps replacing your additions so the props file explained in that post is an alternative

gentle bone
#

its like a configuration file for your project...

burnt vapor
#

It should automatically adjust your csproj file with this, but I have heard it might not work properly

chilly prism
#

hey man as long as the code works i am happy

burnt vapor
#

Remove the TargetFramework part if you do plan on adding this

#

Pretty sure LangVersion can also be bumped to 13, which gives more language features

chilly prism
#

i dont wanna add stuff i dont understand

burnt vapor
#

Then ask

chilly prism
#

pretty sure imma come across this again when i am an expert

burnt vapor
#

This is very basic stuff. It's jsut that Unity doesn't add this yet. Modern .NET does add this to projects by default

#

Alrighty

teal viper
#

At best it's gonna create compile errors, since it's compiler doesn't support these features.

burnt vapor
#

Lame

#

In that case you can also add the #nullable enable directive on top of files to enable it. Would be nice if it could just be enforced globally

slender nymph
#

it is possible to increase the language version, but you only get access to the syntax sugar stuff. anything that actually relies on stuff added in newer .net versions won't work

teal viper
burnt vapor
slender nymph
#

yeah that could probably work for some of them

sour fulcrum
burnt vapor
#

Like file-scoped namespaces just have their blocks readded during lowering.

slender nymph
teal viper
slender nymph
#

gotta update the roslyn compiler to support it

teal viper
#

So mess with unity compiler toolchain?

burnt vapor
sour fulcrum
#

All the nerds having their fun with nullables while i wait to use statics in interfaces

teal viper
burnt vapor
#

This is based on language version, not necessarily what version of .NET you use

burnt vapor
teal viper
teal viper
sour fulcrum
#

not sure if im wrong but i dont think you need to go that far?

burnt vapor
#

I wonder how much Unity does in terms of compilation, though. Is this part of an installed version? Does it even provide one?

sour fulcrum
#
The extension will insert Analzyer element into .csproj when generating the project file. As a result, you can run Roslyn Analyzer when editing code in Visual Studio. (of course, you can use it before 2020.2!)

i seee

teal viper
slender nymph
teal viper
sour fulcrum
#

oh shit i did not know c# 13 let lists and ienumerables go into param[]'s. that would be cool to have

#

need those static extensions too

teal viper
#

I also wonder how acceptable it is to upgrade the compiler from the perspective of the terms of service.

#

At the very least they would probably decline support for such projects. If they can detect it somehow.

sour fulcrum
#

Always curious how much certain studios stick by terms of service

#

I went to a cool talk where a studio was using Harmony in editor to do some cool stuff with assembly injection for workflow and quality of life

#

Like some cool setup that was able to link specific assets and in-scene objects to jira tickets and shit

#

probably not tos-friendly

teal viper
sour fulcrum
#

right

#

Can't go into it too much but a friend was showing me how to tip toes into the c++ side of things and im really curious to mess with that purely just to know whats going on behind the scenes with a couple things

chilly prism
#

made an enemy and gave it a boxcollider2D, i want the bullet to destroy the enemy upon impact, but this code doesn't work for some reason

keen dew
#

Don't use the name to check what object it is. Give the bullets a tag and compare the tag

wintry quarry
#

Start debugging it. Add a Debug.Log and print the name of the object you entered

keen dew
#

You didn't need to delete the existing code but yes

chilly prism
#

it doesn't show anything in the console

#

my console is filled with wakatime things

north kiln
chilly prism
#

Thx it works now

vital zodiac
#

OnInteract is not being called

Inputmanager:

using System;
using UnityEngine;

public class InputManager : MonoBehaviour
{
    private InputActions inputActions;
    public event Action OnInteractEvent;

    void Awake()
    {
        inputActions = new InputActions();
        inputActions.Player.Enable();

        inputActions.Player.Interact.performed += ctx => OnInteractEvent?.Invoke();
    }


    public Vector2 GetMoveInputNormalized()
    {
        Vector2 moveInput = inputActions.Player.Move.ReadValue<Vector2>();

        return moveInput.normalized;
    }

}

player.cs:


    void Awake()
    {
        inputManager.OnInteractEvent += OnInteract;
    }

    void Update()
    {
        Vector2 moveInput = inputManager.GetMoveInputNormalized();
        Vector3 moveDir = new Vector3(moveInput.x, 0f, moveInput.y);

        HandleMovement(moveDir);
        HandleAnimation(moveDir);
        HandleInteractions(moveDir);
    }

    public void OnInteract()
    {
        if (selectedCounterScript)
        {
            selectedCounterScript.Interact();
        }
    }
slender nymph
vital zodiac
#

my player is going inside the counter when trying to enter from the corners

player.cs


    private bool IsCollision(Vector3 moveDir, float moveDistance)
    {
        return Physics.CapsuleCast(transform.position, transform.position + Vector3.up * 2f, playerRadius, moveDir, moveDistance + 0.1f);
    }

    private void HandleMovement(Vector3 moveDir)
    {
        float moveDistance = moveSpeed * Time.deltaTime;

        bool isCollision = IsCollision(moveDir, moveDistance);
        if (isCollision)
        {
            Vector3 moveDirX = moveDir.x * Vector3.right;
            bool isCollisionX = IsCollision(moveDirX, moveDistance);

            if (isCollisionX)
            {
                Vector3 moveDirZ = moveDir.z * Vector3.forward;
                bool isCollisionZ = IsCollision(moveDirZ, moveDistance);

                if (!isCollisionZ)
                {
                    moveDir = moveDirZ.normalized;
                }
            }
            else
            {
                moveDir = moveDirX.normalized;
            }
        }
        

        float rotateInterpolation = 5f * Time.deltaTime;
        transform.forward = Vector3.Slerp(transform.forward, moveDir, rotateInterpolation);


        transform.position += moveDistance * moveDir;
    }
strong shoal
#

is it possible to check if an dictonary contains a key that was pressed???

vital zodiac
#

which dictonary

strong shoal
vital zodiac
#

just add debug.log

modest dust
vital zodiac
strong shoal
#

do i check which key was pressed

vital zodiac
#

ask chatgpt

vital zodiac
#

use a input manager ( new unity input system )

#

or do Input.getKey("keycodee")

strong shoal
#

so i cant do it this way

vital zodiac
strong shoal
#

i dont want to make 100 if statements

#

or case

vital zodiac
#

you have to

strong shoal
#

for sure there are other ways

vital zodiac
#

use switch case get the key pressed (any key) then put in switch case and run each case

modest dust
vital zodiac
#

if keyPresed is in dictionary

#

someone

#

it should go to either x or z

#

why is it going inside the cube

modest dust
#

@vital zodiac Please stop spamming, if you have something to say, send it in a single message.

vital zodiac
#

i did

modest dust
#

I'm talking about your later messages.

modest dust
strong shoal
#

wait it probbably wouldnt

modest dust
#

Try it and see

strong shoal
#

depends how many keys i have

modest dust
#

It would just return true if any key is pressed.

polar dust
#

why exactly do you need a dictionary of keys?

vital zodiac
#
void Update()
{
    if (Input.anyKeyDown)
    {
        foreach (KeyCode key in System.Enum.GetValues(typeof(KeyCode)))
        {
            if (Input.getKeyDown(key) in keyDict.Keys)
            {
                Debug.Log("Key pressed: " + key);
                break;
            }
        }
    }
}
modest dust
#

Once again, it doesn't check if the key is in the dictionary.

vital zodiac
#

just add that condition

modest dust
#

Why check every single key in the first place?

#

I already wrote the solution

polar dust
#

what problem is being solved by looping over an entire dictionary? when Input.GetKey is able to tell you when a certain key is pressed

vital zodiac
modest dust
vital zodiac
static breach
#

im driving crazy. my buttons doesnt work in world space

vital zodiac
#

it will definately exist

modest dust
#

A lot of them are not even related to the keyboard

burnt vapor
burnt vapor
#

Pretty sure it also has this build in so you don't need to do all this

vital zodiac
polar dust
# vital zodiac ```cs void Update() { if (Input.anyKeyDown) { foreach (KeyCode k...

this code is pretty bad, ngl
every frame you'll check if "literally any key is pressed", so for most games that will be almost always happening
then you loop over a dictionary, but unless the dictionary contains every single key that can be pressed, it will be wasteful (imagine the letter G is never used in the game, but I decide to hold G down)

but also each iteration in the loop, youre doing an if statement to check if a certain key is pressed (first if condition already establishes that a key is pressed, a second check is pointless) and if it happens to be in the dictionary you return early, just hope that the user isnt pressing the key thats the last one in the dictionary

vital zodiac
#

its probably like 0.4ms process

static breach
polar dust
#

its "if literally any key is pressed, check every item in the dictionary, but lets check again if the user is pressing a key, and if they are pressing a key is that key in the dictionary"

modest dust
#

You're overcomplicating it

burnt vapor
polar dust
#

whats the reason why you want to do this dictionary lookup thing?

modest dust
burnt vapor
#

This whole thing is probably just an XY problem anyway and it is getting snowballed into poor solutions even though it could be fixed a different way

polar dust
#

sounds like pre-optimisation "I might in the future have more keys" type thing
if you dont actually have many keys right now, dont try and fix a problem that does not exist right now

burnt vapor
#

By all means not a bad thing, but definitely something that might have a better solution

polar dust
#

linq is a very powerful thing

eager elm
# vital zodiac my player is going inside the counter when trying to enter from the corners pla...

First of all, why not use Unity's physics system to handle collisions?
lots of strange things in the code

Vector3 moveDirX = moveDir.x * Vector3.right```
We don't know what moveDir is, but I assume it's x for left/right and y for up/down?  Why are you multiplying it by Vector3.right? Vector3.right is (1,0,0) so you are multiplying by 1 which doesn't do anything. Same with moveDir.z * Vector3.forward

The reason for your problem is probably that you are checking for a Z collision inside your If statement for the X Collision.
polar dust
#

the amount of messy and overly long if statements and for loops that often take multiple lines, can often be shortened down to a single linq method

vital zodiac
#
We don't know what moveDir is, but I assume it's x for left/right and y for up/down? = yes its comming from the inputManager (new)
 Why are you multiplying it by Vector3.right? Vector3.right is (1,0,0) so you are multiplying by 1 which doesn't do anything. Same with moveDir.z * Vector3.forward = i am actually throwing ray to both x and y for not making the charectes stop when the collison is happend, for example if the moveDir is 0.71 at x and y it will not move toward x because of rayhit so i am doing that to make that happen

and i have figured the issue just now

Actually at the corner both the x and z ray are hit. and this condition is not in the code, causing it to just continue to move in the movedir
i prefented that but adding that and doing return from the function
vital zodiac
polar dust
#

what is faster?

#

I was saying linq could be a cleaner way to check a dictionary to see if the current key pressed exists in the dictionary

vital zodiac
#

oh i thought u were talking about my code

polar dust
#

I hadnt totally worked out what was going wrong in the code you posted earlier

#

I get the sense of what its doing

burnt vapor
polar dust
#

linq is at a disadvantage when used with unity?

burnt vapor
#

If they do a normal iteration without LINQ it will be a lot better than using LINQ with it. It's still bad, but at least not much slower

burnt vapor
shell sorrel
#

its fine for one offs and quick and dirty things but yeah do not use linq in things happening every frame

#

also there is nothing linq can do that you just cant do with some loops

polar dust
#

ah, I thought there wasnt much of an issue with its performance

I would say that, unless you start chaining lots of things together, the readability at least provides some benefit

shell sorrel
#

also its main issue is not speed but allocations and garbage

#

doing things manually allocations become very obvious and easy to just reuse things or use stuff like pooled collections to avoid them

#

but yeah i will totally use it in like startup logic or things that happen rarely

burnt vapor
#

Speed definitely also plays a part. Modern .NET does something with hardware accelleration to an extend, which goes beyond my knowledge, and it is definitely a lot faster.

#

For one off actions it's very good, also if you only call simple methods. When it's more often or bigger you might want to reconsider it for now

polar dust
#

thing is speed is still a relative thing, I'd be certain their original nested if statement where its is any key pressed, foreach the dictionary, check again if a key is pressed and compare it to the current item would be far less optimal than the simplified linq version

its just that the linq version would be less optimal than writing the original block in a way that sucks less
the linq at least (in theory) allows them to simplify things down into a way "that just works"

#

using the actual input system is really the best option, not any kind of check like that what theyre doing

burnt vapor
#

If they cache Enum.GetValues(typeof(KeyCode)) then it is nanosecond work

harsh drift
#

hello. lampMaterial.SetFloat("_EmissiveIntensity", 0); its why not work correctly? im change the emissive intensity but its changed only the inspector, the graphics not modified

burnt vapor
#

So speed really doesn't matter here, it's the fact they are doing something obscure when they could just use the new input system and do it properly

#

Only Enum.GetValues(typeof(KeyCode)) is bad because in older .NET it would do a lot under the hood, which doesn't change with the next iteration so it should be cached.

polar dust
#

I'd like to know what the dictionary is for in the first place, what the key-value-pair is in it

burnt vapor
#

I asked, no response

polar dust
#

this was posted by them before

#

and seems like its for a similar thing

burnt vapor
#

It has nothing to do with keys, though. I assume it's a later feature being added.

#

I mean regardless, iterating the dictionary is not bad either. Enumerations are incredibly fast

#

I feel like this conversation is base don a lot of assumptions that the logic is slow when it's not. It's just being made slow with a lot of excessively complex logic

polar dust
#

just imagine pressing E tells some method that it should give it the string givemoney

#

the new input system is designed to automate this kind of thing

#

just tell it what keys are able to be used to do a certain thing

burnt vapor
#

That's why I initially said to just use the new system for anything that doesn't require basic input checking

polar dust
#

yeah, i saw them say they didnt want to use it

#

I'd guess that might be because their current code is only designed to work with their specific approach

vital zodiac
acoustic belfry
#

hey, someone knows why my sounds have echo? sounds robotic and with echo wich is creepy, is when the states with sound are called

    {
        animator.Play("Base Layer.MortemRifleSight");
        audioSource.PlayOneShot(troopersight);
        detectoValeria = true;
        delay -= Time.deltaTime;
        if (delay <= 0)
        {
            delay = 0.2f;
            currentState = MortemState.Chase;
        }
    }```
wintry quarry
#

You should play it only when you first transition to the state, not every FixedUpdate

#

I would adjust your structure here so that instead of directly setting the currentState variable, you call a function that handles enter/exit events for the states too

acoustic belfry
acoustic belfry
acoustic belfry
cinder blade
#

can I ask questions in this channel
because I have a problem with a coroutine that stops playing after a yield return null and it is not because the gameobject is desactivated or the monobehavior disabled

Debug.Log("delay");
yield return null;
Debug.Log("delay2");

the delay message is shown but the delay2 message isn t
and the console shows no error

grand snow
burnt vapor
#

A coroutine does not stop unless explicitly stopped or the game object is gone, so let's verify it truly still exists

#

Otherwise look for StopCoroutine calls in your code

cinder blade
#

I have tracked with events if the mono was disabled or destroyed and no where in my code i have a stop all coroutines

burnt vapor
#

Is the game object disabled?

cinder blade
#

no

burnt vapor
#

Sorry, you already mentioned this

cinder blade
#

that s why i can t figure it out

burnt vapor
#

I assume this yield is the first instance of a yield appearing?

#

Can you post the full thing maybe?

cinder blade
#

no I also have a

yield return new WaitForSeconds(typingSpeed)

that has no problem

#

here s the full Ienum

public IEnumerator TransitionScenetoScene()
{
Debug.Log("defaultstate1");
sceneset.DefaultState();
dialoguemanager.indialogue = false;
avancee.canselect = true;
dialoguemanager.stage = 0;
DialogueBox.SetActive(false);

    foreach (Transform child in ChoicesNAvancee.transform)
    {
        GameObject.Destroy(child.gameObject);
    } 
    
    
    foreach (Transform child in IntantiatedObjects.transform)
    {
        GameObject.Destroy(child.gameObject);
    }
  
    Debug.Log("delay");
    yield return null;
    Debug.Log("delay2");
    sceneset.LoadNextScene();

}
burnt vapor
#

Are you modifying the timescale of your game?

#

Not that it would affect a null yield

burnt vapor
burnt vapor
#

Another reason could be that you use Invoke. Is this something you use?

#

I'd triple check the game object is not destroyed, nor disabled, with this log. Lastly also check for Invoke and if you do use it, double check the length added is a valid number, and not NaN. This can silently break coroutines.

cinder blade
#

the Debug.Log("delay", this); shows that the gameobject still exists

#

If something Invoked it stops the coroutines ? even in others scripts ?

#

every Invoke in my project have a 1f parameter

lilac fractal
#

I'm struggling to design a system for storing types of projectiles. I can't quite get the balance of Behaviors vs ScriptableObjects right.

Every projectile has a set of data associated with it (sprite, weight, damage, speed, etc). I feel like this is a good candidate for ScriptableObject data.

But then we also have a set of behaviors associated. For instance, one projectile might have an "explode on hit" behavior, or a "poison on hit".

#

Ideally I would love to define these behaviors as a configurable item in the interface. I want to create an instance of ExplodeOnHitBehavior, set its Radius, and then attach it to a ExplodingProjectileData as one of its behaviors.

#

I'm having issues with being able to drag/drop scripts, or knowing which ones to make behaviors vs scriptableobjects.. it feels like I'm fighting the separation of data and behavior here.

#

Are there any references for how folks have put together systems like this before?

#

If I can't figure this out, the caveman approach in my head is just to define a series of projectiles as MonoBehaviors and hardcode everything - no reusability, just reimplementing OnHit functionality in each of them.

eager elm
# lilac fractal I'm struggling to design a system for storing types of projectiles. I can't quit...

https://github.com/mackysoft/Unity-SerializeReferenceExtensions
this is probably what you want. You can create your OnHitEffects as a normal C# class and then add a List of them to your SO.

[System.Serializable]
public abstract class OnHitEffect
{
    public int radius
}

public class PoisonEffect : OnHitEffect
{
    public int duration;
}
```Then you can add them in the inspector and assign the fields there
pallid nymph
lilac fractal
#

My goal was to sort of rip out behavior into reusable modules

pallid nymph
#

So, sub-prefabs perhaps?

#

So, one behaviour is one prefab, it can have whatever it wants (more than one Mono), but you can drag and drop it as part of another prefab and it'll add the behaviour

lilac fractal
#

Mmmmh... that might be the play.

#

I feel like ScriptableObjects don't have a place here then

pallid nymph
#

SOs tend to be good if you just vary data (and maybe a tiny bit of behaviour... non-extensivle behaviour, perhaps 🤔)

lilac fractal
#

I believe these behaviors are going to hold state and component references too, which also further pushes me away from SOs

pallid nymph
#

Like, having 50 of the same thing with different params, where you would only want to modify the params to distinguish the things, and you don't need to customize the thing that uses them

lilac fractal
#

so we might have..

public class PoisonOnHitBehavior: MonoBehavior, IOnHitBehavior
{
  public void OnHit(ProjectileController p, GameObject o)
  {
    if (o.TryGetComponant<EnemeyController>()..)
      StartCoroutine(PoisonEnemey(enemy));
  }
}
#

Something like that.

#

So I could see each projectile being a prefab, assigned a series of these behaviors, and then instantiating them when we spawn the projectile and letting it rip as it hits enemies.

pallid nymph
lilac fractal
#

Got it. It makes sense, I think I got lost in the sauce thinking SOs were a good fit here, but not so much. Need to re-review their use cases.

#

Thank you c:

nimble apex
#

i gonna start with a use case, this function will only be called when player join other rooms, so its really once in a while

lets say player will open X amount of UIs, it would be many, >=1 or >1, without recording/storing reference of the opened UIs, can u accept using GetComponentsInParent or GetComponents to turn off all existing UIs?

#

an alternative would be reloading the scene, such that every UI will be dropped

whole osprey
#

You're worried about an efficiency of using GetComponent... calls when closing all UI panels? If you're just finding them all one time, then closing them, it shouldn't really be a problem. Especially if the only other option you are considering is reloading the scene, which will take forever relative to the GetComponent idea.

This doesn't sound like the best way to handle this system, but it should work.

grand snow
#

Re loading a scene to "reset it" quickly becomes a shit solution

nimble apex
#
  1. find them all at once and destroy them in loop
    public void CloseAllUI()
    {
        ICommonUIFunctions[] allAssociatedUIs = FindObjectsByType<MonoBehaviour>
(FindObjectsInactive.Exclude,FindObjectsSortMode.None)
.OfType<ICommonUIFunctions>()
.ToArray();

        foreach (ICommonUIFunctions element in allAssociatedUIs)
        {
            Destroy(gameObject);
        }
    }```

2. reload the scene only to drop all the UIs  (switching session in my game does not require reload scene)

3. have a dynamic list where u update it in realtime, if u spawn one UI then add it to the list, if u destroy the UI then delete it on list
#

2 is overkill, and too unnecessary

#

3 gonna make the code scatter everywhere

#

thats why i chose 1

#

even if i find "all monobehaviors", if its only once in a while, then it will definitely less expensive than reloading a whole scene right?

grand snow
#

Why not track the things that can be closed later in 1 place when you open them...

#

e.g. central script for opening UI popups/dialogs/modals that tracks what it opens so you can close things later

digital haven
#

okay so i got a new xbox controller and set it up on unity. made sure all the code should be correct but i still can only get my character moving one direction and not controlled with the xbox controller. Any thoughts?

rich adder
nimble apex
whole osprey
nimble apex
#

actually i planned all 3 implementation already

rich adder
#

don't post code like this its unlegible mess, use links provided in !code 👇

eternal falconBOT
nimble apex
#

if the loc of ur code is >50 i think u better use some external pastebin sites

digital haven
nimble apex
#

plz delete ur code wall first😭

digital haven
#

sorry about that

nimble apex
#

i thought of 3 before, but imagine i need to create a list and a manager . Plus i need to update the list frequently just for turning off UIs

#

but if thats the best bet i will go for it , ty👍

grand snow
#

Games I work on where I work have a central "Root UI" that you can open, close and get dialogs from.

#

dialogs get opened with a provided addressable address (to load the prefab asset) and can be retrieved later with their unique string ID

rich adder
digital haven
rich adder
nimble apex
grand snow
#

All that means for my example is 1 controlled parent to spawn them all in

digital haven
nimble apex
rich adder
nimble apex
#

ty

digital haven
rich adder
grand snow
digital haven
# rich adder send it the same way as you did b4

Learn to move characters in Unity 3D with this beginner-friendly explanation of Unity's new input system and root motion!

With this deep dive tutorial, you will not only have a better understanding of root motion and Unity's new input system, but you will also have an animated character by the end of the video!

SUPPORT THE CHANNEL:
💛 http...

▶ Play video
rich adder
#

so you are using root motion / animator to drive the transform ?

digital haven
#

i am unsure on the second one

#

the xbox controller seems to respond to the game when i press forward left stick so maybe I missed something that doesnt give me full control. or i didnt add something correctly

#

and yes i am using root motion

rich adder
digital haven
#

where could i check?

rich adder
#

he adds rotation right after the part you sent

#

HandleRotation()

digital haven
rich adder
#

the timestamp you sent his also just moves forward only

digital haven
#

ah, my bad. Well i will look over it again fully

rich adder
#

15:00 min starts the rotation part

digital haven
#

Yes, I feel silly about that sorry

rich adder
#

no worries

digital haven
#

Thank you I got it

nimble apex
#

IT WORKED😭 😭 😭

#

now im using an UI manager to record/track all opened UIs, and turn them all off using this

    public void CloseAllUI()
    {
        foreach (GameObject element in AllActiveUIs)
        {
            Destroy(element);
        }
    }```
#

was planned to use a stack but its way too vulnerable

#

i gonna use functions to simulate stack instead

#

if u dont know what i mean

heres two UI , lets call the big one A and small one B

if i opened A and then someone send me a request (B)
stack will be populated as {A,B} right
if u gonna pop(remove) element, ur forced to start from B(smaller UI)

#

if i put all of them into stack, there will be error if i close A first right?

#

and theres no way u gonna force users to deal with join request first

wintry quarry
#

sure, which is why I don't see that this particular UI lends itself to a stack structure

#

but maybe I don't understand it

naive pawn
#

you wouldn't have those on the same stack, they don't have dependencies on each other

#

they aren't nested menus

nimble apex
#

maybe an extra list then?

wintry quarry
#

A stack would be for like modals, or for a tree-style menu

nimble apex
#

i see

#

ty 👍

naive pawn
#

@nimble apex perhaps take a step back and think about how you're thinking about the problem
you're thinking "how do i make these 2 things work with a stack", which is the wrong direction to go
figure out what you want to do, then how to do it - not the method, then the behaviour
you should instead consider what relation those 2 have, and how you would implement that - once you go from that direction, it should be clearer that a stack doesn't fit into that relationship at all

digital haven
#

okay i got this working but i am having a bit issue having them slow down. Is there a thing i missed so it doesnt move back into a slow to stopped animation. I did have a idle one within walking and running animation. @rich adder

#

I used a blend tree a few times, but i dont think that is needed if i just want them to slow down and stop on command

rich adder
digital haven
rich adder
digital haven
#

Yes

rich adder
# digital haven

I cant see what are the values of the paraemeters in the animator through video you have Layers selected instead :\

#

also I'd probably rewrite this though.

animator.SetBool(isWalkingHash, movementPressed);
animator.SetBool(isRunningHash, runPressed);```
or better yet, use blend tree
digital haven
#

blend tree would be good but i rather just add some commands still

#

the parameters just are what i see right here, because its just true or false boolean.

rich adder
digital haven
#

I still dont see where that is even while in play mode

rich adder
digital haven
#

oh well the iswalking bool keeps cutting out at times i did notice that?

#

I mean i guess i am confused still if it supposed to bring up a number or something?

rich adder
digital haven
#

Yeah me either, I am still learning everything I can.

rich adder
#

thats why i mentioned to check carefully how you copied video

#

tbh these if statements just seem so unecessary..

digital haven
#

wow that worked, yeah I just keep missing those small details

rich adder
digital haven
#

That is a good point, Ill start doing that. The thing is i feel like i don't retain unless i am doing something but i rather not miss simple code

sterile radish
#

hi, i'm making a dialogue system for my game and im currently stuck on how to make text effects. i've made a tag reader that detects text in a tag and adds it to an fx text list.
so for example if a character was saying "this is <w>super cool wavy<w> text!" the fx text would be "super cool wavy". im just stuck on how to actually apply these text effects onto the dialogue box?

my typer/tag reader script
https://paste.mod.gg/zimvffpdivko/0

dialogueui script:
https://paste.mod.gg/czwtamdlocip/0

grand snow
#

You can modify the tmp mesh after its made so that is how you would do your own effects like this

#

there is an event you can sub to react and modify the mesh each time it changes

rocky canyon
#

some of the tweening librarys can do tmpro stuf too

frosty hound
rocky canyon
#

🏆 winner!

#

lol.. as someone thats made a typewriter script ^ id def buy that if i were doing text stuff (or anything heavily dialog based)

grand snow
#

I've done my own "reveal text typewriter" thing before and its not that hard

#

anyway plenty of options available, free or paid

candid garden
#

Hey, I have a button which on click instantiates a preview of a building it will create on left click. on trigger enter of another collider it'll set the preview to invalid, but if I have a building behind the button, when the preview is instantiated it'll infinitely trigger ontriggerenter until I move the cursor which breaks my validate check. is there a way to stop that?

sour fulcrum
#

what trigger is it hitting

candid garden
#

another previously placed building

sour fulcrum
#

This is kind of a game design/logic problem than a specifically code one

#

What do you want to happen in this situation?

teal viper
candid garden
#

OnTriggerEnter is incrementing an int which is tracking how many "obstacles" the preview is over, so it's incrementing a bunch until I move the cursor

sour fulcrum
#

OnTriggerEnter in theory should only run once per time a collider "enters" the trigger collider. if the preview building isn't constantly exiting and entering the collider that shouldn't be ticking up

#

OnTriggerStay is what constantly invokes if a collider is inside the trigger

candid garden
#

I added a debug log to on trigger enter and once I click the button to instantiate the building preview, as long as I don't move the cursor and there's a building already behind the button it'll keep triggering ontriggerenter

teal viper
#

Ideally with the inspector, hierarchy and the console visible as well.

candid garden
#

does this help?
edit: oh the cursor didn't record, when the log fills up I'm just leaving the cursor still after clicking the button

teal viper
#

Can you share the relevant code?

candid garden
#

this is it

#

Is it because I'm using eventsystem?

teal viper
teal viper
candid garden
#

Oh i'm just changing the material when SetPlacementMode is called

candid garden
#

After messing around I noticed it is being set active properly (I removed a line making it active when it shouldn't have), but ontriggerenter still triggers a few times when the cursor leaves the button

teal viper
candid garden
#

It's kinda working most of the time now... Might just need to do some digging

candid garden
lilac cape
#

How do y'all generally organize your player input controls when using the new input system? Do you keep all the actions related to the same Action map in the same player controls script or do you separate the actions into different scripts based on the feature? I understand it's probably one of those "how ever you want to do it" but for now I'd rather just do what the majority of people do lol.

For example, I have a pretty basic player controls script but am starting to add complexity by adding an Inventory action. Should I enable/disable the inventory action in the inventorymanager and then just reference the playerinputactions? Utimately causing some actions to be handled by some scripts and some others? Maybe down the road I'll just have a movement scripts, inventory script, combat, etc?

spiral oracle
#

guys how do I get the velocity of a Rigidbody

rich adder
#

try typing it into google exactly like that and you will get your answer

rich adder
#

PlayerInputHandler will talk to all the scripts, that need input from player.. They don't directly know anything about Inputs.

#

eg a Movement script has a Move(Vector2 input) method that accepts a vector2 , it doesn't care where the input comes from.. it can be Player Controlled or like EnemyAI can be moved with a Simulated input by AI

lusty star
#

Hi i just made a multiplayer game and it works locally, how to buy it a server?

rich adder
lusty star
#

I really dont understand it, but i saw the dedicated server package should i install it

rich adder
lusty star
#

Like C# yeah im getting the hang of it so just got excited thats all

rich adder
lusty star
#

Couldnt be that hard right?

rich adder
#

the cheapest way is probably doing the unity Free Relay/Lobby stuff

#

or dedicated server if you dont want to do p2p

#

VPS cost money but less usage limits

lusty star
#

Like its based on player count?

#

The cost i mean

rich adder
#

the free tier unity has is pretty generous to get started, many people never come even close to the limits

lusty star
#

Alright yeah im getting it, ill be screenshoting this convo for when ill get more expirienced i think you are right

rich adder
#

good idea lol

lusty star
#

Thank you dude appriciate it

rich adder
#

btw if you're just trying to test it with like a friend or something like that, you could also temporarily open your port in router and give them your IP with port to connect to if you host.

lusty star
#

Huh that sounds complicated

sour fulcrum
#

this is complicated

lusty star
#

I think after ill understand all the terms stuff would get easier

rich adder
#

there was a time where all this (port forwarding) was pretty common thing to do especially when hosting to play with friends over the wire, dedicated servers were more expensive lol

tiny bloom
#

I have this simple code, the if statement, sees _destructEffect as "null" and not null
why is that?

[SerializeField] GameObject _destructEffect = null;


void Destruct()
{
    Destroy(gameObject);
    if (_destructEffect is not null)
    {
        Instantiate(_destructEffect, transform.position, Quaternion.identity);
    }
}
rich adder
lusty star
tiny bloom
#

dang you're right

#

ty

rich adder
# lusty star Like with hamachi correct?

hamachi lets you skirt opening ports (pretends everyone is on the same network / LAN ) but you cant host like a dedicated , say a Battlefield server or something

#

hamachi wasnt a thing before

rich adder
lapis parrot
#

how would you make something where if the player gets close to it text appears and when the player gets far it would disappear

wintry quarry
#

Use a trigger collider

#

And OnTriggerEnter/Exit

lapis parrot
wintry quarry
sand dagger
#

Trying to make a basic top down shooter and it's going great so far, but I'm a little stuck on how to get the enemies to face me when the game is playing.

#

I've gotten them to go towards the player, but they'll just point in any which way.

#

Wait, nvm no they do actually point towards me, I've just got them positioned wrong lol

sharp bloom
#

Yeah the moment you ask a question here you immediately solve the problem yourself xd

sand dagger
#

It only occurred to me to check the collider once I asked the question lmao

#

Turns out, there’s a very helpful line that tells you what the “front face” is for the circle collider

sharp bloom
# lilac cape How do y'all generally organize your player input controls when using the new in...

I have been learning and messing around with the new input system as well. Took me a good while to wrap my head around it.

public class GameInput : MonoBehaviour
{   
    public static GameInput Instance;
    private MainInput mainInput;
    public bool isRunning;
    public Vector2 movementInput;
    public Vector2 mouseDelta;
    public static event System.Action OnPlayerShoot;
    public static event System.Action OnPlayerInteract;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(this);
        }
    }
    
    void Start()
    {
        mainInput = new MainInput();
        mainInput.Enable();
        mainInput.PlayerControl.Move.performed += ctx => movementInput = ctx.ReadValue<Vector2>();
        mainInput.PlayerControl.Look.performed += ctx => mouseDelta = ctx.ReadValue<Vector2>();
        mainInput.PlayerControl.Run.performed += ctx => isRunning = !isRunning;
        mainInput.PlayerControl.Shoot.performed += ctx =>
        {
            OnPlayerShoot?.Invoke();
        };
        mainInput.PlayerControl.Interact.performed += ctx =>
        {
            OnPlayerInteract?.Invoke();
        };
    }
}

I don't know whether it's the most optimal, but I split all input reading away from my player controller class to its own class which is singleton so I can easily access the Vector2 values for instance.

#

Then I can just subscribe to those shoot and interact events from anywhere I like

topaz mortar
#

Uff

                        }
                    }
                }
            }
        }

    }
}```
lusty viper
# topaz mortar Uff ``` } } ...

I think I read a coding tip somewhere that said, if you ever get more than like 4 indents deep, you need to rethink your decisions lmao

sharp bloom
#

Yes

#

My life got better when I realized I could invert most of my ifs and just say return

sour fulcrum
#

or continue 😄

sharp bloom
#

There's a method in one of my projects that consists of a switch with 5 cases, and each case has 4 nested ifs inside

#

Pasta is ready

chilly prism
#

music slider and sfx slider work in editor but dont work when i build the game

visual linden
ripe flame
#

Hello there :D
I want to check for a button press via the getkeydown thing.
Should I put that into update?
I do not want to trigger the function that I will connect to it every frame, but only once per button press

halcyon geyser
#

GetKeyDown() inside ur Update

#

Then you'll have to create some toggle to only call it function once

visual linden
ripe flame
#

That is great

#

That makes it so much easier

#

Thanks yall

sharp bloom
#
public SO_ItemConfig itemConfig;
   
public void Interract()
{
    if (itemConfig.GetType() == typeof(SO_WeaponConfig))
    {
        Debug.Log("it is a weapon");
    }
    else
    {
        Debug.Log("it is not a weapon");
    }
}

How would I correctly check the type of the scriptable object in question? The SO_WeaponConfig inherits from the abstract class SO_ItemConfig. Currently this returns false even though the itemConfig is infact a SO_WeaponConfig.

#

I mean I could just make them seperate things I guess

naive pawn
#

wouldn't it be itemConfig is SO_WeaponConfig

wintry quarry
#

Both of those would work fine, this is kind of an anti pattern though

sour fulcrum
#

can even get the cast like

if (itemConfig is SO_WeaponConfig weaponConfig)
naive pawn
#

GetType() == would make it false if you have a subtype of SO_WeaponConfig

sour fulcrum
naive pawn
#

(once you've copied the question over, remove it from here to avoid getting double help)

sharp bloom
#

The interface is actually badly named because I plan to use it for pushing buttons and interacting with similar objects

sour fulcrum
#

so is it more like IInteractable?

sharp bloom
#

Yes

#

When the item is on the ground it's an interactable object

sour fulcrum
#

you may want to do your inheritance in a kinda sibling esque way so you have a Weapon : Item class that overrides Item's implementation of IInteract

sharp bloom
#

Okay yeah that makes more sense

sharp bloom
teal viper
#

I'd rather have a separate interactable object that has an inventory(or just 1 item slot)

sour fulcrum
teal viper
#

For dropped items

sour fulcrum
#

(It's possible my suggestion is not the prefered way to go, many different ways you can do this tbh)

#

@grand badger ?

sharp bloom
#

Yea I'm mostly just trying things around

grand badger
sour fulcrum
#

I am going off the context of the information they have provided

grand badger
#

if there's a IUseable item in the plan then this pattern is solid imo

modern path
#

Why is this always returning true? bool grounded = Physics2D.Raycast(transform.position, Vector2.down, 0.1f); if (grounded) { print("Grounded"); } else { print("Air"); }

grand badger
sharp bloom
grand badger
#

if you're a beginner, it's a trap 😛

#

what's your scope for this game, specifically? (in e.g. months + target/goal, like release, portfolio, etc)

modern path
sharp bloom
#

Ye for smaller games might not matter that much but I feel they are useful to learn still

grand badger
modern path
#

The raycast is hitting the ground

#

I am checking with debug.drawray

#

And the ground platform does have the Ground layer applied

grand badger
#

some people prefer using feetTransform.position, some others prefer using transform.GetComponent<Collider>().bounds.bottom + Vector3.up * 0.05f;

modern path
#

Oh wait

grand badger
#

yeah, but the debug drawray likely doesn't match your raycast's hit. Currently, you're using 0.1f as length

modern path
#

I see what you mean

grand badger
#

for beginners, my advice is to experiment with what's believed to be wrong, and find out for themselves why other solutions are proposed.

#

what's believed to be wrong: not exactly, but more like "What YOU believe is good, with your current understanding", even if other people/best practices are against it.

sharp bloom
#

Well I have some older projects that use GameObject.Find() for literally everything. At least I'm past that stage lol

grand badger
#

ya that's what my first project was like as well xD

#

soon refactored to use references, then refactored again to use OOP, and so on

modern path
#

I am using 2D

#

if that helps

naive pawn
#

or you could add the extents.y to get the bottom

modern path
naive pawn
#

or you could set the pivot to the bottom

modern path
#

The raycast just always returning false for some reason

naive pawn
#

have you set the layermask correctly?

modern path
#

I think so?

naive pawn
#

show your current !code

eternal falconBOT
modern path
#
private float playerInput = 0;

// Horizontal player speed
[SerializeField] private float speed = 250;



private Rigidbody2D rb;
public float jumpPower = 10;



void Start()
{
    // Get component references
    rb = GetComponent<Rigidbody2D>();
}




void Update()
{
    
    
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = new Vector2 (rb.velocity.x, 0);
        print("jump");
        rb.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);

    }
    
    playerInput = Input.GetAxisRaw("Horizontal");
    SwapSprite();
    IsGrounded();
}


void IsGrounded()
{
    
    Debug.DrawRay(new Vector2(transform.position.x, transform.GetComponent<Collider2D>().bounds.min.y), Vector2.down, Color.green, 0.1f);
    bool grounded = Physics2D.Raycast(new Vector2(transform.position.x, transform.GetComponent<Collider2D>().bounds.min.y), Vector2.down, 0.1f, LayerMask.NameToLayer("Ground"));
    if (grounded)
    {
        print("Grounded");
    }
    else
    {
        print("Air");
    }
}
void SwapSprite()
{
    // Right
    if (playerInput > 0)
    {
        transform.localScale = new Vector3(
            Mathf.Abs(transform.localScale.x),
            transform.localScale.y,
            transform.localScale.z
        );
    }
    // Left
    else if (playerInput < 0)
    {
        transform.localScale = new Vector3(
            -1 * Mathf.Abs(transform.localScale.x),
            transform.localScale.y,
            transform.localScale.z
        );
    }
}
void FixedUpdate()
{
    
    rb.velocity = new Vector2(
        playerInput * speed * Time.fixedDeltaTime,
        rb.velocity.y
    );
}```
naive pawn
#

you should probably use a serialized field for the layermask

modern path
#

ok

naive pawn
#

make sure the layer name is accurate, including casing stuff

modern path
#

the spelling is correct

naive pawn
#

btw though, you shouldn't use GetComponent every frame like that, if you're going to use it a lot like here you should put that in a field that you set in Start/Awake like you've done with rb

#

the drawray isn't accurate though btw. you need Vector2.down * 0.1f for the drawray

modern path
#

Ok, I'll do that

naive pawn
#

where you have Vector2.down now

#

drawray doesn't take a separate distance parameter like raycast

modern path
#

oh

naive pawn
#

what you have as 0.1f in the drawray is how long to draw the ray for

#

anyways, make sure the ground is on the right layer and has a non-trigger collider

sharp bloom
#

Wouldn't checking if player is touching the ground with something like OnColliderStay also work here?

modern path
#

scratch that

#

it is not trigger

#

my brain farted

naive pawn
#

can you show the inspector for the ground object

modern path
sharp bloom
naive pawn
modern path
naive pawn
modern path
#

Difference between collider and rigidbody collider?

naive pawn
#

rigidbody collider there refers to dynamic rigidbody + collider

modern path
#

Imma just google an example this is too frustrating

naive pawn
#

but yeah i think that chart is somewhat misleading in saying "trigger rigidbody" as if it's a property of rigidbodies lol

#

it's not relevant to the raycast check though

#

ah the issue was the layermask lmao

modern path
#

oh

modern path
naive pawn
#

it suggested several methods

#

which one are you using

modern path
#

the public layermask one, I am about to try the other

naive pawn
modern path
#

No

#

What

#

II swear I set it

#

Anyways it works now

#

I must of set it whilst it was running

naive pawn
#

probably yeah

modern path
#

When the square hits the ground, it kinda pushes itself into the ground and then moves back up

#

Is there an easy way to fix that? Or is that just how the physics work

#

imma just get back to it tomorrow

silver fern
#

Is it possible to load/copy methods from a file?

naive pawn
#

load/copy to where?

silver fern
#

I'm trying to make a character selection thing similar to a fighting game, where every character has different attacks, and I think it wouldn't be smart to put a method for each attack of every character into the controller class so I wanted to load it in from somewhere

sharp bloom
#

This is the case for scriptable objects I believe

silver fern
#

so I make the character controller a scriptable object instead of mono behaviour?

naive pawn
#

no, you would just supply the attacks via scriptable objects

silver fern
#

I don't understand how to use this

naive pawn
#

did you find the manual page?

silver fern
#

yes but I don't understand how this applies to my case

#

unless I replace the whole controller with one of these objects

twin pivot
#

Make a script, make it a scriptable object, fetch the so from another script, call the method in the so

sharp bloom
#

No, your controller needs to accept a scriptable object as input. Inside the object you have some values and methods for different attacks. That is quite literally "loading methods from a file" .
I think at least that's the use case here.

silver fern
#

my original thought was to have a general character controller and to load in all the values and methods from a file

twin pivot
#

Thats what a SO is

sharp bloom
#

Yes you can also turn scriptable objects to files

silver fern
#

ah I see

#

so I'd have one scriptable object per character with all the data relevant to each?

sharp bloom
#

Something like that

silver fern
#

ok cool, thanks

silver fern
#

Different characters can have different health values, but if I store the health value in the character's scriptable object and two players choose the same character, will their health values be the same variable?

#

So when one character gets hit, both lose health?

#

Or will they be separate instances since they're loaded for separate players?

naive pawn
#

that's something you can control

sharp bloom
#

There is ScriptableObject.CreateInstance

naive pawn
#

changing the health of the so vs changing the health of the character

#

but you would treat the SO as stats and keep the actual current health on the character

sharp bloom
#

My understanding is scriptable objects are best used as "templates" for data, not necessarily changing it at runtime?

hardy bobcat
#

Ugh, I finally decided it was time to restructure my code.

#

Never again. Nothing was worse than 4 hours of namespace errors

#

Any time I will one day save by not having collisions

#

I have burned through in the worst way. Possible

sharp bloom
#

How do you get that many namespace errors? Renaming bunch of stuff or something?

hardy bobcat
#

Yeah I went from function to feature based

#

Basically all my UI code used to be in my UI name space

#

Now if it’s like, character editor UI. It’s I. The character editor namespace

#

Helped with dependency

#

Still ate my soul

#

I let an LLM do the renaming and moving

#

So this one is on me

placid oxide
#

anybody knows why when I drop a spreadsheet with an animator on canvas, it's always behind? Tried playing with layers and z and it won't come up. Tried talking with my bff chatgpt but just tells generic things

sharp bloom
silver fern
#

Can I load different parts of a scriptable object into different controllers or do I have to make a separate scriptable object with the data relevant to each controller?

naive pawn
silver fern
#

In this case, stats like health, attacks and special abilities would be handled by different controllers

#

Maybe I'm still not understanding these scriptable objects properly but I haven't been able to find information on how to properly use these in a case like mine

#

And the manual is completely useless

#

Can I just store the data in json instead or something

eager elm
silver fern
#

but I can't figure out how

eager elm
# silver fern yeah that's what I want to do
public class UnitData : ScriptableObject
{
    public int startHealth = 50;
}
-------------
public class Unit : MonoBehaviour
{
    public int currentHealth;
    public int maxHealth;
  
    public void Setup(UnitData unitData)
    {
        maxHealth = unitData.startHealth;
        currentHealth = maxHealth;    
    }
}```
silver fern
eternal needle
# silver fern yeah that's what I want to do

was the scriptable objects intended to be for the attacks? just skimmed through from the above conversation.
for what you were asking above, I would also just consider having each attack be its own monobehaviour if it requires state just to attach it to a prefab. Then you can drag them into your controller.
If you wanted to supply the attack methods by putting them in a scriptable object, they cant store any state inside the SO. So you'd have to find a way to copy this

#

though its not too clear, what are these relevant variables?

silver fern
eternal needle
silver fern
eager elm
silver fern
#

basically, each attack and ability has different code

eternal needle
#

you'll need different prefabs for each character anyways

#

If you try to just reuse one prefab where you change out everything from scriptable object data, it will get a bit complex

silver fern
#

I don't understand. The data has to come from somewhere right? So either I code each attack in to the controller, or I load it in from a file/SO after character selection

eternal needle
sharp bloom
#

ScriptableObjects can be made into files by [CreateAssetMenu], then you can just create a bunch of them with any data you want and plug them wherever you want. The data being usually values like health, name, damage, etc.

silver fern
#

And methods?

eternal needle
eternal needle
#

because at this point im just repeating it while you repeat that attacks/abilities are unique

silver fern
eternal needle
silver fern
#

So each character would be a prefab with relevant components attached?

#

and a scriptable object for values like health

#

Or is there something I'm missing still?

#

and then each prefab has their own copy of all the controllers

eternal needle
silver fern
#

yeah the controller is basic methods like movement etc

naive pawn
silver fern
#

or is current health in the prefab/SO too?

eternal needle
# silver fern or is current health in the prefab/SO too?

its up to you if you want to provide the current health as well, if the starting current health is different from the max health. they usually are the same but thats game design. you just make sure to copy the data so you arent modifying the SO in any case

#

health is definitely also a stat

silver fern
#

no the characters start at max health so that's not an issue. I would have the controller create a variable that stores the current health

#

unless I'm not supposed to do that

eternal needle
#

thats fine as well

naive pawn
#

but not on the SO

silver fern
#

yes, I mean max health would come from the SO

naive pawn
#

im referring to current health there

silver fern
#

so if I understand correctly, I have a prefab for each character that imports the controllers for basic methods and components for attack methods, and it gets instantiated with the stat values from the SO

#

controllers being the same for each character

#

does that sound right?

ivory bobcat
#

So just to clear things up, you'd have a base stats SO that you'd create multiple instances of as assets and have your characters reference those SO instances to initialize your stats. You'd have the characters current stats on each character and not the SO.

silver fern
#

yes

#

the SO is basically the 'file' that I load the initial stat values from

naive pawn
#

i think you're kinda conflating the prefab idea with the SO idea

ivory bobcat
spice mist
#

hello i recently made my first game and build it into mobile but im noticing a significant performance issue and input lag any reason why it is happening

eternal needle
naive pawn
# silver fern so if I understand correctly, I have a prefab for each character that imports th...

you need 2 things here - a runtime controller, and a static place to store stats

option 1 - a unified, single prefab for the controller as the former, and several SOs to supply the latter

option 2 - prefabs for each individual character, possibly as variants of a base controller, where you could then have the static stats on each prefab individually (the runtime aspect would be instances of that prefab)

#

if you have separate prefabs for each character anyways then there's no point for the separate SOs for stats, you can just have stats on the prefabs

eternal needle
spice mist
#

okay

#

and i saw a method of sprite atlas should i also implement that?

eternal needle
eternal needle
ivory bobcat
#

I'd use an SO if you've got data to share between multiple prefabs - reuse. If you're just needing to input/setup unique data from the inspector, you'd be able to do so on a prefab instance.

silver fern
#

OK so I don't actually need the SO, I just make a prefab for each character which already contains the initial stats, and has attached components for each attack

#

If I turn a GameObject into a prefab and later add something to the object, will the prefab change as well or do I have to edit each prefab individually in that case?

#

afaict, I have to start by turning my player object with the controllers into a prefab

steel smelt
# silver fern If I turn a GameObject into a prefab and later add something to the object, will...

A prefab lives in your project folder. It is considered an asset. From the moment you grab that asset and drag it into your scene, you create an instance of that prefab. A living copy.

If you modify that living copy(the one in your scene) and you do not apply the changes, then changes will not apply to the prefab(the asset, the template).

If you modify the actual prefab, so the one residing in your project folder, or if you apply the changes to the living copy you brought into your scene, then those changes will be reflected upon all copies of the prefab.

The exception happens when you modify living copies and do not apply the changes. Say you have an apple prefab. Apple has an exposed field with 20 hitpoints. You create an instance of that prefab by dragging it into the scene, and you change the hitpoints, in the hierarchy, to say 15.Then this specific instance knows it has a different value for hitpoints, and whenever the prefab is modified, it won't be reflected onto that specific instance

silver fern
#

The plan is to have about two dozen characters ultimately and I am worried that if I find and fix a bug in one of the controllers for example, I will have to do this individually 24 times for each prefab

steel smelt
#

If you expose fields in your controller(e.g. public fields or fields marked with [SerializeField], then yes, you will need to manually tweak the values across all of your prefabs since they each will have their own values

silver fern
#

not values, I mean things like movement methods

#

Right now I have a player object with different controllers handling stuff like movement for example. But I have to make a prefab for each character, and each character uses the movement method from the controller

#

But the controller script would be part of each prefab no?

steel smelt
#

Do all prefabs require a controller? If so, then yes, each prefab has a controller.

#

It is perfectly acceptable to have several prefabs with the same components

silver fern
#

yes they do, each prefab uses the same movement controller but different attack methods

#

and if I later find a bug in the movement controller, I have to apply the fix individually to each prefab?

steel smelt
#

It's a bit rough but it's perfectly acceptable

#

No, you apply the fix to the controller script, this has nothing to do with the prefab.

#

If you need to change which components are used for whatever reason, this is where you'll need to modify prefabs

silver fern
#

the logic behind unity data organization is so obtuse to me for some reason

steel smelt
#

Right now, what confuses you the most?