#💻┃code-beginner
1 messages · Page 608 of 1
I meant did you have it reversed that GetButtonDown actually works and GetButton doesn't
the toggle never gets called of anything inside
doesn't one of these get logged?
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
{
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
is it supposed to be Joystick Button instead of Joystick Axis or something
what are the types in there
why did you change the type
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
see what happens if you change it back to Key or Mouse button
because it's a button not an axis
even tho its coming from a joypad
it's still a button not an axis
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
button = on or off, no in between
axis = value from -1 to 1 based on current amount of input
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
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
Yh thats why i stuck with this one cuz i watch a quick video and it looked fairly simple
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
once the bool is true start a timer (ie add Time.deltaTime to a float in Update)
you can also just write the current time into a variable
Time.time - startTime is a duration!
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
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
camera needs to exist only on the client that sees it
that question still belongs in #archived-networking and hasn't changed since the last time you asked
ah mb
The errors dont have a fix and idk what to do
What do the errors say
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
let me check
also i heard statesmachines work for make waits in the script, how?
You do
wat
State Machines are just a programming pattern.
You will change states whenever you code in the state changes
this is the enable error
i mean, inside an state, the state itself will change the current state
for go to another state?
I can't give an example, I didn't write your state machine code
So, whatever PlayerControls.PlayerLocomotionMap is, it doesn't have a function .Enable()
This is setcallbacks error
Same thing. PlayerControls.PlayerLocomotionMap is apparently of type object, which doesn't have those functions
im new and a bit slow how do i fix that
What is PlayerControls.PlayerLocomotionMap?
im doing a tut and i believe its a movement script idk yet
its for like controller movement and pc movement
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Well, this variable is of type object
i think i nailed it,
for example
{
if (changeit == true)
{
currentState = State.Bee;
}
}
void Bee()
{
dancing:3
}```
which does not have Enable or SetCallBacks functions
this is how it changes states?
i know the rest, what bothers me is how states change, thats all
This is so psuedo-code I cannot actually answer
This is so far from the actual code I can't really answer if you've grasped the concepts or not
im no good at context pleasee explain
You can't call Enable or SetCallBacks on that type
object is probably not the type you want to use
what i mean is. If im inside a state, and i wanna change to another, i just write inside a what if scenario or smt
currentState = State.Iwanna;
can you send fixed script?
No
I literally do not know what you want to happen
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?
I cannot possibly answer this without knowing how you've implemented a state machine or what the context is for this
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
It's something in the editor. If you haven't made any editor scripts, it's probably internal
Either way it won't be in any builds so if it's not breaking things, you can probably ignore it
so its not my fault?
send me the tutorial
Ok
Check DMs
i havent implemented them yet, im just checking examples and examples to see how to archieve my enemy
Unless you're making custom editors, probably not
but i can give the context
Its only that i want it to wait for or what an animation lasts, or, for an specific amount of seconds
i hope this helps
Well, if you want it to wait for a certain amount of time it is probably going to take that amount of time
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
i mean
i want to know a line of code that makes the enemy stay still for an specific amount of time
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
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
By counting Time.deltaTime until 5 seconds pass, then making it do something else
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
Better cache time.time and check if curren time.time is 5 bigger
Instead of waiting for 5 seconds to pass, wait for the duration of an animation to pass
how do i set that up
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
an if statement does not take a significant amount of processing power
If it's animation related, may e use animation events though. Or query the current animator state
how specificly animation events work? i tried to find but i didnt find good awnsers
Stop worrying about performance until you actually have a problem.
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
it doesn't have the right to be that simple
its like a boolean...but inside an animation?
or i didnt understand it
It's a thing you put in the animation that calls a function
like the same way a frame of a sprite...But its a caller?
I cannot make sense of this question
just a quick test, dont mind me, just wanna know something.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
like, you said its inside the animation
the same way sprites, positions and others are?
yay my scriptbin is actually in there, im gone again, thats all i was here for
Basically. It's like a keyframe that calls a function instead of changing a property
got it
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?
This is what you should do. Checking for null will inform you if the coroutine is currently running or finished . . .
But it's needed for me to declare the null at the end or that happens automatically?
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 . . .
So, if it points to a coroutine that has ended but the reference is not set back to null it would be a nullpointer?
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 . . .
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
what
Drag and move the camera
But to exaclty same position that are the mouse
So, transform.forward/right doesn't works because uses speed value
i really dont know what you mean
maybe show an example?
^ they're trying to recreate this
The video is the example ;-;
is that what you have or what you want
What I want
why cant you use a speed value
Because I only want that my camera get the same position that my mouse
Don't need a speed value
I'm trying to make the camera gets mouse X and Z value to move
Because is a 3D camera
well you dont want the camera to teleport to where you click you want to drag it right?
I guess yes
But no Lerp
harsh-snapping doesnt look so good
I want that the mouse and the world be in the same spacepoint
Like the example
https://www.youtube.com/watch?v=rnqF6S7PfFA heres wat i used if u wanna check it out
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
Only the art is 2D
The game is 3D
I'm trying to reproduce your guide
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
Don't works
I don't know what I doing wrong
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
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
When click not happens nothing
I'll send a record
and code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Works with arrows and WASD, but I cannot make works with the mouse drag
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
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;
> }
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is my first time asking for advice here, sorry if I did it wrong
!code please
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Rather tell the lines without fragmenting your post into all those parts
the number of the lines of the pastebin? For example, "the loop is in lines 36 to 45"?
From what I see, you never create the card in your for loop but outside? so with each iteration, you overwrite your card object.
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
I fixed it a bit
So, I should create a new instance of the card in the loop each time, right?
First of all, what is your Card public field. Is it a prefab or is it a script or what is it? Is card just a class? If its just a class, you isntead of set a public value, just generate a new class instance of it with Carta newCard = new Carta(); and set your values to newCard
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?
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
understood, it's better in this case to have it separated
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
so it doesn't have to be generated every time I start the game?
should I do that with JSON?
You could, but it's also an excellent case for Scriptable Objects, I think
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
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:...
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Although nothing like an official Unity tutorial :D
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
like the deck in this case
That is a good point. For authoring data (at runtime), something like json that's easily writable is more appropriate
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.
if for example I wanted to have different decks to play (IE: one without faces or without jokers), scriptable objects wouldn't work?
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.
You can make predefined decks, which would just be an inspector holding a list you predefine, sure. But you cant create decks with a created Scriptable object in runtime. You cant create SOs in runtime in general
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
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)
On point
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
Happy coding 🙂
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#)
Have one place where your health value is updated and let the sprites with some simple mono listen to that update of health and get its value. Google for delegates or !learn 🙂
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
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
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)
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
ill see what i can do with this! thank you very much
i was relying on ontriggerenter cause thats what im used too haha
im watching tutorials.. and i think i cant understand all by lua logic, like define things are much different than lua local
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
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 (
autoandvarrespectively)
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
see what exists in the pinned messages in #🖱️┃input-system
if you can't figure it out from there, try asking in #🖱️┃input-system, and provide some more specifics
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
please don't crosspost
Create an empty object where you want the pivot to be, make your object a child of that positioned how you want it relative to the pivot, then rotate the pivot
hey guys! i have this code over here
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?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i was thinking of maybe putting PlayerData aside MonoBehaviour but it didnt seem to work, does that work?
yeah! i just don't know how to use the add component in this case, because like, this is in the same script!
should I just do playerData = GetComponent<PlayerData>() ?
if you hover over the PlayerData in the error, what does it say?
nothing...?
are you not using an IDE?
show a screenshot of your IDE
your issue is because you are using new MainManager() in the PlayerData class
oh, i missed that
oh, wait wait wait, i pasted the wrong error, im sorry
yeah your SavePlayer doesn't make sense
let me re-phrase my error
also you never actually return the loadedData from the LoadPlayer method which means you load the data then just throw it away
i totally confused myself sorry, im super sleepy
When you show an error, you should really just give the screenshot. It'll tell the exact line number and like almost everything we need to know anyways
no need to paraphrase
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
that line is actually irrelevant to the error.
that doesn't initialize the playerData field
you would need playerData = new PlayerData(), without the declaration, to initialize the field to be usable elsewhere
(although the placement of that line means that you will get another error after you fix this first one)
it is though. it's incorrect
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
userText.text = "User: " + playerData.playerName;
so, this is the line thats causing the error, im assuming that by putting the new PlayerData() its making the variable "local" if that makes sense? what do you call a variable that can only be used in only one method? i forgot
which line?
you aren't creating a local variable. you are just not creating the instance of playerData until after you attempt to use it
wdym which line? you already know which line
alright, so how would I use get component to instantiate playerData?
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.
setUserName();
playerData.LoadPlayer();
playerData = new PlayerData();
you mean here?
i changed it
yes
so now i got another error, same thing
show how you changed it then
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)
then wtf did you change
i changed that! i just changed it back here in discord to ask if thats what i needed to change lmao
wait that wasnt code beginner? it was worse than code beginner? 😭
thats a link to a message in this channel
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
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
got it, but why is it pointing to deathzone.cs:13?
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
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
it doesnt matter if they created it or not. a runtime error can be cause you simply forgot to assign a value to something
though what you were seeing is just the stack trace
Is PlayerData a monobehaviour
that's not even the code from the error, that was code from a previous error
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 😭
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.
Disable the normal movement script when you go into ragdoll mode.
Ofcourse but, "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."
Not sure what you mean by " an empty"
childnode or whatever its called, like this groundcheck i added
You would of course need to switch to an totally different set of colliders and rigidbodies
These are called GameObjects
ah i see thx
🙏 thx <3
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?
rescaling a child object
this is a feature. this is literally what parenting is for
this is a code channel, and that's not a code question
when I rescale it, it deforms
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
I use a joint then
no clue what that has to do
like carwash mentioned, if you want to discuss this further, move to #💻┃unity-talk
How do I make them stick togther then?
this
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
@wintry quarry the non-code chat has moved away from the code channel -> #💻┃unity-talk
Is there a function I can call like Start() or Update() that gets called when you exit the program
take a look under Messages: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.html
Thanks!
not a code question, shouldn't be in here. As you're using #🎥┃cinemachine you should move your question there (Delete from here)
You can see there was discussion happening there just yesterday
not relevant.
one side always rotates a little more than the other because of Time.deltaTime
is there a way to avoid this
use an animation
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and also configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
never works for some reason
also i don't think ^ means what you think it means
to the power of?
i don't see how bitwise xor factors in here
then you've done it wrong
not what that means in programming languages, no
ah i see
some languages do have an exponentiation operator, **
c# doesn't
there's a function for it, but here you can just do i * i
thanks
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.
is there a guide link to animations somewhere?
#🏃┃animation will have stuff in the pinned
Sort your VS out though
(It's a requirement to get help in code channels)
why is doing math in the coroutine a mistake?
he didn't say that
why is it a flaw?
the math itself and the overall idea was wrong, doing math itself in a coroutine is not an issue. you are doing the rotations over a set number of frames. these 41 frames could be 0.5 seconds for someone or 5 seconds for someone else
yes but doesn't multipling by Time.deltaTime fix that?
if it did, would this even be a question?
#💻┃code-beginner message
It does reduce it, but the last frame could still cause it to overshoot by varying amounts
ah i see
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
so im guessing my way of implementing this was flawed from the start
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
kinda a bandaid solution im guessing
could you give me an example of how you use a lerp?
its fine if its all you need, ive definitely written code before where i control an object like that rather than an animation
yea i just need a button to wobble
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.Lerp.html
Quaternions are how rotations are stored, so this is the Quaternion.Lerp
yea an animation does sound better for that
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
Could someone help me figure out how to use slerp with an array of Transform objects (I think that's what it's called?)
That's a really vague question that is essentially meaningless without further context
loop through the array and slerp each one?
a transform would be the component on a gameobject. you should specify what you're actually trying to do here (like move an object to positions over time)
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
if you have an array of transforms, thats likely so you can place them in the inspector and visualize where they actually are. you would want to get the position of each transform then lerp your position to that using
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.Lerp.html
[SerializeField] Transform[] emptyPoints drag n drop
then use foreach / for loop change the index as you move close to 1 point
What's "SerializeField"..?
Lets you set private variables in the inspector
Oh I see
Probably a stupid question, but how would you get the positions of each transform?
.position
is there an easier way to understand what a quaternion is
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.html
always check the docs for api shows propertie of each component
you dont need to understand it, and you likely wont. the actual math is very complex
you just need to understand that it is a rotation, and what the built in methods do for it
You don't really have to know how they work, just what they're for. You wont be manually touching them , ever lol
oh thank god
they prevent gimbal locking issues
i searched up what a euler angle is and i got a video on astrophysics
euler is what you normally see as degrees
so when you do this in Unity (eulers)
internally turns it into this
so for example im trying to rotate an object on the z axis 90 degrees, how would that look like?
You can use Transform.Rotate, for example
using quaternions
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
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)
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
could i have an example
// combining quaternions
Quaternion compound = qA * qB;
// rotating by some quaternion
transform.rotation *= q;
// setting a rotation
transform.rotation = q;
3 separate things here
Rotate only works with eulers but yeah
damn
i dont quite understand the first one
transform.rotation = Quaternion.Euler(0, 0, 90)
Equivalent to
transform.eulerAngles = new Vector3(0, 0, 90);
oh i see
if you had qA = 0,0,30 and qB = 0,0,60, you'd get compound = 0,0,90
you rotate according to qA and then according to qB
compound is the overall rotation from both quaternions
yeah
in two consecutive frames
no
same frame?
it's combined into a single compound representation
this is completely unrelated to frames
oh then its just math?
yes
That's like assuming player.health += 1 + 2 would add 1 and 2 to health in different frames
It's just a struct that represents rotation
Here's what you need to understand about Quaternion math: Don't do Quaternion math
so what im taking from all this is
i should just ditch quaternions and learn animations instead
If there is any alternative to using Quaternions, do it
I don't think I'm a very mathy person at all but I use quaternions all the time
That doesn't mean you have to like it.
but one question
But I do :(
you couldve just... asked the question
Someone can help me to do this cam effect?
I want to drag my 3D cam like this example
I tried +10 youtube guides, but nothing works :/
not sure why you'd want to use quaternions specifically
mate, are you even reading the documentations or anything at all?
you use quaternion functions from euler angles
you'd want to rotate something, quaternions would just be how you do it
i have 20 tabs open
anyways i literally gave you an example here @twin pivot
and?
open a 21st one then. it's not like there's a limit
or open a new window
im feeling a severe lack of brainpower
minimize the other 20 tabs or something
i have the tabs for quaternions open
.rotation = Quaternion.Euler(0,0, variableInDegrees)
so you have the docs open, you just aren't reading them...?
i am reading them
i just dont really understand it
-
Read the documentation for transforms, quaternions and rotations
-
Find a tutorial on youtube where someone explains these things and try to understand it, not just copy the first thing you see
-
Summarize what works and what doesn't work, then ask for help
You probably skipped the first steps
what is there to understand. quaternions it just works ™️
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.
You're never going to mannually constructing a Quaternion struct.. It just makes no sense to do so..
i didnt
comprehension is part of the first step
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
then start simpler - try to move a gameobject with transform.position, and just play around with the different methods
did that
there was a website that explained this stuff wasn't there
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
holy shit i guessed the url
damn it doesn't have quaternions
Hello, I have an issue with my Unity character, when it hits something, it instantly moves backward can someone help me ?
if its rigidbody you probably want to lock the constraints
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
in freeze rotation and position ?
depends how you "moves backward "
most likely rotation
if anything, show the weird behavior happening
show the full code
you probably have Collapse enabled
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
even with ref chincanery, it'd be a struggle
oh most likely its the position
the debug logs were just an example so i wouldnt have to explain the whole thing but that seems nessecary hold on
What does ToString do? Try using Debug.Log($"Damage: <color=cyan>{dmg}</color>"); . . .
show how you are using it
i freeze x y z rotation and that's fix now
thx !
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
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
but would it not be the same since i previously put it to an integer?
single bit flips
singular solar flare particle
You're running the getter twice
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
Ah, right, I just assumed that would be a DamageCard
Well, actually, now that I think about it, does RandomDamageCard extend DamageCard? If so, it would still be a DamageCard and run that
i thought there was no intervening else, meaning that both blocks could have run
Ah, got me again, I had the same thought
nope, just derives from Card, which doesnt have a damage value
to be fair my else structures are formatted strange
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
ill set it to 6 since normal damage cards only go up to 5
just so the UI doesnt explode
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
oh the Ui can just handle 1 digit
I think they mean they just want to keep it 1 digit
its just sized that way
so it doesn't run over the bounds
Okay so we're in the Evil Zone
I was looking for anywhere you might be capturing the variable
the world punishes me with evil for attempting to make evil balatro
but I don't see any lambda expressions in there
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
Try using the debugger and follow this dmg value all the way to its conclusion
I'm thinking it might be some sort of awkward variable capture since it's in a coroutine which is technically an enumerator?
wait, this is the enemy card logic
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
this is what happens when i skip out on making the code structured well to get the game done in time for the gamejam 😭
yeah that was it whoops 😭
i wouldve found out earlier if the evilness that was occuring diddnt actually make a tiny bit of sense
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
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?
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
This will be my first use of a particle effect, but I'm sure its simple enough for this. Its the changing the sprite and animation set that I'm having trouble with. How would I reference two separate sprites in the code?
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
Is there a way to freeze constraint for example Z rotation and unfreeze it via script?
thx <3
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?
You'd have one Sprite Renderer, and two Sprites. Then you'd swap out which sprite the renderer uses
so it would be more like ```
SpriteRenderer2D spriteRenderer;
public Sprite playerOne;
public Sprite playerTwo;
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
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
}
}
}
can I ask why this way instead of the Sprite Library?
I have no idea what Sprite Library is
iirc you can set the action map w/ different hold timers..
say if u hold it 1 sec -> this action happen
but if u hold it 2 sec -> this action happen
but i could be wrong.. as ive not used the new input system much tbh..
I wanted to calculate it dynamically though
but yea u can always do the logic in an update loop
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
get up get down
yeah but can I do it without that
since im using new input system
just found this actually
is it possible to mark the time when you press the key down then
when it goes up
what about GetKeyDown and GetKeyUp?
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
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
Started and Cancelled
would do the same thing w/ the new i think
void OnEnable()
{
ThrowAction.Enable();
ThrowAction.started += ctx => StartHold();
ThrowAction.canceled += ctx => ReleaseHold();
}```
i usually use both
but im trying to ween off of the old
is this => anonymous methods?
lambda, but specifically anonymous method yes
lambda expression
oh lambda
ThrowAction.started += delegate (InputAction.CallbackContext ctx) { StartHold(); };
i think its short for something like this ^
but im not 100 sure
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
^ yessir i forgot u could do that
soo.. u could poll like u did in the older one with the new one as well
holy heck, nice bookmark
well arent u special?
😭
teach me? 😈
i can do keyboard inputs.. but the mouse inputs still kinda confuse me
straight up the easiest method I use now Generate C# class from Input Action Map
actually i think its the fact u can use different types of data..
then its all type safe
yea, thats the only way i know how
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
so far I only used input from mouse as a vector2
you mean the Component u put on ur gameobject?
no issues?
Player Input component yeah
i remember a while back it was really inconsistent it seemed like
no, the only difference was the sensitivity scaling was different
ohh! 🤪
you can set a preprocessor for that iirc
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
for an animation statemachine do you drag animations into them?
sure
also not a code question
how would you set it up to compare, I have no clue how to code that and your solution is something I'm having trouble googling
You can literally just use == to check if the sprite is one of your two
and if it's not, then it'd be the other one
so it doesn't matter which step in the animation its in, it should just immediately switch the sprites?
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
you make a reference for each object you want to control, the script doeosnt have to be on the same object at all
once you declared your reference you put inside the field, whichever one you want to do stuff on
so like if you had multiple characters you can control or whatever would you spawn in one movement controller game object and then refrence it from each character?
Depends what you're doing. Sometimes you have one script for multiple object, sometimes each object controls themselves. It really depends
movement can mean many things
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?
so for the animator, would I also just reference one animator or how would I reference the animations for a second character?
You'd use the same Animator, swap the Animator Controller
Or Animator Override Controller
depending on how similar the two are
show code
- log
Are you sure you have the correct instance of the class? Make sure you aren't accidentally messing with prefab values.
is this the right idea?
animator.runtimeAnimationController = newController
Yep
thats the code and inspector after i used the ability in game
and this is the variables
so where is it returning false at exactly ?
and you are certain you are referencing the object instance thats showing in inspector
Oh i missed this function, it returns false here
I believe so? is there a way to check/know for certain?
debug the instance name or something
eg ($"{name}'s coolDown = {isCooldown}", this);
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
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
Oh it's checking the last abilities cooldown, not it's own... Idk how I'd fix that
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)
A tool for sharing your source code with the world!
not really sure why
the method is right there
it's checking the move action only, all of these use the same Action base which is where the cooldown stuff is stored
i think im just gonna call it for the day before i have a melt down lol
they all share the value if its inherited
I see, so it has to be in each individual ability script damn
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?
Get a reference to the component, then check whatever properties of it you want
not normally..just noticed this has networking? that might have something to do with it
I can reference the properties in a component unity provides?
thank you for the tip
I hadn't thought so but it might be a part of it, im using mirror
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
I only used netcode so no idea.. you can try checking in #archived-networking
Shouldn't it be running for each ability though? it's only running for the move ability which is odd
if its physics on physics. it should act accordingly
yes, as long as you're using rigidbodies
unity physics has forces yes. It will only smash harder its depending on its force hit and mass
unless its kinematic ofc
if your object thrown has lots of mass and ragdoll doesnt, ur ragdoll will go flying
Ah so i need to give my moving square physics 2d too
ofc
yes.
Ah 🤣 thx
any moving body ideally should have a rigidbody
if not u'll have to log the collision, grab the forces urself and apply it w/ translation
(fake physics)
colliders are for the shape
I tried doing gravity drag fraction and everything but that
gravity drag fraction? idk what that is tbh lol
anything u want to interact (as a physics objects) needs atleast a rigidbody
btw collision mode might be important depending how fast you throw those
true true..
2d you only have 2 options though anyway
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
Continuous if they are fast.
In 3D they also have Continuous Dynamic which is very good for 2 moving bodies
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
what would u say i should use for a purely physics game
think.. Pinball
probably Continuous
Continuous dynamic if other rigidbodies move just as fast and you want decent detection
so many memories
moderately fast for pinball i would assume
other objects move too ?
I always thought this pinball board looked like a bear taking a piss
paddles and bumpers do..
surpsingly this was when EA Games was good lmao
bumpers or w/e they're called actually have a wedge on their side.. and they pinch the ball
yeah but they aren't moving fast
less say you wanted 2 fast balls to hit each other, then yeah dynamic is better there
ahh yea i see what u mean
thats what I'd do
sometimes the bouncing feels like precise with just straight up collision
thats pretty clean ngl
ya, that artwork is incredible
cant quite put my finger on it tho
its like hand-painted mixed w/ cut-out Cellshaded-ish
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?
@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?
I barely remember what i did this mornin friend lol
gotta remind me a bit
sometimes its nicer to return early so you dont need a big if surrounding the contents of your function
e.g. if(bad) return;
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
im currently using events in the Menu Manager to display the correct text
ya events are dope
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
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.
but i could stop the decreasing of the timer if GameState != InGame
yeah that could work
and before you changed the movement to fixedupdate right?
what do you mean before
can i return in Update()? would that stop the execution?
It would exit the function
void Update()
{
if (currentState != GameState.InGame) return;
if (remainingTime >= 0)
{
remainingTime = timeForLevel -= Time.deltaTime;
}
else
{
GameManager.Instance.changeGameState(GameState.GameOver);
}
if (remainingObjects == 0)
{
GameManager.Instance.changeGameState(GameState.Won);
}
}```
this already cuts 1 nest
it will stop execution early for that function. even if a function is void we can return.
example above is good
remaining objects can def be an event based too
Invoke event when objectCount goes -=1
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
remainingTime = timeForLevel -= Time.deltaTime;
You essentially decrement 2 variables here, do you really need both?
that too ^
ohhh i thought i can only return if i have a method with a data type. Thanks guys!
am i muted
wut?
joking
the changeGameState Method triggers an Event in the GameManager Class
where do you decrease remainingObjects
only need to check that when you decrease, no reason to poll to call Win
remainingObjects -= amount;
if(remainingObjects == 0)
Win()```
can i get some help please
you havent really explained or showed the problem well..
hard to offer help if its not clear
whatever makes it easy to show problem
as long as you know.. dont dox urself
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
so you want to activate it after ?
I'm a bit confused how this supposed to work, when is shadow supposed to activate
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
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?
where did you put won ? that should not affect update
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);
}
}
so keeping the same distance you mean?
yeah
idk why the visual scripting using is in there
might want to create an offset from the player then
i said that
you removed the early return ?
i know but did you create offset ? send code in link
this caused my Update function to stop entirely
again i already have
void Start()
{
remainingObjects = GameObject.FindGameObjectsWithTag(destroyableTagName).Length;
}
ooof plz change this when you can 😐
you removed the check that the game is in playmode tho
isnt it instantly going to GameOver timer?
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
Out of curiosity why?
and dont get re-executed if the state changes to InGame
be patient mate, I'm busy lol
there are others who can help too thats whole point of this channel lol
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
void Update()
{
if(remainingTime >= 0 && currentState == GameState.InGame)
{
remainingTime = timeForLevel -= Time.deltaTime;
}
if(remainingTime <= 0 && currentState == GameState.InGame)
{
GameManager.Instance.changeGameState(GameState.GameOver);
}
}```
why not kiss 😄
It’s on the start of a GlobalManager, seems fine to do tbh. I could def see/prefer using an actual class rather than hardcoded tag and having that class register itself to the manager on their awake but it’s not the worst sin in the world
thats not through a link I can't see it well on mobile
what was the whole point of timeForLevel
well yeah at very least youd use FindObjectsByType
though its something you'd do if serialized field isnt possible
The total time to finish the level
tags / strings in general are not good
Ye ways to improve the workflow but not a massive red flag imo
its best to get good habits early. Tags become more and more useless as you progress ime
i have a lot of experience in modding unity games so you don't gotta convince me to be a tag hater 😛
not trying to convince anyone lol just stating an opinion
well with mods you may have to do weird shit but im still one for following good practice
I suppose with mods you dont mind strings because you are probably doing lots of Reflection anyway
(for context tags from a modding standpoint are a sin because they are super hardcoded and not expandable at runtime)
wdym through a link
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
ehhh the workflows avoid being super sinful with them
I will research for other solutions, i have max. 30 Objects with that tag. If you could provide a docs link/blog/example of a better implementation i would be really happy to learn, to do it better 🙂
we can't reflect most tag stuff because it happens in c++ land
Yeah i wouldn't stress on the tag thing too much right now. imo a quick and easy compromise is to instead just use an empty monobehaviour and to grab them via FindObjectsByType(FindSortMode.None) or whatever. This will give you the same thing you have rn but will set you up nicely if you ever wanna clean it up later on
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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.
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
its good to know for future projects as well
its not big deal now or later, but its good to do because of good Type safe benefit to components over strings
Id have a serialized list/array with the objects you care about, then you can reference them all easily + know the length
[SerializedField]
List<MySpecialScript> objects;
for a gamejam grabbing objects at the start is fine
yeah this the best option when runtime assign is not concern ^
serializefield is cleanest
the gain in iteration time is worth the honestly pretty minor cost of grabbing them globally
we know the function isn't expensive, that isn't the point lol
Yeah i think its important to learn some best practices to get better at coding. Actually i try to google how to make x,y and try to put it in my code ^^.
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
Oh yeah, that would be cleaner as i can remove items and add them in the inspector. Thanks for the hint!
well yes, I do that too, i believe thats the point. Thats already a step more complex than serialized references rn tho lol
You can even add something to make it easier to fill the list/array in editor
[ContextMenu("Fill Objects List")]
private void FillObjectsList()
{
objects = FindObjectsOfType<MySpecialScript>().ToList();
}
cus we do the finding up front its not a cost to pay at runtime
the cost is small and doing it automatically at runtime avoids any user error
in OnValidate you can do if(objects != null && objects.count ==0)
that elimnates any second guess
# if editor
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);
}```
yaa thats why its "early return" the function will still run until return . In update thats every frame
had a feeling the state was messing with that :p
Could you tell me why Type of a Script is better then Tag?
Is it because Tag is a string, and strings suck for conditions?
strange are not type safe. So you could mispell a string and your IDE would not even tell you its wrong or correct
types are always "safe" like you cannot mispell itt and expect it to work, it will throw an error that its missing
Much thanks for your patience!
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
If we use a Component type its more reliable. a tag could be incorrectly set or miss spelled but if a script is missing it has a bigger impact.
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.
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.
javascript nightmares 😮
Typescript or go home ✊
fr. it was intimidating at first but it makes soo much sense when you already do c#
also learning this is the first step of being tricked into learning generics
Some features like decorators lets you implement some super cool things, its worth using if you can.
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?
its rare because I only use JS now to call interop functions when working with JS libraries
mainly blazor doing web
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
a singleton (as you understand it) is never the best or "correct" approach.
wont stop me
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
If anything, singleton the canvas (UIManager) for which is holding that dialogue box
quick question, booleans start default as true or false?
false
thanks :3
I think this kinda opinion doesn't really accurately reflect reality
well that raises another question, how do developers make UI and stuff? like pause menu, settings, etc. do they just add it to every scene manually?
yes this is what i was trying to do
you arent really asking about "singletons"
you can keep your UI in a ui scene, or in a ui prefab and add/place those inside the scenes that need them
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
singleton basically makes easy referncing between scenes without doing proper DI
oh my bad 😅 i wasnt sure what its called
its not called anything
And in scenes too 😄
yea that too
i see
singleton makes it easy now and very hard later
but if its already in the same scene you could get away with DI
Really depends on the person and project
i would say they are the pot you cook in, you need one, maybe 4, if you need more, think about your process.
yeah I think at most I have 3-4 singletons that manage other managers
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
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
Being lazy isn't always a bad thing
if the game runs well and is fun to play who cares how you wrote the code
as long as you can maintain it
in certain types of games you never get there without half decent code
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
and in certain types of games you won't find out if they are worth committing to without garbage code
thats also true but most problem are design flaws dont impedee performance per se,
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
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!
overcomplication comes from not understanding what patterns result in a dung heap of half-baked fixes to support changes that the system was never ready to support.
and from not knowing what the goal is... which leads to overengineering generic systems that aren't fun
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
start with understanding exactly what you need, what the variables are, i.e. what needs to stay flexible, and then build the simplest solution to everything in a way that any piece of code can be thrown out and replaced easily without causing pain.
It's honestly just a long term skill you gotta build up on a case by case basis
thats true , its a balancing act at the end of the day
maybe don't conflate prototyping with production
my gamejam template is composed of nothing but singletons as I can't be bothered to think during those
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
Also in a lot of games prototyping happens at the same time as production 😄
it's funny when it comes to optimization, it's games that matter the most
gotta make sure those frames are buttery smooth
commonly underestimated how smooth they need to be and how hard it is to get there
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?
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"
ok but they had to make the game fun