#💻┃code-beginner

1 messages · Page 608 of 1

wintry quarry
#

so what's NOT working when you do GetButtonDown?

#

I meant did you have it reversed that GetButtonDown actually works and GetButton doesn't

honest haven
#

the toggle never gets called of anything inside

wintry quarry
#

doesn't one of these get logged?

honest haven
#

no

#

nothing

wintry quarry
#
        if (PlayerController.instance.currentState != PlayerController.State.Attacking 
            && !GameManager.instance.npcAttacking)```
#

put a log before this

#

this condition is not evaluating to true

#

and it's probably only true during a few certain frames. GetButton is letting you overlap with those frames better

honest haven
#
        {
            Debug.Log("Button Down");
           ``` empty
#

I am also using pixel crushers Dialogue Manager - not sure if you used it or not, and if somthing like that could stop get button down. trying to think outside the box

wintry quarry
#

is it supposed to be Joystick Button instead of Joystick Axis or something

#

what are the types in there

honest haven
#

i copied what was in fire1 but changed the name and the type

slender nymph
#

why did you change the type

honest haven
#

to work with joystick

#

is thta incorrect other option was mouse and keys

#

I didnt replace fire1 i added to the array but copied the basics like gravity etc... as it was a button

slender nymph
#

see what happens if you change it back to Key or Mouse button

honest haven
#

ok

#

lol that work - why lol

slender nymph
#

because it's a button not an axis

honest haven
#

even tho its coming from a joypad

slender nymph
#

it's still a button not an axis

honest haven
#

well a xbox controller

#

well i never would have worked that one out - thank you very much

#

so only mouse x and y should be joystick

#

and i added them on 4th and 5th axis

slender nymph
#

button = on or off, no in between
axis = value from -1 to 1 based on current amount of input

honest haven
#

totally get it now penny has dropped - thank you

#

i do have a follow up question - does unity detect if a controller is connected as down the line i will have to swap ui button interation images to controller images etc... i.e pick up on keyboard is A and controller is B sort of thing

slender nymph
#

probably? i don't use the old input manager so i don't have a whole lot of experience with it. i know the input system (which is far better in nearly every way, just a bit of a learning curve to get started with) can detect when the input device has changed automatically

honest haven
#

Yh thats why i stuck with this one cuz i watch a quick video and it looked fairly simple

vagrant mist
#

Whats a simple way of keeping track how long a bool has been true for? I want a character to move faster after moving for a few seconds. I've got a bool to check if it is moving, but I'm not sure how to really go about keeping track of how long it's been true

slender nymph
#

once the bool is true start a timer (ie add Time.deltaTime to a float in Update)

swift crag
#

you can also just write the current time into a variable

#

Time.time - startTime is a duration!

slender nymph
#

ah yeah that too. i don't know why i didn't think of that considering it's how i typically do timers now lmao

wanton epoch
#

Would anyone know what would be the best way to assign new cameras to each player that joins a lobby in photon? I tried making it so that, if a player joins, it spawns a new camera prefab but that doesnt seem to work and breaks the displays for all players

ripe shard
slender nymph
wanton epoch
#

ah mb

polar loom
#

The errors dont have a fix and idk what to do

polar acorn
acoustic belfry
#

hey, i been trying to study the statemachines for improve my enemy. And i got a question.
What triggers the states?, i mean, how it specificly works? im pretty confused

polar loom
acoustic belfry
#

also i heard statesmachines work for make waits in the script, how?

acoustic belfry
polar acorn
#

State Machines are just a programming pattern.

#

You will change states whenever you code in the state changes

acoustic belfry
#

what

#

example

#

sorry im dumb ;-;

polar loom
#

this is the enable error

acoustic belfry
#

i mean, inside an state, the state itself will change the current state

#

for go to another state?

polar acorn
polar acorn
polar loom
#

This is setcallbacks error

polar acorn
polar loom
polar acorn
polar loom
#

im doing a tut and i believe its a movement script idk yet

#

its for like controller movement and pc movement

muted pawn
#

pls send the whole code @polar loom

#

!code

eternal falconBOT
polar loom
#

ok

polar acorn
acoustic belfry
polar acorn
#

which does not have Enable or SetCallBacks functions

acoustic belfry
#

this is how it changes states?

#

i know the rest, what bothers me is how states change, thats all

polar acorn
#

This is so far from the actual code I can't really answer if you've grasped the concepts or not

polar loom
polar acorn
#

object is probably not the type you want to use

acoustic belfry
polar loom
#

can you send fixed script?

polar acorn
#

I literally do not know what you want to happen

acoustic belfry
# polar acorn Usually

good, thats what i wanted to hear :3

B u t. what bother's me is, some ppl say its used for "waits", even for wait for an animation to end (i still have that issue, i thought i fix it, but nah ;-;). how that works? atleast for my understandment this is just...states moving and etc, how this can work for waiting?

polar acorn
stray thorn
#

SerializedObjectNotCreatableException: Object at index 0 is null
UnityEditor.Editor.CreateSerializedObject () (at <9e6ebc012b944bf1ac9a620fd8e232d1>:0)
UnityEditor.Editor.GetSerializedObjectInternal () (at <9e6ebc012b944bf1ac9a620fd8e232d1>:0)
UnityEditor.Editor.get_serializedObject () (at <9e6ebc012b944bf1ac9a620fd8e232d1>:0) why could this possibly be happening i wanna make a basic neural network and i have never in my life encountered this bs error

polar acorn
#

Either way it won't be in any builds so if it's not breaking things, you can probably ignore it

stray thorn
#

so its not my fault?

muted pawn
polar loom
polar loom
acoustic belfry
polar acorn
acoustic belfry
#

i hope this helps

polar acorn
polar acorn
# acoustic belfry what

You were asking about if a state machine introduces a "wait", and if you code it to wait a certain amount of time it's gonna have to wait that amount of time

#

I don't really understand what your question is

acoustic belfry
#

literally, w a i t, for an amount of time

#

the enemy is still

polar acorn
#

So what is the actual question about that?

#

how to wait?

acoustic belfry
#

i mean

#

i want to know a line of code that makes the enemy stay still for an specific amount of time

polar acorn
#

Everything stays still unless you're specifically telling it not to

#

So, in order to make it stay still, stop making it not do that

acoustic belfry
#

what i mean is, lets say in an extremely raw metaphor
(execute animation of dancing)
dance for 5 secs
(start making a havoc)

#

how the heck i can make it dance for 5 secs

polar acorn
#

By counting Time.deltaTime until 5 seconds pass, then making it do something else

acoustic belfry
#

i c o m p l e t e l y forgot about that...

#

but wait

#

how i can make this work for make the timer work with the duration of an animation?

#

my only issue here is, i want it to wait a sec when the enemy executes the realizing animation of facing the enemy, and to wait the long animation of reloading before shooting again

teal viper
#

Better cache time.time and check if curren time.time is 5 bigger

polar acorn
#

Instead of waiting for 5 seconds to pass, wait for the duration of an animation to pass

acoustic belfry
#

how do i set that up

polar acorn
acoustic belfry
#

ah

#

ok

#

well, thanks

#

but i mean, using a timer for such trivials things is ok? im still worried about the performance of my script

#

i mean, i just discovered the existence of statemachines, meaning my script is shit

polar acorn
teal viper
#

If it's animation related, may e use animation events though. Or query the current animator state

acoustic belfry
teal viper
acoustic belfry
#

thats the issue, i want to prevent them...But i guess that makes sense, cuz how do i would find them if im preventing stuff that just overwhelmes me

#

makes sense, thx

acoustic belfry
#

its like a boolean...but inside an animation?

#

or i didnt understand it

polar acorn
#

It's a thing you put in the animation that calls a function

acoustic belfry
#

