#💻┃code-beginner

1 messages · Page 43 of 1

wicked cairn
#

only pause is just figuring out the best way to make the game build know what port is available

rich adder
#

if you aint turning a profit from more than 50CCU monthly something is wrong lol

wicked cairn
#

All I asked for is the best web request code for making sure theres no interferance with a existing request to that url

rich adder
wicked cairn
#

I need code tho

#

web request for checking if someone elses build is requesting xd

rich adder
#

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

arctic ridge
#

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

arctic ridge
#

StartCoroutine(Wait(1)); I have this, but it doesnt work

#

Ok one sec, ill read that

wintry quarry
#

coroutines only delay themselves

arctic ridge
#

Oh ok, so do i need to put the code under the StartCoroutine?

wintry quarry
#

no

#

the code that needs to have a delay in it goes in the coroutine itself

arctic ridge
#

Ok

wintry quarry
#

e.g.

Debug.Log("About to wait 2 seconds");
yield return new WaitForSeconds(2);
Debug.Log("2 seconds have now passed");```
topaz mortar
#

Is there an alternatie for OnPointerExit that also triggers when you close the parent?

wintry quarry
topaz mortar
#

SetActive(false)

wintry quarry
#

OnDisable will run when you do that

bitter carbon
#

sorry i was busy

#

here it is if ur still there

arctic ridge
heady nimbus
#

Holy moly

heady nimbus
eternal falconBOT
rich adder
topaz mortar
bitter carbon
#

sry caps lock

#

oh

#

ye ok

#

does that count as large blocks of code

#

or do i use `` `

rich adder
#

I have no clue why mods took away the "Do not send screenshot of code unless requested"..

rich adder
#

use a link

bitter carbon
wintry quarry
rich adder
bitter carbon
#

yes

bitter carbon
#

and the other ui such as the timer also is disabled

rich adder
#

is the component staying enabled ?

bitter carbon
#

one sec ill check

arctic ridge
#

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

rich adder
#

any other scripts controlling GameUi1's canvas ?

rich adder
wintry quarry
bitter carbon
#

yea it stays disabled

arctic ridge
bitter carbon
wintry quarry
#

you can only use yield in your coroutine

#

you can't put it in Update

rich adder
#

are you referencing the correct canvas ?

arctic ridge
#

Ok, then how is the coroutine shown, so i know where to put this code? Or should i chang void update() to something else?

wintry quarry
rich adder
#

did you look at the docs example ?

wintry quarry
#

See examples here:

arctic ridge
bitter carbon
#

yea the timer canvas stay enabled but it disappears

#

which is what i want

heady nimbus
rich adder
bitter carbon
arctic ridge
#

Ok, thanks

bitter carbon
#

and here is my inspector

arctic ridge
bitter carbon
heady nimbus
#

He's just using the free-form tool rather than the box select tool

bitter carbon
#

this is just more accurate ig

rich adder
arctic ridge
#

Ah

rich adder
bitter carbon
#

i think it might be cuz the object the script is one is disabled at certain times

rich adder
#

in playmode

#

scripts dont run on disabled Gameobjects

bitter carbon
#

yea but it gets enabled when the fire appears

#

and that is how udie so ig that isnt issue

rich adder
#

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

bitter carbon
rich adder
#

GameUi1.gameObject.SetActive(false)

