#💻┃code-beginner
1 messages · Page 43 of 1
if you aint turning a profit from more than 50CCU monthly something is wrong lol
im not interested in profit even if it has a lot of players
All I asked for is the best web request code for making sure theres no interferance with a existing request to that url
you're in #💻┃code-beginner asking custom #archived-networking questions 🤷♂️
unity game has no concept of "someone else" though thats something you have to distinguish in the server build first
You can make some sort of Queue of requested ports so you make sure you only handle 1 at a time to the correct request
Hi there, i was wondering what the best way to make my code wait for one second is? Ive tried looking online, but everything is very complicated
Coroutine
coroutines cannot delay the code that called StartCoroutine
coroutines only delay themselves
Oh ok, so do i need to put the code under the StartCoroutine?
Ok
e.g.
Debug.Log("About to wait 2 seconds");
yield return new WaitForSeconds(2);
Debug.Log("2 seconds have now passed");```
Is there an alternatie for OnPointerExit that also triggers when you close the parent?
what does "close" mean exactly in Unity terms?
SetActive(false)
OnDisable will run when you do that
so is the yield return new the only code that i need to pause the coroutine? Sorry, i am having some trouble understanding how this works
Holy moly
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
bruh
thx, that works 🙂
YES?
sry caps lock
oh
ye ok
does that count as large blocks of code
or do i use `` `
I have no clue why mods took away the "Do not send screenshot of code unless requested"..
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
that will make the coroutine pause for 2 seconds, yes. That's what it does. How it works is another discussion entirely, but you don't need to know right now.
so you're saying this runs
Debug.Log("player has been killed"); ?
yes
Perfect, thanks so much!
and the other ui such as the timer also is disabled
did you check the inspector as wel
is the component staying enabled ?
one sec ill check
What does this error mean?
Assets/Scripts/PaintballControl.cs(57,9): error CS1624: The body of 'PaintballControl.Update()' cannot be an iterator block because 'void' is not an iterator interface type
I can send a screenshot of the code if needed
any other scripts controlling GameUi1's canvas ?
send code.. dont use screenshots.
you're probably trying to use yield inside Update
It means you tried to do yield inside Update
yea it stays disabled
With the link posted earlier?
the DeathScreen i mean
no code is needed here, the error is clear
you can only use yield in your coroutine
you can't put it in Update
im talking about GameUi1
are you referencing the correct canvas ?
Ok, then how is the coroutine shown, so i know where to put this code? Or should i chang void update() to something else?
You put the code in a coroutine...
did you look at the docs example ?
I did, but i am having trouble understanding it.
A Coroutine is its own TYPE of function with a return type of IEnumerator.
this shows yeild return
#💻┃code-beginner message
Ok, thanks
and here is my inspector
Why are they shaped like that??
idk if u do screenshot u can change it near the top
He's just using the free-form tool rather than the box select tool
this is just more accurate ig
that doesn't answer if Canvas is the correct object?
Ah
it is
hmm can I see the Canvas inspector when that debug.log runs ?
i think it might be cuz the object the script is one is disabled at certain times
yea but it gets enabled when the fire appears
and that is how udie so ig that isnt issue
if the log is running then the code is running
if you disabled it somehow before that line hits then idk that must be magical timing
yea, but its wierd cuz the other ui disappears but isnt disabled
make sure script is out of the canvas. try disable the whole gameobject
GameUi1.gameObject.SetActive(false)
I was going to say, SetActive seems to be more accurate here
I think I remember having a similar problem when swapping between canvas. I pulled up some code from an older project I was working on and I'm doing a similar thing
private void HandlePausedState(GameState prevState)
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
_gameHUD.gameObject.SetActive(false);
_pauseScreen.gameObject.SetActive(true);
Time.timeScale = 0f;
}```
One more question, if i use Debug.Log("Text here!");, when the code is triggered it will send a message to the console, correct?
Ok, great
canvas.gameObject.SetActive()
oh sorry
hello im back with a new problem xd how i can made for my UI dont be crazy like that
oh ty i have not see
also you need probably have Scale with ScreenSize
my canva has already scale with screen size
also 1 more question, how do i reset a scene without leaving then joining it again
your anchors dont look properly done though
my anchor make the size of my collider
how i need to put?
"without leaving then joining it again"
wdym
no anchoring is where its gonna be stuck while you move the screensize
so i want it so the scene the player is on, is reverted to how it was when they first clicked it
so you have to reset it
up to you to determine what that is
Load scene resets it
can u load ascene u r alr in
otherwise you have to determine what changed and restore it back
yes
but it will reset player too
unless player is DDOL
whatever you dont want to destroy on scene change can b inside DontDestroyOnLoad
ok thanks
if i reset/reload a scene
well i did
and it doesnt do anything
do i need to disable ui and stuff by code
?
@rich adder
wdym doesn't do anything?
so there is ui that pops up when u die
and i wanna make it so when u click retry it gets rid of it
but its fine ill just disable with code
manually
something like that ?
void Start()
{
clientComponent = GameObject.Find("Player").GetComponent<CLIENT>();
MyID = clientComponent.NewID;
Debug.Log("PlayerID is : " + MyID);
}
void Update()
{
if (clientComponent.NewID == MyID)
{
X = clientComponent.XValue;
Y = clientComponent.YValue;
Z = clientComponent.ZValue;
YRot = clientComponent.YRot;
}
Vector3 CurrentPos = new Vector3(X, Y, Z);
transform.position = CurrentPos;
Vector3 CurrentRotation = new Vector3(0, YRot, 0);
transform.eulerAngles = CurrentRotation;
if (clientComponent.DisconectedID == MyID)
{
Destroy(gameObject);
}
}
better than before sure
you mind as well make
clientComponent = FindObjectOfType<CLIENT>();
shouldnt you have a method when the client connect it passes its component to the manager
In the manager when the client disconnect his ID disapear from the list of connected ID , here I just say to the clone to diseappear
what is supposed to go un the box underneath runtimeonly,
is it supposed to be a cnavas or smth as rn i have it as a empty and it doenst owrk
wokr
work
you should have an event or something for disconnect? checking in update is unnecessary
huh you assume supposed to know what you're referring to and what doesn't work mean ??
oh yes I see what you mean, yes I might create something like that, it will be better
I have never seen anyone ss like that
its a lasso snip or freedom snip
whys everyone talking about that lol🤣
cuz it looks bad
Because it's terible
They know what it is, I assume, but why? It is so awful. It makes it harder to view and less accurate
it makes it more accurate
deamn. Like, the boxed shape is way easier and take less time to make
ok fine ill switch abck
I can't even see the box underneath. What is this?
not really
It makes my autism trigger more accurate indeed
is this supposed to be a canvas or button, as i have it as a empty (with the script attached of course) and it isnt even recognising me clicking the button
can u just show the whole inspector
this is as useful as soggy bread
Well, what GameObject is this attached. We have no idea what component this is on. Is it a custom UnityEvent?
its a empty
yep
then you're missing event system probably
empty gameobject is the thing its attached too in the ss above
its not empty tho, it has an Image component.
Is there another UI object obscuring it?
forget what isaid about empty
it wasnt important i dont think
no dont think
ok no
It either does or doesn't. You can clearly see if another UI object is over (on top) of this one . . .
check the inspector for Event System during playmode , it gives a debugg window to see what your mouse hit
Then do what navarone mentioned, make sure you have an EventSystem in your hierarchy . . .
in your hirerchy
yea i have it but it is in other scene
You need one in that scene
so then ur UI interactions wont work
Then you don't have it . . .
The current scene has no knowledge of another scene . . .
so can iduplicate it?
just add one
and additional one, or 1 in total?
oh ok,
So... something simple because I'm unsure...
About switch case,
I have case A, B, C and D.
A and C met their condition.
Does the function only execute case A or both? Case A and C?
normally you have a break then yeah it will run A and exit
the Plus button in hirerchy
same way you add anything else
If I want it to run both, do I just don't put the break? Or does it cause a syntax error?
nah i mean where in there
The compiler is smart enough that, in some cases where the case elements are clear, it'll actually error, saying that the condition is already handled before, and therefore the case is unreachable
ok i found it
But yes the switch runs top-down like all other statements, so it'll stop at the first matching case
ok it works now
Got it... then I'll have to use 4 different ifs in that case
thank you @rich adder
I suppose You can use goto iirc to go to another case .
but I would not play my luck with it, Ive seen a few people recommend against it
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements#the-goto-statement
I'm having a weird issue with gameObject stretching. I get a list of 4 cars that are children of separate empty gameObjects that are used for parking lot spaces (parkingLotPoint1 through parkingLotPoint4). the cars are supposed to be positioned and rotated to the parents transform but they end up stretching. what could be the issue? Here is some code I use, it's a for loop switch to iterate through the cars in a list. this sets the car inactive, disables the components, moves the car and rotates it to the parent object, and finally re-enables the components on the car.
//setting up parking lot cars to be in the right spot
for (int i = 0; i < parkingLotList.Count; i++)
{
switch (i)
{
case 0:
DisableComponentsOnCar(parkingLotList[i]);
parkingLotList[i].gameObject.transform.localPosition = new Vector3(0, 0, 0);
parkingLotList[i].gameObject.transform.rotation = parkingLotPoint1.transform.rotation;
EnableComponentsOnCar(parkingLotList[i]);
break;
the stretching comes from the fact that they have parent objects with non-uniform scaling
i.e. the MechanicShop object is probably scaled non-uniformly
the fix for this is you need to move the renderer and/or colliders etc of the mechanic shop into a separate child object which you can scale as you wish (without any children). Leave the MechanicShop object itself empty and scaled at 1:1:1
so what if I make a new empty gameObject and name it MechanicShopParent with a scale 1:1:1 and put the current MechanicShop gameObject as a child of that?
Weird stuff happens
never mind, I see the issue would still happen that way as well. So I'll do that but remove the parkingLotPoints from being children of the original MechanicShop gameObject
yes but then move all the other stuff that is currently a child of MechanicShop to be children of MechanicShopParent
those things all need to not be children of MechanicShop if it's scaled
Use the empty object as the central point of vehicle, like the chassis. Then, if your machine have a modular part (like a door or the trunk) you make another empty between the joints of that part
And don't forget to make it the child of the central part of the vehicle
how do I make a script which has a collection of variables readable and modifable to all other scripts? I want all variables in the script to be able to be changed from other scripts, and I also want these changes to be visible to all scripts as well (i.e. script A adds GameElement cube to list cubeList, and if script B has a function taking in cubeList.length, the length will have increased by 1
To make variables visible/modifiable from other scripts, mark them as public
The second part of your question is covered by an understanding of how references work in C#
Just add public to them, if the script needs to use a gameobject as reference, drag the object to the script (that will show in the inspector)
yes but then I have to instantiate an object to read/write, in which case if I instantiate and object in script B, the changes will not reflect. Correct?
Not correct. You can pass references around to existing objects
you do not have to create new objects all the time
oh how do I do this? I am not extremely skillled with OOP
I mean... It's not a simple answer
you should probably spend some time learning the basics of C# and Unity
at a basic level you can simply assign references like anything else.
List<int> exampleList = new();
List<int> a = exampleList;
both "a" and "exampleList" now refer to the same List object
Some stuff is easier by experiencing than by getting an explanation
in the case of having two scripts and one list - it's best to simply accept that one of those scripts is the "owner" of the list, and to only access the list through a reference to that script
I'm going to be honest I went through like 5 different online courses and none of them covered it well
or in a way I could understand at least
This is really the kind of thing you need to learn through experience and trial and error
you need to get a feel for it
before it makes sense
yeah I get that
The core idea is that reference types are not stored directly
the actual object is floating out in the heap somewhere
variables just hold a reference to the object
Writing code on the paper is so... sheeee
And for something apparently simple...
Then I go to write in code... there's so much stuff to keep track of...
But I think I'm almost cracking the logic for it to work
may I please ask about visual scripting in one of the server channels(#💻┃code-beginner, #💻┃unity-talk) because the Bolt server is pretty much dead
if you read my message you would've known that I already visited the server linked in #763499475641172029 and had to wait for several hours(up to a day) every time I asked
So what, you have no right to help, just wait
Here's my issue:
I have a grid array, I'll name it int ar[x,y];
Every cell in the grid will have a single digit number that represents a color (0 and 1 being the exception).
The objective of the script is to tell the number of sequence of matching colors that are "touching" either horizontally or vertically, without repeating.
Single tiles and pairs are not counted.
I am aware that nobody has to help me, I was just wondering if I could ask a simple question here, that's it, thanks either way
Then, after counting the group of colors, the script will send that info to another script to... not relevant
Something that looks so simple in a human brain... it's way complicated to make for a computer
I keep thinking of several methods to achieve this but... each one of the approaches, I realize that there's a flaw that makes fail to met the requirements
Not that complicated when you understand Graph algorithms. Sounds like a pretty standard "finding islands in a graph" problem which is well understood / solved
basically you just do BFS or DFS from each unvisited node in the graph (each grid space) and the result of each of those will be a single island.
The result is the number of islands you found
How would I change this to write text on a file? Theres actually no unity docs on this at all which is weird
I can read the text this way.. but theres no function to write it??
So... instead of trying to create one of those algorithms from scratch... I could have just used these to solve it?
System.IO namespace, has all the functions /classes you need
eg WriteAllText or StreamWriter write
etc
Excuse me a bit while I stuff my face on a pillow and scream...
My project got halted for almost a year because of that...
These are very well known algorithms in the world of computer science. You don't need to "create" them but you do need to implement them, which is very well trod ground.
I had no prior knowledge about those algorithms... so I was trying to create from scratch
So much time lost...
I feel your pain, its a eureka moment when someone with no formal CS bg learns about these
Well... on the bright side... the project is actually very simple.
A simple puzzle game and that algorithm was required to calculate the score
Yeah graphs are one of the most important data structures to know inside and out for game development
Especially for something like a puzzle game
But also for pathfinding
Because to calculate, I need the machine to know how many sequences of colors with size 3+ is on the grid
I already had the script to count the score ready, I just couldn't figure out how make it count the grid perfectly.
according to google its not possible. sorry. guess it needs php
3 or more, with no repeats.
And no counting from tiles that aren't adjacent even if the same color
wdym its not possible. I suggest you learn a bit more plain c# before doing anything that involves multiplayer
writing to a file is like basics 202
I know how to write to a file. But it doesnt work for a url
and with web request it returns error
whats that mean ? for a url
a website
And the worst part is... I know that I could make the script if I just put everything properly...
are you talking about a remote file ?
yea
something you should mention this is a remote file you trying to write to
This is just a logical problem using a few For functions and if statements
need unity to overwrite data on my webhost from the url
should I do it through php?
probably if right permissions are granted
im already using the php for sql
UnityWebRequest with a content-type of text/plain should do the trick
Attach the text directly, not in a form
got a example? ive tried quite a bit
UWR.Post("url", fileContentsHere, "text/plain")
does it require three arguments? ive tried including the extension in the url
is UnityEngine.Random.Range in a for loop suitable to determine item drop chances?
I seem to get a lot of items all at once and then none for a while, might just be randomness
(I am regenerating the number inside the for loop)
hello, can anyone assist me in using DOTween? I might be misunderstand sequence
sequence.Append( cameraPivot.DOMove(entrance.position, 1f).SetEase(Ease.InOutCubic) );
sequence.Append(cameraPivot.DORotateQuaternion(entrance.rotation, 0.4f).SetEase(Ease.InCubic));
sequence.Append(cameraPivot.DOMove(exit.position, 1f).SetEase(Ease.InOutCubic));
sequence.Append(cameraPivot.DOMoveY(playerCamera.position.y, 0.4f).SetEase(Ease.InElastic));
sequence.Join(cameraPivot.DOMoveX(playerCamera.position.x, 0.4f).SetEase(Ease.Linear));
sequence.Join(cameraPivot.DOMoveZ(playerCamera.position.z, 0.4f).SetEase(Ease.Linear));
Documentation said they should run in sequence (except for the last two) but no, they all ran at the same time. Why?
even if I didn't ran the last two, it still ran at the same time.
show code
{
float modifiedDropChance = 1.331f;
float luckyNumber = Random.Range(0f, 100f);
if (luckyNumber <= modifiedDropChance)
{ // drop item```
they don't drop all at once, but in close intervals, dunno
How could I write a script to make this object follow the mouse's horizonal movement?
It already follows the camera's horizonal movement due to being a child of the main camera, and I want it to stop following that but instead follow the mouse whenever I hold left click
go to youtube and type: "unity script to make object follow mouse"
oo alright ty!
should be similar to your camera script by following the rawaxis
ah okay ill try that out, ty!
what exactly do you want to do not drop all at once or something?
it goes through a list of items, each has it's own drop chance
but it doesn't seem real random
and I've read Random.Range is not true random, but dunno if that applies here
This is expected. Randomness is clumpy.
yeah I know
part of randomness is repetition no ?
just wondering if maybe if it uses a timestamp or something it might generate a lot of very low numbers at the same time
If that was possible, the RNG would be very bad
kaj good, so the not true random thing only applies for encryption & stuff then?
even cryptography does not depend on "true randomness"
nothing you'll use is true random
its very very rare to actually need it
it just depends on the pseudorandom number generator being indistinguishable from true randomness
yeah I don't need true random, whatever that is
I just need to make sure that during one for loop it's not generating similar numbers
there is an annoying bug in URP right now that causes Unity.Random to be seeded with the current frame number. This caused me to see the same results every time I ran the game
(in unity 2022 and later, iirc)
how do I make a value increase each time the score is increased by 5
like 5, 10, 15, 20... etc.
Depending on the exact requirements there are many ways
One basic way is just using a property that depends on the score
int myVal => score / 5;```
oh thanks
to be more specific im recreating flappy bird and I want the pipes speed to be increased every time a player scores 5 times by going through the pipes.
I would use a Modulus for this if (score % 5 == 0) { increase speed }
shouldn't be too hard to find a way around that 😉
what PraetorBlue said is best if you want the speed to increase in proportion to the score. Mod (which is actually the remainder operator in c#) loses you the information of how large the score is
if you dont have an exact formula you want in mind tho, its just up to you to experiment for what feels good
I mean you could just do it when you add score only
Oh
public void AddScore()
{
score++;
if (score % 5 == 0)
{
Debug.Log("Increase speed");
}
}```
Hai all! Having an issue with some code that was wrote by a moderator and amazing hellper here on the server. I'm having some compilor issues with it and I have little to know knowledge of coding so I'm unsure what to do. Heres the thread: #💻┃unity-talk message
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Hi, I am VERY new to this.
I'm currently trying to do the UI for a game I'm trying (and currently failing hard at)
But, I can't add the Dropdown UI to my script.
It's meant to read the Selected option from the dropdown menu and apply it to change the resolution.
Well first note that TMP_Dropdown and Dropdown are two different things
Make sure You're using the correct type
Second you can just drag it from the scene/hierarchy you don't need to use that selection menu
(same for TMP_Text vs Text)
Text and Dropdown are legacy and it's unlikely you're actually using them
That's my problem then!
I actually don't see another option for Dropdown.....
I only have TMP Text and Dropdown.....
Hi im looking for help on how to make my code work been struggling af for the last couple days on it, im trying to make the character able to crouch but struggling to figure out how. i have managed to get it down to a position where it says it is crouching as soon as you press play until you end the game, the primary code that is dedicated to crouching is lines 127-158. thanks alot in advance
you have the others too but you shouldn't use them
it's not a problem
just use TMP_Dropdown and TMP_Text in your code
sorry what's the question exactly?
I don't see any code that changes crouchPressed anywhere
Awesome, cheers; I'll give that a go then, go to bed!
It's 8.22am & I haven't slept yet! 😅 😂
literally just wondering what code to add to make it work like a crouch should, when c is pressed crouch
input handling you already have examples of in your Update method
you can use Input.GetKeyDown for example to check when C is pressed
or Input.GetButtonDown and make a Crouch axis similar to your Jump axis
if (Input.GetKeyDown("C")
is that all i need to add for it to work do you think or is it more elaborate?
@wintry quarry
That would be how you tell if someone pressed C (although the syntax is wrong. It takes a KeyCode, not a string)
Nm, I'm dumb. It can take a string
thanks, so what would i need to add and where to impliment something where if c is pressed it will crouch
sorry i am dumb im just starting and tried every vid online they all just use different code to what inhave used previously
The behaviour for crouching
You have the code for detecting the key press
Now you need to REACT to that key press
how do i go about doing that i dont know what that would be in code ive struggled to find the appropriate code online
Depends on how things work in your code.
You using animations? Can you see the player?
Could be as simple as lowering the camera
Could be as involved as making a custom animation in blender
yes i have animations to switch him to crouch from whatever other animation he is doing
i got this transform which is responsible for the head IK, and i need the transform to move with the mouse position of the player, how do i do that, i tried something like this but it didnt really work
Then inside that check for if they press c, go into that animation state and it'll swap to that sprite
like a mario game basically
this is how the animations look in the animator, how do i go about adding a check for c into that?
You wouldn't add a check for c into that. Ignore that
Look up how to use animations in unity. You set a bool or trigger (or a float, which doesn't make as much sense here) and the transitions will read them and nove to the appropriate state if it's set up right.
Just look up a GENERIC animation tutorial that has nothing to do with crouching
It will be super obvious once you know the basics
how can i find the material of the face that a raycast hit on a multi material object?
You can get the triangleindex your raycast hit and parse out the UV index of that triangle
would you mind sending me a snippet or something? i have tried many times but im not sure what to do
https://forum.unity.com/threads/detecting-material-material-index-and-raycast-hit.40377/
https://gamedev.stackexchange.com/questions/113315/how-to-find-a-material-through-a-raycast-in-unity-5
Hello there,
I have an object having several materials applied to it (Element 0 to Element 3).
I do this:
if...
thanks, it works
Ive figured it out in the animations department its figuring out how to actually do the crouch in game specifically when c is pressed and not as a constant from start to finish if that helps
in the amimator tab i have it set to play animation when crouch is true, but right now it is never true because crouch is always working it says in debug but not specifically when i want it to(whhen c is pressed)
Well, the animation part is the only part to of the code implement. Set an animation bool to true on GetKeyDown and false on GetKeyUp
And have it default to false
animator.SetBool("Crouch", crouchFlag); is that not what this is or am i extremely wrong
in the project setting i had this and i thought this would make it work originally but clearly not, was i on the right track with this or was i doing the project settings for no relevence ti the code @summer stump
Should work
thats what i already have in my code
That is an axis, you are using GetKey not GetAxis
so any idea why it doesnt work
Gotta show the code 🤷♂️
^^^
Sorry i put it in a while ago but its been a long time ahah, thankyou for the help so far tho i appreciate it
Wait... where do you flip crouchPressed? Where do you check if the C key is pressed?
I dont have a check if c key is pressed i couldnt figure it out and removed it before showing code in hope someone could tell me the correct place to put it, and i dont know what flipping the crouch flag would do hence it not being there if you could explain pls
Well that is why it doesn't work then....
Simply do the code praetor said and I've said. Put it where you check for jump
In Update
That would be it.
Just the GetKeyDown and GetKeyUp in update
When down crouchPressed is true, when up it's false
i dont know what flipping the crouch flag would do
Do you understand what anything in your script is doing at all?
Where did you get the code from?
to be honest i understand the basics of moving and jumping + basic animations but the crouch has really thrown me. im usually an unreal blueprints guy but had to move to unity recently so gathering help from here to build an efficient movement script to use. alot is from guides ive been watching and following from youtube.
if (Input.GetKeyDown("C"))
{
crouch = true
}
else
{
crouch = false
}
would this be right for the get key up or am i wrong? sorry im still figuring out how to write code
for this
No
Use GetKeyUp
Input.GetKeyDown("C") is wrong in the first place
Input.GetKeyDown(KeyCode.C) is what you want
Also you don't want to know when GetKeyDown is NOT happening. You want to know when the button is released
that's GetKeyUp as mentioned above
I thought that at first, but I did see it takes a string?
https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
But I dunno what the correct string is. And of course a KeyCode is way better
I don't think it's juse "C"
the correct string would be "c"
but the keycode is better
the strings are listed here https://docs.unity3d.com/Manual/class-InputManager.html
Ok yeah. I hate strings for things like that lol
so if i place this instead of the original get key down i put does that still need something else adding to it to work, or do i need to add a get button down?
var crouch = Input.GetKey(KeyCode.C);
if you permanently want to check if its pressed or not at this frame
sorry if it sounds like im just not listening i am, im just really struggling to understand
this will work too actually
so if i add this to update tab it should work?
crouch
but you actually care about the crouchPressed variable
think about it
read what your script is actually doing
Replace crouch with crouchPressed (which is your variable name)
Oh. Yeah, as praetor said
yeah sorry i did mean that i just meant the general line of code with the correct name
Then yeah. Every frame it would check if the key is pressed
If it isn't, it's false.
var crouchPressed = Input.GetKey(KeyCode.C); ive added this to my updates and its still just showing through the debug that the crouch is working from the second you press play, have i done soemthing else wrong?
yes you've created a completely different irrelevant variable that the rest of your script is ignoring
which is the irrelevant variable?
var crouchPressed
the fact that you typed var there means you created a new variable
you don't want to create a new variable
you want to just assign the existing variable
so i dont want to be adding the var
and i want to change crouchpressed to crouch
or am i again very wrong
no
just read what I wrote
how do you assign a value to a variable?
so literally remove the var
yes
is it = or am i on the wrong page
here its the script attached to the fire: void Start() { //transform.rotation = Quaternion.identity; } private void OnDestroy() { var toilet = gameObject.transform.parent.GetComponent<ToiletBehaviour>(); toilet.hitsReceived = toilet.maximalHitsToDestroy; }
to the explosion: ```public float explosionRadius = 10f;
public float explosionForce = 10f;
[System.Obsolete]
void Update()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, explosionRadius);
foreach (Collider col in hitColliders)
{
if (col.TryGetComponent(out ToiletBehaviour toilet))
{
Vector3 direction = col.transform.position - transform.position;
float distance = direction.magnitude;
float forceFactor = 1f - (distance / explosionRadius * 2);
float appliedForce = explosionForce * forceFactor;
col.GetComponent<Rigidbody>().AddForce(direction.normalized * appliedForce, ForceMode.Impulse);
if (!toilet.isInFire)
{
col.GetComponent<ToiletBehaviour>().setOnFire();
}
if (toilet.isInFire)
{
toilet.hitsReceived = toilet.maximalHitsToDestroy;
}
}
if (col.CompareTag("ToiletSherds"))
{
Vector3 direction = col.transform.position - transform.position;
float distance = direction.magnitude;
float forceFactor = 1f - (distance / explosionRadius);
float appliedForce = explosionForce * forceFactor;
col.GetComponent<Rigidbody>().AddForce(direction.normalized * appliedForce, ForceMode.Impulse);
}
}
}```
and to the toilet: ```public GameObject toiletSherds;
public GameObject explosionParticlesPrefab;
public int minimunHitsToDestroy = 6;
public int maximalHitsToDestroy = 12;
public int hitsReceived;
public float impactForceScale = 1.0f;
public float velocityOfImpactForExplode = 7f;
public float velocityOfCollisionByObject = 4f;
public bool isInFire = false;
public GameObject fireParticles;
private GameObject fire;
public int random;
public int random1;
public int random2;
public float maxDetectionDistance = 10;
public float maxDetectionForce = 5;
[System.Obsolete]
private void Start()
{
if (isInFire)
{
setOnFire();
}
random2 = Random.RandomRange(5, 7);
random1 = Random.RandomRange(minimunHitsToDestroy / 2, maximalHitsToDestroy / 2);
random = Random.RandomRange(minimunHitsToDestroy, maximalHitsToDestroy);
}
[System.Obsolete]
void Update()
{
if (hitsReceived >= random)
{
//if (random2 <= 3)
//{
Instantiate(explosionParticlesPrefab, gameObject.transform.position, Quaternion.identity);
//}
Destroy(gameObject);
Vector3 position = gameObject.transform.position;
Quaternion rotation = gameObject.transform.rotation;
GameObject sherds = Instantiate(toiletSherds, position, rotation);
}
}
[System.Obsolete]
public void setOnFire()
{
isInFire = true;
if (isInFire)
{
fire = Instantiate(fireParticles, transform);
//fire.transform.position = gameObject.transform.position;
Destroy(fire, random2);
}
}```
oh god the [System.Obsolete]s 😢
ps: sorry for the delay
don't listen to your IDE's complaints about those functions not being used. It's ok.
sorry for treating you all like chat gpt 😅
lol,even i dont know what that thing means
@wintry quarry sorry to bother again but when pressing crouch now its changing the colliders as i want but not changing animations even though parameters appear to be right, any idea?
I know you don't 😉 The fact that it's there tells me you don't.
😔
when you say "parameters appear to be right" what are you basing that on?
@unreal imp at least you almost used what I sent correctly lol
col.GetComponent<ToiletBehaviour>().setOnFire();
this wouldn't be necessary since its all already stored in toilet
Sounds like a transition/state issue
not getting any errors in code
how ans where can i look at fixing that
But that doens't mean your animator is set up properly
The animator
ive got it the same as my jump which works with the bool parameter for crouch so animation should play when crouch is true and all transitions are in order
prove it
also - in #🏃┃animation because at this point it's an animation issue
animator.SetBool("Crouch", crouchFlag); is the code i use
yes we've seen the code
and the other transition?
also what animation clip is on the Crouch state
Show which animation clip is on the Crouch state
each state has a clip
better yet -
run the game with this window open
you can watch the state machine in action
see if anything is going wrong there
You can only go to crouch from the NewAnimation state. What is that?
hope this helps
Quick question, HashSet<Transform> vs Transform[], i guess the latter is faster? Initialization of both with fixed size
Not really
its as thoygh when im crouching its activating the jump animation as if im off the ground when im not
oh shi no it didnt screen record what i wanted
2 secs ill do it again i had 2 screens open
I said "with this window open" ...
"faster" is completely meaningless without information about how it will be used
there that shows the animator and slates sorry i had them open on 2 seoerate screens
yeah it's going into your jump state instead
maybe your jump transitions are messed up
are you adding/removing objects from the collection or just iterating? can you have duplicate transforms? is it a fixed size? there are many things to consider when picking a collection . . .
System:
_group = _contexts.game.GetGroup(GameMatcher.TrackedByCamera);
[...]
var trackedEntities = _group.GetEntities();
var trackedTransforms = trackedEntities.Select(e => e.view.Value.transform);
_targetGroupEntity.ReplaceTargetGroup(trackedTransforms.ToArray());
View:
public void OnTargetGroup(GameEntity entity, Transform[] value)
{
TargetGroup.m_Targets = value.Select(t => new CinemachineTargetGroup.Target()
{
radius = 1,
target = t,
weight = 1
}).ToArray();
}
Thats mainly how i use them
what am I looking at here? Which collection are we talking about?
also var is everywhere masking types
i dont think only fixed them otherday, the jump anim is activated whenever the player isnt on the ground, so its as if when crouching its lifting me off the ground
The one stored with ReplaceTargetGroup in my TargetGroupComponent
Yes I see that but I mean the settings in the animator for that
That doesn't show how you use it then
just how you create it
you mean m_targets?
The second code block shows usage
now the second block shows it being created and stored in a field
how do you use m_Targets
Thats internal of cinemachine
for the jump anim?
so why are you considering a HashSet when CInemachine only accepts arrays anyway?
Where and how would you use a HashSet here?
Because of the transformation to CinemachineTargetGroup.Target, camera will potentially track hundreds of objects changing per frame
unless you plan do Add, Remove, or do Contains checks on the collection, there's no reason to consider a HashSet
You aren't doing anything here except iterating over the entire collection
Alright, thanks
you're also creating a ton of garbage by using Linq here
you're creating brand new collections every time this runs
what type is trackedEntities
the settings for the jump is exact same as crouch only one crouches and one jumps, bool jumpanim when true jump when false return to idle
GameEntity[] (internal thing of Entitas library)
Basically just an array of classes storing components
Rather use c# loops instead of linq?
Yes and reusing your collections
I have no control what _group.GetEntities() is outputting though
I mean technically I control whats in it by game logic but its a call into a third party lib
well I would strongly guess that they aren't allocating a fresh array every time
Nope they dont
also you do have control over:
- the array of
CinemachineTargetGroup.Targets you pass into the vCam - not creating random other intermediate arrays
Well you got me onto something, rn I create an array of transforms, just to create an array of Targets afterwards, i can just create an array of targets directly i guess, cutting the middleman
that's low hanging fruit yes you can get rid of at least that intermediate array very easily just by passing the IEnumerable through directly
But I'm not sure how you would go about reusing anything here, could you tell me how you'd go about that?
Well for one this seems like something that only needs to happen whenever an enemy is added or removed
And when that happens you can just use https://docs.unity3d.com/Packages/com.unity.cinemachine@2.9/api/Cinemachine.CinemachineTargetGroup.html#Cinemachine_CinemachineTargetGroup_RemoveMember_UnityEngine_Transform_ and https://docs.unity3d.com/Packages/com.unity.cinemachine@2.9/api/Cinemachine.CinemachineTargetGroup.html#Cinemachine_CinemachineTargetGroup_AddMember_UnityEngine_Transform_System_Single_System_Single_ to add/remove them to/from the target group
yeah thats done already, its not in an update loop
Never looked at Entitas internally before now, and dear lord I definitely will never touch this library haha. Why are entities classes, when they are meant to just be a minimal indentifier. Every entity makes at least two completely new lists, as well as an array during Init. It seems to nuke the locality that sparse sets provide, or even what archetypes provide, as this just seems to spread your pointers all over the place.
This reminds me of when I went though DOTween's source code and saw all of their hidden allocations all over the place lmao (especially with making arrays all over the place mid-function).
yeah not sure what framework this is but it seems a little sketchy
I was under the impression DOTween was careful about allocations 😢
Its a bit of an older ecs framework from back when unity ecs wasnt a thing and I have used it at work extensively, its more userfriendly than unity ECS but definitely doesnt have the performance benefits of it
tbh i've been enjoying PrimeTween instead of DOTween recently (kind of like a modern DOTween centered around minimal allocs and struct usage). Pretty cool lib from what I've used over the last month.
Cool
i second PrimeTween. i never really used tween libraries cuz i don't do cool stuff, but i've messed with/used it over DOTween . . .
damn how did I not know about this
I am new to unity and following the tutorials but it wont let me open my script does anyone know why and how i can fix it.
!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
• Other/None
seems pretty clear...
Oh yeah, and that 😄
what do i do to fix it tho
rename your project path
microsoft is often very allergic to anything that isn't letters and numbers
maybe dashes
Any suggestions on the cleanest way to clamp a transform rotation value to its closest 90o angle? Like ideally I wanna know if a transform is facing
Forward
Left
Right
Backward
you would use quaternions probably
you can get the angle between two directions to check which way an object is facing or the dot product between two normalized vectors (directions) . . .
using Vector3.Dot will be the same as using Vector3.Angle
well, almost
angle: pick the one that's the smallest
dot product: pick the one that's the largest
You have a component on something whose script no longer exists
i forget if Unity has a convenient way to find those
yeah, tried to give them options . . .
i believe Dot is a bit more (expensive) work bcuz it also uses the cosine of the angle, which is what Angle does solely . . .
typically, it happens when you change the name of a file or class . . .
just saying the error will occur if any class or filename is renamed, but it can appear from editing a script while in play mode as well . . .
it's only a warning; just be aware that changes were made to a class during play mode . . .
i just ran a test. it'll pop-up if you edit a class during play mode. you should only worry if you changed only the class name or file name but not both (which is required) . . .
having issues with Inheriting, can someone point out my mistake.
private void Awake()
{
targetingSystem = FindObjectOfType<TargetingSystem>();
if (!targetingSystem)
{
Debug.LogError("No TargetingSystem found in the scene!");
}
}```
what kind of issue?
There is nothing related to inheritance there
public class FireBall : GameAction
{
private void Awake()
{
ID = 1001;
actionName = "FireBall";
iconPath = "Icons/FireMage/Fireball_Icon";
//particleEffectPath = "Path_to_your_particle_effect";
damage = 50;
manaCost = 20;
icon = Resources.Load<Sprite>(iconPath);
if (icon == null)
{
Debug.LogError("Failed to load icon from path: " + iconPath);
}
}
public override void Execute()
{
base.Execute();
if (targetingSystem)
{
Transform target = targetingSystem.GetCurrentTarget();
if (target)
{
Debug.Log($"You've casted {actionName} on {target.name} dealing {damage} damage");
}
else
{
Debug.Log($"No Selected Target");
}
}
else
{
Debug.LogError("No TargetingSystem found in the scene!");
}
}
}
Debug.LogError("No TargetingSystem found in the scene!");
this is triggers
sorry pressed enter by accident on the first one
this doesn't give us any inheritance unless there is more code . . .
is hooked to a gameobject.
So... FindObjectOfType is not finding it? That seems like the issue?
you have two classes that log the same error. which one of them is the problem?
Fireball
Was the first code you sent GameAction?
private void Awake()
{
targetingSystem = FindObjectOfType<TargetingSystem>();
if (!targetingSystem)
{
Debug.LogError("No TargetingSystem found in the scene!");
}
}
it finds it here in the Action Class
yea sorry i made it confusing
what class is the first snippet belong to?
You never called base.Awake in fireball
You cant even call it, there should be warning of hiding base method
Awake is not overriden — not set to virtual; then Fireball can override it . . .
Oh yeah of course. I saw the override on Execute and my brain said of course it's on awake too lol
i thought so at first, as well . . .
That was my mistake, I'm sorry. If I wasn't tired I would have problaly caught it.
i just didn't know what class the first snippet belong to. that fooled me for a bit . . .
Sorry again, I realized I made it super confusing. Brain wasn't operating correctly.
no worries. problem solved . . .
AHH yes, debug.log spam.
updating your scripts during play mode isnt good, i dont know why its a feature honestly because it doesnt really work well
unless you are using some hot reload plugin
maybe the instance is null somehow after updating in play mode
Hello guys, No matter value I put here, 1 or 10000000 the laser of my ship always go up same velocity. any ideas?
the value is serialized in the inspector, meaning its gonna stay at 1 regardless of what you change the default value to. Change it in inspector for the existing instances of this script
also your !ide doesnt look configured
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
• Other/None
That fixed the problem, amazing, thank you my friend
What do you mean?
are you getting auto complete/error checking for unity stuff? Honestly not sure how vscode highlights things but your Start() and Update() shouldnt be greyed out, that indicates its unused but its not
should i install extensions?
the bot command i linked above has the VS Code guide for configuring your ide
i also find wierd as tutorials and courses I bought their code looks dif i mean with dif colors
thank you
Done it, now looks correct, thank you again
Vs code is weird, the suggestions weren’t working for the past week and now they are today
-_-
#💻┃code-beginner message
well i did say this, and you really shouldnt be updating your scripts while in play mode still
why? its happening because you are editing scripts in play mode. its not a good feature and will lead to unexpected results, like the case you are experiencing now
Just move on and exit/reenter playmode to properly test. Or download fast script reload from the asset store
even fast script reload has its limitations that you must exit play mode for but its useful for smaller changes
Mornin' all, I was wondering if anyone had played with the Mimic Prototype on the asset store? I'm trying to figure something out, but can't seem to. lol.
https://assetstore.unity.com/packages/3d/characters/creatures/mimic-prototype-245997
is there a way to go back to previous level (not depending on index -1 thing)? Im scripting a button right now to restart the level if the player dies, but the thing is i only want one restart scene but make it so that if level 1 was where the character died, it restarts to level 1 and if its on level 2 it restarts to level 2 instead etc
I think.............
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
Grabs current scene name and loads it. Unless I'm misunderstanding what you mean?
ah no cause the scenario would be:
player is in level 1 scene-> player dies -> player gets sent to "game over screen" scene with restart level and go back to home -> player clicks restart and goes back to level 1 scene
but then i want it to work with level 2 and 3, etc so i guess the sceneindex-1 thing doesnt work cause even then they wouldnt be in order either
Would it not be way more efficient and cut down on loading times etc. to have the 'game over screen' as a UI element in the actual scene? (die, it pops up, gives you the options etc)?
If not, one way to do it (although I know a lot of people don't like using it), upon death you could send the current scene name to PlayerPrefs as a string (lastLevelPlayed) and on the 'game over screen' read that value?
ah hmm you're right
advantage of playerprefs really is that it's persistant across game 'sessions' (ie, with just doing it through UI etc. it won't 'remember' if you close the game.
Of course you could do both.
public class MapUIButtons : ScriptableObject
{
public int NumOfRewards;
public RewardScriptableObjects Reward1;
public RewardScriptableObjects Reward2;
public RewardScriptableObjects Reward3;
}
i need to create X RewardScriptableObject depends on the int value of NumOfRewards
so if numofrewards = 1 i have 1 rewardscriptableobjects
2 = 2 rewardscriptableobject
etc etc
You should be using an array there.

!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
yes ty
I was expecting more questions ngl.
I'm having such a weird brainfart moment.
I need to 'convert' this......
foreach (Leg g in FindObjectsOfType<Leg>())
{
Destroy(g.gameObject);
}
So that it only finds the 'leg' objects that are children of the first child of the current object (at the moment it's finding every 'leg' in the scene, but my brain just really isn't working.
Object hierarchy is as such
Root
Object
Leg
Leg
Leg
Could anyone point me in the right direction please?
Find objects of type is a global search. 
Just get the common parent of the legs and iterate through them and check if the child is a leg.
To iterate on the child, use the foreach with a transform.
https://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html
Doesn't this solve it too?
GetComponentsInChildren would probably be better
Forgot that exists lmao.
Yeah that's even better.
Yeah I realised that, which is why I need to 'convert' it. Just my brain is refusing to cooperate. lol.
Thanks though 🙂
So annoying when something is so simple but you can't think of it. lol.
Aye.
GetComponentsInChildren works like a charm. Thanks 🙂
i want it in the editor but seems i can only get it to work when i hit play
does anyone know the values to make geometry dash jump look smooth?
this is what i have right now https://pastebin.com/zna1GLr5
and its buggy
anyone know whats happening with my players arms?
when i switch back to scene view they are fine its just when i get into game view
Yeah and it is normal in scene view
Can your record the video where you show that?
How do I do this without editing my actual prefab?
SpriteRenderer monsterDropSprite = newMonsterDrop.GetComponent<SpriteRenderer>();
monsterDropSprite.sprite = itemDropSO.ItemSO.ItemSprite;
Instantiate(newMonsterDrop, monster.transform);```
GameObject newMonsterDrop = Instantiate(monsterDropPrefab, monster.transform);
Why cant i see my Dictionary in inspector? I want to assign variables myself
Dictionarys are not serializble by default in Unity
is there any way to serialize them
there are assets you can get that can do it. just google "unity serializable dictionary"
thanks
You can make a class for your dictionary then use [System.Serializable]
You could also have a serialized List that then creates the dictionary for you
I want to work on a good working platformer is there some guide for advanced movement control or just a full working script someone recommends? I want to work more on the visual part
using UnityEngine;
public class PressSpaceToStart : MonoBehaviour
{
// Start is called before the first frame update
public GameObject spaceToStartUI;
public bool isPaused;
private void Awake()
{
spaceToStartUI.SetActive(true);
Time.timeScale = 0f;
isPaused = true;
}
void Start()
{
}
// Update is called once per frame
void Update()
{
SpaceToStart();
}
public void SpaceToStart()
{
if (isPaused && Input.GetKeyDown(KeyCode.Space))
{
Time.timeScale = 1.0f;
isPaused = false;
spaceToStartUI.SetActive(false);
}
else
{
return;
}
}
}
I have this simple script which makes my game start paused and makes player to press space to start. Then my ui gets disabled. But sometimes when player fails and the scene reloads and prompts the user to press space again, the ui does not get disabled. I am wondering why it happens.
When you reload the scene your UI elements will also reload
My project isn't even very big yet and the re-build/play are taking like 25 seconds each already...
Don't reload the scene instead find a way around such as moving the player back to start etc
If your project is not in C it takes longer to compile I don't know why
I've seen plenty of videos about platformer movement. Some re-creating from top platformers like Celeste, others taking that and improving. Just have to do a few youtube searches. They're there
It only happens in Unity
I want to see the space to start screen whenever player fails. Its just that sometimes after failing, when I press space the ui does not get disabled.
here is the countdown timer which makes player stop moving and enables Game Overcanvas
!code proper formatting please
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Use a paste site
oh come on
You're almost there
Your code block is large. Link to it
Ok how do i share a GDL space code?
paste your code, click save, and copy the new url
what is a good way of keeping track of the distance between the center of 1 object and another object, and saving that distance the moment the moving object gets destroyed?
DONE
im trying to create a sort of accuracy value for my DDR project, not really sure how I would do it
Here is the Countdown Timer script
here is the player movement script
[ContextMenu("Steal spr image")]
public void c352751()
{
BuildingImage = GetComponent<SpriteRenderer>().sprite;
UnityEditor.EditorUtility.SetDirty(this);
}```is this enough to save my changes to my class in a prefab in the project tab?
did u solved “nonzero exit code” problem?
I also called AssetDatabase.SaveAssets(); after marking the object as dirty
But that's just what I found when googling the same problem
just finished testing, reloaded my editor and my code just did fine
I'm not actually sure what causes individual assets to save
me neither, i just spam them on things i change lol
it's very fast to call it anyway
exept this AssetDatabase.SaveAssets();, Though, I assume this is also called when you control+S
Can someone help me with this one? I cannot seem to get it right.
make sure that the game is paused (IsPaused is true) when it have to
It is paused before I press space bar.
Its just that sometimes when I press space bar. The game continues but the ui does not go away.
Even though i disable it in the script
are there other things that open that ui?
No
then how does the UI appear when you die?
The game starts again
you are loading the whole scene?
yeah
there shouldnt be a problem if that's the case. Can you send the script that reloads the game?
I realized I was using the setactive bool on the on click event. I deleted that and it seems fine now?
So I was enabling both in script and as a bool on the inspector
quick question, how do I tell the script to only execute something if a float is between a value of 0.58 to 0.3?
oh, so you also call it in a button
if(x > 0.3f && x < 0.58f)
Yeah it seems to be working now. Thanks for the help.
didnt really do much, anyways neat

can also do ```cs
if(x > 0.58f)
{greater than 0.58}
else if(x > 0.3f)
{between}
else
{below 0.3}
its only doing 1 thing so the one you pasted earlier works great
yea I got curioused why it had to be specificly between that numbers
I dont see anyone writing using underscores in names in c#, is this a problem to do so or not?
there is c# conventions, but it depends on you if you want to follow it or not
its for a DDR project im doing where I'm measuring the distance of the note collider from the hit line collider, and assigning the player a rating of either bad, good or perfect based on that distance when they press a button
but if you working in a team, maybe, do follow the established convention of that team
I do not work in a team and I'm a bit used to python where I also use underscores
oh i see, so the 0.5 < x < 0.3 is like an average
yeah pretty much
to give the player some leeway
i'll probably be tweaking it quite a lot
What does it mean to mark an object as dirty? 
It means that the object has been changed
it is no longer in sync with the serialized asset data
speaking of underscores, today i learn we can put consecutive underscores as member names haha
fill in the blanks
without that, unity would have to just save every object to disk every time
underscores are great, but everyone in unity/c# uses camel/pascal case, so I had to change
too much incompatibility in style
Those 2 comparisons return a true/false
why?
because that's how a comparison works
^
if you want to use comparisons in a switch, you'll need to use the relational pattern
or just use if/elseif chain
but isn't && equivalent to "and"
"distFromCenter > 0.3" from itself already only returns true/false
yea, but not in a switch
oh i see
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed.
is there a way to check if both of those values are true in a switch statement? I dont want to use an if because its slow and I need everything in this to run quickly
look at the pattern matching link sent, and you can maybe turn your code to adapt it
if something is greater than 0.5, it is also greater then 0.3
so it's mostly math
+logic
I mean... If youw ant to know if both of those are true, just check is > .58... Then it's also > .3
why would you assume an if statement is slow? and also why would you assume that a switch would be any faster in this case?
Yea, where did you get that switch was faster thatn if
yeah this is 100% not a concern here lol
me no 100 🥹
especially with pattern matching -> pretty sure it's going to compile to the same as a series of if statements
made a typo in the script, its meant to check if x > .3 and x < .58
if statement is deffo better here lol
unless there are going to be several cases
its because im going to have 3 separate if statements checking the value of x between a range
but either way it's a readability thing not a performance thing
If you have like 5+ nested if elses, you might want to start looking into different ideas, but you're fine with if 98% of the time
that will be no slower than a switch
oh ok, thats good to know. I just thought that if its more than 2 if statements i should use a switch
if anything in this case it might be faster
Google if vs switch. There's definitely scenarios for switch, but 90% of the time people over value it when an if would work perfectly fine if not better
i've been watching too many yandere dev critiques
got a phobia of if statements from that dude
I have no idea what that is, but I looked it up and I'm terrified of it already... 0/10 would not watch
99% of a time a switch statement should have been handled by inheritance instead
time to break out the ol' compiler
this is like saying you have a phobia of variables
i get chills whenever i see a float
bools got me running for tha hills 🏃♂️
How do I get my code editor to work like it does in the video? I think I got what I need but I got 0 autosuggestions or correct colour coding
!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
• Other/None
Follow the instructions for VSCode.
Perform every single step. Do not skip any steps.
Honestly, considering no actual programming videos came up for that person on youtube, just videos about how horrible they are, I'm not surprised if you have some issues after watching them 😵💫
I was curious how the compiler would handle a small chain of if/else vs a switch expression, and wtf. it created a nested ternary for the if/else chain then used an if/else chain (with some nested ifs) for the switch (and a few gotos)
https://sharplab.io/#v2:D4AQTAjAsAUCDMACciDCiDetE+UkALIgLIAUAlJtrjQGYA2A9gIYAuiAHogLyIBsATgDc1GjgCWAO3YBPETDG5RY8bVJcAPIgCsADkQAyA50QA+RAW3llNLAsViZPRBHkPEAXxu4ApvQDOPoiqiOqIWgDsAAyGxlzmfGDW9op27jROvGBuDl4pYn6BwbShmogCFbEm5gRgUcnuaek4mYjwOYp57oU+3jhNza0EHWJdDn3IEAKkMuQjNMpjOMoIyEQAchTKA2IMLOxcvILzuFKyJ8v5Gc5c/gDu4qwAxgAWEzvuWnqIzJIAJmYLNoeOYIAAaCY0SIxX4AhJgEGIMAQq4OLQVAQ/f6A2oxbjmeAo5qKAD6iIIRNyF0QExAUxmc0WsA8QA=
I was also writing something on sharplab
lmao
if / else if / else and switch produce slightly differently shaped IL
switch does all the branching up front
the dude just uses an if statement for everything. He has like 20 if statements in a row some places
who are we talking about here?
yandere dev
ah
multiple if statements is fine. that guy just had dozens of them running on so many objects per frame instead of setting up a proper state machine. and also the ridiculously detailed assets with thousands of verts for simple things like a toothbrush
i have to wonder if some of that was codegen
codegen can produce very awkward looking C#
or maybe it was just copypizza all day
nah he already said he has no formal education in coding
which is also wild considering he's been coding that game for over 5 years now, which should mean he knows by now to stop using so many if statements
What do you do when all of your TMP-Text Buttons just, stop working??
Everything 'was' working and then suddenly, that all just stop.....
Do you have an event system in the scene
That, along with another thing getting in the way, are the two most likely causes
you start debugging
These differences come mainly from the decompiler, trying its best to convert the IL to C#. The IL for the two methods look very similar, just a bunch of "load constant", "set/load local variable" and "branch to target if greater than/less than/etc..."
Both use jumping/goto, but for whatever reason, the decompiler decided to interpret the first method as a ternary.
I do have an event system, yes.
Try disabling everything but one button. You might have an invisible object catching all raycasts
Okay, I'll give that go
Could someone help me? Its just a blank screen
Im very new to visual studio so i don't know what to do
try restarting it?
then try reinstalling it
alright
also don't crosspost
My games uses WASD control keys and it moves in different directions. Why is this?
you will have to share your code.
presumably, you have one of the following problems:
- each key has the wrong vector (W is left, etc.)
- the player has rotated, but you're still using a local direction (you turn right, so W should go right, but W still goes up)
- you're doing trig to calculate which direection to go, and the math is wrong
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Hi im trying to add reload to my gun. But it says "error" and the namespace "IEnumerator" could not be found. Whats wrong
Youre not using the System.Collections library
do you have the namespace to use IEnumerator?
you need to add the correct using at the top of the script . . .
your IDE should give you a suggestion or quick fix that will add it . . .
thanks
Hey I want to make a non-grid building system, and I made everything except the mouse position part. In 3D, I want to have the buildable object where is my cursor, but I just cant figure it out.
This line didnt help me: GetComponent<Rigidbody>().position = Camera.main.ScreenToWorldPoint(new Vector3(-Input.mousePosition.x, -Input.mousePosition.y, -Camera.main.transform.position.z));
Well my cursor is not always in the center of the screen
Is it a problem?
Where in that link did you see that it only works for the center of the screen
If you don't need to use the cursor you might as well use raycast instead
https://paste.ofcode.org/GLvuSG9hzDxwYJa5Qp8QWM
It does this. I mean I'm progressing though
I got it
Hi just windering if anyone knows the fix to this, might not be a code issue but my assumption was it is although i have no idea what the fix is after alot of testing. When pressing c its showing the bool for jump and crouch to be true, when jump is only true when not touching the ground. Anyone know the fix? thankyou in advance
show code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Looks like you set the "JumpAnim" parameter if you're ever off the ground for any reason. Likely, when you switch to the smaller crouch collider, you are off the ground for at least one frame, which sets the "JumpAnim" parameter
You could try to adjust your crouch collider so the bottom of it is lined up with the bottom of the standing one, or make it so the animation only plays when you press jump
this is how they are lined up, i had a animation set for is jumping but got told in here im better off changing it to the ground isnt being touched, is that going to have to change to fix this?
Those look pretty lined up to me, that should work. Taking a closer look at it, it seems you're doing a boxcast from coll's position, but you don't change coll as you change between states. BoxCasts don't detect colliders they start inside of, so maybe for a frame when swapping colliders, it's casting from the wrong position and it's actually already on the ground?
You might want to swap that boxcast out for either a raycast (if you want a single point to be the ground detection), or an overlapbox (if you want a wide flat bottom ground detection)
i don’t understand the issue. he is jumping? or is the detection janky?
is there any way that i could check the bool from a different script in my player controller
The animation state for not being grounded is overwriting the animation state for crouching, because crouching seems to be causing a frame or two of "airtime"
give the bool a public getter, get a reference to the player controller script, then just call the getter
Reference the object whose bool you want to get.
https://unity.huh.how/programming/references
public bool myBool {get; private set; }
this automatically defines a backing field (k_myBool or something), and gives you a publicly exposed property to get the value, but keeps the changing of the value to just be hidden to the one class
make sense?
somewhat yeah,thanks
and if you need to set the value in inspector, then add [field:SerializedField] in front, so you can serialize just the backing field
Anyone have a guide on how to make a shatter affect for a 2d sprite, like make it break into parts and fall down while fading away
ie
[field: SerializeField] public bool myBool {get; private set; }
where would i add the raycast or overlap box sorry?
i’d also like to know this. lmk if you get an answer for it
Your IsGrounded method. But not ADDING it there. Fixing what is already there
it wouldn’t be hard to code, but very tedious to make it from scratch
I would either use Cast, CircleCast, or OverlapBoxAll tbh
- Cast is generic to different Collider2D, in case you use the code for enemies too. Casting also gets you contact normals and distance info.
- CircleCast is cheaper than cast, but you need to do some math to position right.
- OverlapBoxAll lets you check very crudely, and gives no distance info
return Physics2D.OverlapBoxAll(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, 0.1f, jumpableground); - would this work if changed from the box cast or is more work needing to be added?
I would personally use Cast/CircleCast because you want to be able to get normals if you add slopes to your game later
i don’t remember, and don’t have time to check syntax, sry
https://m.youtube.com/watch?v=Gr_E-WdInOA
If u want to make the pieces fade away or move differently it shouldn’t be hard
A simple way to create shattering effect for your sprites in Unity. I'll show you how to destroy 2D elements using object replacement and physics. Simple script.
🎮Play my games for FREE at https://pawel-drozdowski.itch.io/
👌 Consider subscribing to make my day! https://bit.ly/362EWCB
🎧Sound Effect: https://sfx.productioncrate.com/royalty-free...
This issue seems to be the changing position
So just changing the query type won't help...
the position of the colliders or the player as a whole?
Hey, having a minor IDE issue that I don't see a resolution for in the VSCode guide on here. I don't seem to have intellisense for monobehavior functions like Start, Update or the OnTrigger/OnCollision functions or OnDrawGizmosSelected....
The colliders i think. That sounds like what Digi was saying. But I only briefly saw the conversation sorry
Actually, it sounds like they WERE just saying change the query type
I'm sorry, looks like I misread
Ignore me
he said that couldve been the issue but with how they was lined up it couldnt have been and was just a boxcast issue they thought
dont stress it 🙂
so was changing the boxcast to a OverlapBoxAll all that was needed or wont that help??
Instead of the boxcast for IsGrounded
Boxcasts don't detect ground they start inside of, meaning if the collider is partially inside the ground it won't detect the ground
OverlapBox doesn't move, but it does detect what it starts on top of
Earlier, I said my buttons didn't work; I deleted EVERYTHING but x1 button; that still didn't work.
Also, I had no errors reported in the console.....
when changing to the OverlapBoxAll it says vector 2 cant be changed to an int anymore, why is this?
Do you have an event system in your scene? Deleting buttons definitely wont have an affect, unless one button specifically disables all buttons
Why are you using OverlapBoxAll
loup said that was a better one to use over raycast, unless ive mistaken what she said
On the bottom of the inspector for your Event System, it should show whatever you've got selected. Does anything change?
OMFG; I'm an idiot.....
I said OverlapBox, not OverlapBoxAll
I don't know how long ago that one disappeared. 😂
when changing to overlapbox its still giving the same error for vector 2
Probably because you're using the wrong parameters. Did you just change the function or did you actually use the parameters it expects?
THANK YOU!
Would have been a pain to do it all again. 😂
*cough*
Yeeeeeeaaahhh, it WAS there; I swear! 😂
How are you usually setting this up with colliders You can go in the door, but cannot collide with the front wall?
i just changed the boxcast to an overlapbox, what else would need to be changed? sorry im just struggling to understand the parameters
Put a different collider on the door than the wall
2 cols, same go?
Look at the documentation I sent. Those are the parameters that function expects and the order it expects them in
or what?
Why is this all one object
If that's a hole and not a door built into it, then just use a mesh collider
Sure, default mesh collider, or should I use something specific, eg.: Convex, etc
It looks like there's a solid object inside that doorway from the perspective of your screenshot
Oh sorry, there is not

Mess with settings
find what works
https://gdl.space/ugiwurovas.cs
This function makes the transluscent backdrop of UI buttons only visible when moused over, how can I make it not "stick" buttons with quick movements?
When your raycast hits something, check if that something is different than the current selected object. If it is, make sure to deactivate the selected object before selecting the new one
Right now you only deselect anything if you go from hovering over it to hovering over nothing
but if you change objects without passing over empty space, nothing tells the old one to deactivate
Ohhhhhhhh that makes sense
there's a gap between all buttons but it's so small it must have been between frames
so something like if selectedObject != selectedObjectLast?
mesh collider = as big as the mesh
so no
you would need a separate mesh with diff sizes
When your raycast hits, you still have your old selectedObject variable. Just compare that with the object you hit before setting selectedObject to it
also, make sure the previous selectedObject isn't null as well
Good idea! Thanks!
what can i use for the layermask? i tried adding the jumpableground as thats my only layer mask in my code or do i need to make a new layer mask for this/
?
What layers do you want to detect
return Physics.OverlapBox(gameObject.transform.position, transform.localScale / 2, Quaternion.identity, jumpableground); is this right?
or am i way off
@polar acorn
Hi guys, I'm making a game using photon Fusion where a group of robots are on the server interacting and players can enter and interact with them, but when the server is empty the objects in the robots' hands go to the wrong position.
I wasn't the one who wrote the script to hold the objects and I'm looking for any solution to the problem
Possibly? See if it works
it gives the error - Cannot implicitly convert type 'UnityEngine.Collider[]' to 'bool'
OverlapBox returns a Collider array
Your IsGrounded method says it returns a bool
So, you have an array of objects that are overlapped by that box. What is a yes or no question you can ask of that array to determine if you've overlapped anything