like the same way a frame of a sprite...But its a caller?

polar acorn
tawdry quest
#

just a quick test, dont mind me, just wanna know something.
!code

eternal falconBOT
acoustic belfry
tawdry quest
# eternal falcon

yay my scriptbin is actually in there, im gone again, thats all i was here for

polar acorn
acoustic belfry
#

got it

frigid sequoia
#

Guys, I keep doing this on my Coroutines, but, it's really necessary or am I overcomplicating it?

#

Like, the coroutine turns to null anyways when it's done rigth?

cosmic dagger
frigid sequoia
#

But it's needed for me to declare the null at the end or that happens automatically?

cosmic dagger
#

Yes, you must set it to null. The variable holds a reference to a Coroutine object. Assigning to null indicates that the coroutine is complete . . .

frigid sequoia
#

So, if it points to a coroutine that has ended but the reference is not set back to null it would be a nullpointer?

cosmic dagger
#

The coroutine just runs and ends. There is no automatic "assign to null." It's the same as any reference variable; you have to manually assign them to null . . .

frigid sequoia
#

Kk

#

Thxs

onyx blaze
#

I'm trying to do this Camera Move effect
But the tutorials aren't working with me

When click and drag with the mouse, move the camera to exactly same point where are my mouse

Someone can help me? Please

onyx blaze
#

But to exaclty same position that are the mouse

#

So, transform.forward/right doesn't works because uses speed value

drifting cosmos
#

i really dont know what you mean

drifting cosmos
rich ice
onyx blaze
drifting cosmos
onyx blaze
drifting cosmos
onyx blaze
#

I'm trying to make the camera gets mouse X and Z value to move

#

Because is a 3D camera

drifting cosmos
onyx blaze
#

Yeah

#

I tried almost 20 tutorials
But nothing works :/

rocky canyon
#

ya, you'd use some sorta of smoothing...

onyx blaze
rocky canyon
#

harsh-snapping doesnt look so good

onyx blaze
rocky canyon
#

possibly could remove the smoothing

#

my mouse is a UI element just using screen space

#

then raycast into the world for the camera stuff

#

what u showed is 2D tho.. and tilemaps like scrolling around a big picture

#

tad different than going for 3d like u said u want i think

onyx blaze
onyx blaze
rocky canyon
#

i think he goes over both orthographic and perspective.. altho i cant really remember..

#

for zooming and stuff that'd matter.. you'd either be modifying the orthographic size.. or moving the actual camera

#

oh..

#

and technically all Unity game's are 3D games ;0

onyx blaze
rocky canyon
#

what exactly isn't working right?

#

what do you expect to happen?
what is actually happening?

also show any !code or anything we can try to help ya with

eternal falconBOT
onyx blaze
#

I'll send a record

rocky canyon
#

and code

onyx blaze
onyx blaze
#

Works with arrows and WASD, but I cannot make works with the mouse drag

astral falcon
#

I do not see any logs. Maybe start by adding them, so you actually know, whats going on. or use a debugger, whatever you prefer

silent sphinx
#