heady nimbus
#

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;
    }```
bitter carbon
arctic ridge
#

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

heady nimbus
rich adder
bitter carbon
#

oh sorry

fossil tree
#

hello im back with a new problem xd how i can made for my UI dont be crazy like that

fossil tree
bitter carbon
#

ty it works no

#

now

rich adder
fossil tree
bitter carbon
#

also 1 more question, how do i reset a scene without leaving then joining it again

rich adder
fossil tree
#

how i need to put?

rich adder
rich adder
bitter carbon
#

so i want it so the scene the player is on, is reverted to how it was when they first clicked it

rich adder
#

up to you to determine what that is

bitter carbon
#

wdym

#

is there not a word to reset it

rich adder
#

Load scene resets it

bitter carbon
#

can u load ascene u r alr in

rich adder
#

otherwise you have to determine what changed and restore it back

rich adder
#

but it will reset player too

#

unless player is DDOL

#

whatever you dont want to destroy on scene change can b inside DontDestroyOnLoad

bitter carbon
#

si there a way i can see where my script is in the hierarfchy

#

is

rich adder
#

inside hierarchy search

bitter carbon
#

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

rich adder
bitter carbon
#

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

warm raptor
#

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);
    }
}
rich adder
#

you mind as well make
clientComponent = FindObjectOfType<CLIENT>();

rich adder
warm raptor
bitter carbon
#

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

rich adder
rich adder
warm raptor
barren vapor
cerulean stirrup
#

its a lasso snip or freedom snip

bitter carbon
#

whys everyone talking about that lol🤣

cerulean stirrup
#

cuz it looks bad

heady nimbus
#

Because it's terible

summer stump
bitter carbon
#

it makes it more accurate

barren vapor
bitter carbon
#

ok fine ill switch abck

cosmic dagger
cerulean stirrup
barren vapor
bitter carbon
#

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

rich adder
#

this is as useful as soggy bread

bitter carbon
cosmic dagger
bitter carbon
#

its a empty

rich adder
#

wdym empty

#

you're saying its not turning white when you hover the pink ?

bitter carbon
#

yep

rich adder
#

then you're missing event system probably

bitter carbon
#

empty gameobject is the thing its attached too in the ss above

rich adder
#

its not empty tho, it has an Image component.

cosmic dagger
#

Is there another UI object obscuring it?

bitter carbon
#

it wasnt important i dont think

bitter carbon
rich adder
#

dont guess

#

be sure

bitter carbon
#

ok no

cosmic dagger
#

It either does or doesn't. You can clearly see if another UI object is over (on top) of this one . . .

rich adder
#

check the inspector for Event System during playmode , it gives a debugg window to see what your mouse hit

cosmic dagger
#

Then do what navarone mentioned, make sure you have an EventSystem in your hierarchy . . .

bitter carbon
#

where is the even system?

#

event

rich adder
bitter carbon
#

oh i think i ahev ti in other scene

#

can i have 2?

rich adder
#

u only need 1

bitter carbon
#

yea i have it but it is in other scene

summer stump
rich adder
#

so then ur UI interactions wont work

cosmic dagger
#

The current scene has no knowledge of another scene . . .

bitter carbon
#

so can iduplicate it?

rich adder
#

just add one

bitter carbon
#

and additional one, or 1 in total?

rich adder
#

bruh

#

1 per scene

bitter carbon
#

oh ok,

strange shale
#

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?

rich adder
#

normally you have a break then yeah it will run A and exit

bitter carbon
#

ik i can copy it but i wanna know, where is it

#

like to add it

#

where do i gp

rich adder
#

same way you add anything else

strange shale
#

If I want it to run both, do I just don't put the break? Or does it cause a syntax error?

bitter carbon
#

nah i mean where in there

short hazel
bitter carbon
#

ok i found it

short hazel
#

But yes the switch runs top-down like all other statements, so it'll stop at the first matching case

bitter carbon
#

ok it works now

strange shale
#

Got it... then I'll have to use 4 different ifs in that case

bitter carbon
#

thank you @rich adder

rich adder
# strange shale If I want it to run both, do I just don't put the break? Or does it cause a synt...

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

tame mist
#

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;
wintry quarry
#

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

tame mist
strange shale
#

Weird stuff happens

tame mist
#

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

wintry quarry
#

those things all need to not be children of MechanicShop if it's scaled

tame mist
#

yeah that's what I was thinking

#

alright I'll try it out

strange shale
#

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

edgy fox
#

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

wintry quarry
#

The second part of your question is covered by an understanding of how references work in C#

strange shale
#

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)

edgy fox
wintry quarry
#

you do not have to create new objects all the time

edgy fox
#

oh how do I do this? I am not extremely skillled with OOP

wintry quarry
#

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

strange shale
#

Some stuff is easier by experiencing than by getting an explanation

wintry quarry
edgy fox
#

or in a way I could understand at least

wintry quarry
#

you need to get a feel for it

#

before it makes sense

edgy fox
#

yeah I get that

swift crag
#

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

strange shale
#

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

umbral bough
languid spire
umbral bough
languid spire
strange shale
#

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.

umbral bough
strange shale
#

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

wintry quarry
#

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

wicked cairn
#

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??

strange shale
rich adder
#

eg WriteAllText or StreamWriter write

#

etc

strange shale
#

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...

wintry quarry
strange shale
#

I had no prior knowledge about those algorithms... so I was trying to create from scratch

#

So much time lost...

swift crag
#

Learn yourself some basic data structures!

#

Graphs come up a lot

rich adder
#

I feel your pain, its a eureka moment when someone with no formal CS bg learns about these

strange shale
#

Well... on the bright side... the project is actually very simple.

A simple puzzle game and that algorithm was required to calculate the score

wintry quarry
#

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

strange shale
#

Because to calculate, I need the machine to know how many sequences of colors with size 3+ is on the grid

rich adder
#

@wintry quarry you helped me a long time ago with that 🙂

#

hexmap range finder 😭

strange shale
#

I already had the script to count the score ready, I just couldn't figure out how make it count the grid perfectly.

wicked cairn
strange shale
#

3 or more, with no repeats.
And no counting from tiles that aren't adjacent even if the same color

rich adder
#

writing to a file is like basics 202

wicked cairn
#

and with web request it returns error

rich adder
wicked cairn
strange shale
#

And the worst part is... I know that I could make the script if I just put everything properly...

rich adder
#

are you talking about a remote file ?

wicked cairn
rich adder
#

something you should mention this is a remote file you trying to write to

strange shale
#

This is just a logical problem using a few For functions and if statements

wicked cairn
rich adder
#

think you need to get into FTP here

#

or HttpRequests with file attachment

wicked cairn
#

itll write to that file every few seconds

#

has to be fast

rich adder
#

pretty sure you can still use System.IO if you do //server/directory

#

as your path

wicked cairn
#

should I do it through php?

rich adder
#

probably if right permissions are granted

wicked cairn
#

im already using the php for sql

short hazel
#

UnityWebRequest with a content-type of text/plain should do the trick

#

Attach the text directly, not in a form

wicked cairn
short hazel
#

UWR.Post("url", fileContentsHere, "text/plain")

wicked cairn
#

does it require three arguments? ive tried including the extension in the url

short hazel
#

URL, body, content type

#

You need that overload if you want to POST plain text

topaz mortar
#

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)

lean basin
#

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.

topaz mortar
#
{
    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

tame thorn
#

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

topaz mortar
timber tide
#

should be similar to your camera script by following the rawaxis

tame thorn
rich adder
topaz mortar
#

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

swift crag
topaz mortar
#

yeah I know

rich adder
#

part of randomness is repetition no ?

topaz mortar
#

just wondering if maybe if it uses a timestamp or something it might generate a lot of very low numbers at the same time

swift crag
#

If that was possible, the RNG would be very bad

topaz mortar
#

kaj good, so the not true random thing only applies for encryption & stuff then?

swift crag
#

even cryptography does not depend on "true randomness"

eternal needle
#

its very very rare to actually need it

swift crag
#

it just depends on the pseudorandom number generator being indistinguishable from true randomness

topaz mortar
#

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

swift crag
#

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)

hexed slate
#

how do I make a value increase each time the score is increased by 5

#

like 5, 10, 15, 20... etc.

wintry quarry
#

One basic way is just using a property that depends on the score

#
int myVal => score / 5;```
hexed slate
#

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.

