#💻┃code-beginner

1 messages · Page 583 of 1

rich adder
#

what "didnt work"

proper needle
#

i tried and it doesnt work bc theres no new updates

rich adder
slender nymph
#

follow all of the instructions. simply checking for updates is not sufficient

proper needle
slender nymph
#

was visual studio not listed in the dropdown?

rich adder
#

if you did it correct it should show in dropdown

proper needle
slender nymph
#

then why did you click browse?

proper needle
slender nymph
#

then why did you click browse

queen adder
#

it's a special unity class

rich adder
proper needle
rich adder
# proper needle

alr close VS. click regen Project files button, open script again

proper needle
proper needle
rich adder
proper needle
rich adder
proper needle
#

it does nothing when i click regenerate project files

rich adder
#

just click it and open script from unity

#

if nothing changes show your View -> Solution Explorer window in VS

proper needle
#

do i restart visual studio or smth

rich adder
#

there ya go

#

ok now fix your formatting

#

start from the top

burnt vapor
#

Hint: The errors are because you made a mistake at the start of the file somewhere most likely

proper needle
rich adder
#

probably a missing bracket

proper needle
#

nvm i found it

rich adder
# proper needle wdym

check the file from top to bottom , usually where red underline starts its where issue is

proper needle
#

thanks

rich adder
acoustic sequoia
#

does anything look wrong with this? it's not chnaging behavior at all, and i read the docs.

                    Vector3.RotateTowards(
                        snakeBrain.forward,
                        _player.position - snakeBrain.position,
                        Time.deltaTime * 1f,
                        0.0f
                    );
                snakeBrain.rotation =
                    Quaternion.LookRotation(
                        Vector3.forward,
                        newDirection
                    );```
real tinsel
#

Hey everyone, hope you're all alright. I'm trying to get this hitbox to be infront of my character when they change direction. Which I thought was easy and I'm pretty sure it is. In my update function I have

m_meleeHitbox.transform.position = transform.position.ConvertTo<Vector2>() + (1.0f * m_playerDirection)

Which makes sense in my head,
location = 1 unit ahead of player in the players direction

any ideas? cheers

ocean loom
#

my bullet is spawining inside my player, and sometimes knocking the player, so i tried to fix it by removing the rigidbody, and then adding it after a delay. However i have two problems with this code. no.1, the rigid body, isnt being added to the bullet. And no.2 it isnt moving after the player shoots.

slender nymph
ocean loom
rich adder
hot laurel
ocean loom
real tinsel
acoustic sequoia
short hazel
rich adder
real tinsel
#

Well Im not even rotating the sprite really. The character sprite is the root object, but instead of rotating it, because it is a top down game I can make the character "rotate" by using the different animations. E.g. I have a walking up, down, left and right animation

ocean loom
hot laurel
rich adder
late burrow
#

floats dont change in memory right? only when used in scene?

hot laurel
#

Floats stay the same in memory until modified.

late burrow
#

and do they get invalid offsets after modification

hot laurel
#

why would it even happen?

north kiln
#

What do you mean

#

Are you talking about general floating point accuracy?

#

If you try to assign a value to a float and it can't be represented it'll be rounded appropriately

#

beyond that, nothing happens

late burrow
#

ok so if i go too many decimal points then it rounds up

hot laurel
#

float have it own adress, well 4 adresses since i take 4 bytes, and it stays the same

north kiln
hot laurel
#

you reached the max capacity for 4 bytes then

north kiln
#

It's not about decimal points

polar acorn
#

There's basically a very large basket of numbers that a float can hold. If you try to give it something that's not in that basket, it'll find the closest one instead.

#

At no point can you ever store anything that's not in that basket in a float

ember tangle
#

Not sure if this is the right place to post this but my prefab randomly died and I did nothing to cause it. It was working last time I had the project open

keen owl
ember tangle
#

I am using github, but every other commit has worked fine and I don't think I even changed the prefab last commit

keen owl
#

Not sure if you edited the prefab outside unity but it seems that it’s probably a corrupted file. I’d try going back a commit and see if it persists

ember tangle
#

100% certain I did not edit the prefab outside of unity

hot laurel
# ember tangle

can you show meta file of that prefab, and open the prefab itself in notes and show the context

ember tangle
#

I have a "binary file has changed" message for the entity prefab when looking at my latest uncommitted github changes.

keen owl
ember tangle
keen owl
#

Just stash them, you can always apply them back

ember tangle
#

Hmm I'm even getting that 'binary file has changed' with my fonts and im even more certain that those didnt change...

ember tangle
hot laurel
#

press on that prefab, right mouse btn, show in explorer then there is .meta file with the name of that prefab

#

check the guid inside

ember tangle
#

Uhhh okay I just uncommitted the changes for the prefab specifically in GitHub and it fixed everything

#

Is this a bug?

#

I swear I didnt do anything

keen owl
#

Could just be human error, you might have done something by mistake not knowing you actually modified it.

#

Or it was corrupted

hot laurel
#

or somehow renamed outside unity when it was closed, so new .meta file was generated with new guid
renaming outside unity, when its still open, also cause generating new guid

ember tangle
#

Now I'm paranoid about malware or some other error because I'd bet my life no input I made changed that file,

#

Or a bug

#

Oh well its all fixed ty!

calm pawn
#

how do I use that pixel per unit size and change the size of the camera without effecting pixel per unit size? I also have Vcam

keen owl
calm pawn
keen owl
#

Not sure if that will do much. You need to make sure the camera distance is also modified along with sprite pixel per unit (if needed) to keep the changes consistent with the resolution you are setting it to

calm pawn
keen owl
#

So you’re saying you want the camera to be bigger but maintain the same pixel dimensions?

calm pawn
keen owl
#

Not 100% sure but try adjusting the camera’s orthographic size proportionally to the screen’s height while keeping the pixel per unit constant?

keen owl
calm pawn
keen owl
#

I haven’t worked with #🎥┃cinemachine which is why you’d have better luck there. Besides, not code related

acoustic sequoia
#

hey everyone, does anyone else ever deal with script compiling time increasing over the span of working in your project? when i close unity and reopen it, the compile time goes back to almost instant. i don;t want to keep restarting unity to keep my compile time down. how to fix?

calm pawn
#

can someone help fix the issue where pixels have different sizes in unity

rich adder
rich adder
grizzled spoke
#

Does anyone know if it's possible to have the new input manager assign different sets of keys (for the same actions) to different player objects
I need to have a game with 2-4 players on the same computer using the keyboard

#

I understand how bad game design that is, it's for a competition 😭

grizzled spoke
lean cipher
#

im having trouble attaching my GameController script to my BallLogic script, does anyone know why?

polar acorn
lean cipher
#

just an empty object called GameController

polar acorn
#

Drag that in

lean cipher
#

and BallLogic is on the Ball gameObject

lean cipher
polar acorn
wintry quarry
lean cipher
#

yeah

lean cipher
#

same thing happens when i just try to do it with the script

polar acorn
lean cipher
#

what does that mean

#

im very new to all this

#

sorry

wintry quarry
#

Show full uncropped screenshots

polar acorn
# lean cipher what does that mean

Is the object with the GameController script on it in the hierarchy of the scene, or is it on a Prefab object?
Is the object with the BallLogic script on it in the hierarchy of the scene, or is it on a Prefab object?

lean cipher
wintry quarry
#

We know what you want

#

we're asking clarifying questions to figure out your issue.

lean cipher
wintry quarry
# lean cipher

Ok so you're trying to drag a reference to a scene object into a prefab

#

this is not supported

#

Prefabs cannot reference objects in scenes

polar acorn
wintry quarry
polar acorn
lean cipher
#

So should it be a prefab object then?

#

because I want it to be destroyed then spawned with GameController

wintry quarry
#

Refer to the link above for how to handle this properly

lean cipher
#

or is there a way for me to get it when it spawns like with GetComponent<>()

lean cipher
polar acorn
lean cipher
polar acorn
wintry quarry
#

GameController sounds like something that should just be a singleton tbh

lean cipher
wintry quarry
#

Definitely use a singleton

lean cipher
#

ill check that out

steep void
#

How can I check the distance to the nearest object, not knowing what the object is? Like if myObject needs to be at least 0.2 from anything else in the scene. I have Vector3.Distance but I dont know how to define the second argument.

wintry quarry
polar acorn
wintry quarry
#

Oh if you just want to make sure there aren't any objects yeah you can use CheckSphere

hot jolt
#

Anyone have an alternative to this that's just as simple?
https://youtu.be/qQLvcS9FxnY?si=Was7iplZSnt7q4fD
Not sure if it's a me problem or what but I cannot get it to work

Very fast tutorial to make an FPS character in Unity in less than a minute!

PasteBin link for code: https://pastebin.com/RXZ1dXgw
GitHub link: https://github.com/dustinmorman/FPSControllerTutorial

Link to my Upcoming Game - Survive the Uprising: https://store.steampowered.com/app/1984690/Survive_the_Uprising/

Link to the Discord - https://dis...

▶ Play video
wintry quarry
#

this stuff is clickbait and not very useful

steep void
wintry quarry
#

In the long run it is going to cost you time, not save time

polar acorn
wintry quarry
polar acorn
steep void
#

thank you

slender nymph
#

the input system is definitely going to be better for this than the old input manager.
have you actually logged what is happening, including the relevant velocity? also you should show the inspector for the rigidbody and aalso make sure that there aren't possibly any colliders that might prevent it from moving vertically

grizzled spoke
slender nymph
#

I doubt it's something to do with my code
then why did you post the question in a code channel

slender nymph
#

and if it works using the Fire action then check what is different about that action

grizzled spoke
#

oh there's an input system channel 🤦‍♂️

slender nymph
#

yes

#

it does

#

you could also just continue; if the object is disabled

toxic frigate
#

@teal viper

public void MoveAndRotateToTarget(Vector3 targetPosition)
    {
        Vector3 direction = targetPosition - transform.position;

        if (direction != Vector3.zero)
        {
            direction.y = 0f;
            targetPosition.y = 0f;
            Quaternion toRotation = Quaternion.LookRotation(direction, Vector3.up);

            // Use Rigidbody.AddTorque for rotation
            Vector3 torque = Vector3.Cross(transform.forward, direction.normalized) * rotationSmoothness * rb.mass / Time.deltaTime;
            rb.AddTorque(torque);

            float distanceToTarget = Vector3.Distance(transform.position, targetPosition);
            float deceleratedSpeed = Mathf.Lerp(0f, moveSpeed, Mathf.Clamp01(distanceToTarget / decelerationFactor));

            // Use Rigidbody.AddForce for movement
            rb.AddForce(transform.forward * deceleratedSpeed * rb.mass / Time.deltaTime);

            // Clamp the velocity to ensure it does not exceed the moveSpeed
            rb.velocity = Vector3.ClampMagnitude(rb.velocity, moveSpeed);
        }
    }
nimble apex
#

oh ok

#

ty

toxic frigate
#

in the build exe it moves at different speeds, most likely due to different framerates

eternal falconBOT
nimble apex
#
        foreach (GameObject element in parent.transform)
        {
            if (!element.activeInHierarchy)
            {
                continue;
            }

            counter += element.GetComponent<Rect>().height;
        }

        print($">>> {counter}");```