Hello, I'm doing a poker simulator as practice, but I'm having problems creating the deck.
I have a public list with a "card" class (that has the info of the card, such as it's suite and number), but when I try to modify the List contents, it doesn't.
I am debugging with the logs, and it gives the expected results (the first card is C1 for example), but when checking the List on the inspector while running the game, all the cards are without suite and their number is "0".

In my code, the cards are created and added to the list in the "crearBaraja" method, starting on line 34 to 45.

This is the full code of the GameController where the code is.
https://pastebin.com/VhbEmdpr

and the "carta" (card) class.

> using Unity.VisualScripting;
> using UnityEngine;
> 
> public class Carta : MonoBehaviour
> {
>     public char palo;
>     public int numero;
>     public bool seleccionado;
> }
#

this is my first time asking for advice here, sorry if I did it wrong

astral falcon
#

!code please

eternal falconBOT
astral falcon
#

Rather tell the lines without fragmenting your post into all those parts

silent sphinx
#

the number of the lines of the pastebin? For example, "the loop is in lines 36 to 45"?

astral falcon
#

Because you add the same reference to your list all the time in your loop, you have 14 times the same card inside with the values of the latest loop run

silent sphinx
astral falcon
silent sphinx
#

it's a prefab
the idea is to have the cards rendered for each player, and have a list of the cards each player has in their respective gameobjects

#

it's a bad idea to it like this?

#

would it be better if I separated the actual 3d rendered card and the scripting part?

astral falcon
#

Your prefab can of course hold a reference to your class object, but I would not let live the card data inside the visual representation but rather have your monobehaviour card have a reference to carddata, that you create in your loop and assign to your list. so you can always calculate stuff based on those lists without needing to have a visual representation

silent sphinx
#

understood, it's better in this case to have it separated

astral falcon
#

In most cases, its good to have data separated from visual representations. Because in that case, you just have your data and can do whatever you want with it. Throw it on a card but also on a visual list of effects you are currently applying or or or.

#

You can even store that lists somewhere else as a premade deck then and do not have an extra conversion from visual monobehaviour back to an actual data list

silent sphinx
#

should I do that with JSON?

visual linden
astral falcon
# silent sphinx so it doesn't have to be generated every time I start the game?

Could be one way to go, yes. If its somehow serialisable to and from json, you are good to go. can even make a share deck script later that just gets a deck json from a server later and so on. sorry, I might get crazy here in the range of features 😄 But I love handling data passing around and doing whatever you can with it

silent sphinx
#

I'll try with the Scriptable Objects, I haven't used that, is this a good tutorial on how to use them?
https://www.youtube.com/watch?v=PVOVIxNxxeQ

In this video, we are going to show you how to use Scriptable Objects to manage your data in Unity.

Download the Unity Royale Project here!
https://on.unity.com/33FplpG

Learn more about Scriptable Objects here!
https://on.unity.com/33PzcJR

Get Inspiration on what else to do with Scriptable Objects here!
https://on.unity.com/2RKXXkK

Chapters:...

▶ Play video
astral falcon
#

Unity learn I would always check first place

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

visual linden
#

Although nothing like an official Unity tutorial :D

astral falcon
#

But Scriptable objects are a wacky thing in runtime, because they DO NOT save states over runtimes

#

So you have to store your latest state in a file anyway again, cause SOs reset after you end your application/game

silent sphinx
#

like the deck in this case

visual linden
astral falcon
#

your cards data being scriptable objects, could be fine to have it in a explorer/finder like of way organising it instead of a table/database. But not to store a deck that you want to reuse later

#

I used scriptable objects with a custom node editor to create quests queues for example, but had to save the state and reload it on runtime and overwrite the scriptbaleobjcets on runtime then, to have the real savegame applied.

silent sphinx
#

if for example I wanted to have different decks to play (IE: one without faces or without jokers), scriptable objects wouldn't work?

visual linden
#

I like scriptable objects for this type of stuff because it's outside of code, so you can easily allow designers or whoever to create new items.

astral falcon
#

Like, imagine having a tutorial deck, there you can just create SOs for you to handle because they are predefined and will never change after being used once

silent sphinx
#

alright, so SOs is for premade stuff from outside the game, but not for creating things inside the game (like a saved game or an ingame map editor)

astral falcon
#

On point

silent sphinx
#

wonderful, thanks, I'll try to remake what I have with this new approach, if I find problems I'll return here

#

thanks a lot

astral falcon
#

Happy coding 🙂

dim egret
#

Hello, does anyone know how i can link health between 2 sprites? like if 1 takes damage the other sprite also takes damage and lowers the health by 1. (in c#)

astral falcon
eternal falconBOT
#

:teacher: Unity Learn ↗

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

plucky abyss
#

Ive been coding for a while now but recently took a bit of a break. Im back and making a 3d game, im trying to make a door in my game move to a different position by pressing e on it (itll be a sliding door) Ive made some decoding to see if it works and it is but the actual door in game isnt moving, and i can walk through it before i even press e on it. Any help would be appreciated

lethal smelt
#

did you give it a collider component?

#

also make sure its not 2d

plucky abyss
#

Yeah the door has a box collider and is set to is trigger, if i uncheck is trigger i cant walk through it but it doesnt open when pressing e (doesnt react to the script)

slender nymph
#

trigger colliders do not collide because they are just trigger volumes. it sounds like you have an oversized trigger collider and are probably relying on OnTriggerEnter to interact with the door, i recommend against that and instead recommend using a physics query like a Raycast to interact with it

plucky abyss
#

ill see what i can do with this! thank you very much

#

i was relying on ontriggerenter cause thats what im used too haha

flat holly
#

im watching tutorials.. and i think i cant understand all by lua logic, like define things are much different than lua local

slender nymph
#

c# is a very different language from lua. if you don't understand the basics of the language then start by going through some c# courses like the ones pinned in this channel

flat holly
#

yeah

#

damn.. C# dont use local
it define by class + custom name instead

naive pawn
# flat holly damn.. C# dont use local it define by class + custom name instead

lua doesn't have static typing, so it uses keywords to declare variables.
c# does, it uses types to declare. you'll need a type anyways, why use another keyword?

this is a general rule of thumb for most languages. there are exceptions though, of course

  • python usually doesn't have static typing, but still supports adding typehints to variables
  • typescript does have static typing, but it's built on top of js which doesn't, so it can have both a keyword and a type in a declaration
  • even c++ and c#/java have dynamically typed variables using a keyword instead of a type, where the type is inferred from the initializer (auto and var respectively)
hollow wraith
#

Does anyone have a link to a guide or video that explains how to use the Unity's input system for controllers like xBox 360 controllers? ( That's what I'm trying to get working ). All of the resources I can find online show different results and none of them work. Keep getting error's or told the thing I'm trying to reference doesn't exist

hexed terrace
naive pawn
queen adder
#

Hi, I want a rectangle rotate on the z "around" a sphere but rotate it like the hammer on getting over it, it's always attach to player

naive pawn
#

please don't crosspost

polar acorn
compact stag
#

hey guys! i have this code over here

https://pastebin.com/81AdFJVw

I tried putting PlayerData playerData = new PlayerData() outside of the start method but it just returned an error You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(), but as soon as i put it on the start it didn't seem to work in other functions, what can I do about this?

#

i was thinking of maybe putting PlayerData aside MonoBehaviour but it didnt seem to work, does that work?

naive pawn
#

did you read the error

#

you shouldn't use new for components

compact stag
#

yeah! i just don't know how to use the add component in this case, because like, this is in the same script!

naive pawn
#

oh it isn't a component there

#

hm one sec

compact stag
#

should I just do playerData = GetComponent<PlayerData>() ?

naive pawn
#

if you hover over the PlayerData in the error, what does it say?

compact stag
#

nothing...?

naive pawn
#

are you not using an IDE?

compact stag
#

i am, but its not prompting an error

#

in which line are you talking about?

hexed terrace
slender nymph
naive pawn
#

oh, i missed that

compact stag
#

oh, wait wait wait, i pasted the wrong error, im sorry

naive pawn
#

yeah your SavePlayer doesn't make sense

compact stag
#

let me re-phrase my error

slender nymph
#

also you never actually return the loadedData from the LoadPlayer method which means you load the data then just throw it away

compact stag
#

i totally confused myself sorry, im super sleepy

eternal needle
#

no need to paraphrase

compact stag
#

I changed my playerData so now its in the start method, but now i get this error

#

i put the PlayerData playerData = new PlayerData() in the start method btw

#

thats what i changed

slender nymph
#

that line is actually irrelevant to the error.

naive pawn
#

you would need playerData = new PlayerData(), without the declaration, to initialize the field to be usable elsewhere

slender nymph
naive pawn
slender nymph
#

yeah i just noticed they are also accessing playerData on that line that is throwing

#

i saw the userText object and assumed that was it

compact stag
slender nymph
#

you aren't creating a local variable. you are just not creating the instance of playerData until after you attempt to use it

slender nymph
compact stag
slender nymph
#

you wouldn't

#

PlayerData is not a component. it doesn't make sense to use GetComponent to access it. you're just creating the instance after you try to use it.

compact stag
#
        setUserName();
        playerData.LoadPlayer();
        playerData = new PlayerData();

you mean here?

#

i changed it

slender nymph
#

yes

compact stag
#

so now i got another error, same thing

slender nymph
compact stag
#

not same thing, sorry

#
You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor ()
MainManager:.ctor () (at Assets/Scripts/MainManager.cs:13)
MainManager/PlayerData:SavePlayer () (at Assets/Scripts/MainManager.cs:100)
MainManager:GameOver () (at Assets/Scripts/MainManager.cs:84)
DeathZone:OnCollisionEnter (UnityEngine.Collision) (at Assets/Scripts/DeathZone.cs:13)
UnityEngine.Physics:OnSceneContact (UnityEngine.PhysicsScene,intptr,int)

slender nymph
#

then wtf did you change

compact stag
#

i changed that! i just changed it back here in discord to ask if thats what i needed to change lmao

slender nymph
#

okay so now that is correct

compact stag
#

wait that wasnt code beginner? it was worse than code beginner? 😭

eternal needle
#

thats a link to a message in this channel

compact stag
#

oh, i forgot you can do that now

#

dude im so fucking stupid rn sorry guys, horrible night of sleep

#

thing weird is though, its popping errors from like, other codes, even though the other codes were made by the guys at unity learn

slender nymph
#

wtf does that even mean

#

i already pointed out the reason for your issue. it is not from "other codes" it is from your code

compact stag
#

got it, but why is it pointing to deathzone.cs:13?

slender nymph
#

because that is likely where the save method is being triggered

#

it calls GameOver which seems to call the PlayerData.SavePlayer method

#

and, as i pointed out, you are using new MainManager() in the SavePlayer method

compact stag
#

oh, makes sense, because this is the code of DeathZone

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

public class DeathZone : MonoBehaviour
{
    public MainManager Manager;

    private void OnCollisionEnter(Collision other)
    {
        Destroy(other.gameObject);
        Manager.GameOver();
    }
}
#

wait a minute

eternal needle
#

though what you were seeing is just the stack trace

polar acorn
slender nymph
#

that's not even the code from the error, that was code from a previous error

compact stag
#

ill go rest and take a nap, my brain isnt braining at the moment

#

thank you either way guys! special thanks to boxfriend thats always helping me out 😭

teal shale
#

I have a question. Let's say you have a 2d player character (dynamic rb) with basic movement etc and you want to implement a ragdoll state of which your singular capsule collider player will go to that state when something triggers it such as fall from certain height or a high velocity square hits the player. Should i code it for my current player script or create an empty for my player in which i swap between "player" and "ragdoll" when such events happen? What's the best approach.

I've done it in another engine, very new to unity & confused.

wintry quarry
teal shale
wintry quarry
#

Not sure what you mean by " an empty"

teal shale
#

childnode or whatever its called, like this groundcheck i added

wintry quarry
#

You would of course need to switch to an totally different set of colliders and rigidbodies

wintry quarry
teal shale
queen adder
#

how do I fix the editor rescaling a child object or how do I change the mesh size of the parent directly in the editor?

naive pawn
hexed terrace
#

this is a code channel, and that's not a code question

queen adder
naive pawn
#

you may want those 2 objects to be siblings in another root object instead of as parent/child

#

well yeah, that's what scaling is

naive pawn
#

no clue what that has to do

queen adder
wintry quarry
#

Rule of thumb:
Any object that has a child should only be scaled Uniformly, if at all

#

Put your renderers and colliders on leaf nodes in the tree

#

Only scale the leaf nodes

hexed terrace
#

@wintry quarry the non-code chat has moved away from the code channel -> #💻┃unity-talk

tulip stag
#

Is there a function I can call like Start() or Update() that gets called when you exit the program

slender nymph
tulip stag
#

Thanks!

hexed terrace
#

not a code question, shouldn't be in here. As you're using #🎥┃cinemachine you should move your question there (Delete from here)

lusty star
#

ok dude

#

its just that the channel looks dead

tulip stag
hexed terrace
twin pivot
#

one side always rotates a little more than the other because of Time.deltaTime

#

is there a way to avoid this

eternal needle
naive pawn
#

!code

eternal falconBOT
eternal needle
#

and also configure your !ide

eternal falconBOT
twin pivot
naive pawn
# twin pivot

also i don't think ^ means what you think it means

twin pivot
#

to the power of?

naive pawn
#

i don't see how bitwise xor factors in here

eternal needle
naive pawn
twin pivot
#

ah i see

naive pawn
#

some languages do have an exponentiation operator, **
c# doesn't

#

there's a function for it, but here you can just do i * i

twin pivot
#

thanks

eternal needle
#

your code is flawed in many ways. like the coroutine running for a certain amount of frames and the math being done there. realistically you should
solve this either with an animation
or
store 2 rotations, the start and end rotation then lerp to these rotations.

#

but really, look at configuring your ide first.

twin pivot
hexed terrace
#

Sort your VS out though

#

(It's a requirement to get help in code channels)

twin pivot
#

oh god

#

i just figured it out

#

thats so much better

twin pivot
naive pawn
#

he didn't say that

twin pivot
#

why is it a flaw?

eternal needle
twin pivot
eternal needle
polar acorn
twin pivot
#

ah i see

eternal needle
#

Time.deltaTime is the time between frames. with what i said above, the total delta time over 41 frames could be 0.5 seconds or 5 seconds

twin pivot
#

so im guessing my way of implementing this was flawed from the start

#

and im gonna have to redo the entire thing using animations

eternal needle
# twin pivot and im gonna have to redo the entire thing using animations

if you wanted to do this through code, store the start and end rotation then lerp to these rotations. You can use a coroutine but instead of keeping track of the frames, keep track of how long you want it to take. Then in your lerp you use the (current time) / (total time) as your T value in lerp

#

this would essentially just be a shitty animation though

twin pivot
#

kinda a bandaid solution im guessing

#

could you give me an example of how you use a lerp?

eternal needle
#

its fine if its all you need, ive definitely written code before where i control an object like that rather than an animation

twin pivot
#

yea i just need a button to wobble

eternal needle
#

yea an animation does sound better for that

twin pivot
#

i already did the math to make it look good so i'm just gonna use this for now

#

and use animations the next time i need something for this

stark ingot
#

Could someone help me figure out how to use slerp with an array of Transform objects (I think that's what it's called?)

wintry quarry
naive pawn
#

loop through the array and slerp each one?

eternal needle
stark ingot
#

Sorry, let me try again. I'm trying to get a square to follow empty objects in a loop, if that make sense. My professor said I should use an array, but I've haven't used an array with objects so I'm not sure what I'm doing

eternal needle
rich adder
stark ingot
#

What's "SerializeField"..?

polar acorn
stark ingot
#

Oh I see

stark ingot
naive pawn
#

.position

twin pivot
eternal needle
rich adder
twin pivot
#

oh thank god

rich adder
#

they prevent gimbal locking issues

twin pivot
#

i searched up what a euler angle is and i got a video on astrophysics

rich adder
#

euler is what you normally see as degrees

rich adder
twin pivot
verbal dome
twin pivot
verbal dome
#

You can combine quaternions with *

#

So you can multiply transform.rotation with Quaternion.AngleAxis(angle, zAxis)

#

Does the same thing, though.

#

The order of operations matters in some cases though

twin pivot
#

i think i get what you mean

#

so if the original angles are (0,0,1) and you want to set it to (0,0,90) you just do Transform.Rotate*Quaternion.AngleAxis(90, zAxis)

naive pawn
#

no

#

Transform.Rotate is a function, you can't use it like that

#

if you want to set a rotation to 0,0,90, you wouldn't combine rotations, you'd just replace the old one

twin pivot
#

could i have an example

naive pawn
#
// combining quaternions
Quaternion compound = qA * qB;

// rotating by some quaternion
transform.rotation *= q;

// setting a rotation
transform.rotation = q;
#

3 separate things here

verbal dome
#

Rotate only works with eulers but yeah

naive pawn
#

damn

twin pivot
#

i dont quite understand the first one

verbal dome
twin pivot
#

oh i see

naive pawn
#

you rotate according to qA and then according to qB

#

compound is the overall rotation from both quaternions

twin pivot
#

so basically

#

it rotates 30 and then by 60

naive pawn
#

yeah

twin pivot
#

in two consecutive frames

naive pawn
#

no

twin pivot
#

same frame?

naive pawn
#

it's combined into a single compound representation

naive pawn
twin pivot
#

oh then its just math?

naive pawn
#

yes

verbal dome
#

It's just a struct that represents rotation

twin pivot
#

so just rotational addition

#

i see

polar acorn
#

Here's what you need to understand about Quaternion math: Don't do Quaternion math

twin pivot
#

so what im taking from all this is

#

i should just ditch quaternions and learn animations instead

polar acorn
#

If there is any alternative to using Quaternions, do it

verbal dome
#

I don't think I'm a very mathy person at all but I use quaternions all the time

jagged hare
#

That doesn't mean you have to like it.

twin pivot
#

but one question

verbal dome
#

But I do :(

naive pawn
#

you couldve just... asked the question

twin pivot
#

if i wanted to use quaternions to rotate something by a variable

#

how would i do it

onyx blaze
naive pawn
#

not sure why you'd want to use quaternions specifically

wispy finch
#

mate, are you even reading the documentations or anything at all?

rich adder
#

you use quaternion functions from euler angles

naive pawn
#

you'd want to rotate something, quaternions would just be how you do it

twin pivot
naive pawn
wispy finch
naive pawn
#

or open a new window

twin pivot
naive pawn
#

minimize the other 20 tabs or something

twin pivot
rich adder
naive pawn
twin pivot
#

i just dont really understand it

wispy finch
# twin pivot im feeling a severe lack of brainpower
  1. Read the documentation for transforms, quaternions and rotations

  2. Find a tutorial on youtube where someone explains these things and try to understand it, not just copy the first thing you see

  3. Summarize what works and what doesn't work, then ask for help

#

You probably skipped the first steps

rich adder
#

what is there to understand. quaternions it just works ™️

naive pawn
#

In most cases, you can use existing rotations from methods such as Transform.localRotation or Transform.rotation to construct new rotations. For example, use existing rotations to smoothly interpolate between two rotations. The most used Quaternion functions are as follows: Quaternion.LookRotation, Quaternion.Angle, Quaternion.Euler, Quaternion.Slerp, Quaternion.FromToRotation, and Quaternion.identity.

rich adder
#

You're never going to mannually constructing a Quaternion struct.. It just makes no sense to do so..

twin pivot
naive pawn
#

comprehension is part of the first step

rich adder
#

aside from that, all that matters is you're aware unity does -180 to 180 instead of 0-360..
touch only eulers. pass as converted quaternions

wispy finch
#

then start simpler - try to move a gameobject with transform.position, and just play around with the different methods

naive pawn
#

there was a website that explained this stuff wasn't there

verbal dome
#

I visualize quaternion as these sort of ball joints that you can stack/put inside each other

#

I think you'll understand it best when you start experimenting with the helper methods

naive pawn
#

damn it doesn't have quaternions

stray sentinel
#

Hello, I have an issue with my Unity character, when it hits something, it instantly moves backward can someone help me ?

rich adder
final trellis
#
int dmg = rdmgcrd.Damage;
Debug.Log(dmg.ToString());
Debug.Log(dmg.ToString());```

the ``Damage`` value of ``rdmgcrd`` gives a random value as its ``get`` function ( theyre 'random damage' cards ), but when i do this, the outputs are different instead of the same when i try assigning an initial output to reuse to specifically avoid this
stray sentinel
rich adder
#

most likely rotation

#

if anything, show the weird behavior happening

final trellis
swift crag
#

thus making it look like multiple identical messages are actually a single message

#

there is zero way for this to give you two different results

swift crag
#

even with ref chincanery, it'd be a struggle

rich adder
final trellis
#

the debug logs were just an example so i wouldnt have to explain the whole thing but that seems nessecary hold on

cosmic dagger
stray sentinel
#

thx !

final trellis
#

code with video of the thing being weird

polar acorn
# final trellis

Every time you call .Damage it will be different. You are calling it when you display the damage, then calling it again when you pass it to playerDmg.Damage

final trellis
#

basically, when a random damage card is triggered, it shows a question mark, then changes it to a different number, then adds that number to the damage, but those two numbers are being different for some reason

final trellis
naive pawn
final trellis
polar acorn
#

You're running the getter twice

swift crag
#

That's the non-random case

#

I guess I would sanity-check that it's not actually running, but I see the "?" coming up, suggesting that we're in the RandomDamageCard case

polar acorn
#

Ah, right, I just assumed that would be a DamageCard

swift crag
#

is RandomDamageCard derived from DamageCard?

#

oh, there's the sneaky else

polar acorn
#

Well, actually, now that I think about it, does RandomDamageCard extend DamageCard? If so, it would still be a DamageCard and run that

swift crag
#

i thought there was no intervening else, meaning that both blocks could have run

polar acorn
final trellis
polar acorn
#

I need coffee

#

I'm missing a lot of these

final trellis
#

to be fair my else structures are formatted strange

swift crag
#

If I were debugging this, I would replace the .Damage access with a nice dumb constant

#

9999 or something

#

so int dmg = 999;, then the rest carries on

final trellis
#

ill set it to 6 since normal damage cards only go up to 5

#

just so the UI doesnt explode

swift crag
#

if the UI can only handle numbers up to 5, that suggests you're doing some special for each number

#

perhaps the UI is just bugging out and you haven't noticed it yet

final trellis
#

oh the Ui can just handle 1 digit

polar acorn
final trellis
#

its just sized that way

polar acorn
#

so it doesn't run over the bounds

final trellis
swift crag
#

Okay so we're in the Evil Zone

#

I was looking for anywhere you might be capturing the variable

final trellis
swift crag
#

but I don't see any lambda expressions in there

final trellis
#

honestly i might aswell just add a function in Damage Card that just does the same thing instead of have it be an int with a random getter that becomes evil

polar acorn
#

I'm thinking it might be some sort of awkward variable capture since it's in a coroutine which is technically an enumerator?

swift crag
#

wait, this is the enemy card logic

final trellis
#

oh OH

#

fucking explodes

swift crag
#

I know you're making this game kind of backwards so that might just be the name for the cards on your side of the field

final trellis
#

this is what happens when i skip out on making the code structured well to get the game done in time for the gamejam 😭

final trellis
#

i wouldve found out earlier if the evilness that was occuring diddnt actually make a tiny bit of sense

vagrant mist
#

I want to make a character swap system. One character exists, I press a key, theres a puff of smoke and the new character is in the position of the old one.
For now, I just need the sprite to swap, but whats the best outline to doing this?

#

I'm thinking of making an OnSwap() method for the keybind, but the two roadblocks I'm at right now are getting the sprite to swap and to have my smoke animation play right on top of my character

lament birch
#

I'm making a billboard script that rotates a GameObject towards a camera using RenderPipelineManager.beginCameraRendering, but I'm having problems with trying to clean up afterwards so the actual rotation is untouched - I tried using RenderPipelineManager.endCameraRendering to reset it, but this isn't called when I expect it to - in the editor window it's called after the camera finished rendering (as I expected) so the billboard effect remains, but in the game window it's called before the camera actually renders and overrides the intended rendering rotation - anyone know why?

polar acorn
#

Create a child object with the smoke effect on it (presumably a particle effect), activate it, then change the sprite of the renderer and/or the AnimatorController

vagrant mist
polar acorn
#

You'd just have two variables, one for each sprite, that you'd set in the inspector, and change out your renderer to use whichever one isn't currently set

teal shale
#

Is there a way to freeze constraint for example Z rotation and unfreeze it via script?

timber tide
#

should be there in the API

#

assuming we're talking rigidbody

teal shale
#

yes

#

but i wanna do it via script, so i can turn on n off depending on circumstances

teal shale
#

thx <3

vagrant mist
#

so ```
SpriteRenderer2D playerOne;
SpriteRenderer2D playerTwo;

public void OnSwap(InputAction.CallbackContext context)
{
if (context.started)
{

}
}

would be the base to work from?
or should I use a SpriteLibrary and Sprite Resolver?
polar acorn
vagrant mist
polar acorn
#

Pretty much, yeah. You could also add in a boolean to track which one is currently active, or you could compare the renderer's currently loaded sprite to one of the other two to see which one is active

true owl
#

hello, i set up my input system to have an input called DiscThrow, which throws a disc when "M" is pressed, but i want to make it so that if you hold it it increases the speed. Is there a better way of doing this than just Input.GetKey(M), since I think that's reminiscent of the old input system way from my understanding

#
    // check if we have >= 1 discs, if we do we can throw
    // if input is pressed while one is not flying, time held determines throw speed
    // if input is pressed while one is currently flying then we stop it
    void OnDiscThrow()
    {
        // we have a disc
        if (PlayerInventoryManagement.discs >= 1) {
            // we need to stop it
            if (isDiscCurrentlyFlying) {
                
            } else {
            // we need to throw a new one

            }
        }
    }
vagrant mist
polar acorn
#

I have no idea what Sprite Library is

rocky canyon
#

but i could be wrong.. as ive not used the new input system much tbh..

true owl
#

I wanted to calculate it dynamically though

rocky canyon
#

but yea u can always do the logic in an update loop

true owl
#

my issue is checking how long the key is held, I only know how to do it via Input.GetKey

#

Not sure if that's the standard

true owl
#

yeah but can I do it without that

#

since im using new input system

#

just found this actually

drifting cosmos
#

is it possible to mark the time when you press the key down then

#

when it goes up

rocky canyon
true owl
#

I mean this is no issue, it can work, but I'm wondering if there's something better with the new input system

#

that's pretty much the whole issue

#

I can do it with GetKeyDown, GetKeyUp

#

but it seems kinda conflicting cause then i'm merging two styles

rocky canyon
#
     if (Input.GetKeyDown(KeyCode.Space))
        {
            holdStartTime = Time.time;
            isHolding = true;
        }

        if (Input.GetKeyUp(KeyCode.Space) && isHolding)
        {
            float holdDuration = Time.time - holdStartTime;
            float force = Mathf.Lerp(MinForce, MaxForce, Mathf.Clamp01(holdDuration / MaxHoldTime));
            Throw(force);
            isHolding = false;
        }``` something like this
rocky canyon
#

would do the same thing w/ the new i think

true owl
#

sweet

#

is the new input system standard now

#

or do people just use the old

rocky canyon
#
    void OnEnable()
    {
        ThrowAction.Enable();
        ThrowAction.started += ctx => StartHold();
        ThrowAction.canceled += ctx => ReleaseHold();
    }```
rocky canyon
#

but im trying to ween off of the old

drifting cosmos
#

is this => anonymous methods?

rocky canyon
#

lambda, but specifically anonymous method yes

rich adder
#

lambda expression

drifting cosmos
#

oh lambda

rocky canyon
#

ThrowAction.started += delegate (InputAction.CallbackContext ctx) { StartHold(); };

#

i think its short for something like this ^

#

but im not 100 sure

strong wren
#

Keyboard.current and Mouse.current makes it convenient to prototype with the new input system if you don't yet want to bother with actions

rocky canyon
#

^ yessir i forgot u could do that

#

soo.. u could poll like u did in the older one with the new one as well

rich adder
#

this tells you all the corresponding methods from Old to new

rocky canyon
rich adder
#

yeah it was very handy in the beginning

#

I no longer poll anymore now I'm spoiled

rocky canyon
#

😭

#

teach me? 😈

#

i can do keyboard inputs.. but the mouse inputs still kinda confuse me

rich adder
rocky canyon
#

actually i think its the fact u can use different types of data..

rich adder
#

then its all type safe

rocky canyon
rich adder
#

oh okay good. I was using Messages for a while, it was quick but dirty

#

its like saying I use SendMessage() in unity instead of proper referencing lol

rich adder
rocky canyon
rocky canyon
rich adder
rocky canyon
#

i remember a while back it was really inconsistent it seemed like

rich adder
rocky canyon
#

ohh! 🤪

rich adder
#

you can set a preprocessor for that iirc

rocky canyon
#

that simple eh?

#

i thought i was using the wrong type

rich adder
#

basically is just Mouse_X and Mouse_Y combined

#

but yeah that one had weird quirk where my cursor with same sensitivity would move way faster, then I found out that unity applies some sort of scale factor

rocky canyon
#

heres my example script i have set up.. bout as far as ive gotten

rich adder
#

oh I sub directly with the method

#

performed += OnMove;

rocky canyon
#

ya, im not very sure that this is completely correct

#

or actually the best way

rich adder
#

forgot tbh lol

#

I just make sure I unsub in OnDisable

drifting cosmos
#

for an animation statemachine do you drag animations into them?

rich adder
#

also not a code question

vagrant mist
polar acorn
#

and if it's not, then it'd be the other one

vagrant mist
#

so it doesn't matter which step in the animation its in, it should just immediately switch the sprites?

drifting cosmos
# rich adder sure

well how do the scripts attached to objects work like what if i want to have multiple things using one script would the c# type of objects made in it be local to the game object or would you have to change the code for each thing you attach to it for and make a different object

rich adder
#

once you declared your reference you put inside the field, whichever one you want to do stuff on

drifting cosmos
rich adder
#

movement can mean many things

candid garden
#

I've got a base class for abilities with an iscooldown bool, when the turn ends it updates the cooldown if iscooldown is true, but it's always returning false even though when I look at the ability in the characters components it shows true? Should I not be putting the cooldown stuff in the base class?

vagrant mist
polar acorn
#

You'd use the same Animator, swap the Animator Controller

#

Or Animator Override Controller

#

depending on how similar the two are

strong wren
vagrant mist
polar acorn
#

Yep

candid garden
#

and this is the variables

rich adder
#

and you are certain you are referencing the object instance thats showing in inspector

candid garden
candid garden
rich adder
vagrant mist
# polar acorn Yep

final thing, if my end goal is to have the two characters have separate abilities and stats, is it better to create a new game object to put all this in instead of doing it through a playerController script?

#

I am terribly new to this so even finding the right questions to ask has been painful

polar acorn
#

You will probably have one "Shared" script, and swap out child objects that have their own scripts for their unique stuff. You can probably rearrange it so those have their own sprite renderer/animator as well

candid garden
true owl
#

https://paste.mod.gg/bracnmqbnmkj/0 I tried doing this, but I get an error

MissingMethodException: Method 'DiscThrow.OnThrowDisc' not found.
System.RuntimeType.InvokeMember (System.String name, System.Reflection.BindingFlags bindingFlags, System.Reflection.Binder binder, System.Object target, System.Object[] providedArgs, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, System.String[] namedParams) (at <ed969b0e627d471da4848289f9c322df>:0)
UnityEngine.SetupCoroutine.InvokeMember (System.Object behaviour, System.String name, System.Object variable) (at <44f3679c53d1477a9c6e72f269e3a3a9>:0)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)
#

not really sure why

#

the method is right there

candid garden
vagrant mist
#

i think im just gonna call it for the day before i have a melt down lol

rich adder
candid garden
finite hornet
#

Hello I am working with components in my script, and I was wondering if it is possible to have the script control the component. For instance I am adding a mesh collider and would like to have the script know if it is attached and not function if not attached the way i want it.

#

I know how to use a if statement to see if the component is added, but what about certain details in the component?

polar acorn
rich adder
finite hornet
polar acorn
#

You can reference the properties of anything

#

as long as they're public

finite hornet
#

thank you for the tip

candid garden
teal shale
#

Does unity understand the concept of force. Like if i make a block fly towards my ragdoll character will he maintain that force and keep flying a bit or do i have to script it myself

rich adder
candid garden
#

Shouldn't it be running for each ability though? it's only running for the move ability which is odd

rocky canyon
#

if its physics on physics. it should act accordingly

polar acorn
rich adder
rocky canyon
#

unless its kinematic ofc

rich adder
#

if your object thrown has lots of mass and ragdoll doesnt, ur ragdoll will go flying

teal shale
rich adder
#

ofc

rocky canyon
#

yes.

teal shale
#

Ah 🤣 thx

rich adder
#

any moving body ideally should have a rigidbody

rocky canyon
#

if not u'll have to log the collision, grab the forces urself and apply it w/ translation

#

(fake physics)

rich adder
#

colliders are for the shape

teal shale
#

I tried doing gravity drag fraction and everything but that

rich adder
#

gravity drag fraction? idk what that is tbh lol

teal shale
#

Didnt know i had to add physics to the other object too

#

Thx guys

rocky canyon
#

anything u want to interact (as a physics objects) needs atleast a rigidbody

rich adder
#

btw collision mode might be important depending how fast you throw those

rocky canyon
#

true true..

rich adder
#

2d you only have 2 options though anyway

teal shale
#

Yeah i only had my ragdoll physics but my square to push it didnt have so it only pushed my ragdoll but not put force in it no matter mass or whatever

rocky canyon
rich adder
#

Continuous if they are fast.
In 3D they also have Continuous Dynamic which is very good for 2 moving bodies

rocky canyon
#

it gets more accurate.. and more expensive the lower down the list u go

#

the bottom one is actually "predicting" what would happen

#

thats speculative ofc.. not 💯 sure

rich adder
#

just speculating here..

#

ayo

rocky canyon
#

think.. Pinball

rich adder
#

probably Continuous

#

Continuous dynamic if other rigidbodies move just as fast and you want decent detection

rocky canyon
#

im thinking i should re-make this >8)

#

such a classic

rich adder
#

so many memories

rocky canyon
rich adder
polar acorn
rocky canyon
#

paddles and bumpers do..

rich adder
rocky canyon
#

bumpers or w/e they're called actually have a wedge on their side.. and they pinch the ball

rich adder
#

less say you wanted 2 fast balls to hit each other, then yeah dynamic is better there

rocky canyon
#

but i doubt id' need to do anything that complex

#

just some Reflect

rich adder
#

sometimes the bouncing feels like precise with just straight up collision

rocky canyon
#

holy remake batman

rich adder
#

thats pretty clean ngl

rocky canyon
#

ya, that artwork is incredible

#

cant quite put my finger on it tho

#

its like hand-painted mixed w/ cut-out Cellshaded-ish

daring crescent
#
    void Update()
    {
        if(currentState == GameState.InGame)
        {
            if(remainingTime >= 0)
            {
                remainingTime = timeForLevel -= Time.deltaTime;
            }   
            else
            {
                GameManager.Instance.changeGameState(GameState.GameOver);
            }

            if(remainingObjects == 0)
            {
                GameManager.Instance.changeGameState(GameState.Won);
            }
        }
    }```
Are nested ifs bad practice? Or would you say in that particularly case its ok?
misty sand
#

@rich adder nav i think you might remember the issues ive been having with my shadow chasers game, there fixed now however theres still kind of a problem, i was wondering if i could toggle seperate scripts for the same shadow controller depending on what ground its standing on, would something like that be possible with is trigger box colliders?

rich adder
#

gotta remind me a bit

grand snow
#

e.g. if(bad) return;

rich adder
#

early return pattern ftw

#

also learn about events so you dont even have to poll any of this in Update

#

but thats like another topic lol

daring crescent
#

im currently using events in the Menu Manager to display the correct text

rich adder
#

ya events are dope

daring crescent
#

In that case i've made the nested if to avoid that if the time will go below zero the GameState will change to GameOver even if its already Won

misty sand
#

fair enough lol, it was a platformer game where the player has a shadow that can interact with shadow only platforms, my problem was that the shadow couldnt jump but ive fixed it now. to do that i used a different script i dont entierly understand and now the shadow delay is kind of weird. i was wondering if i could use 2 different scripts, one with a delay that could be toggled depending on what the shadows touching. ive already tried an easier way by making a delay radius around the player so theres only a delay if in that radius but it didnt work, i am looking for a solution that has the same effect. i can show the shadow controller if it helps.

daring crescent
#

but i could stop the decreasing of the timer if GameState != InGame

rich adder
#

and before you changed the movement to fixedupdate right?

misty sand
#

what do you mean before

daring crescent
polar acorn
rich adder
#

this already cuts 1 nest

grand snow
#

example above is good

rich adder
#

remaining objects can def be an event based too

#

Invoke event when objectCount goes -=1

misty sand
#

public class ShadowController : MonoBehaviour
{
    public Rigidbody2D rb => GetComponent<Rigidbody2D>();

    public bool isIndependent = false;

    public void FollowPlayer(float moveInput, float moveSpeed, Vector2 playerPosition)
    {
        if (isIndependent)
            rb.linearVelocityX = moveInput * moveSpeed;
        else
        {
            Vector3 newPosition = Vector2.MoveTowards(transform.position, playerPosition, moveSpeed * Time.fixedDeltaTime);
            rb.MovePosition(newPosition);
        }
    }

    public void Jump(float jumpForce) => rb.linearVelocityY = jumpForce;
}
``` heres the script for my shadow controller
short hazel
#

remainingTime = timeForLevel -= Time.deltaTime;
You essentially decrement 2 variables here, do you really need both?

rich adder
#

that too ^

daring crescent
#

ohhh i thought i can only return if i have a method with a data type. Thanks guys!

misty sand
#

am i muted

rich adder
#

wut?

misty sand
#

joking

daring crescent
rich adder
#

only need to check that when you decrease, no reason to poll to call Win

#
remainingObjects -= amount;
if(remainingObjects == 0)
Win()```
misty sand
#

can i get some help please

rich adder
#

hard to offer help if its not clear

misty sand
#

you fine with me screen recording to show the problem

#

its easiest

rich adder
#

whatever makes it easy to show problem

misty sand
#

yeah ok

#

1 sec

rich adder
#

as long as you know.. dont dox urself

misty sand
#

i want to have a delay with the shadow so its a constant disance away until it interacts with a shadow platform then it works like it does in the video so the shadow can still jump

rich adder
#

I'm a bit confused how this supposed to work, when is shadow supposed to activate

misty sand
#

i want the shadow to have a constant delay so its always behind the player, apart from when its on the shadow platforms because for some reason with a delay it cant jump

daring crescent
# rich adder only need to check that when you decrease, no reason to poll to call Win

oh you're right, no need to have it on Update. The Objects are getting destroyed if they hit the floor, these Objects then call a Method which does remainingObjects -=1 and Invoke an Event which is subbed by the UI Manager. I've put the won() now in that function and added the return at top in Update(), but that stops the Update() instant because the Game does not Start with InGame.

#

How can i call Update without making it public?

rich adder
daring crescent
#
using System;
using Unity.VisualScripting;
using UnityEngine;
using static GameManager;

public class GlobalManager : MonoBehaviour
{
    [SerializeField] float timeForLevel;
    [SerializeField] string destroyableTagName;
    private float remainingTime;
    private int remainingObjects;
    public static GlobalManager Instance;
    public static event Action<int> onObjectDestruction;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Awake()
    {
        if(Instance != null) {Destroy(Instance);}
        else Instance = this;
    }

    void Start()
    {
        remainingObjects = GameObject.FindGameObjectsWithTag(destroyableTagName).Length;
    }
    // Update is called once per frame
    void Update()
    {        
        if(remainingTime >= 0)
        {
            remainingTime = timeForLevel -= Time.deltaTime;
        }   
        else
        {
            GameManager.Instance.changeGameState(GameState.GameOver);
        }              
    }
    public int getRemainingSeconds()
    {
        return (int) remainingTime;
    }
    public int getRemainingObjects()
    {
        return remainingObjects;
    }
    public void removeOneObject()
    {
        remainingObjects -= 1;
        if(remainingObjects == 0)
        {
            GameManager.Instance.changeGameState(GameState.Won);
        }  
        onObjectDestruction?.Invoke(remainingObjects);
    }
}
rich adder
misty sand
#

yeah

daring crescent
#

idk why the visual scripting using is in there

rich adder
rich adder
daring crescent
#

this caused my Update function to stop entirely

grand snow
#
void Start()
    {
        remainingObjects = GameObject.FindGameObjectsWithTag(destroyableTagName).Length;
    }

ooof plz change this when you can 😐

rich adder
#

isnt it instantly going to GameOver timer?

daring crescent
#
if(currentState != GameState.InGame) return;
        if(remainingTime >= 0)
        {
            remainingTime = timeForLevel -= Time.deltaTime;
        }  ```
The remaining time will never be = timeForLevel
#

The Game start in Menu

#

So the Update gets instantly returned because GameState != InGame

sour fulcrum
daring crescent
#

and dont get re-executed if the state changes to InGame

misty sand
#

@rich adder you alive or naw

#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

rich adder
grand snow
# sour fulcrum Out of curiosity why?

Doing a find/finds by name/tag/type can be inefficient and slow and prone to breaking. If possible its better to have a serialized list instead of the things you want to reference

daring crescent
sour fulcrum
rich adder
rich adder
rich adder
#

though its something you'd do if serialized field isnt possible

daring crescent
#

The total time to finish the level

rich adder
#

tags / strings in general are not good

sour fulcrum
#

Ye ways to improve the workflow but not a massive red flag imo

rich adder
#

its best to get good habits early. Tags become more and more useless as you progress ime

sour fulcrum
rich adder
#

not trying to convince anyone lol just stating an opinion

grand snow
#

well with mods you may have to do weird shit but im still one for following good practice

rich adder
#

I suppose with mods you dont mind strings because you are probably doing lots of Reflection anyway

sour fulcrum
#

(for context tags from a modding standpoint are a sin because they are super hardcoded and not expandable at runtime)

misty sand
rich adder
#

at very least for example if one wants to use tags, you'd play it smart to have a class that contains all the Constants for string tag this way at least you have less chance of mispelling the same tag else where

sour fulcrum
daring crescent
sour fulcrum
rich adder
#

oh no idea never modded for unity

#

only dabbled a bit with Ghidra

sour fulcrum
polar acorn
eternal falconBOT
daring crescent
#

Maybe for context im making a trashy game for the brackeys gamejam, its my first gamejam and i need to learn so much more 😄 You play a cat and have to push objects from shelfs in a defined time period. I used that to track how many Objects which needs to be pushed from shelfes are in the current scene.

sour fulcrum
#

Forsure homie. You know the context of the project more than anyone so acknowledging that your doing something unideally and deciding that's the best way to do it for now is a perfectly valid decision

rich adder
#

its not big deal now or later, but its good to do because of good Type safe benefit to components over strings

grand snow
sour fulcrum
#

for a gamejam grabbing objects at the start is fine

rich adder
#

yeah this the best option when runtime assign is not concern ^

#

serializefield is cleanest

sour fulcrum
#

the gain in iteration time is worth the honestly pretty minor cost of grabbing them globally

rich adder
#

we know the function isn't expensive, that isn't the point lol

daring crescent
sour fulcrum
#

ye but if your minmaxxing imo it's more ideal to instead have the class tell the globalamanger about itself than do a serialized list

daring crescent
rich adder
grand snow
#

cus we do the finding up front its not a cost to pay at runtime

sour fulcrum
#

the cost is small and doing it automatically at runtime avoids any user error

rich adder
#

in OnValidate you can do if(objects != null && objects.count ==0)
that elimnates any second guess

#

# if editor

daring crescent
# rich adder we know the function isn't expensive, that isn't the point lol

I've managed to find the issue with the code and the early return works also! Somehow i thought it would stop the Update() function but that was just a brainfart of me. The Update() will continue but will not go below the early return if conidition is not met 😄

public void changeGameState(GameState newState)
    {
        currentState = newState; #<-------- this i've missed in the GameManager, so the currentState was never InGame
        switch (newState)
        {
            case GameState.MainMenu:
                handleMainMenu();
                break;
            case GameState.InGame:
                handeInGame();
                break;
            case GameState.GameOver:
                handleGameOver();
                break;
            case GameState.Won:
                handleWon();
                break;
            default:
                break;
        }
        onGameStateChange?.Invoke(newState);
    }```
rich adder
#

had a feeling the state was messing with that :p

daring crescent
rich adder
daring crescent
sour fulcrum
#

Less hardcoded and allows you to potentially provide more logic to them in the future. There's just not that much benefit to using tags

grand snow
daring crescent
#

yeah i will change that tomorrow to a List, thats much cleaner and i want to get better habits 🙂

Thank you so much guys for all the help and patience 🙂 Have a good night.

sour fulcrum
#

Not something you need to do for this project but the example of a more ideal approch we mentioned earlier would be something like

GlobalManager

    public void RegisterMyThing(MyThing myThing)
        listOfMyThings.Add(myThing)
MyThing

    private void Awake()
        GlobalManager.Instance.RegisterMyThing(this)

Although something like this would require your singleton to be set before any of MyThing awakes which would require you telling your project to explicitly load that class before anything else, which is something i personally do but i know others might have an opinion on

This is kind of the equivilent to rocking up to work and clocking in for the day, rather than your store manager running around the building checking for who is here.

grand snow
rich adder
#

fr. it was intimidating at first but it makes soo much sense when you already do c#

sour fulcrum
grand snow
teal shale
#

When a dynamic object interact with a dynamic player with movement script it will interfere with the normal physics. In theory if i implement addforce and impulse, wouldn't that fix the physics?

rich adder
#

mainly blazor doing web

spice adder
#

hello, i was wondering if having dialogue box as a singleton(?) (like game object with dontdestroyonload()) is good or not? like is it the right approach or is there a better way that devs usually use

ripe shard
timber tide
#

wont stop me

rich adder
#

if its the only thing playing the visuals onscreen I dont see a big issue using a singleton here

#

keep the Dialogues inside array in Scriptable objects or something, then read them from Singleton to display

timber tide
#

If anything, singleton the canvas (UIManager) for which is holding that dialogue box

acoustic belfry
#

quick question, booleans start default as true or false?

rich adder
#

false

acoustic belfry
#

thanks :3

sour fulcrum
spice adder
spice adder
ripe shard
ripe shard
#

you use a loader/DDOL scene to hold your managers

#

whether you use a singelton or better pattern to access them is a wholly different question

rich adder
#

singleton basically makes easy referncing between scenes without doing proper DI

spice adder
ripe shard
#

its not called anything

rich adder
#

yea that too

spice adder
#

i see

ripe shard
#

singleton makes it easy now and very hard later

rich adder
#

but if its already in the same scene you could get away with DI

sour fulcrum
rich adder
#

Singletons are like seasoning

#

You want to sprinkle a little, not too much

ripe shard
#

i would say they are the pot you cook in, you need one, maybe 4, if you need more, think about your process.

rich adder
#

yeah I think at most I have 3-4 singletons that manage other managers

sour fulcrum
#

i tend to have 1 per scene and 1 globally, then anything else uses either of those two to middleman any neccasary communicaiton

#

but in early prototypes whatever gets shit done fast is whatevs

ripe shard
#

if you have one singleton, thats basically a service locator

#

if you have 4, you probably have identified the 4 things in your game that truly must be unique for keeping it simple (network manager, physics & time, localization, etc.)

#

if you have more, you probably are just lazy

sour fulcrum
#

Being lazy isn't always a bad thing

rich adder
#

if the game runs well and is fun to play who cares how you wrote the code

#

as long as you can maintain it

sour fulcrum
#

yup

#

games with perfect code do not release 😄

ripe shard
timber tide
#

I'd keep everything a child to GameManager but the syntax is just too damn long to call stuff from it

#

of course I could also do some alias stuff but im lazy

sour fulcrum
rich adder
#

more like code maintainability issues

#

but overcomplicating is a thing too that can impede progress, spending all that time doing "clean structure" 2 years passed and not much has been done even tho its clean lol

loud flax
#

Hey everyone, I'm diving into design patterns and SOLID principles, and feeling a bit overwhelmed! I'm curious how you all approach preventing over-engineering, especially in Unity. Do you tend to start with a more monolithic structure and refactor as patterns emerge, or do you plan out your architecture upfront and adapt as needed? Any tips for finding that balance between a flexible codebase and analysis paralysis? Thanks!

ripe shard
#

and from not knowing what the goal is... which leads to overengineering generic systems that aren't fun

sour fulcrum
#

you don't know what the goal is at the start

#

hence why you need to do it shitty first to discover that

#

it's a balancing act

ripe shard
sour fulcrum
rich adder
ripe shard
sour fulcrum
#

babygirl we are talking generally

#

a specific context has not been mentioned

timber tide
#

my gamejam template is composed of nothing but singletons as I can't be bothered to think during those

rich adder
#

now days its pretty rare to f up a lot because computers are so fast and tolerant these days thats why mediocre code can still work

sour fulcrum
#

Also in a lot of games prototyping happens at the same time as production 😄

timber tide
#

it's funny when it comes to optimization, it's games that matter the most

#

gotta make sure those frames are buttery smooth

ripe shard
rich adder
#

haha yeah City Skylines is good example

#

once city gets big enough it runs like a slideshow

#

im sure those are seasoned Unity devs and yet the performance was crap , but also cause I think they still used old pipeline?

ripe shard
#

basically all of those "shit code but fun game" examples went through 100k+ in payments to someone who fixes the most egregious errors of the "creative coding team"

sour fulcrum
#

ok but they had to make the game fun

rich adder
#

Ill take the creative coding team anyday plz 🖐️

#

ill let someone else optimize my shit code lol

#

"I made it fun, now you make it run good"