topaz mortar
hexed slate
#

thats the thing but 0 % 5 = 0

#

so the pipe goes fast at the start

topaz mortar
#

shouldn't be too hard to find a way around that 😉

eternal needle
# hexed slate thats the thing but 0 % 5 = 0

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

rich adder
hexed slate
#

Oh

rich adder
#
public void AddScore()
    {
        score++;
        if (score % 5 == 0)
        {
            Debug.Log("Increase speed");
        }
    }```
ripe oyster
#

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

lusty socket
#

!code

eternal falconBOT
timid gale
#

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.

wintry quarry
#

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

timid gale
lusty socket
#

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

wintry quarry
#

it's not a problem

#

just use TMP_Dropdown and TMP_Text in your code

wintry quarry
#

I don't see any code that changes crouchPressed anywhere

timid gale
#

Awesome, cheers; I'll give that a go then, go to bed!

It's 8.22am & I haven't slept yet! 😅 😂

lusty socket
wintry quarry
#

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

lusty socket
#

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

summer stump
#

Nm, I'm dumb. It can take a string

lusty socket
#

sorry i am dumb im just starting and tried every vid online they all just use different code to what inhave used previously

summer stump
#

You have the code for detecting the key press

#

Now you need to REACT to that key press

lusty socket
summer stump
#

Could be as involved as making a custom animation in blender

lusty socket
#

yes i have animations to switch him to crouch from whatever other animation he is doing

tender stag
#

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

lusty socket
#

it is also a 2d sprite game

#

so it is like the camera follows him through the level

summer stump
tender stag
lusty socket
#

like a mario game basically

tender stag
#

my canvas is behind the player

#

anyone know how else i could do it?

lusty socket
summer stump
#

It will be super obvious once you know the basics

upper spire
#

how can i find the material of the face that a raycast hit on a multi material object?

silk night
upper spire
silk night
#
upper spire
#

thanks, it works

lusty socket
#

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)

summer stump
#

And have it default to false

lusty socket
#

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

lusty socket
summer stump
lusty socket
#

so any idea why it doesnt work

summer stump
lusty socket
#

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

summer stump
lusty socket
summer stump
#

In Update

#

That would be it.

#

Just the GetKeyDown and GetKeyUp in update

#

When down crouchPressed is true, when up it's false

wintry quarry
#

Where did you get the code from?

lusty socket
#

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

lusty socket
wintry quarry
#

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

summer stump
#

I don't think it's juse "C"

wintry quarry
#

but the keycode is better

summer stump
#

Ok yeah. I hate strings for things like that lol

lusty socket
silk night
lusty socket
#

sorry if it sounds like im just not listening i am, im just really struggling to understand

summer stump
#

Misunderstood. Sorry

#

Yeah, use the keycode instead of the string

wintry quarry
lusty socket
wintry quarry
#

depends what you mean by "work"

#

it will set that variable

#

suire

lusty socket
#

crouch

wintry quarry
#

but you actually care about the crouchPressed variable

#

think about it

#

read what your script is actually doing

summer stump
#

Oh. Yeah, as praetor said

lusty socket
#

yeah sorry i did mean that i just meant the general line of code with the correct name

summer stump
#

If it isn't, it's false.

lusty socket
#

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?

wintry quarry
lusty socket
#

which is the irrelevant variable?

wintry quarry
#

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

lusty socket
#

so i dont want to be adding the var

#

and i want to change crouchpressed to crouch

#

or am i again very wrong

wintry quarry
#

no

wintry quarry
#

how do you assign a value to a variable?

lusty socket
#

so literally remove the var

wintry quarry
#

yes

lusty socket
wintry quarry
#

yes = is how you assign values to things

#

it's called the assignment operator

lusty socket
#

ahh right

#

sorry im still learning the different code words

unreal imp
#

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);
    }
}```
wintry quarry
#