gonna try it
toxic frigate
#

ill paste the update function and the movement function

teal viper
teal viper
toxic frigate
#

multiplying?

teal viper
#

Dividing. Doesn't matter

toxic frigate
#

what should i do instead

teal viper
#

Nothing. Just don't divide it by delta time.

#

It would also help if you name the variables properly and learn the difference between forces, acceleration, velocity and speed.

#

If you want to apply an impulse, acceleration or velocity change, you should pass in a second parameter to AddForce. Check the details in the docs.

river kettle
#

Hey i was wondering if i could have some help with my code snippet all I'm trying to do is have the camera follow the player with a delay so that the cam doesn't just lock onto the player like just equaling out their transforms would do and I've nearly done it but no matter what i do I cant seen to stop the camera from jittering when the player gets to far away it starts unnoticeable around 1 or 2 units away but gets really noticeable the further away the player is i believe is has something to do with the speed constantly changing but I genuinely have no clue I've been trying to debug for a while now but to no avail any ideas?(sorry for the lack of grammar😅 )

#
        Vector2 direction = playerPrefab.transform.position - transform.position;
        
        //calculates the distance/magnitude between the camera and player
        float magnitude = direction.magnitude;

        //makes the camera move towards the player
        if (magnitude > stopDistance)
        {
            //normalizes the direction
            Vector3 distanceBetweenNormalized = direction.normalized;

            //sets the speed
            cameraSpeed = magnitude * 1.5f;

            //calculates the movement vector
            Vector3 moveVector = distanceBetweenNormalized * cameraSpeed * Time.deltaTime;

            //moves the camera towards the player
            transform.position += moveVector;```
river kettle
#

after some testing I thoroughly believe that its the way that im managing the players movement instead of the cameras but im even more lost as to how i can alter that to make it work

#
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");

        Vector2 inputVector = new Vector2(horizontalInput, verticalInput);

        if (inputVector.magnitude >= 0.9f)
        {
            inputVector = inputVector.normalized;
        }

        rb2D.velocity = inputVector * moveSpeed;
    }```
ornate aurora
#

This code is generating 50kb of garbage when the Cell.Clone() method is called. Is there a way to bring that down by not calling it?

public class AbstractBoard
{
    public InfiniteBoardGenerator boardGenerator;
    public Dictionary<Tuple<int, int>, Chunk> loadedChunks;
    public int chunkSize;
    private int[,] numbersBuffer;
    private int[,] minesBuffer;
    private Cell[,] cellsBuffer;


    public Cell[,] GetChunk(int chunkXPosition, int chunkYPosition)
    {
        Tuple<int, int> chunk = new(chunkXPosition, chunkYPosition);
        if (!loadedChunks.ContainsKey(chunk))
        {
            ComputeChunk(chunkXPosition, chunkYPosition, ref cellsBuffer);
            CellsToChunk(chunkXPosition, chunkYPosition, cellsBuffer);
            foreach (Cell cell in cellsBuffer)
            {
                cell.state = Cell.State.Revealed;
                cell.type = Cell.Type.Mine;
            }
        }
        return loadedChunks[chunk].cells;
    }

    private void ComputeChunk(int chunkXPosition, int chunkYPosition, ref Cell[,] cells)
    {
        ComputeMinesInChunk(chunkXPosition, chunkYPosition, ref minesBuffer);
        ComputeNumbers(minesBuffer, ref numbersBuffer);
        for (int i = 0; i < chunkSize; i++)
        {
            for (int j = 0; j < chunkSize; j++)
            {
                GetCell(i, j, ref cells[i, j]);
            }
        }
    }

    private void CellsToChunk(int chunkXPosition, int chunkYPosition, Cell[,] cells)
    {
        Tuple<int, int> chunkPosition = new(chunkXPosition, chunkYPosition);
        Cell[,] newCells = new Cell[chunkSize, chunkSize];
        for (int i = 0; (i < chunkSize); i++)
        {
            for (int j = 0; (j < chunkSize); j++)
            {
                newCells[i, j] = cells[i, j].Clone();
            }
        }
        loadedChunks[chunkPosition] = new()
        {
            cells = newCells,
        };
    }
}
#

To not call it directly will copy a reference only and there will be unwanted modifications to the "original" instance

teal viper
ornate aurora
#

I want to have a dictionary that saves chunks of cells so they don't have to be calculated again

#

So each time the player finds an unexplored chunk, it is calculated and saved into the dictionary

#

I don't know how to initialize the cells without a new() so I'm always forced to generate garbage that way

teal viper
#

Are you sure it's garbage and not just an allocation? For it to be garbage it would need to be allocated/disposed every frame

#

Does it actually cause a performance issue?

#

Can you share the profiler data?

ornate aurora
teal viper
#

Also, I think there's an issue with you using Tuples there. It seems to be a reference type version, so you'll never get them from your dictionary. Use Vector2Int or something instead

teal viper
ornate aurora
ornate aurora
teal viper
#

There's really no reason to use tuples here, since we have vectors

dense peak
#

sorry to ignore but how do i start learning coding?

ornate aurora
teal viper
#

You could probably use a ValueTuple as well, but just don't. Use unity API as much as possible to keep the code consistent.

cosmic dagger
ornate aurora
#

Nice. Thank you

cosmic dagger
# dense peak where do i learn?

any tutorial from YouTube or a blog post. you can check the pinned messages from this channel for the Unity related stuff . . .

dense peak
#

ok

teal viper
#

And thus every time you try to get one, you allocate a new chunk

cosmic dagger
#

@dense peak here's a list of stuff as well . . .

ornate aurora
#

That wasn't an issue actually. Everything works just fine

teal viper
#

Sorry, I mean add an else block and add a log there

ornate aurora
#

Yes, the dict does contain the tuple

teal viper
#

That's weird, but ok.

verbal dome
#

Latter would cut down on allocations

#

Feel free to correct me if im wrong

teal viper
verbal dome
#

Yeah, its a low hanging fruit

burnt vapor
#

Oh, I guess it would be a ValueTuple?

verbal dome
#

Latter is valuetuple yeah

nimble apex
#

im making a automatic function to shrink and enlarge dialog based on the elements inside the dialog, just like bootstrap from web development

lets say all the height added up from all elements are 50, then the parent height will be 50 + some offset

however, all these elements u see are controlled by certain vertical/horizontal layout group

#

when they are under control of the group, i know u cant change the value, but not even getting it???

#

when u get the value , they return 0, either from rect.height, or sizedelta.y , or getrectheight()

#

is there any ways to bypass this encryption?

verbal dome
nimble apex
# verbal dome Where are you getting it? Might need to do it at the end of the frame but not su...
    private void RefreshDialog()
    {
        float counter = 0;
        
        foreach (Transform element in parent.GetComponent<Transform>())
        {
            if (!element.gameObject.activeInHierarchy)
            {
                continue;
            }

            counter += element.gameObject.GetComponent<RectTransform>().rect.height;
        }


        foreach (RectTransform element in coreTransforms)
        {
            element.GetComponent<RectTransform>().sizeDelta = new Vector2(element.rect.width, counter + 40 + stepParents[steps].GetComponent<RectTransform>().GetRectHeight());
        }
        GetComponentInChildren<BasicDialogFrame>().RefreshSize(true);
    }```
all of them are event driven functions , when u press the button, the next parent is loaded , and this function will be called after next UI parent is set active
buoyant finch
#

https://paste.ofcode.org/iXKchBT9ksWX4JJ5AN2PEZ hello so I have this code which has all the movement needed I have an animation freezing system and the walk animations freeze and after 4 frames they should reset the walk animation but they continue by repeating for 6 to 7 frames and then are switched pls someone explain how to fix it all the animations are of 5 fps and the animator.speed is the problem I think it should be smth like delta time
I tried it but then it slows animator.speed down a lot
I tried setting animatorspeed to 2 but it is unreliable as frames change

nimble apex
#

my friends shared a way to let me get the value , but it destroys the original layout completely, u cant get the value u want to get with this tho

LayoutRebuilder.ForceRebuildLayoutImmediate(parent.GetComponent<RectTransform>());```
verbal dome
buoyant finch
teal viper
#

They are trying to increment the animations frame by frame using the animator... That's the issue.

teal viper
buoyant finch
verbal dome
#

I saw them manually incrementing spriterenderer frames before

teal viper
buoyant finch
teal viper
teal viper
buoyant finch
# teal viper Wdym? Of course it's possible.

I'm not sure. The non-animator approach might not make it easier. I think the animations don't instantly update when you change direction because public float animationFrameRate = 0.2f;, effectively forcing the frame to linger for 200 milliseconds before it can update to the new direction and the run animation freezes which I don't want

teal viper
buoyant finch
#

If the value is changed the animations are sped up

nimble apex
#

i found a way to do it now

buoyant finch
#

How??

nimble apex
#

no its my problem lol

nimble apex
teal viper
buoyant finch
teal viper
buoyant finch
#

Along with run switching to idle and walk running defaultly as well with it

teal viper
warm rock
#

!code

eternal falconBOT
warm rock
#

everything works except the true part of HandleInteractions()

#

the else outputs not interacting, but the true should happen

verbal dome
#

What "true" part? You mean if (Physics.Raycast...?

warm rock
#

yes

verbal dome
#

This part makes no sense to me cs if (moveDir != Vector3.zero) { moveDir = lastMoveDirection; }

#

And lastMoveDirection will always be zero, you aren't changing it anywhere

warm rock
#

but im changing it when InputVector changes

verbal dome
#

Show me where

warm rock
#
        Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
        ```
verbal dome
#

Is that lastMoveDirection?

warm rock
#

thats moveDir

verbal dome
#

Yeah I can read

warm rock
#

ye

verbal dome
#

But I said you aren't changing lastMoveDirection anywhere

#

Not moveDir

warm rock
#

isnt lastMoveDirection dependant on moveDir cuz i add moveDir = lastMoveDir

verbal dome
#

Other way around

#

moveDir is dependant on lastMoveDir

warm rock
#

ohhh its in order...

#

i thought its both sides

verbal dome
#

Of course lol

warm rock
#

sry

#

ty

potent barn
#

Hi,
I am following a tutorial on how to make pong in unity as I am just starting out, but I have come across this error even though I am copying the tutorial's code which did not come up with the error.

Error: 'Vector2' is an ambiguous reference between 'UnityEngine.Vector2' and 'System.Numerics.Vector2'

Thank you so much

astral falcon
#

And for some reason, you import the usage of System.Numerics, which you should not. It just tells you, it cant decide, if you using unity.vector2 or the numerics one, but certainly you want the unity one

potent barn
#

Thank you! It worked, from now I will try and just follow along with the code, I am mainly just using the guide to get familiar with what each of the buttons does!

gloomy cosmos
#

Hello, I'm trying to render stuff using a particle system. For layering I put the particlesystem into depth mode and set the z coordinate of particles to their layer. But it seems like the particle system depth mode doesn't actually sort based on z-coordinate, or not in a conventional manner atleast. How can I specify which particles draw on top of others ones?

Edit: I found a solution, it's not perfect and might introduce problems later on, but for not it works. I will post again if I this solution no longer works in the future

timber tide
#

Are you sure this is all done with z-coordinates and you're not using the transparent layering queue as the sort

gloomy cosmos
timber tide
#

I've used it in 3D and it does sort on depth, where as Unity 2D does most with rendering queues and not coordinates

gloomy cosmos
#

anyway as I said I found a solution so it's not a problem anymore

buoyant finch
split hull
#

Hi, I have a "small" problem with the car engine.

I did it from the Guide ( https://www.youtube.com/watch?v=gEwNHUDc8uE&list=PL0JXhw1odpJLTRBDdv4ybtYkuD1lEcF-N&index=2 ) and now after starting it doesn't want to go

(as far as I can tell the problem is with the wheels )

In the tutorial we will make a Car controller with smoke particles when slipping, variable steering and camera movement.
The car controller that contains: A car controller script with a car model, that allows the car to accelerate, brake, reverse, drift and countersteer. A camera controller script.

To download the code go to:
https://github.co...

▶ Play video
obsidian plaza
#

car engine

#

what is that

split hull
#

Error Codes

obsidian plaza
#

post that script please !code

eternal falconBOT
obsidian plaza
cinder schooner
# split hull Error Codes

it looks like your code is trying to get from the list or array an index which the list doesn't have.

split hull
#

The script is now irrelevant to me.

Wheels.

obsidian plaza
split hull
#

Wheels?

#

Code?

hexed terrace
#

code obvs

obsidian plaza
#

yea idk what im missing here

split hull
#

i fix it around 7PM

tough tartan
#

https://youtu.be/4H6-obIxnjg?si=w1kQMlasa4WuPJjy 2:30 he does something with the materials. How would i do this on the newer version of unity

Learn how to create your own classic First Person Shooter in Unity!

Get the assets for this series here: https://www.dropbox.com/s/juihs7yq93x1aon/GPJ_FPS_Assets.zip?dl=0

Don't forget to hit that like button and if you'd like to see more gaming goodness then subscribe for more!

Support the show by pledging at http://www.patreon.com/gamesplu...

▶ Play video
hexed terrace
split hull
#

ok now I know what... Orientation

rugged ferry
#
        if (playerSenseRage.Value == true)
        {
            up.color = _restColor;
            right.color = _restColor;
            left.color = _restColor;
            down.color = _restColor;
            center.color = _activeColor;
        }
        else if (lookDir == Directions.Up)
        {
            up.color = _activeColor;
            right.color = _restColor;
            left.color = _restColor;
            down.color = _restColor;
            center.color = _centerColor;
        }
        else if (lookDir == Directions.Right)
        {
            up.color = _restColor;
            right.color = _restColor;
            left.color = _activeColor;
            down.color = _restColor;
            center.color = _centerColor;
        }
        else if (lookDir == Directions.Left)
        {
            up.color = _restColor;
            right.color = _activeColor;
            left.color = _restColor;
            down.color = _restColor;
            center.color = _centerColor;
        }
        else if (lookDir == Directions.Down)
        {
            up.color = _restColor;
            right.color = _restColor;
            left.color = _restColor;
            down.color = _activeColor;
            center.color = _centerColor;
        }
        else if (lookDir == Directions.None)
        {
            up.color = _restColor;
            right.color = _restColor;
            left.color = _restColor;
            down.color = _restColor;
            center.color = _centerColor;
        }
#

How can I improve this code?

verbal dome
#

You could first set them all to their default value (_restColor/_centerColor) and then only change one of them to _activeColor based on lookDir (and playerSenseRage?)

#

This would be one extra assignment but at least less code repetition

#

lookDir could be checked in a switch

grand snow
#

I would say have a direction mapped to each one so you just compare if the dir matches and set the active/rest colour otherwise

rugged ferry
#

good ideas, thanks guy

timber tide
#

switch statements look nicer and vs will usually do it for you if you highlight the statements see what it has to say

grand snow
#

doesnt solve this crud though but yes switch statements are good

timber tide
#

there's also the pattern match statement which can make it even smaller

brave tendon
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

muted plume
#

i dont have the script option thing anyone can help?

#

i try make movement

astral falcon
eternal falconBOT
#

:teacher: Unity Learn ↗

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

faint osprey
#

how do u wait for an animation to finish before continuing the function

astral falcon
faint osprey
#

how do you check the state

muted plume
astral falcon
astral falcon
wooden sky
#

is this the place to ask about tilemap?

astral falcon
wooden sky
#

rendering tiles in isometric view idk where to ask

astral falcon
verbal cairn
#

hi guys i am new here

compact stag
#

hey guys! just wanna confirm, using GameObject.Find is like, not good at all right? what would be the best way to do it? trying to access a void function from another script and i'm using this:

    [SerializeField] GameObject gamemana;

    void Start() {
      gamemana = GameObject.Find("GameMana");
   }
    private void OnMouseDown() {
        Destroy(gameObject);
        GameManager scriptAdd = gamemana.GetComponent<GameManager>();

        scriptAdd.UpdateScore(1);
    }

it works but just wondering if theres a better way to do this

grand snow
compact stag
grand snow
#

If its loaded later at runtime or something id say a single Find isnt too bad but you should avoid finding by a name. Instead FindObjectOfType<GameManager>(); to more reliably get this game manager instance.

The alternative is to make it a singleton

grand snow
#

if its something else then can you explain a bit clearer or send some screenshots?

compact stag
grand snow
compact stag
grand snow
#
[SerializeField]
GameManager gamemana;
compact stag
compact stag
grand snow
#

yea cus its already that.
e.g.

[SerializeField]
AudioSource myAudio;

private void Start()
{
   myAudio.Play();
}
#

@compact stag If the script that wants to reference game manager is Instantiated in play mode then ofc you cannot reference via the inspector (i presume this is what you are doing).

But if its in the scene already then reference it directly like i just demonstrated

compact stag
#

it is not instantiated in play mode

#

let me try something real quick

grand snow
#

Cool then this should work nice and simply

compact stag
#

wait, nevermind it is instantiated in playmode

compact stag
#

so if i cant change the reference via the inspector, how should i do it? whats the best way to do that?

grand snow
#

If you can reference in scene

[SerializeField]
GameManager gamemana;

private void OnMouseDown()
{
    Destroy(gameObject);
    
    if(gamemana != null)
    {
        gamemana.UpdateScore(1);
    }
    else Debug.Log("Game manager is missing!", this)
}
burnt vapor
compact stag
#

and if i cant should i use FindObjectOfType<GameManager>(); ?

grand snow
#

Id try to avoid FindObjectOfType() as say you kept spawning in objects that do this, it could affect performance.

#

If its 1 find rarely its not too bad (e.g on game load, on level load)

compact stag
#

so a singleton is pretty much just a single script with few lines of code (for most cases i assume) ?

grand snow
#

what you put in it is up to you

compact stag
#

alright, ill write a few lines and ill update you soon! thank you either way ❤️

grand snow
#

np. that website has lots of good info for how to do stuff

compact stag
#

and its way better looking than the actual docs

#

why tf no dark theme? where are we? 2013? jeez

verbal dome
#

Just use a browser extension for that

compact stag
compact stag
#

i made a singleton (or at least i think i did???) and it came out to this

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;

public class SingletonTest : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI scoreText;
    private int score;

    public static SingletonTest instance;

    private void Awake() {
        if(instance == null) {
            instance = this;
        }
        else {
            Debug.Log("Another instance foi found");
            Destroy(this);
        }
    }
    public void UpdateScore(int scoreToAdd) {
        score += scoreToAdd;
        scoreText.text = "Score: " + score;
    }
}

can i apply this code to any game object or...? what should i do? because i do need to reference the text mesh somewhere

grand snow
#

elsewhere you use SingletonTest.instance.UpdateScore(1)

compact stag
#

and then instead of putting my variables in this code i put it in the other code?

grand snow
#

er can you be more specific?

compact stag
#

i was about to say lol too vague

grand snow
#

using this singleton pattern is to get a reference to a script instance easily without find/inspector ref

compact stag
#

so, i was thinking of putting it in my "enemy" script, as when you click on an object it disappears and you should get a point, its a recreation of the game fruit ninja

grand snow
#

then in the enemy script. use SingletonTest.instance.UpdateScore(1) to update score.
Perhaps you should read up on c# basics if this is confusing

compact stag
#

it isnt! i'm just wondering where i'd put the [SerializeField] TextMeshProUGUI scoreText; private int score;

#

should i put it in the singleton script or in the enemy script?

grand snow
#

in your singleton script ofc

#

your singleton manager class is managing the ui text and score value so it goes there.
enemies get created/destroyed a lot so should just tell the manager to update score when needed.

compact stag
#

right, so since i have a serialized field that takes my scoreText i'd have to put this singleton script somewhere, correct?

#

so i can reference my text mesh through the inspector

cosmic dagger
grand snow
cosmic dagger
#

@compact stag when the enemy dies, send an event (notification). have a score manager or your singleton listen to this event and update the score accordingly . . .

grand snow
#

Scene loads -> manager sets instance static ref -> spawn enemy -> enemy dies -> tells manager to increase score.

compact stag
compact stag
grand snow
#

what game object it goes on makes no difference. as long as its in the same scene and it isnt destroyed too early.

compact stag
#

ill put it in my game manager as it doesnt get destroyed

cosmic dagger
grand snow
compact stag
#

thats fair, how would i apply it on my code? just use that method in the singleton script?

#

since its a simple recreation game to learn stuff i won't be using that but its always good to know

compact stag
#

ill take a look at it as soon as im finished here, but another question popped up in my head, sorry for the billion questions

#

but why do we use serialized field?

cosmic dagger
#

to view the variable from the inspector . . .

compact stag
#

yes, but why not use public?

grand snow
#

you probably know that public int myInt also works to have a var in the inspector right?

cosmic dagger
grand snow
#

correct!

compact stag
grand snow
#

well protected lets sub classes also access it and ofc you can use that if you want

#

usually wise to start with the least access and change as needed

cosmic dagger
timber tide
#

protected everything

cosmic dagger
#

a private field cannot be accessed from a derived class, only the enclosing class (it was created in) . . .

timber tide
#

the cooler private

keen sierra
#

how do i make it so when i look down my player doesnt do this and ill send the link to the script in a bit

compact stag
#

alright! thank you guys, much love! i'll let the other beginners take the chat

#

good luck! 🫡 🫵

keen sierra
verbal dome
#

Nothing here is rotating your character

timber tide
#

ye where be it

cosmic dagger
keen sierra
#

oh i forgot the turning script

cosmic dagger
#

wouldn't that be the only one to send?

keen sierra
umbral siren
keen sierra
#

how do i do that

spare mountain
keen sierra
#

but then the player doesnt rotate at all i think

verbal dome
#

You can do Y rotation for the body and X rotation for the camera

spare mountain
umbral siren
keen sierra
verbal dome
#

If you understood your own code then you'd know how to do it

#

You are already doing it, just need to split it up

cosmic dagger
#

also, just use cinemachine. it'll solve all your problems and has a bunch of tutorials for different types of camera views . . .

rich adder
keen sierra
#

tutorial

verbal dome
#

We all know where that code came from

umbral siren
verbal dome
umbral siren
#

here was my approach

keen sierra
#

wait let me check

hot laurel
#

probably copy pasted from unity learn tutorial

rich adder
keen sierra
umbral siren
#

i followed it

keen sierra
#

i didnt do the unity tutorial tho

rich adder
#

so which one

keen sierra
#

this one

rich adder
#

oh wow even crappy video put Time.deltaTime on mouse Input

verbal dome
#

I was almost sure that it's from ChatGPT (though the comments weren't exactly gpt like)
This is what ChatGPT gives

#

It always does thet deltatime mistake

timber tide
#

brackys!!!!!!

rich adder
#

goddam brackys mistake has influenced GPT too ? rip

thorny basalt
keen sierra
#

so how do i fix the thing i was talking abt

umbral siren
rich adder
#

mouse input already independent from framarate

verbal dome
#

Look how similiar it is

keen sierra
#

my brother who makes unity games gave me the link

thorny basalt
#

This is why I don’t recommend using AI for programming

rich adder
#

my cousin works at nintendo

umbral siren
rich adder
timber tide
#

See, the cool thing about Godot is AI is terrible for it and is way behind. So you're forced to actually give some legitimate code to work out ;p

keen sierra
ivory bobcat
#

Maybe you should consider doing the learning tutorials

cosmic dagger
rich adder
tender birch
#

Does anyone know how to save a blendtree and connect it to a player? I have my blendtree setup, but its not connected to my player, my player has a diffrent animator component and i dont know how to change it. this pic might be a little confusing, but the inspector tab on the right is my setup blendtree, and the animator tab on the left is the one my player is connected to

rich adder
tender birch
#

I have paramters, its kinda confusing idk how i messed this up so bad

rich adder
#

MouseX and MouseY have to be created

tender birch
#

The paramaters are correct and working on my inspector tab

#

i can move the red circle around and it will work properly

#

also

rich adder
tender birch
#

public class PlayerController : MonoBehaviour
{

    private Rigidbody2D myRB;
    private Animator myAnim;

    [SerializeField]
    private float speed;
    // Start is called once before the first execution of Update after the MonoBehaviour is created


    void Start()
    {
        myRB = GetComponent<Rigidbody2D>();        
        myAnim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        myRB.linearVelocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;

        myAnim.SetFloat("MoveX", myRB.linearVelocityX);
        myAnim.SetFloat("MoveY", myRB.linearVelocityY);



    }
}
tender birch
#

im trying to figure out how to connect my other blendtree to my player

rich adder
#

the process is the same, make the paramaters and control them

tender birch
#

im explaining the poorly i think 😭

rich adder
#

probably

tender birch
#

ok so

#

I setup the blendtree correctly, but it wasnt linked to my player

rich adder
#

also you shouldnt move rigidbody in Update but Fixed Update instead, and adding Time.deltaTime on velocity is hella wrong

tender birch
#

my player has a diffrent animator component linked

tender birch
rich adder
buoyant finch
tender birch
#

its 5years old lmao

rich adder
#

regardless of age, its wrong

tender birch
#

yea i get what your saying

#

ok

#

ill use diffrent tutorial

rich adder
#

you can use whatever tutorial if you're aware of the mistakes to correct, which are hard to do when you're new lol

tender birch
verbal dome
#

Man why are these people so confident to make these tutorials

cosmic dagger
verbal dome
#

No one gets movement physics or mouse look or other basic stuff right

tender birch
#

what i was trying to ask is how do i connect my blendtree to player component

#

I have the animator option

#

but it just makes a whole new blendtree

#

am i slow

cosmic dagger
rich adder
tender birch
#

ok i get the tutorial is wrong but i think you guys dont get what im asking 😭

rich adder
#

but that explain why mine are stuck at 5k views xD

tender birch
#

ill use a dif tutorial after this part

verbal dome
#

They are just another state

cosmic dagger
rich adder
tender birch
#

yes

#

when i do

rich adder
#

wdym "connect" like a reference you mean ?

tender birch
#

regardless of which mouse key is pressed

#

it always does animation up

#

howevere

#

my blendtree is correct

verbal dome
tender birch
#

look

verbal dome
cosmic dagger
#

honestly, if you have a blendtree it should already be a part of your Animator . . .

tender birch
#

this one is working

rich adder
tender birch
#

how do i change which one its connecting too?

#

my player animator component is using the wrong blendtree

buoyant finch
tender birch
#

ok i think im js slow ngl

rich adder
rich adder
#

or you talking about the state ?

tender birch
#

thats what the guy said to do in the tut is make a window in inspector💀

rich adder
#

you right click it and make it default

#

you're skipping many lessons here though

tender birch
#

this?

tender birch
#

this one is very painful

rich adder
rich adder
tender birch
#

the one on the right

#

is my working one

rich adder
#

WalkUp and WalkDown are pretty confusing labels

tender birch
#

i move the red dot

#

and he does the right thing

rich adder
#

ok? I get that but you didnt make the parameters that control those?

tender birch
#

I wish i could send a screen recording

tender birch
#

thank you

#

I was trying to find a tutorial

buoyant finch
#

np

rich adder
tender birch
#

i just fucked it all up tbh

rich adder
#

where is MouseX and MouseY

tender birch
#

its in the inspector windows paramaters

#

lemme send a screenshot with better layout

rich adder
#

man you gotta start with like Flappy Bird or something, an RPG is gonna be too complex as a first project

tender birch
hallow bridge
#

This is not exactly a coding question but since it's my first time using unity in 2 years and I recently switched to linux, is this how the editor is supposed to look or am I having rendering issues?

tender birch
#

i have the paramaters

#

wtf

#

whty do i keep getting blocked messages

rich adder
# tender birch

those are parameters you wrote but they are not the ones you created

hallow carbon
#

Where shuold I ask something aubout a bug

buoyant finch
rich adder
hallow bridge
hallow bridge
tender birch
#

ok im just gonna restart the blendtree

buoyant finch
rich adder
#

if you're gonna use animator, then you need to learn animator first

#

not Learn as you do something else

#

BlendTree expects you to have the parameters ready to go for the dropdown, You can type them in but it just resets because it expects the one from Parameter window in animator

buoyant finch
#

oh btw I have a quick question https://paste.ofcode.org/jBtb4xxJmTPrqaXzw649hZ this works but another problem is that after running when the directional key is released and then Z key is released the walk animation is played instead of idle can someone help pls

rich adder
#

is there a reason to manually swapping frames instead of just using animtion clips

buoyant finch
tender birch
#

so i dont have to deal with the outdated code like in the other yt vid

buoyant finch
rich adder
hallow carbon
#

Just fixed

#

it

buoyant finch
rich adder
buoyant finch
#

yeah its a good source

rich adder
#

at least this treats it like school material with assignments and such

#

the other videos on YT you're just copying and pasting , not learning

tender birch
#

ok thank you for the help guys

buoyant finch
buoyant finch
verbal dome
#

Why are you checking if Z is being pressed here

buoyant finch
verbal dome
#

This whole thing is pretty confusing

#

You posted a video of what you want earlier, it looked like the "idle" animation was just a single frame from the walk animation

tender birch
#

is there a good tutorial for learning the basics for the unity UI

verbal dome
#

@buoyant finch Describe clearly:
When do you want Run anim
When do you want Walk anim
When do you want Idle anim

tender birch
#

idk why but i cant even snap windows into diffrent parts of the layout, so everything is just a floating window and its annoying asf

buoyant finch
verbal dome
buoyant finch
#

as the walk animation is iterated frame by frame

#

I have achieved that all but when I release the directional keys and then when I release Z sometimes walk animation is played instead of idle

verbal dome
#

If you run and then release Z before releasing directional keys then yeah of course it will go to walk

vagrant lynx
#

Hey! I need help with the rotation of the player with the camera.

I have a character controller and the player can move left-right and forward-backward. And have set up a freelook cinemachine camera.

What I want to create is that-

The player rotates with the rotation of the camera and also goes forward in that direction. I don't want the player to be rotated with movement keys (wsad)

buoyant finch
wintry quarry
#

But FreeLook is intended to have decoupled player and camera rotation, so it's not what you want

true owl
#

So I'm still working on this camera shake but

#

i'm confused, when i first spawn in, the camera is already shaking and i need to dash to reset it

#
using UnityEngine;

using Unity.Cinemachine;
public class CinemachineShake : MonoBehaviour
{

    public static CinemachineShake Instance { get; private set; }

    CinemachineCamera cinemachineCamera;
    private float intensity;
    private float time;

    private float shakeTimer;

    void Start()
    {
        Instance = this;
        cinemachineCamera = GetComponent<CinemachineCamera>();
    }

    public void ShakeCamera(float intensity, float time)
    {
        CinemachineBasicMultiChannelPerlin cinemachineBasicMultiChannelPerlin = cinemachineCamera.GetCinemachineComponent(CinemachineCore.Stage.Noise) as CinemachineBasicMultiChannelPerlin;

        cinemachineBasicMultiChannelPerlin.AmplitudeGain = intensity;
        shakeTimer = time;
        this.intensity = intensity;
        this.time = time;
    }

    // Update is called once per frame
    void Update()
    {
        if (shakeTimer > 0)
        {
            shakeTimer -= Time.deltaTime;
            if (shakeTimer <= 0f)
            {
                // Timer is done
                CinemachineBasicMultiChannelPerlin cinemachineBasicMultiChannelPerlin = cinemachineCamera.GetCinemachineComponent(CinemachineCore.Stage.Noise) as CinemachineBasicMultiChannelPerlin;

                cinemachineBasicMultiChannelPerlin.AmplitudeGain = Mathf.Lerp(intensity, 0f, 1 - (shakeTimer / time));
            }

        }
    }
}
rancid tinsel
#

there is some easy simplification here that I'm just not remembering could someone point me in the right direction

wintry quarry
#

or... really I guess I would just get rid of the second if entirely here

rancid tinsel
#

yeah ig its kind of useless

wintry quarry
#

There's no circumstance in which it should be null by then right?

wintry quarry
#

And if it is, we would want an error message

#

rn there will be no error if it is, which may be confusing

rancid tinsel
#

i was more referring to the inputActions bit tho, i really dont like calling it by name especially since its a group project

wintry quarry
#

You could just directly reference it instead of using Resources.Load

rancid tinsel
#

could you elaborate? as in via inspector or?

wintry quarry
#

yes

rancid tinsel
#

ah okay ill try that

wintry quarry
#

And if you mean the .FindActionMap and FindAction stuff - you could use the generated C# class instead

rancid tinsel
#

oh yeah i forgot about the generated class

wintry quarry
#

there's a slight simplification you can do with the current method though:

inputActionsAsset["Command/MoveTo"].performed += ...```
rancid tinsel
#

i did some stuff with the input system a while back but im just jumping into it again on a new project and its like my mind is blank lol

knotty quail
#

Zenject simply doesn't work, I tried through various methods, tried to fix it with the gpt chat but nothing helped, does anyone have a solution?

swift crag
#

what does "doesn't work" mean?

#

please share your !code properly, too

eternal falconBOT
timber tide
#

Tags dont exist I dont know what you're talking about

ripe shard
#

Tags are (almost) useless; for everything they do, a better option exists. layers are for performance critical filtering. Tags are like an unlimited number of layers. The name ‘tag’ is misleading since each object can only have one tag.

timber tide
#

Interfaces will always be the better identifier

polar acorn
#

Tags have no use case outside of your own code. Nothing internal will actually use them.

Layers are another case, there are a few layers that Unity provides that have some built in functionality, such as the IgnoreRaycasts layer which, as the name suggests, ignores raycasts, or the UI layer, which is what a canvas defaults to displaying and ignores everything else.

#

You can add functionality to either of them in your code by checking tags with CompareTag, or by using LayerMasks for things like physics queries

ripe shard
polar acorn
#

It's just that there are some layers that come with some baggage built in

ripe shard
#

You put everything on default until you have a functional reason not to.

timber tide
#

The ultimate problem with tags is that you can only have one per object

ripe shard
timber tide
#

otherwise I would probably use them if I felt lazy enough not to include my own bitwise enum indentifiers

polar acorn
#

Unless you've specifically coded some physics queries to look for specifically Interactable or Ground, they're the same

ripe shard
#

I would encourage anyone to not use layers for identification, only for performance oriented filtering

polar acorn
#

This OverlapSphere will only detect colliders on objects with the "Interactable" layer

#

What is the specific problem? Is the issue that the OverlapSphere is detecting things that don't have the layer "Interactable", or that there are "Interactable" objects the overlap sphere isn't picking up?

#

Well, have you told it anywhere not to do that?

#

Okay, and what does GroundLayers do?

timber tide
#

In your screenshot you've also got "Exclude Layers"

polar acorn
#

What does that "checkIfGrounded" function do, exactly?

timber tide
#

Since every new gameobject defaults to that I would just make a dedicated layer

#

There's also a matrix where you can set the layer interactions for physics in the settings instead of setting it independently per body

polar acorn
#

I believe if you set the exclude layers to "Everything" then specifically un check the one layer, it'll automatically mark new layers as excluded as you make them

timber tide
#

if you want to go about it the opposite way and just use "Include Layers" then turn off all physics interactions in the matrix and use that property instead

polar acorn
#

There's actually always 32 layers, even if you haven't made them yet. Setting it to everything will mark those even if you can't see them

knotty quail
#

Ping me pls if you answer

#

Half an hour to copy it there UnityChanFrustrated

austere crypt
#
        {
            CellClass cellClass = new CellClass();
            return cellClass;
        };

        itemDeck.bindItem = (element, i) =>
        {
            element.dataSource = inventorySettings.Types[i];
            
            ListView listView = element.Q<ListView>("EListView");
            if (inventorySettings.Types[i] == null)
            {
                inventorySettings.Types[i] = new ObjectData();
            }
            
            listView.itemsSource = inventorySettings.Types[i].paths;
            listView.makeItem = () =>
            {
                return new FloatField();
            };
        };

why floatfield not being add in ElistView (on ui )?

gloomy cosmos
#

Hello, what's the easiest way to get a LateFixedUpdate going?

north kiln
verbal dome
ripe shard
gloomy cosmos
#

sometimes you wanna make sure some positions are set before you do other stuff like custom collision

ripe shard
gloomy cosmos
#

it's unneccessary delay

ripe shard
#

Easiest would be to use UniTask, it has timing hooks for that kind of thing

gloomy cosmos
#

anyway I just thought of a way to do the thing I need to do, positions are batched already so some sort of manager that calls position updates, then collision checks will work

verbal dome
#

I always prefer managing stuff like this manually yeah

slow thunder
#

in 2d, how can i create a freecam system like in the editor, but using scripts and inside the play mode?

knotty quail
ripe shard
ripe shard
ripe shard
#

it would be the same, trivial to adjust in any case

vagrant lynx
# wintry quarry > The player rotates with the rotation of the camera For this, instead of using ...

Hey, I somehow managed to do this thing without losing the free look cam, I deleted my move script and used a 2D blend tree with root motion enabled. So, the character is moving according to the input and also not rotating when I press "a" or "d"
And then just assigned the camera's eulerAngles.y to transform.rotation

Well I needed the cinemachine camera for applying some shakes later.
It's working but what do you think I should have done? I mean what's the better way? Creating a new script for camera and player?

wintry quarry
vagrant lynx
#

Which one to use then?

vagrant lynx
noble sigil
#

ive made 2d games before but im working on my first 3d project and i honestly have no idea what im doing haha. i made a model for a character and am just trying to do basic movement but when i use controls on him, his body splits into two separate parts going different speeds. i made this script for him but i cant figure out why he splits like this. is this a model issue? or am i doing something wrong in the code?

{
    public float speed = 5f; // Movement speed

    void Update()
    {
        float moveX = 0f;
        float moveZ = 0f;

        if (Input.GetKey(KeyCode.W)) moveZ += 1f;
        if (Input.GetKey(KeyCode.S)) moveZ -= 1f;
        if (Input.GetKey(KeyCode.A)) moveX -= 1f;
        if (Input.GetKey(KeyCode.D)) moveX += 1f;

        Vector3 move = new Vector3(moveX, 0f, moveZ);

        if (move.magnitude > 1f)
        {
            move.Normalize(); // Ensures diagonal movement speed is the same as straight movement
        }

        transform.Translate(move * speed * Time.deltaTime, Space.World);
    }
}```
sorry if i interrupted
rich ice
#

discord cant embed mkv files

west radish
#

in obs, change the export setting from .mkv to .mp4

#

@noble sigil

noble sigil
#

my bad 😭 i had to clean install windows and it wiped my settings

rich ice
west radish
#

its only mkv because its the default format obs saves recordings as

#

ooh I misread

rich ice
#

thus is why the remux recordings option is even there

noble sigil
#

does it not let you see the mkv file?

#

oh i guess i see what you mean

west radish
#

we can, it just doesnt embed

noble sigil
#

lemme rerecord it rq thank you

west radish
rich ice
#

its cumbersome to change it back and forth in the settings. im sure this person is planning to use OBS in the future too

west radish
rich ice
west radish
#

oh thats weird, downloading that .mkv file saved it as .mp4

noble sigil
#

this is whats going on for me

#

this is why i stick to 2d

west radish
#

how odd

noble sigil
#

right? nothing in my script should impact the rate of individual meshes i would think but...

timber tide
#

it's a feature

rich ice
#

you probably just placed the movement script onto multiple objects

noble sigil
#

its crazy how obvious that was thank you so much

#

hes in one piece now 🙂

true owl
#

does anyone know how to cut off the particle emitter

#

i want it to stop where my cone ends

rich ice
#

not a code question

#

also just lower the lifetime

true owl
#

oh mb

rich ice
true owl
#

that'd do it thx

late burrow
#

can i exclude 0 values from json

wintry quarry
#

Remember JSON is just a data format

verbal dome
wintry quarry
#

you can do whatever you like

late burrow
#

yeah i wanted do something like exclude default values

true owl
#

public class ParticleEmission : MonoBehaviour
{

    [SerializeField] ParticleSystem dustParticles;
    private Rigidbody2D parentRb; // gets the rigidbody of the parent aka the player
    private CapsuleCollider2D capsuleCollider2D;
    void Start()
    {
        parentRb = transform.parent.GetComponent<Rigidbody2D>();
        capsuleCollider2D = transform.parent.GetComponent<CapsuleCollider2D>();
    }
    void Update()
    {
        bool isTouchingEmissionLayers = capsuleCollider2D.IsTouchingLayers(LayerMask.GetMask(ScStrings.groundLayer)) || capsuleCollider2D.IsTouchingLayers(LayerMask.GetMask(ScStrings.railLayer));

        Debug.Log(isTouchingEmissionLayers);
        Debug.Log(Mathf.Abs(parentRb.linearVelocityX) > 1);
        if (Mathf.Abs(parentRb.linearVelocityX) > 1 && isTouchingEmissionLayers)
        {
            dustParticles.Play();
        }
        else
        {
            dustParticles.Stop();
        }
    }
}

#

not sure why the particle effects aren't playing both of the Debug.Log's are outputting true as expected

simple hawk
#

Came up with an idea for creating a passenger system for a taxi game, let me know if it's feasible/needs adjustments: player gets to passenger, script for player to interact with passenger, adds +1 to passenger count (thinking I might add a limit to this so player can only pick up 1 passenger at a time), this also destroys the game object/
Passenger.

#

Also an area where player drops off passengers, basically checks passenger count and -1 to it

rich ice
simple hawk
#

Just wondering what stuff I'd use for the code, I'm very new to coding and only know a few things. I know I'd use variable for the passenger count; could I use an if statement and a trigger to do the picking up passengers thing?

upper yoke
#

Hey, is there a way to use SceneManager.LoadScene but without using the scene list in the build settings?
I have a project with a lot of them and I would like to do something like passing them in parameter of my script or something, if it's possible

wintry quarry
rich ice
naive pawn
astral falcon
wintry quarry
upper yoke
#

Yeah I would rather avoid adding them there
I'm making a game with lot of minigames and each minigame is a scene added additively, but linking everything in the scene list is a bit annoying

simple hawk
rocky canyon
wispy wraith
#

!code

eternal falconBOT
upper yoke
rich ice
# rocky canyon how so?

i can see it getting annoying when you've got hundreds of scenes or something. since you can barely organise them in the scene list. thats the only real case i can think of though

upper yoke
astral falcon
upper yoke
naive pawn
upper yoke
#

So I'm trying to make tools so it can be as simple as I can for them

naive pawn
#

ah, ok, "people" was kinda vague there and it kinda sounded like you meant players lol

upper yoke
#

Yeah my bad :p

astral falcon
upper yoke
#

I'm thinking maybe use the GitHub above so they can reference the current scene of the minigame inside a scriptable object where other metadata about the minigame would be, and then doing that yeah :)

astral falcon
upper yoke
marble turret
#

Is there a way to require a serialized Scriptable object field (exposed through the inspect) to implement a certain interface when assigning it in the inspector?

night mural
proper needle
#

when my player goes through portal with all of the coins and a key, nothing happens

hollow zenith
#

Seems like I Have 2 folders, one for Unity and another for Unity 2022

#

But neither of them works with the above

hollow zenith
#

in C:\Program Files

#

following the above guide

#

either way, both folders give me same result

grand snow
#

open task manager to check if you put it in the correct editor installation? (it can show the path of a process)

hollow zenith
#

do I really have to set templates for each specific unity version?

astral falcon
#

You could just use unity hub

hollow zenith
#

Based on what I Found my installations are in:

C:\Program Files\Unity\Hub\Editor\6000.0.24f1\Editor\Data\Resources

But the guide says:

Windows:.C:\Program.Files\Unity\Editor\Data\Resources\ScriptTemplates
#

Is the guide outdated?

#

tbh I have resource folder in all of these folders

astral falcon
#

I highly suggest you go through !learn instead of some random tutorial

eternal falconBOT
#

:teacher: Unity Learn ↗

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

hollow zenith
#

This is not a random tutorial, it's from Unity website

proper needle
astral falcon
#

Randomly chosen I mean. You seem not to be familiar with the basics yet, so it would be more useful to go through the beginning tutorials before an ebook on a specific sub topic

astral falcon
hollow zenith
astral falcon
astral falcon
hollow zenith
#

Thats why I asked here, I am asking someone that knows how to do it.

astral falcon
#

I mean, the guide you have is obvious. Place your file in the template folder of the version you want to use it with

astral falcon
# proper needle

thats just resetting the player to start position. Seems like you should go to the basic tutorials, because you cant find your spot in the code where you move your player.

hollow zenith
#

The guide doesnt say that, it points to this folder:

Windows:.C:\Program.Files\Unity\Editor\Data\Resources\ScriptTemplates

Which is not version specific, version specific folders are elsewhere, I would suspect that it would work for all versions otherwise why is it even here?

#

Something has changed between Unity\Hub and Unity\Editor at some point I guess

astral falcon
astral falcon
# proper needle

Looks fine so far. You should Debug.Log all your if statements, to check if they are met

hollow zenith
#

script templates folder is everywhere, both in hub and editor folders.
Hub has version specific and editor is for everything I guess, cant tell as it doesnt have a version

#

it is 5 years old tho, so maybe its no longer used 😄

astral falcon
#

I would remove all not hub related installations and go along with hub 😄

hollow zenith
#

Unlucky, I'd have to set templates manually for each version.
There is a way to automate it tho, but by trying to "save" time I will waste more of it automating the process than simply not having a template lol

#

Guess it's fine for larger teams, but not for me 😄

astral falcon
#

why for each version? If its for one project, you can even place it in the projects folder

hollow zenith
#

Yeah I know that, but per project is even worse 😄

astral falcon
proper needle
astral falcon
proper needle
proper needle
proper needle
proper needle
north kiln
# proper needle

Is your IDE configured? That looks like a lack of highlighting that would indicate to me it isn't.
You should have errors underlined in red and advanced autocomplete if it's working correctly

north kiln
#

!ide

eternal falconBOT
proper needle
proper needle
north kiln
#

If you're using VS2022 then that step looks already valid?

#

If you're not, then you'll need to browse to your IDE's executable

proper needle
#

@astral falcon u still online?

simple hawk
#

How do I get my code to check if a variable is equal to a specific number? Asking cuz I know that there's a difference between == and =, so wondered which one to use

#

Oh, thnx

night mural
#

you could make worldspace canvases and place them in the world if you want it to be UI, or you can always just make an object with a textmesh and a SpriteRenderer and put it in the world that way

#

I don't know what your game is, but the simplest thing is probably to have your 'items' each include a worldspace canvas as part of them

grand snow
#

the real solution is to detect the object via say a raycast and in you UI reveal some UI element and you move it to follow the world position
you can convert from world to pixel space via camera.

#

ofc you will keep updating the ui objects position to follow the object until you decide to hide it.
Yes overlay mode.

rocky canyon
#

its gonna take some tuning...
lots of tuning.. u need to have good offsets.. u need to have it face the camera..

#

theres a few other things i uneed to do to

grand snow
#

You could have the "X to pickup" thing in world but id advise against unless you desire it to appear like its really in 3d space.

#

Yea ideally your system that detects things you can pickup can somehow report an item is able to be grabbed so your UI can show this info and follow until this state changes.

#

That to me is the "jank" solution because ofc it can be hidden or stick into stuff accidently soo easily.

#

there is a component to make something look at something

#

if you wanna do the jank way so be it 🤷‍♂️

#

i did warn you 😆

hollow zenith
grand snow
#

with that way you can use world to screen point and set the .position of your ui element and it will work

#

line count isnt really a good way to judge code

night mural
#

yep, in practice it probably doesn't matter for most things, but if that solution makes sense to you then it's probably cleaner

whole ivy
#

Is anyone able to help me out with a small problem that I ran into?

ripe shard
#

The world canvas approach is perfectly fine. Neither is more performant than the other. If you care about performance, don’t use canvases at all.

night mural
#

well you're still going to have to process all of those things to figure out which ones to display in your overlay canvas

ripe shard
#

Tutorials are never doing the things that are right for your project.

#

They do what’s right for a tutorial.

#

And one truth about tutorials is that real solutions would never fit into a tutorial.

night mural
#

yeah, and now every interactable also needs to be a physics object. Which is fine, and maybe makes sense for other reasons for your game! Again, I think your solution is a good one. But I wouldn't worry that much either way

ripe shard
#

That’s still only a jumping off point.

whole ivy
#

Hopefully someone can help with this:
I have a GameObject, ButtonU, and I have a public variable that is set to ButtonU in a separate script. I want to access the 'isPressed' variable that is part of ButtonU, but I am not sure how. How would I do this?

ripe shard
#

Not a performant one. Physics is the best thing for anything related to spatial lookup that you get in unity. You would have to do a lot of work to improve on it.

whole ivy
night mural
#

There's always a different way. Like Anikki said, I'm not sure I'd recommend any offhand, but everything is dependent on your game. If your game already has a chunk or room-based location system and the player is in distinct 'zones', you can tie items to their location and query them that way. If the player is only 'allowed' to interact with certain items and you already need to keep track of that, you can reference/activate those directly. etc etc.

ripe shard
#

Whatever you do, consider that spatial lookup (colliders and such) are a very intuitive, easy to understand way to organize a world. If your game is one where you walk around in a world, you can simplify many things by simply using space to separate and group things. Going down the symbolic route is often only neat in the beginning. Though it can be fantastic but you need a lot of experience to make the right decisions early on when you don’t yet fully understand what you need.

#

Space (noun):
the dimensions of height, depth, and width within which all things exist and move

night mural
#

(compared to, say, a card battler, where there is no real 'location' within which everything exists from the perspective of the game)

frigid sequoia
#

Let's say I want like entities to be able to have like status effects in sorta of like you have X effect for Y seconds AND this can be stacked (or reset the duration) and removed by external means. Would it be a good idea to make it like a separated script that I can attach to the entity for a given time and then remove itself when it is gone?

night mural
#

up to you, basically you have an ID for the effect and a stack count (and duration if those are not the same in your game). Then I would either do it OOP style where you have 'auras' which have OnApply/OnTick/OnRemove handlers, or 'systems' style where the auras are just data and you check for the relevant ones at the proper times

#

in either case you'd probably want one script which handles storing active auras for a given entity

#

you could also do it your way, but you'll run into issues where you need to do things like 'check if an aura is active and add stacks to it instead of attaching a new aura component' and it's nice to be able to write your own code for that instead of relying on the component system

frigid sequoia
#

Well, adding a stack would pretty much just mean adding a new instance of the script and removing them all or just one depending of the case if I do it in that way

sudden grove
#

hi guys! im making a breakout project for uni, and im trying to get the ball to bounce back in a random direction back at the player, but only for the first bounce cause once the direction is offset, it'll reflect like normal off of everything else

#

this is my orb behaviour code !

barren harbor
#

How they make NPCs walk around and talk to main character? what is the best method to achieve this

wintry quarry
#

both of your if statements have:
&& !collision.gameObject.CompareTag("Player")

#

so you are never handling player collisions

#

(ps you don't need the .gameObject there)

sudden grove
#

hold on lemme reread this, ive had some help from AI and im very very very tired just trying to get this last feature added lol

wintry quarry
#

Seems like yes you need to basically just reread your code carefully because the logic isn't right

sudden grove
#

cause im not trying to do anything when it hits the player

#

im trying to do it when it hits ANYTHING else

#

so the process should look like this

wintry quarry
sudden grove
#

shoot - first bounce from ball - random direction back at the character - disable the random logic until the next fresh ball - ball will reflect off of everything normally

wintry quarry
#

or actually - if I know breakout- the reflection angle should be based on which part of the paddle you hit

#

unless you're not doing that part

sudden grove
sudden grove
#

im trying to do my own 3d spin on it for the project

wintry quarry
sudden grove
#

heres some visual context as to how this looks

wintry quarry
#

shouldn't it just be:


bool firstBounce = false;

void OnCollisionEnter(Collision collision) {
  if (!firstBounce) {
    // bounce in a random direction
    firstBounce = true;
  }
  else {
    // do the normal reflection logic
  }
}```
#

it doesn't make sense to me that you're doing any tag checking

#

Isn't the first hit always going to be a wall?

sudden grove
wintry quarry
#

How could the first hit ever be a player?

wintry quarry
#

ChatGPT is not magic

#

you can read and understand the code

sudden grove
#

its a mixture of both atm, I promise I will start actually understanding the code though

wintry quarry
#

Like - it should be setting off alarm bells in your head if you see this:

        // For subsequent hits (wall or player), reflect the velocity normally
        if (!firstBounce && !collision.gameObject.CompareTag("Player"))```
#

The comment says "wall or player"

#

but the if statement specifically excludes the player

sudden grove
#

yeah that would make alot of sense

#

i did read that tbf but thought nothing of it for some reason

#

im probs just missing things cause its late

wintry quarry
#

The other thing you should be doing is adding Debug.Log statements in your code

#

printing things like the tag or name of the object you hit and which code path you're going down

#

then you can reason about what's actually happening and going wrong in the code

sudden grove
sudden grove
#

would it work to have sorta rounded/slightly elongated shapes as colliders so it just changes the direction?

calm adder
#

!vs

eternal falconBOT
#
Visual Studio guide

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

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

buoyant thistle
#

how could i change a vairble of a TMP text from another object/script

acoustic sequoia
#

why is this not working? after reading everything idk why the viewcone is 90 degrees off?

public static void ViewCone(float radius, float viewInDegrees, Transform transform) {
            var rotationRadians = transform.rotation.eulerAngles.z * Mathf.Deg2Rad;

            var halfFOV = viewInDegrees * 0.5f * Mathf.Deg2Rad;
            var leftDirection =
                new Vector3(Mathf.Cos(rotationRadians + halfFOV), Mathf.Sin(rotationRadians + halfFOV));
            var rightDirection =
                new Vector3(Mathf.Cos(rotationRadians - halfFOV), Mathf.Sin(rotationRadians - halfFOV));
            Line(transform.position, transform.position + leftDirection * radius, Color.yellow);
            Line(transform.position, transform.position + rightDirection * radius, Color.yellow);
        }
wintry quarry
#

What are you expecting?

acoustic sequoia
wintry quarry
#

cos(0) is 1

#

sin(0) is 0

acoustic sequoia
wintry quarry
#

so at angle 0 radians you will get (1, 0)

#

which is the red axis (x axis)

#

so it seems perfectly correct for your code

acoustic sequoia
wintry quarry
#

add 90 degrees or PI / 4 radians

acoustic sequoia
#

to both the left and the right ?

wintry quarry
#

you could also drop the trigonometry and do this:

Vector3 forward = transform.up;
Vector3 leftDirection = Quaternion.Euler(0, 0, -halfFov) * forward;
Vector3 rightDirection = Quaternion.Euler(0, 0, +halfFov) * forward;```
wintry quarry
#

which will apply to both yes

wintry quarry
acoustic sequoia
#

like this?

public static void ViewCone(float radius, float viewInDegrees, Transform transform) {
            Vector3 forward = transform.up;
            var halfFOV = viewInDegrees * 0.5f;
            Vector3 leftDirection = Quaternion.Euler(0, 0, -halfFov) * forward;
            Vector3 rightDirection = Quaternion.Euler(0, 0, +halfFov) * forward;


            Line(transform.position, transform.position + leftDirection * radius, Color.yellow);
            Line(transform.position, transform.position + rightDirection * radius, Color.yellow);
        }
wintry quarry