oh god the [System.Obsolete]s 😢

unreal imp
#

ps: sorry for the delay

wintry quarry
#

don't listen to your IDE's complaints about those functions not being used. It's ok.

unreal imp
#

sorry for treating you all like chat gpt 😅

unreal imp
lusty socket
wintry quarry
rich adder
#

😔

wintry quarry
rich adder
#

@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

summer stump
lusty socket
lusty socket
wintry quarry
summer stump
lusty socket
wintry quarry
lusty socket
#

animator.SetBool("Crouch", crouchFlag); is the code i use

wintry quarry
#

yes we've seen the code

lusty socket
#

animator

#

sorry i was just showing both for context

wintry quarry
#

and the other transition?

lusty socket
#

was just getting the screenshot sorry

wintry quarry
#

also what animation clip is on the Crouch state

lusty socket
#

the crouch

#

sorry i dont fully get the question

wintry quarry
#

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

summer stump
# lusty socket

You can only go to crouch from the NewAnimation state. What is that?

silk night
#

Quick question, HashSet<Transform> vs Transform[], i guess the latter is faster? Initialization of both with fixed size

summer stump
lusty socket
#

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

wintry quarry
wintry quarry
lusty socket
wintry quarry
#

maybe your jump transitions are messed up

cosmic dagger
silk night
# wintry quarry "faster" is completely meaningless without information about how it will be used

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

wintry quarry
#

also var is everywhere masking types

lusty socket
#

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

silk night
wintry quarry
wintry quarry
#

just how you create it

#

you mean m_targets?

silk night
#

The second code block shows usage

wintry quarry
#

now the second block shows it being created and stored in a field

#

how do you use m_Targets

silk night
#

Thats internal of cinemachine

lusty socket
wintry quarry
#

Where and how would you use a HashSet here?

silk night
#

Because of the transformation to CinemachineTargetGroup.Target, camera will potentially track hundreds of objects changing per frame

wintry quarry
#

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

silk night
#

Alright, thanks

wintry quarry
#

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

lusty socket
silk night
#

GameEntity[] (internal thing of Entitas library)

#

Basically just an array of classes storing components

silk night
wintry quarry
silk night
#

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

wintry quarry
silk night
#

Nope they dont

wintry quarry
#

also you do have control over:

  • the array of CinemachineTargetGroup.Targets you pass into the vCam
  • not creating random other intermediate arrays
silk night
#

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

wintry quarry
#

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

silk night
#

But I'm not sure how you would go about reusing anything here, could you tell me how you'd go about that?

silk night
#

yeah thats done already, its not in an update loop

zenith cypress
#

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. pain 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).

wintry quarry
#

yeah not sure what framework this is but it seems a little sketchy

#

I was under the impression DOTween was careful about allocations 😢

silk night
#

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

zenith cypress
#

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.

wintry quarry
#

Cool

cosmic dagger
wintry quarry
#

damn how did I not know about this

tough trench
#

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.

eternal falconBOT
silk night
#

Oh yeah, and that 😄

tough trench
#

what do i do to fix it tho

silk night
#

rename your project path

wintry quarry
#

get rid of the special characters in the project path

#

probably the # is the issue

swift crag
#

microsoft is often very allergic to anything that isn't letters and numbers

#

maybe dashes

sour fulcrum
#

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

late burrow
#

you would use quaternions probably

cosmic dagger
sour fulcrum
#

oh fuck i gotta learn dot products

#

i was praying this day would never come

swift crag
#

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

cosmic dagger
#

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) . . .

crisp anvil
#

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!");
        }
    }```
cosmic dagger
#

what kind of issue?

summer stump
crisp anvil
#

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

cosmic dagger
#

this doesn't give us any inheritance unless there is more code . . .

crisp anvil
#

is hooked to a gameobject.

summer stump
cosmic dagger
crisp anvil
#

Fireball

summer stump
crisp anvil
#
 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

cosmic dagger
#

what class is the first snippet belong to?

summer stump
#

You never called base.Awake in fireball

gaunt ice
#

You cant even call it, there should be warning of hiding base method

cosmic dagger
#

Awake is not overriden — not set to virtual; then Fireball can override it . . .

summer stump
#

Oh yeah of course. I saw the override on Execute and my brain said of course it's on awake too lol

cosmic dagger
crisp anvil
#

That was my mistake, I'm sorry. If I wasn't tired I would have problaly caught it.

cosmic dagger
#

i just didn't know what class the first snippet belong to. that fooled me for a bit . . .

crisp anvil
#

Sorry again, I realized I made it super confusing. Brain wasn't operating correctly.

cosmic dagger
#

no worries. problem solved . . .

static cedar
#

AHH yes, debug.log spam.

eternal needle
#

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

solemn fractal
#

Hello guys, No matter value I put here, 1 or 10000000 the laser of my ship always go up same velocity. any ideas?

eternal needle
#

also your !ide doesnt look configured

eternal falconBOT
solemn fractal
solemn fractal
eternal needle
# solemn fractal 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

eternal needle
#

the bot command i linked above has the VS Code guide for configuring your ide

solemn fractal
#

i also find wierd as tutorials and courses I bought their code looks dif i mean with dif colors

solemn fractal
weak isle
#

Vs code is weird, the suggestions weren’t working for the past week and now they are today

#

-_-

eternal needle
#

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

ruby python
stable jackal
#

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

ruby python
stable jackal
#

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

ruby python
#

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?

stable jackal
#

ah hmm you're right

ruby python
#

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.

lavish terrace
#

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

static cedar
#

You should be using an array there.
UnityChanThink

ruby python
#

!code

eternal falconBOT
static cedar
#

I was expecting more questions ngl.

ruby python
#

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?

static cedar
#

Find objects of type is a global search. UnityChanThink

#

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.

fossil drum
slender nymph
#

GetComponentsInChildren would probably be better

static cedar
#

Yeah that's even better.

ruby python
#

So annoying when something is so simple but you can't think of it. lol.

static cedar
#

Aye.

ruby python
#

GetComponentsInChildren works like a charm. Thanks 🙂

lavish terrace
static cedar
#

Wut.

#

Show code.

crude prawn
#

does anyone know the values to make geometry dash jump look smooth?

#

and its buggy

cloud flume
#

when i switch back to scene view they are fine its just when i get into game view

teal viper
#

Did you try switching to the scene view during play?

#

@cloud flume

cloud flume
teal viper
topaz mortar
#

How do I do this without editing my actual prefab?

SpriteRenderer monsterDropSprite = newMonsterDrop.GetComponent<SpriteRenderer>();
monsterDropSprite.sprite = itemDropSO.ItemSO.ItemSprite;
Instantiate(newMonsterDrop, monster.transform);```
languid spire
#
GameObject newMonsterDrop = Instantiate(monsterDropPrefab, monster.transform);
queen adder
#

Why cant i see my Dictionary in inspector? I want to assign variables myself

languid spire
#

Dictionarys are not serializble by default in Unity

queen adder
#

is there any way to serialize them

slender nymph
#

there are assets you can get that can do it. just google "unity serializable dictionary"

restive badger
#

You can make a class for your dictionary then use [System.Serializable]

eager elm
gilded cradle
#

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

final kestrel
#
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.

restive badger
#

When you reload the scene your UI elements will also reload

heady nimbus
#

My project isn't even very big yet and the re-build/play are taking like 25 seconds each already...

restive badger
#

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

heady nimbus
restive badger
#

It only happens in Unity

final kestrel
queen adder
#

here is the countdown timer which makes player stop moving and enables Game Overcanvas

young warren
eternal falconBOT
young warren
#

Use a paste site

queen adder
#

oh come on

young warren
#

You're almost there

north kiln
#

Your code block is large. Link to it

queen adder
#

Ok how do i share a GDL space code?

north kiln
#

paste your code, click save, and copy the new url

queen adder
muted wadi
#

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?

queen adder
#

DONE

muted wadi
#

im trying to create a sort of accuracy value for my DDR project, not really sure how I would do it

queen adder
#

here is the player movement script

queen adder
#

    [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?
tame horizon
#

did u solved “nonzero exit code” problem?

swift crag
#

But that's just what I found when googling the same problem

queen adder
#

just finished testing, reloaded my editor and my code just did fine

swift crag
#

I'm not actually sure what causes individual assets to save

queen adder
#

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

final kestrel
queen adder
final kestrel
#

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

queen adder
#

are there other things that open that ui?

final kestrel
#

No

queen adder
#

then how does the UI appear when you die?

final kestrel
#

The game starts again

queen adder
#

you are loading the whole scene?

final kestrel
#

yeah

queen adder
#

there shouldnt be a problem if that's the case. Can you send the script that reloads the game?

final kestrel
#

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

muted wadi
#

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?

queen adder
#

oh, so you also call it in a button

final kestrel
#

Yes on a button

#

but i removed it

final kestrel
#

Yeah it seems to be working now. Thanks for the help.

muted wadi
#

thank you

queen adder
final kestrel
queen adder
# muted wadi ah, i see

can also do ```cs
if(x > 0.58f)
{greater than 0.58}
else if(x > 0.3f)
{between}
else
{below 0.3}

muted wadi
#

its only doing 1 thing so the one you pasted earlier works great

queen adder
#

yea I got curioused why it had to be specificly between that numbers

gilded cradle
#

I dont see anyone writing using underscores in names in c#, is this a problem to do so or not?

queen adder
muted wadi
queen adder
#

but if you working in a team, maybe, do follow the established convention of that team

gilded cradle
#

I do not work in a team and I'm a bit used to python where I also use underscores

queen adder
#

oh i see, so the 0.5 < x < 0.3 is like an average

muted wadi
#

yeah pretty much

#

to give the player some leeway

#

i'll probably be tweaking it quite a lot

calm coral
swift crag
#

It means that the object has been changed

#

it is no longer in sync with the serialized asset data

queen adder
#

speaking of underscores, today i learn we can put consecutive underscores as member names haha

#

fill in the blanks

swift crag
#

without that, unity would have to just save every object to disk every time

buoyant knot
#

underscores are great, but everyone in unity/c# uses camel/pascal case, so I had to change

#

too much incompatibility in style

muted wadi
#

why am I getting this error?

#

is case a bool or something? I'm very confused

halcyon geyser
#

Those 2 comparisons return a true/false

muted wadi
#

why?

slender nymph
#

because that's how a comparison works

halcyon geyser
#

^

slender nymph
muted wadi
#

but isn't && equivalent to "and"

halcyon geyser
#

"distFromCenter > 0.3" from itself already only returns true/false

queen adder
#

yea, but not in a switch

muted wadi
#

oh i see

halcyon geyser
#

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.

muted wadi
#

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

queen adder
#

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

heady nimbus
#

I mean... If youw ant to know if both of those are true, just check is > .58... Then it's also > .3

slender nymph
heady nimbus
#

Yea, where did you get that switch was faster thatn if

wintry quarry
queen adder
#

me no 100 🥹

wintry quarry
#

especially with pattern matching -> pretty sure it's going to compile to the same as a series of if statements

muted wadi
halcyon geyser
#

if statement is deffo better here lol

wintry quarry
#

unless there are going to be several cases

muted wadi
#

its because im going to have 3 separate if statements checking the value of x between a range

wintry quarry
#

but either way it's a readability thing not a performance thing

heady nimbus
#

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

slender nymph
muted wadi
halcyon geyser
#

if anything in this case it might be faster

heady nimbus
muted wadi
#

i've been watching too many yandere dev critiques

#

got a phobia of if statements from that dude

heady nimbus
#

I have no idea what that is, but I looked it up and I'm terrified of it already... 0/10 would not watch

eager elm
#

99% of a time a switch statement should have been handled by inheritance instead

swift crag
#

time to break out the ol' compiler

swift crag
muted wadi
#

bools got me running for tha hills 🏃‍♂️

gilded cradle
#

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

swift crag
#

!ide

eternal falconBOT
swift crag
#

Follow the instructions for VSCode.

#

Perform every single step. Do not skip any steps.

heady nimbus
#

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 😵‍💫

swift crag
#

lmao

#

if / else if / else and switch produce slightly differently shaped IL

#

switch does all the branching up front

muted wadi
muted wadi
swift crag
#

ah

slender nymph
#

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

swift crag
#

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

muted wadi
#

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

timid gale
#

What do you do when all of your TMP-Text Buttons just, stop working??

Everything 'was' working and then suddenly, that all just stop.....

polar acorn
swift crag
#

That, along with another thing getting in the way, are the two most likely causes

brave compass
timid gale
eager elm
hollow path
#

Could someone help me? Its just a blank screen

#

Im very new to visual studio so i don't know what to do

slender nymph
#

try restarting it?

hollow path
#

I have

#

My computer too

slender nymph
#

then try reinstalling it

hollow path
#

alright

slender nymph
#

also don't crosspost

azure zenith
#

My games uses WASD control keys and it moves in different directions. Why is this?

swift crag
#

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
floral glen
#

!code

eternal falconBOT
floral glen
#

Hi im trying to add reload to my gun. But it says "error" and the namespace "IEnumerator" could not be found. Whats wrong

spiral oak
cosmic dagger
#

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 . . .

floral glen
#

thanks

delicate portal
#

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));

delicate portal
#

Is it a problem?

polar acorn
restive badger
#

If you don't need to use the cursor you might as well use raycast instead

lusty socket
lusty socket
#

!code

eternal falconBOT
lusty socket
polar acorn
# lusty socket https://gdl.space/ofujewupan.cs

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

lusty socket
polar acorn
# lusty socket this is how they are lined up, i had a animation set for is jumping but got told...

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)

buoyant knot
#

i don’t understand the issue. he is jumping? or is the detection janky?

gusty hazel
#

is there any way that i could check the bool from a different script in my player controller

polar acorn
buoyant knot
buoyant knot
#

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?

gusty hazel
#

somewhat yeah,thanks

buoyant knot
#

and if you need to set the value in inspector, then add [field:SerializedField] in front, so you can serialize just the backing field

weak isle
#

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

buoyant knot
#

ie
[field: SerializeField] public bool myBool {get; private set; }

lusty socket
buoyant knot
summer stump
buoyant knot
#

it wouldn’t be hard to code, but very tedious to make it from scratch

buoyant knot
#
  1. Cast is generic to different Collider2D, in case you use the code for enemies too. Casting also gets you contact normals and distance info.
  2. CircleCast is cheaper than cast, but you need to do some math to position right.
  3. OverlapBoxAll lets you check very crudely, and gives no distance info
lusty socket
buoyant knot
#

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

weak isle
# buoyant knot i’d also like to know this. lmk if you get an answer for it

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...

▶ Play video
summer stump
lusty socket
heady nimbus
#

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....

summer stump
#

Actually, it sounds like they WERE just saying change the query type

#

I'm sorry, looks like I misread

#

Ignore me

lusty socket
lusty socket
lusty socket
polar acorn
#

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

timid gale
#

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.....

lusty socket
eternal needle
polar acorn
lusty socket
polar acorn
polar acorn
timid gale
lusty socket
polar acorn
timid gale
timid gale
delicate portal
#

How are you usually setting this up with colliders You can go in the door, but cannot collide with the front wall?

lusty socket
polar acorn
delicate portal
polar acorn
delicate portal
#

or what?

polar acorn
delicate portal
#

there is no door go

#

Its just a door frame

polar acorn
#

If that's a hole and not a door built into it, then just use a mesh collider

delicate portal
#

Sure, default mesh collider, or should I use something specific, eg.: Convex, etc

polar acorn
#

It looks like there's a solid object inside that doorway from the perspective of your screenshot

delicate portal
#

Oh sorry, there is not

polar acorn
#

Mess with settings

#

find what works

delicate portal
#

Sure thank you

#

can I change mesh collider's size?

green copper
#

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?

polar acorn
#

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

green copper
#

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?

rich adder
#

so no

#

you would need a separate mesh with diff sizes

polar acorn
#

also, make sure the previous selectedObject isn't null as well

green copper
#

Good idea! Thanks!

lusty socket
#

?

polar acorn
lusty socket
#

return Physics.OverlapBox(gameObject.transform.position, transform.localScale / 2, Quaternion.identity, jumpableground); is this right?

#

or am i way off

#

@polar acorn

fiery geyser
#

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

lusty socket
summer stump
polar acorn