#💻┃code-beginner

1 messages · Page 501 of 1

silk night
#

do you have a material assigned to the second slot visually in the inspector?

frozen plaza
#

idk what I changed but it works now

#

thank you anyway, I appreciate the help

bright arch
#

is there any way for a gameobject (not ui) to, on pointer enter, get an outline? the outline component doesnt show anything up for me...

alpine yarrow
#

It keeps saying my code has a error

devout flume
#

Because a semicolon is a statement on its own

alpine yarrow
#

Fixed

#

It isnt

#

Dang

polar acorn
alpine yarrow
#

Idk how but I was using a 2yo vid so I deleted the code

bright arch
#

if you dont give any details on what youre doing or what error it shows, no one can help x)

polar acorn
#

Unless it's got to do with render pipeline code or networking, code from 2 years ago is going to be mostly identical

mystic dawn
alpine yarrow
#

It's already gone sorry if I have a new error I will send it

limber robin
#

Hi, I'm trying to use OnTriggerEnter2D and having an issue. I want the OnTriggerEnter2D to be called when the player partially exits the area and then re-enters, but it seems that the function is only called again when the player fully exits the area and re-enters. Is there any solution to this?

vestal isle
#

How would I load an image using relative path to use in an EditorWindow script?
Say if I move the Editor folder, then it wouldn't be able to load the file
Currently I use AssetDatabase.LoadAssetAtPath<T> but it doesn't seem to accept relative path

polar acorn
astral falcon
limber robin
#

I just have 2 touching zones and I want a distinct function to happen every time the player moves from one zone to the other, I just don't know how to handle the player going from zone 1 to zone2, then going back to zone 1 before they ever fully exited

#

like they could just stick their front toe in zone2, then go back the way they came

verbal dome
#

Could use OnTriggerStay and check if the character's position is inside the collider

limber robin
#

Okay I haven't heard of ontriggerstay I'll look into that

polar acorn
hallow sun
limber robin
#

but since i was using OnTriggerEnter2D it DOES activate from the toe entering

polar acorn
limber robin
#

I'd like for it to just count as being in 1 zone

verbal dome
#

Could also store the zones in a stack.
Enter zone1 -> Push zone1 to the stack
Enter zone2 -> Push zone2 to the stack
(Zone2 is now considered the current zone it's on top of the stack)
Exit zone2 -> Pop zone2 from the stack
(Zone1 is now considered the current zone because it's on top of the stack)

polar acorn
verbal dome
#

^Yeah, same idea

wild tartan
#

i want to creat a 2d game like hollow knight 0 experience anyone got tips or a tutorial for me to watch

eternal falconBOT
#

:teacher: Unity Learn ↗

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

limber robin
#

you too Osmal

#

And Faywilds

lethal swallow
valid turtle
#
public void PlayGame()
    {
        SceneManager.LoadScene("SampleScene");
    }

For some reason I cant use the playbutton to go to the other scene. Anyone knows why?

rich adder
valid turtle
#

How would I get that?

#

/ when

rich adder
valid turtle
#

And I add that to the Button right?

rich adder
#

just the root of the scene

valid turtle
#

Thank you alot

#

Confusing why that isnt created automatically on a new scene but whatever

rich adder
stuck palm
#

can you create a sorting layer for 2d objects on a 3d space? i want my 2d shield sprite to be on top of my 3d player model/.

rich adder
stuck palm
#

yeah sorry you told me this yesterday

#

will look into that

#

i just thought sorting layer would be easier if that existed

polar acorn
swift pilot
#

yo guys

#

what does this purple box represent

#

before the text

rich adder
#

if you can mess with shadergraph maybe you can do it there with DepthTexture ? Im not sure tbh this is more shader related

turbid robin
#

i created a code that should create this text in this panel, but the text get created in an invisible position from the game, the code is:

private void UpdatePlacementUI(bool show)
{
    if (show)
    {
        //set the UI elements when showing
        if (placingText == null)
        {
            placingText = Instantiate(placingTextPrefab, placingPanel);
            placingText.GetComponent<TextMeshProUGUI>().text = "You are placing: " + selectedCharacter.UnitName;
        }
        else
        {
            placingText.SetActive(true);  //show existing text
            placingText.GetComponent<TextMeshProUGUI>().text = "You are placing: " + selectedCharacter.UnitName;
        }

        if (placingImage == null)
        {
            placingImage = Instantiate(placingImagePrefab, placingPanel);
            placingImage.GetComponent<Image>().sprite = selectedCharacter.Sprite;
        }
        else
        {
            placingImage.SetActive(true);  //sshow existing image
            placingImage.GetComponent<Image>().sprite = selectedCharacter.Sprite;
        }
    }
    else
    {
        //destroy
        if (placingText != null) placingText.SetActive(false);
        if (placingImage != null) placingImage.SetActive(false);
    }
}```
polar acorn
rich adder
turbid robin
turbid robin
#

the box you can see in the screen

rich adder
#

if its off you have to check the pivots n rect transforms. Not really code question if its working btw

lethal elbow
#

Need a bit of help with a simple rotation, Currently trying to add a clamp and make it so the rotation doesn't reset with a new button click. It's based on mouse position on screen but the cube resets it's rotation angle based on where I click on the screen

#
 if (Input.GetMouseButtonDown(1))
        {

            isRotating = true;
            startMousePosition = Input.mousePosition.x;

        }

        else if (Input.GetMouseButtonUp(1))
        {

            isRotating = false;

        }

        
        
        if (isRotating)
        {
            currentMousePosition = Input.mousePosition.y;
            mouseMovement = currentMousePosition - startMousePosition;
            
            transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);
        
            startMousePosition = currentMousePosition;

            currentMousePosition = Mathf.Clamp(transform.eulerAngles.x, -45, 45);
            Debug.Log(currentMousePosition);

        }
#

Here's an example of what I mean

wintry quarry
#

euler angles are not unique or consistent

#

you will be much better served by tracking the rotation in your own variable and clamping that

#

e.g.

float pitch = 0;

void Update() {
  pitch += Input.GetAxis("Mouse Y");
  pitch = Mathf.Clamp(pitch, -45, 45);
  transform.localRotation = new (pitch, 0, 0);
}```
#

also your use of mouse position and deltaTime doesn't make much sense

#

much better to use the Mouse Y axis which is a diff, and deltaTime doesn't belong there at all.

lethal elbow
tender stag
#

is setting something to false more important then true?

#

does false override true

rich adder
tender stag
#

this is in update, when im not aiming i keep setting the showCrosshair to true;

#

and if i set it to false in another script

#

would that override?

lofty sequoia
#

Is there a way to have 2 overlapping canvases receive a touch?

rich adder
tender stag
#

i did this

#

so when im aiming it keeps setting it to false

#

and when i stop aiming it just calls it once

#

in the AimOut()

lethal elbow
lofty sequoia
short hazel
# tender stag in the AimOut()

Setting it to false repeatedly in HandleAiming is pointless, if and only if AimIn() and AimOut() are the only two places isAiming is modified

rich adder
#

quaternion does not reach above 1

lethal elbow
#

Yeah I changed it

low lagoon
# tender stag

btw if u wanna make ur player manager interface nice and clean and spiff you can do:


class PlayerManager{

...

public static PlayerManager Instance;

...

public static void ShowCrosshair(){
    Instance.showCrosshair = true;
}

public static void HideCrosshair(){
    Instance.showCrosshair = false;
}

which allows you to: PlayerManager.ShowCrosshair(); instead of PlayerManager.Instance.SomeVariableIShouldntCareAboutButHaveToKeepTrackOf = a_value

tender stag
#

oh yeah i can use a static void for this

lethal elbow
low lagoon
#

but that's freaky

verbal dome
lethal elbow
#

I'm not able to move the cube with that code anyway if it's a replacement

verbal dome
#

And yeah no new in front of Quat.euler

rich adder
#

oh yeah I added new() mb

low lagoon
# tender stag would that override?

yes. You're better off creating a second variable if there's extra state to keep track of.

If another script needs to check "Can the player aim based on something other than "isAiming", then you do if (isAiming and ThisOtherThing)

#

then you can simply manage the state of isAiming from one place, and ThisOtherThing from the other place

verbal dome
obsidian granite
#

is there a way to make it so that raycasts don't hit certain objects without using layers? there are raycasts coming out from inside of a car, and i need the raycasts to not hit the collision inside of the car, but i want them to hit other cars.

low lagoon
verbal dome
#

Could also maybe temporarily disable your own car's colliders but that sounds a bit hacky

obsidian granite
#

can't change the implementation of the raycast

#

well i guess i could edit the code in the package? idk

verbal dome
#

What can you change?

#

I'm not familiar with ML tbh.

obsidian granite
low lagoon
# tender stag would that override?

for the record, there is no such thing as "overriding" a variable with some sort of priority or whatever. You're setting the memory slot to a value that is declared. Unless you're trying to modify the value of a variable in a struct after it's been initialized or something, in which case that value is set once and never changed.

verbal dome
#

Can you edit the car's colliders?

obsidian granite
obsidian granite
#

OH nvm the class that unity provides has a field for detectable tags

#

wait but then i have to create a tag for each car

#

can you create tags at runtime?

#

nope you cannot

#

shoot!

low lagoon
obsidian granite
low lagoon
#

Oh I see

verbal dome
#

Apparently they don't have much control over the raycast

obsidian granite
#

layers wouldn't even work

#

it's implemented by a unity package

#

so i can't provide a layermask

#

nvm it does take in a layer mask

low lagoon
#

oh there you go.

obsidian granite
#

but what do i do? just create like 16 tags "Car1, Car2, Car3..., Car16"

low lagoon
#

you could put the sensors on the outisde of the car :)

low lagoon
obsidian granite
low lagoon
#

thank god lmao

obsidian granite
#

the sensor on the object with the car's collision

#

and i have that one project setting that disallows raycasts from interacting with bodies that they originate from or something

#

idk the wording

#

nvm it's a physics2d thing onlyu

obsidian granite
#

like have 4 sensors on each side of the car that all cast forwards? because that sounds smart and i thank you for the answer.

low lagoon
#

if the sensors are components, stick them on child empty game objects and use the arrows to drag them out or something.

If they all cast forward, I would say put them in front of the car but (?)

obsidian granite
#

i just did this

#

four different sensors

low lagoon
#

there you go

#

it looks like the ML stuff is built for wrapping around a robot interface, almost, with the purpose of simulating agents in a way that it can be translated to IRL

true lava
#

may i ask gameobject problem here?

#

Basically i want my idle animation stays like that when i click M4

#

But it wont :(

timid ember
#

when i attach my code to the button, i cannot access my functions for reference

true lava
#

Objective = create rightclick aim

timid ember
#

but when i put my code in an empty gameobject and then put that gameobject as reference i can??

short hazel
#

Yes that is normal. One is the text file itself, the other an instance of the class on your object

short hazel
# true lava Objective = create rightclick aim

Seems like you've got an error in your console. I recommend fixing it even if it comes from another script, as exceptions stops code from running right away, which might cause issues in a related script.

dusty zinc
#

hey im making a top down 2d game and i was wondering if adding overlapping scenes at different scales would be a good way to add depth. the scene you're in always appears the same but everything else scales up or down from your perspective. should i even bother trying to code something like this?

timid ember
short hazel
#

Yes, as long as the script you're trying to reference from the button is in the same scene as the button

lethal elbow
# lethal elbow

I figured out my issue. Current Mouse position was based on Input.MousePosition.Y and was moving with Vector.right (X-axis). I no longer have a weird jitter now

#

I did not figure out my issue after all

low lagoon
short hazel
#

I got that

#

Exception handling and solving should always come first though

low lagoon
#

often times I have exceptions because of editor bugs that can be ignored

#

little things in editor gui's and stuff that never show up again (8

short hazel
polar acorn
timid ember
#

i was crying qbout the calculator 2-3 days ago

lethal elbow
#

Okay, now I've found out my issue. I need to do some clamping now

sand snow
#

how do i change the gravity strength of an object in 3d

low lagoon
wintry quarry
steep rose
polar acorn
#

I really should use it more

sand snow
steep rose
sand snow
#

rb

steep rose
#

then do what either praetor or naeve said

wintry quarry
polar acorn
sand snow
#

is add force (the impulse mode) bad for 3d?, my character kinda just teleports upwards

wintry quarry
sand snow
wintry quarry
sand snow
#

but no other code overwrites the velocity

wintry quarry
#

I don't believe you

#

Cna you show your movement code?

steep rose
#

show us the !code

eternal falconBOT
sand snow
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerJump : MonoBehaviour
{

    public float jumpForce;
    [SerializeField] private Rigidbody rb;
    

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>(); 
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(0, jumpForce, 0, ForceMode.Impulse);
        }
    }
}
wintry quarry
#

this is only jumping code

sand snow
#

oh it needs to be in the same code?

wintry quarry
#

I didn't say that

#

I just said you have other code that is overwriting the velocity

#

Likely that's your movement code.

steep rose
sand snow
#

oh okay then i think you are right

#

my y axis is set to 0

wintry quarry
#

Yes, I've seen this many times

sand snow
#

i will fix it

#

thank you

#

what does quaternion.identity do btw i saw something about it, is it just a fancy way to say 0?

low lagoon
sand snow
#

thank you

lost maple
#

Hi
how to make converter of string to cetrain-characters-lengthstring?
(it cuts my string if it longer than 7 characters or add spaces if initial string is shorter than 7 characters) please?

wintry quarry
#

(yeah using the two functions Sidia linked)

sand snow
#

wait why does GetKeyDown not work in FixedUpdate again?

frosty hound
#

Because it can be skipped during a frame.

#

Update runs every frame, fixed doesn't guarantee it.

sand snow
#

ohhh okay thank you

tender stag
#

is this way of doing this?

#

SetFOV will be used in update in other scripts

#

so i want to automatically set useNormalFOV to true if the SetFOV method isnt being called

polar acorn
#

What are you trying to achieve with this?

tender stag
#

in any script i want to be able to call a method where i pass in the fov i want and the duration to achieve it

#

and if the method isnt being called then run the logic in the UpdateFOV

polar acorn
#

useNormalFOV is going to be true at the start of every frame, and become false once the first thing calls SetFOV, which means that UpdateFOV will skip if it's called after one of these

tender stag
#

the HandleAiming is in update

polar acorn
#

Right now, it would sometimes be called before SetFOV is called, sometimes after, which is going to be inconsistent

tender stag
#

how about this

#

AimOut is called once

#

this would work

polar acorn
#

Probably better to have a script that allows you to set the target and time remaining, then have that function just always smoothdamp towards the target FOV. When the timer reaches 0, set the target back to the default FOV

#

That way if something else adds in a new FOV target, it'd also reset the timer to a specific value and smoothly move towards that new value

waxen adder
#

So I have this object placed on a custom grid. I would like to find the height of the object, specifically within a grid position, not for the whole object. So for example, the leftmost gridpoint would have a height of something like 1, but the height of the rightmost gridpoint would have something like 2. How would I do this?

Currently entertaining the idea of raycasting from the grid position, but curious to hear what others think.

polar acorn
polar acorn
waxen adder
wintry quarry
polar acorn
waxen adder
polar acorn
waxen adder
polar acorn
#

That's why you'd need to cast from above and cast downwards

waxen adder
polar acorn
#

Also, with layermasks, you can absolutely skip the "compute the highest point and cast from there" step, you can cast from way high up as long as you're sure the first thing it'll hit is what you're looking for, which you can do with a layer mask that excludes other stuff

hybrid tapir
#

is there a way to restrict enum options in the inspector based on a condition? like, you cant do animation A if the object isnt far enough away from the top boundary in like a box of rigidbody/box collider objects

eternal needle
lofty lintel
#

Hello, Im trying to add Actions of players. on click just punch but if clicks and hand collider touches object with resource tag then get resource.
I have this script added on Hand of the player.

  public string isHolding;
  private void OnTriggerEnter2D(Collider2D collision)
  {
      if (collision.tag == "Resource")
      {
          Debug.Log("touched Resource.");
      }
  }
#

I just want to know if going like this is a good practice, or what would be best practice which will be easy to modify later in a code.

#

I just want suggestion on how is a good way to make this mechanic. (stuff like if player is holding something then do this or if player hits resource then get resource if player hits enemy then deal damage etc.)

lofty lintel
wintry quarry
#

i.e.Physics2D. OverlapCircle/Capsule/Box

#

you can do that directly in the "punching" code without having to wait for a callback etc

lofty lintel
#

Alright I'll make the punching script right now and try that.

#

also, should I put punching script on the player's hand or on player itself.

wintry quarry
#

Most likely the player

lofty lintel
#

also where would I find this Physics2D overlapCircle and those example codes or documentation, I don't know how to exactly write code for that so

eternal falconBOT
verbal dome
#

I usually use google instead of the doc's own search

lofty lintel
#

also how would I uh... find every resource's points?

wintry quarry
lofty lintel
#

oh wait

#

I don't need to

wintry quarry
#

You would check at the position you are punching or whatever

#

it will tell you which object if any you hit

lofty lintel
#

and then check if whatever I overlapped

#

has tag whatever right?

wintry quarry
#

A layer mask would be better

lofty lintel
#

alright so layer mask.

wintry quarry
#

and a TryGetComponent

#

but yes you could use tags

#

a combination of layermask and either tags or TryGetComponent is typical

lofty lintel
#

also how would I make that overlap only check this part.

#

By this I mean, I see radius and point so

wintry quarry
lofty lintel
#

so wait it will only oh

#

If that specific collider touches something right?

wintry quarry
#

it will find any collider contained in the given layermask and position

lofty lintel
#

ok well how do I get specific point atleast

#

so I might build up other code on it I just don't rly understand how I can implement it now

#

like what vector should I put in the point parameter

#

and also what direction im putting here?

verbal dome
#

Try using the transform.right or .up of your arm object

lofty lintel
#

so connect my arm to the script first right

#

Physics2D.OverlapCapsule(playerRightArm.transform.position,new Vector2(4.5f,9f), playerRightArm.transform.up);

#

So will this work?

#

(I know i have to add other parameters too)

lofty lintel
verbal dome
#

Ah, you need to use the direction of the arm's capsule collider

lofty lintel
#

is this all in documentation?

#

or am i dumb and don't know how to use documentation

verbal dome
#

From that page you can see that direction is a member of CapsuleCollider2D

lofty lintel
#

Physics2D.OverlapCapsule(playerRightArm.transform.position,new Vector2(4.5f,9f), playerRightArm.GetComponent<CapsuleCollider2D>().direction, 0);

verbal dome
#

And its type is CapsuleDirection2D

#

It pretty much says everything there is to say about it

verbal dome
lofty lintel
#

Should I put 7 in that parametere?

verbal dome
#

eulerAngles.z

#

Z is the only angle that usually matters in 2D games

lofty lintel
lofty lintel
verbal dome
lofty lintel
#
    new Vector2(4.5f,9f),
    playerRightArm.GetComponent<CapsuleCollider2D>().direction,
    playerRightArm.transform.eulerAngles.z,
    LayerMask.GetMask("Resource"));```
#

I also want to add animation where collider going to move on left click ofc, so I'll create animation right now.

lofty lintel
verbal dome
#

Usually you can't but Unity made so that any UnityEngine.Object (colliders, components, monobehaviours) can be used as a bool to check if they exist

lofty lintel
#

Didn't quite get result I was excpecting...

lofty lintel
# lofty lintel Didn't quite get result I was excpecting...
private void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Debug.Log("Punched");
        //Left-clicked
        //punch logic.
        var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
            new Vector2(4.5f,9f),
            playerRightArm.GetComponent<CapsuleCollider2D>().direction,
            playerRightArm.transform.eulerAngles.z,
            LayerMask.GetMask("Resource"));
        if (collider)
        {
            Debug.Log("Collided with resource.");
        }
    }
    
}```
verbal dome
rocky canyon
#

Punched

#

yea explain the screenshot a bit if u care

lofty lintel
verbal dome
#

Btw why use new Vector2(4.5f,9f) when you can just use the collider's size

rocky canyon
#

expand on whats the result your expecting

#

or is it up there already?

lofty lintel
rocky canyon
#

what punched code look like?

#

why is it being called

rocky canyon
#

ohh i see its at top

lofty lintel
#

Basically I wanna create punching.

rocky canyon
#

and your Resource is tagged correctly? no misspellings

lofty lintel
#

I do wanna add it so it will be easy to modify later on when I add swords or something

lofty lintel
#

LayerMask.GetMask("Resource"));

verbal dome
#

Make sure that the child collider has the right layer too

rocky canyon
#

oh true true

lofty lintel
#

what child collider

rocky canyon
#

if there are any

lofty lintel
#

ye no there aren't

verbal dome
#

Maybe it's on the same object

rocky canyon
#

some people use a structure like

  • Object
    • Colliders
    • Graphics
#

that why we typically will include asking that

lofty lintel
#

oh so like putting them as a child

#

yeah well no I don't have it like that

verbal dome
#

Yeah but you don't need to in this case

rocky canyon
lofty lintel
#

ok so what maybe causing this

verbal dome
#

Maybe phys2D doesn't hit triggers by default?

rocky canyon
lofty lintel
#

so instead of Resource in layermask

#

I do what

#

remove that part fully?

verbal dome
#

I remember the tree's outer collider being a trigger

lofty lintel
#
if (Input.GetMouseButtonDown(0))
{
    Debug.Log("Punched");
    //Left-clicked
    //punch logic.
    var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
         playerRightArm.GetComponent<CapsuleCollider2D>().size,
        playerRightArm.GetComponent<CapsuleCollider2D>().direction,
        playerRightArm.transform.eulerAngles.z
        /*LayerMask.GetMask("Resource")*/);
    if (collider)
    {
        Debug.Log("Collided with resource.");
    }
}```
#

it did work like this

verbal dome
#

But I'm not sure if that bool is true or false by default (Unity pls add default values to docs)

lofty lintel
#

should I use tag?

verbal dome
verbal dome
#
        Debug.Log("Collided with resource: " + collider.name, collider);```
rocky canyon
#

u could do it directly before the call

rocky canyon
#

good

verbal dome
#

You can use that, I was just avoiding extra confusion lol

rocky canyon
#

string interpolation is the beeeze neeeze

rocky canyon
lofty lintel
#

just don't know unity lab

rocky canyon
#

we can't always assume people know what string interpolation is..

#

then its just an extra conversation

verbal dome
#

I'm also not american so I have a small delay when trying to find the dollar sign on my keyboard 🤦‍♂️

#

But Debug.Logs like these are temporary anyway so performance doesnt matter

lofty lintel
#

im not american so I have a small delay choosing words I should say

rocky canyon
#

i am american and i have neither of those problems

#

lol

lofty lintel
#

worked

rocky canyon
#

alrighty.. now we're getting some data

verbal dome
#

Wish I could do using € = $;

rocky canyon
#

get ur drunken E, C wannabe outta here

rocky canyon
#

i didn't get a chance to read up on it.. but it seemed something similar to that

#

Math symbols or something another

verbal dome
#

I did see a heated conversation about symbols yeah

lofty lintel
#
 private void Update()
 {
     if (Input.GetMouseButtonDown(0))
     {
         Physics2D.queriesHitTriggers = true;
         Debug.Log("Punched");
         //Left-clicked
         //punch logic.
         var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
              playerRightArm.GetComponent<CapsuleCollider2D>().size,
             playerRightArm.GetComponent<CapsuleCollider2D>().direction,
             playerRightArm.transform.eulerAngles.z,
             LayerMask.GetMask("Resource"));
         if (collider)
         {
             Debug.Log($"Collided with {collider.name}");
         }
     }
     
 }```
#

works now I think, now animation time.

rocky canyon
#

so it collides w/ Tree

#

but doesnt seem to think its a Resource

lofty lintel
#

it does

#

Look I added layermask

rocky canyon
#

ohh okay

#

i see i see

lofty lintel
#

Yes.

#

I just have one question

rocky canyon
#

welp, good work homie

lofty lintel
#

will animations break the code? (I will also animate collider so will it work like that?) and also how would I add animation so like when it clicks left click animation plays.

rocky canyon
#

How much wood could a wood chuck chuck if a wood chuck could chuck wood?

lofty lintel
#

wood

rocky canyon
verbal dome
rocky canyon
#

unless ur using a direct vector or something

#

then it shouldn't

lofty lintel
#

but I just realized one more problem.

rocky canyon
#

like it may be better to find the origin starting position of the arm

lofty lintel
rocky canyon
#

and get ur overlap from that

lofty lintel
#

So the tree has two colliders.

verbal dome
rocky canyon
#

instead of using the arm's actual position

lofty lintel
lofty lintel
rocky canyon
#

ahhh soo it was a trigger

lofty lintel
rocky canyon
#

i missed that info

lofty lintel
#

yes and the outer collider is trigger

#

And I do want it to work like that.

verbal dome
#

I only knew it was a trigger because I helped Qvabbyte implement "squishy trees" the other day

lofty lintel
#

I called it smoothnes behaviour idk why xd

rocky canyon
#

like squash and stretch?

lofty lintel
#

Like going inside tree

#

and it forces you out

verbal dome
#

Nah, just softly colliding/pushing out of the tree if you stop in it

rocky canyon
#

ive never been inside a tree

lofty lintel
verbal dome
#

Well we could say "under" the tree's branches

lofty lintel
#

but come to think of it

rocky canyon
#

well, find the colliders center point..

lofty lintel
#

and then range?

rocky canyon
#

cache that as an offset to the transform.position

#

range?

verbal dome
rocky canyon
#

interesting

lofty lintel
#

only inner collision

verbal dome
#

Show the inspector of the tree with both colliders and layer visible

lofty lintel
#

ok no

#

it does.

#

Im tripping wth

#

I just couldn't really realize because

#

When i tried to collde

#

well we have a script on a tree for that squsihiness right

#

which pushed me out before I clicked.

#

so it does work, I'll just make hand collider larger.

tender stag
#

how can i access this field

#

through code

#

i need to be able to change it

verbal dome
#

You checked the docs right

#

...Right?

tender stag
#

of a renderer?

#

i couldnt find it

verbal dome
#

What did you search

tender stag
#

renderer urp unity docs

verbal dome
#

That's the type

lofty lintel
#

I think it doesn't work when the animation plays...

tender stag
#

still doesnt tell me how to access it

#

i got the properties

verbal dome
lofty lintel
#

yes

#
 {
     if (Input.GetMouseButtonDown(0))
     {
         animator.SetTrigger("Punch");
         Physics2D.queriesHitTriggers = true;
         //Debug.Log("Punched");
         //Left-clicked
         //punch logic.
         var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
              playerRightArm.GetComponent<CapsuleCollider2D>().size,
             playerRightArm.GetComponent<CapsuleCollider2D>().direction,
             playerRightArm.transform.eulerAngles.z,
             LayerMask.GetMask("Resource"));
         if (collider)
         {
             Debug.Log($"Collided with {collider.name}");
         }
     }
     
 }```
verbal dome
#

You can either use animation events to trigger the check from the animation

#

Or start a coroutine when you punch and check it for a few frames

#

So put everything after the SetTrigger into its own method and use either of the above to call it

lofty lintel
#
 private void Update()
 {
     if (Input.GetMouseButtonDown(0))
     {
         animator.SetTrigger("Punch");
         checkCollision()
     }
     
 }

 private void checkCollision()
 {
     Physics2D.queriesHitTriggers = true;
     var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
          playerRightArm.GetComponent<CapsuleCollider2D>().size,
         playerRightArm.GetComponent<CapsuleCollider2D>().direction,
         playerRightArm.transform.eulerAngles.z,
         LayerMask.GetMask("Resource"));
     if (collider)
     {
         Debug.Log($"Collided with {collider.name}");

     }
 }```
#

There u go

tender stag
#

someone did this

dry geyser
#

anyone know why im getting this error?

tender stag
lofty lintel
lofty lintel
#

like should I stop coroutine when it detects the collision?

polar acorn
dry geyser
#

mk

verbal dome
#

And you have full control of how often it checks

lofty lintel
polar acorn
# lofty lintel How would I do that tho xd
Unity Learn

Coroutines are a way of performing an operation over time instead of instantly. They can be useful, but there are some important things you need to be aware of when you use them to avoid inefficiency in your game or application. By the end of this tutorial, you’ll be able to: Explain what a coroutine is and how they work. Determine when it is a...

carmine skiff
#

i need to refactor some of this code so more is not done on update else performance is going to die now i need to remember how to set up events
because i dont think its a good idea for me to update my ui every frame Especially as that UI is just for seeing if i can interact with something but then again idk if events is what i need as it constantly needs to check the overlaps sphere to see if i can interact with something

tender stag
#

i got this so far

#

how can i access the Field Of View?

#

i got a reference to both of the render objects

#

but there isnt a .overrides

lofty lintel
#

Is this valid?

 private void Update()
 {
     if (Input.GetMouseButtonDown(0))
     {
         animator.SetTrigger("Punch");
         StartCoroutine(CheckCollision());
     }
     
 }

 private IEnumerator CheckCollision()
 {
     Physics2D.queriesHitTriggers = true;
     var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
          playerRightArm.GetComponent<CapsuleCollider2D>().size,
         playerRightArm.GetComponent<CapsuleCollider2D>().direction,
         playerRightArm.transform.eulerAngles.z,
         LayerMask.GetMask("Resource"));
     if (collider)
     {
         StopCoroutine(CheckCollision());
     }
     else
     {
         yield return null;
     }
 }
#

can I like stopCoroutine inside coroutine?

polar acorn
# lofty lintel can I like stopCoroutine inside coroutine?

So, play through this in your head, assume you can. If you press 0, you start a coroutine. This coroutine does a raycast, and if it hits, you stop the coroutine. Otherwise, you wait a frame and then stop the coroutine. Does that actually do anything?

lofty lintel
#

yield return null; waits a frame and stops coroutine?

polar acorn
#

There's nothing after that

#

so the coroutine ends because it just runs out of things to do

lofty lintel
#

How about this then.

#

Recursion

#
 {
     Physics2D.queriesHitTriggers = true;
     var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
          playerRightArm.GetComponent<CapsuleCollider2D>().size,
         playerRightArm.GetComponent<CapsuleCollider2D>().direction,
         playerRightArm.transform.eulerAngles.z,
         LayerMask.GetMask("Resource"));
     if (collider)
     {
         Debug.Log($"You pucnhed a {collider.transform.name}");
         StopCoroutine(CheckCollision());
     }
     return CheckCollision();
 }```
#

hell no xd

polar acorn
#

You need to know what a coroutine does. When you start it, it runs code as if it were an ordinary function, until it hits a yield statement. When it does, it waits for whatever condition you're yielding for, then resumes where it left off

#

So, at what point do you want this to pause, and for how long

#

and what do you want it to do after the wait

lofty lintel
#

yeah but how could I make so the as long as animation runs don't stop coroutine

#

Like start the coroutine as animation triggers and stop the coroutine as the animation ends.

verbal dome
#

Hint: a synonym for "as long as" is "while"

lofty lintel
#

does animation have like bool kind object which indicates that animation is running?

polar acorn
#

So, you want to repeat this raycast every frame as long as you're in a specific animation?

polar acorn
#

So, maybe while the animation is a specific state, you'd want to do the cast, and then wait a frame

lofty lintel
#

yeah sure

polar acorn
#

So, do you know how to check if the animation is in the specific state?

lofty lintel
#

is it animator.isActiveAndEnabled

lofty lintel
polar acorn
lofty lintel
#

like if component is disabled or enabled?

polar acorn
#

Yes. Is that what you want?

lofty lintel
#

no

#

logically no.

dry geyser
verbal dome
lofty lintel
#

if animator disables itself and enables only while animating then yes

polar acorn
#

So, might be worth looking up how to check for a specific animation state

polar acorn
polar acorn
lofty lintel
#
 do
 {
     Physics2D.queriesHitTriggers = true;
     var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
          playerRightArm.GetComponent<CapsuleCollider2D>().size,
         playerRightArm.GetComponent<CapsuleCollider2D>().direction,
         playerRightArm.transform.eulerAngles.z,
         LayerMask.GetMask("Resource"));
     if (collider)
     {
         Debug.Log($"You pucnhed a {collider.transform.name}");
         StopCoroutine(CheckCollision());
     }
 }
 while (animator.GetCurrentAnimatorStateInfo(LayerMask.GetMask("Default")).IsName("PlayerPunch"))


 yield return null;

so here is what I came up with

polar acorn
# dry geyser

So, it looks like Photon doesn't like that build index. Since you've literally gotten it from the active scene, it doesn't seem to be something wrong with your code, it's something wrong with your configuration. #archived-networking would probably know what you'd need to do to get photon to have the same scenes.

verbal dome
#

I think I have used do-while like twice

#

In my entire life

polar acorn
#

By the way, the way to stop a coroutine from inside it is yield break

verbal dome
#

Actually do-while is not too bad here

lofty lintel
#

it does give me the Invalid Index on layer thing.

verbal dome
polar acorn
verbal dome
#

Yeah but I realized that this is actually a decent use case for it

#

But true, there should be reasoning behind it

polar acorn
lofty lintel
#

oh

#

it needs animator layer?

polar acorn
#

Yes, that is asking for the animator layer you want to check

lofty lintel
#

Its on baseLayer

#

wait I'll check how do I check animator layer

#

So I have another problem, I'll send video guys.

#
public GameObject playerRightArm;
 public Animator animator;
 private void Update()
 {
     if (Input.GetMouseButtonDown(0))
     {
         animator.SetTrigger("Punch");
         StartCoroutine(CheckCollision());
     }

 }

 private IEnumerator CheckCollision()
 {
     do
     {
         Physics2D.queriesHitTriggers = true;
         var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
              playerRightArm.GetComponent<CapsuleCollider2D>().size,
             playerRightArm.GetComponent<CapsuleCollider2D>().direction,
             playerRightArm.transform.eulerAngles.z,
             LayerMask.GetMask("Resource"));
         if (collider)
         {
             Debug.Log($"You pucnhed a {collider.transform.name}");
             StopCoroutine(CheckCollision());
         }
     }
     while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"));


     yield break;
 }```
#

problem is... It doesn't work.

verbal dome
#

Seems to be working fine?

lofty lintel
#

no

#

look at the debug.log

verbal dome
#

You are getting the log when you hit the collider

lofty lintel
lofty lintel
#

Collider is larger then u think

lofty lintel
polar acorn
verbal dome
lofty lintel
lofty lintel
#

take a closer look at debug log

#

im standing really close

#

not getting even when the collider thing turns more green (which I think means that colliders collided)

#

and I think

verbal dome
#

Wait your while loop doesnt even have a yield statement in it

lofty lintel
#

While crashed my unity just now

verbal dome
#

Please just switch to a while loop at least while we debug this

lofty lintel
#

when I switched to while from do while

verbal dome
#

Instead of doowhile

lofty lintel
#

yes I did already

#

unity just crashed I'll open it

polar acorn
verbal dome
polar acorn
#

Also, you're still using StopCoroutine instead of yield break

lofty lintel
# polar acorn Also, you're still using `StopCoroutine` instead of `yield break`
{
    Physics2D.queriesHitTriggers = true;
    var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
         playerRightArm.GetComponent<CapsuleCollider2D>().size,
        playerRightArm.GetComponent<CapsuleCollider2D>().direction,
        playerRightArm.transform.eulerAngles.z,
        LayerMask.GetMask("Resource"));
    if (collider)
    {
        Debug.Log($"You pucnhed a {collider.transform.name}");
        yield break;
    }
}
yield break;```
polar acorn
lofty lintel
#

Oh I missed it, my bad.

#

yield return 0;

#

right?

#
while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"))
 {
     Physics2D.queriesHitTriggers = true;
     var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
          playerRightArm.GetComponent<CapsuleCollider2D>().size,
         playerRightArm.GetComponent<CapsuleCollider2D>().direction,
         playerRightArm.transform.eulerAngles.z,
         LayerMask.GetMask("Resource"));
     if (collider)
     {
         Debug.Log($"You pucnhed a {collider.transform.name}");
         yield break;
     }
     else
     {
         yield return 0;
     }
 }
 yield break;```
#

or not in else

#

You say "and then wait a frame"

#

did u gave me a hint on how I would write the code or hint on what I would search next xd

verbal dome
#

Are we even sure that the animation state changes instantly?

#

If not, it will just skip the while loop and go to yield break

lofty lintel
#

so if I click rapidly fast I get log but if I click like slowly I don't get any response

polar acorn
lofty lintel
polar acorn
#

Yep. That's how you'd wait a frame.

lofty lintel
#

0 won't work?

polar acorn
#

Unsure, but even if it did, there's no reason to use that instead of null. Less garbage generated that way

lofty lintel
#

ok

#

So how do I fix it now

polar acorn
#

Try waiting a frame before the while

lofty lintel
#

Ok

#

crashed.

#
private IEnumerator CheckCollision()
{


    yield return null;
    while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"))
    {
        Physics2D.queriesHitTriggers = true;
        var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
             playerRightArm.GetComponent<CapsuleCollider2D>().size,
            playerRightArm.GetComponent<CapsuleCollider2D>().direction,
            playerRightArm.transform.eulerAngles.z,
            LayerMask.GetMask("Resource"));
        if (collider)
        {
            Debug.Log($"You pucnhed a {collider.transform.name}");
            yield break;
        }
    }
    yield break;
}```
lofty lintel
#

I deleted it

polar acorn
#

why

lofty lintel
#

because thats where yield return null was at

#

and If I moved that before while

#

what would else even do

polar acorn
#

I didn't say to move anything

#

I said to put one there

lofty lintel
#

oh

polar acorn
#

I never said to remove the one in the while

lofty lintel
#

Add another one? Ok I get it

#

I thought u meant moving it before while

polar acorn
#

Remember that only one line of code can ever be running at a time, and a frame cannot end until every line is run

lofty lintel
#

ayyy it works!

polar acorn
#

So, if you don't have a pause in the while loop, the frame cannot end, so the animation cannot update

lofty lintel
#

so frame waits while loop to finish

#

if while loop doesn't have a pause?

#

so that's what our else does in the code, it pauses.

polar acorn
#

The definition of a "frame" is "However long it takes for every object's Update to finish"

#

Combine that with what I linked, when you start a coroutine, it runs that coroutine until it hits a yield

lofty lintel
#

but how did the first yield helped it

polar acorn
#

When it hits a yield, the coroutine pauses, and the code goes back to where it started the coroutine

lofty lintel
#

like yield before while

polar acorn
#

Waiting a frame first means it has time to actually change

lofty lintel
#

So we wait before animation changes, then pause by each frame till in that animation at some point collider touches or else just end the coroutine

#

so we basically check if collider collided in each frame of animation's state right?

polar acorn
#

Yes, you start the coroutine, then immediately hit a pause, and then finish out the frame. Next frame, it resumes with the next line, that starts the while loop. Either you exit the coroutine, or you pause a frame and check again

lofty lintel
#

Ok so this would be detailed info right.

#
 private IEnumerator CheckCollision()
 {
     //wait for animation to run
     yield return null; //<-- wait a frame.
     //while animation is in punch state.
     while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"))
     {
         //Check if Collided.
         Physics2D.queriesHitTriggers = true;
         var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
              playerRightArm.GetComponent<CapsuleCollider2D>().size,
             playerRightArm.GetComponent<CapsuleCollider2D>().direction,
             playerRightArm.transform.eulerAngles.z,
             LayerMask.GetMask("Resource"));
         if (collider)
         {
             //if it did stop the coroutine
             Debug.Log($"You pucnhed a {collider.transform.name}");
             yield break;
         }
         else
         {
             //if it didn't wait a frame.
             yield return null;
         }
     }
     //if animation ended and still didn't collide.
     yield break;
 }```
polar acorn
#

You can remove the last yield break, coroutines automatically end when they run out of code

queen adder
#

Topdown camera, the mouse is on the yellow star, how do I always get the red X position no matter what the camera rotation on y-axis?
raycast, then add camera.transform.up?

queen adder
#

I want to make a name system that always display the name of the units on their heads

#

the camera can rotate freely

#

is worldtoscreen the proper thing for this?

#

nice, it is

lofty lintel
#
private IEnumerator CheckCollision()
{
    //wait for animation to run
    yield return null; //<-- wait a frame.
    //while animation is in punch state.
    while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"))
    {
        //Check if Collided.
        Physics2D.queriesHitTriggers = true;
        var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
             playerRightArm.GetComponent<CapsuleCollider2D>().size,
            playerRightArm.GetComponent<CapsuleCollider2D>().direction,
            playerRightArm.transform.eulerAngles.z,
            LayerMask.GetMask("Resource"));
        if (collider)
        {
            //if it did stop the coroutine
            Debug.Log($"You pucnhed a {collider.transform.name}");
            CheckAnimations(collider);
            yield break;
        }
        else
        {
            //if it didn't wait a frame.
            yield return null;
        }
    }
    //if animation ended and still didn't collide.
    yield break;
}
private void CheckAnimations(Collider2D collider)
{
    if (collider.transform.tag == "Tree")
    {
        collider.transform.GetComponent<Animator>().SetTrigger("GotHit");
    }
}```
polar acorn
lofty lintel
#

no i mean

#

that didn't fix it

#

I fixed it I had problems with animator itself.

#

had to remove exit time.

runic crypt
#

hello! i wanted to use unity 6 for my next project but was wondering if its stable? like i plan on making "game jam" like games (something simple to mediocre nothing too big)

would yall recommend that I stick with lts or can i use unity 6 preview?

#

id assume the preview is prone to bugs? idk i havent been keeping up to alot of the news so

eager spindle
#

preview stuff is not truly meant for production

runic crypt
#

ah oke

eager spindle
#

nothings stopping you from using it

#

what do you need unity 6 for though?

runic crypt
#

o nah just wanted to try the latest features lol - no actual reason behind needing to use it

#

so i kinda just wanted to make sure if unity 6 preview can be used for production just in case haha

eager spindle
#

I don't think you'll encounter any of the "new features"

runic crypt
#

id assume so

#

tyty tho

vagrant pewter
#

Hello, Im new to Unity. I making a small game and i want text to pop up after a collison happens (aka, my character running into another character). Im having troubles getting it to work. i dont think the collsion is being detetced. Im completly stuck ):

eternal falconBOT
compact light
#

@astral falcon @languid spire Just to circle back, I much appreciate the help. My dumbass thought the only debug was the script debugger not the inspector debug as well (which was my issue). Thanks again 🙏

river pecan
#

Is there a way to make Character Controllers ignore collisions? Using Physics.IgnoreCollision(), Physics.IgnoreLayerCollision, and setting layers to not interact hasn't worked work

#

Rigidbodies on the same layer do not collide with each other but still collide with Character Colliders on the same layer

#

Using Physics.IgnoreCollision() with a Character Controller and colliders without a Rigidbody work

wintry quarry
river pecan
#

Calling move on the CC

wintry quarry
#

Calling move on the CC has nothing to do with normal physics collisions

#

it's essentially dooing a capsulecast

#

if you don't want such collisions there's no reason to be using a CC at all

#

disable the CC and just move the Transform directly

river pecan
#

I have platforms that can ignore the collision of the CC that work with Physics.IgnoreCollision()

#

But when I do the same with 2 CC's it doesn't work

wintry quarry
#

because CC.Move doens't use normal physics collisons, as mentioned

river pecan
#

Okay that makes sense

#

So there isn't a way to have 2 CC's ignore only each others collision

#

Without working around and just disabling them both

wise spoke
#

Hello, I beginning in C#, I’m from Python, is there an equivalent for this instruction

l = [0,1,2,3,4,5]
newList = l[0:2]


# >> newList = [0,1,2]

modest dust
#

= l[0..3]

marble hemlock
#

if i were to make a crouching system, would it be best to simply have it where when they click whatever keybind i have chosen for crouch, it just moves the camera?

#

is that the primary idea behind a crouching system for movement or is there more?

slender sinew
night valve
#

But collider will not move along with camera, if you use physics you will have to handle this

marble hemlock
#

ah
pain
thanks

#

i didnt even consider the collider

night valve
#

ig you could simply shrink/extend its bounds on state changed

real geyser
#

i have this code but the bullet wont move

#

same code worked for the player but when i try to add to enemy it doesnt work?

languid spire
real geyser
#

damn

#

thanks man

rare basin
#

Physics.RaycastAll -> what is the proper way to order all hits in the order they've been hit? why isn't it ordered like that by default? I'd like the first detected collider to be [0], the second one as [1] etc

keen dew
#

You'll have to sort the array by the distance property. It doesn't do that by default because sorting is expensive and if the order doesn't matter it's actively harmful

rare basin
#

just sorting by distance would do the trick?

keen dew
#

That would sort them from closest to farthest relative to the starting point

rare basin
#

but i'd need to sort based on the hit.point rather than the collider position itself, right?

keen dew
#

Distance is to the hit.point

#

If you want to sort to the collider position then use that instead

rare basin
#
hitInfos = hitInfos.OrderBy(hitInfo => Vector3.Distance(playerPosition, hitInfo.point)).ToArray();
#

so i guess that should be enough

verbal dome
#

Raycasthits already store a distance

keen dew
#

Sure but you're re-calculating the same info that's already in hitInfo.distance

rare basin
#

oh ok

#

so just hitInfos = hitInfos.OrderBy(hitInfo => hitInfo.distance).ToArray();?

#

thanks

verbal dome
rare basin
#

iterating over it in a foreach loop

#

and returning when i find first valid collider

verbal dome
#

If you are just iterating over it then you can leave it as IEnumerable, no need to convert to array

#

Generates extra garbo

rare basin
#

just this tbh

#

then some extra checks inside that loop

#

what vfx, sfx to play etc

verbal dome
#

You can remove ToArray and it will work

rare basin
#

perfect, ty

#

wait, are you sure?

#

because RaycastAll returns RaycastHit[]

#

i guess i just cannot do hitInfos = orderby...

#

just only hitInfos.OrderBy(hitInfo => hitInfo.distance); without hitInfos = (...)

#

well, without ToArray() it doesn't work properly, with ToArray() it works

verbal dome
#

It works, you just can't assign it to an array variable (hitInfos)

#

You can do var ordered = hitInfos.OrderBy(...)
And then do a foreach on ordered

rare basin
#

ah so i dont loop over hitInfos

#

got it

#

ok, works 😄

verbal dome
#

Extra array allocation avoided 👍

burnt vapor
rare basin
#

yeaa i've figured

#

loopting through the IEnuemrable works

burnt vapor
#

And FYI, IEnumerable exists to be iterated. It's a special type, and in your case since you only do a single iteration it works just like the array

#

However, make sure you don't iterate it multiple times

rare basin
#

no i dont

burnt vapor
#

If you do this, OrderBy is called multiple times too

#

In that case you should just ToArray() again

rare basin
#

i just have 1 loop, once i find first valid collider for my use case i return

#

and that function triggers only when i shoot

burnt vapor
#

Then it's all good, just keep in mind an IEnumerable will invoke all the LINQ methods that defined it when you iterate it

rare basin
#

interesting

#

I thought that it would only order it when you actually call OrderBy

#

but it also invokes all "cached" LINQ methods

#

when iterating over it?

burnt vapor
#

You basically store this method until you iterate the IEnumerable through the foreach, or with ToArray()

#

You can do this yourself. Make a method that returns IEnumerable<T>, and inside you can use the yield keyword

rare basin
#

ahh ok i think i got it

burnt vapor
#

This method will be an iterable method, and it will not invoke until you iterate it

#

It's hard to explain. Unity Coroutines work the same way

verbal dome
#

Yeah IEnumerable methods are pretty powerful

#

And learning them made me realize that coroutines aren't "black magic"

rare basin
#

Quaternions are black magic for me

#

i stick to eulerAngles

#

for most cases 😄

verbal dome
#

No need to understand how quaternions work internally, just learn to use the helper methods: FromToRotation, LookRotation, AngleAxis, Euler etc.

rare basin
#

yea I do know them

night valve
#

If you ever wanted to understand them a bit more, you can just forget about all helpers besides AngleAxis and operate on normalized Vector3 directions
(Its just one way of learning, may not fit your preferences but worth trying imo)

steep rose
#

Or just use docs 😁

night valve
#

This is the other way of learning. Not fitting my prefs xd

steep rose
#

As much as people hate when I say it, it's true the documentation will tell you what it is, how it works, and how to use it.

#

Although a bit tricky at first since nobody knows where they are lmao

night valve
#

Agreed. But for some people like me theoretical explanations even backed by examples aren't always sufficient. I like to visualise things for example having 6 gizmo rays (describing 2 different direction vectors) and runtime see what is happening using AngleAxis. Basically you can recreate any other helper method with it

steep rose
#

Oh yeah 💯 if you can visualize something, best go for that since you will actually see what its doing so your not guessing.

#

Using Handles would also help with visualization, but I haven't grasped and good handle on them yet

#

That was not supposed to be a pun, but I wish it was

night valve
#

Oh... There is such thing o_o

steep rose
#

They only run in the editor afaik

#

Unless they do run while in playmode

night valve
#

Yeah, just checking docs about them. Apparently it's just faster an more customizable way of doing 6 rays 1per axis

steep rose
#

When I saw you can use them to display text above objects I was intrigued

night valve
#

Neat. At least for large teams

steep rose
#

Ah I wouldnt say they are solely for large teams, they can be used by a solo dev with practice of course unless they want to get a project full of errors, this concept applies to anything.

night valve
#

Well yeah, didn't express myself precisely. I mean it is good for everyone, especially large teams

steep rose
#

Of course mb

night valve
#

Like it's a bit must for them ig

clever oar
#

dont know, if this belongs here. i hope so sadok I have question, what does this corountine do? Never seen this syntax anywhere.

languid spire
verbal dome
#

I don't see why the _ = is there

#

Discard assignment or whatever

languid spire
#

yes, it's basically unnecessary.
assign the return value and throw it away. totally pointless

#

what concerned me was OP asked about the coroutine which displays a lack of understanding of the whole situation

#

#🔊┃audio Next time actually try to look for the correct channel

clever oar
runic lance
#

depending on who you ask it's considered to be a good practice to assign the result to a discard variable if it's running something async and you don't care about when it's going to finish
then it's clear that you simply didn't forget about waiting for the results, you simply don't care
this is mostly used for Tasks though, although Coroutines are pretty similar in that regard

#

the StartCoroutine is just starting a coroutine, an asynchronous operation
instead of the discard you could write it as yield return StartCoroutine(WaitAndRecalculate())
then it would wait for the async operation to finish and continue execution in the next line

burnt vapor
#

You can configure VS to warn you by default if a return type is unused and not discarded. I have it onby default

tawny bone
#

okay this isnt a unity question but just a general c# question, why the hell do I get this error in my if else

#

its saying it expects a ;

#

in my else?

#

that doesnt make sense

wintry quarry
#

else can't have a condition attached to it

#

only else if can

#

If you write just else then the next thing better be a { or the start of a statement. You can't have a condition on an else.

#

not only that but you are re-declaring itemCost in every one of those blocks

#

none of them actually change the outer itemCost variable nor what you are returning

#

this seems like the perfect use case for a switch statement:

public decimal GetItemCost() {
  switch (itemCost) {
    case 1:
      return 5.99;
    case 2:
      return 19.99;
    //.. etc
    default:
      throw new Exception($"Unexpected itemCost value {itemCost}");
  }
}```
tawny bone
#

i would use that, but this is for school so i have to use if statements. I did figure it out, but yeah I genuinely am so lost on how to do this program and its probably the most simple thing ever

wintry quarry
tawny bone
#

man i wish my teacher was better, this is miserable trying to learn it on my own

#

basically the code i have to do is to enter in sales info, and there are 5 items with different prices

#

so im trying to use an if statement to return the correct value for which item the user inputs

wintry quarry
#

You've overcomplicated it a bit

tawny bone
#

thats what it seems like

wintry quarry
#

it's as simple as:

public decimal GetItemCost() {
  if (itemCost == 1) {
    return 5.99;
  }
  else if (itemCost == 2) {
    return 19.99;
  }
  // and so on
  else {
    return 0; // default for when we don't know this number?
  }
}```
tawny bone
#

this is the rest of my code, based mostly off of the "skeleton code" we were provided

#

that seems so much easier, damn

rich adder
tawny bone
wintry quarry
#

I strongly suspect this isn't Unity honestly

wintry quarry
rich adder
#

seems like general !csharp

eternal falconBOT
tawny bone
#

thats what I needed, thank you I was only in here so i thought id give it a shot

#

thank you for the help nonetheless!

stuck palm
#

can you get the key of a dictionary using just the value the same way you get a value using the key?

polar acorn
#

Not easily

stuck palm
#

its not reversible?

polar acorn
#

You could loop through all of the keys, then check if the value of that key is the thing you're looking for. But if that value is in multiple places you won't always get the same one

stuck palm
#

i'll just reverse the dictionary f that

ivory bobcat
stuck palm
misty rose
#

any idea why it prints the particle which is called bullet, is it colliding with itself?

    public Transform playerPos;
    public SpriteRenderer SpriteRenderer;
    public float maxShootDistance;
    public KeyCode specifiedKey;
    public int gunDamage;

    public AudioSource shotAudio;
    public AudioClip shotClip;

    public ParticleSystem bulletParticle;
    public ParticleSystem shotParticle;

  private void OnParticleCollision(GameObject other)
    {
        Debug.Log("Collsion with bullet" + " NAME:" + other.name + " TYPE: " + other.GetType());
        if (other.gameObject.GetComponent<AINavigation>())
        {
            AINavigation aiNav = other.gameObject.GetComponent<AINavigation>();

            Debug.Log("Shooting Ai");
            aiNav.Health -= gunDamage;
        }
    }
rich adder
#

When OnParticleCollision is invoked from a script attached to a GameObject with a Collider, the GameObject parameter represents the ParticleSystem.

misty rose
#

Fixed the issue, thanks i appreciate the help man.

wintry quarry
#

so the particle is certainly not colliding with itself

#

it might be colliding with the object that the particle system is attached to, sure.

scenic saffron
#

Visual studio is not showing me options for stuff that is UI releated

slender nymph
#

!ide

eternal falconBOT
scenic saffron
#

thx

marble hemlock
#

im getting this sort of weird thing where when i hover over an interactable item the first time, the camera sort of snaps away. it doesnt do it any time after that. it just does it the first time, which is odd.
https://hastebin.com/share/dinivimagu.csharp

its so slight but it keeps bothering me

#

i know this is the script causing it because i threw out every other script that i couldnt use at this exact moment

#

only the itemcontroller, which holds each item's data as a scriptable object, the player movement, the player camera, and the player interact script is active

#

i dont see anything on my script that would be causing this, since nothing should be affecting the camera rotation

slender nymph
#

there is nothing in the code you've shown that would affect the movement or rotation of any object. maybe check on the interactPrompt object to see if it does anything in its OnEnable or OnDisable that may affect anything like that

marble hemlock
#

currently its just an image with a text object as a child. i really dont know whats causing it.

#

it only happens once, when i move the camera onto the object. oddly, if i move the player (and not the camera with the mouse), it does not do the slight jump

#

whats bugging me is that it wasnt doing this earlier at all

#

ill try removing parts of code until i see what part causes the jump

lofty lintel
marble hemlock
#

its super inconsistent which is whats leaving me so confused

lofty lintel
slender nymph
lofty lintel
#

oh yeah wait

#
public float multiplier;
  private void OnTriggerStay2D(Collider2D collision)
  {

      if(collision.transform.tag != "RightHand")
      {
          Vector2 diff = collision.transform.position - gameObject.transform.position; //character position - transform.position //tree position
          collision.attachedRigidbody.AddForce(diff.normalized * multiplier, ForceMode2D.Force);
      }
     

      //Debug.Log("push out");
  }```
#

This is the code of uh pushing out player if touching the resource

#

Could this cause the problem with physics of those items?

slender nymph
#

what object is that code attached to?

lofty lintel
#

Trees and stones, resources

lofty lintel
#

Items only has collider and rigidbody

#

or could it be because of mass:

#

oh yes it was problem of mass I changed it to 0.1 and it works better now.

slender nymph
#

so the tree adds force to the stone, and it adds a lot since it appears to be adding 260 units of force, in the opposite direction

lofty lintel
#

Player's mass is normal so it pushes out player normally, however throws stuff which has too little mass.

#

Anyways, thanks!

slender nymph
#

you should also consider using reasonable amounts of force. 260 is quite a lot

lofty lintel
#

It's reasonable

slender nymph
#

it's not

lofty lintel
#

It's the kind of physics I want, its for uh squishiness effect.

#

I'll show you difference.

slender nymph
#

are you sure you want to be adding 260 units of force using ForceMode.Force rather than something actually reasonable using ForceMode.Impulse?

#

i'm betting that the reason it seems reasonable is because it is only able to apply that force for a single physics frame before the object is no longer overlapping or its velocity is overwritten

lofty lintel
#

thats difference between 260 and 20

slender nymph
lofty lintel
#

yeah well

slender nymph
#

either that or your objects are absolutely unreasonably gigantic

lofty lintel
#

thats the case

#

they have scale of 4

#

and player is 1.4

#

on X and Y ofc

marble hemlock
#

i dont know how
i dont know why
but this is the cause

marble hemlock
#

i dont get it though its just an image ;-;

slender nymph
#

what is on that object

#

including any children it may have

marble hemlock
#

well it has a TMPro thing on it

#

and this is the inspector for it

#

and this is the inspector for the text game object notlikethis

#

its just the default things set 😭

ruby python
#

Hi all,

Please forgive the potentially silly/simple question.

I have this code.....

https://hastebin.com/share/powanifofe.csharp

Idea being that it deals with the player stats.

I was just wondering if there was a way to write a single method that would update only the specific 'stat' value that's been passed to it?

(as I was typing I thought maybe 2 arrays or lists, one for floats and one for the images and just reference the Index of each? As long as the entries have matching indeces it should work okay?)

deft grail
ruby python
# deft grail the easy way would be just pass a string or something and based of the string up...

I've gone for this route for the moment. I'm sure there's a better way, but this will do for now.

    [Header("Player Stat UI Settings")]
    [SerializeField] Image[] statIndicators;

    [Header("Player Stat Value Settings")]
    [SerializeField] float[] statValues;

    private void Start()
    {
        for (int i = 0; i < statIndicators.Length; i++)
        {
            statValues[i] = Random.Range(0f,100f);
            statIndicators[i].fillAmount = statValues[i]/100f;
        }
    }

    void UpdateStats(int statIndex, float statAdjustment)
    {
        statValues[statIndex] -= statAdjustment;
        statIndicators[statIndex].fillAmount = statAdjustment / 100f;
    }
runic lance
ruby python
runic lance
#
enum Stat {
    Health, Food, Water, Power, Oxygen
}

[Serializable]
public class StatValue {
    public Stat Id;
    public float Value;
}

// your class
    [Header("Player Stat Value Settings")]
    [SerializeField] StatValue [] statValues;
runic lance
ruby python
devout flume
#

How do you call those things between brackets, like [SerializeValue]?

devout flume
#

Oh that's just it lol

devout flume
#

Thanks

#

I guess it's the equivalent of Java's @ attributes

astral basin
#

im building a mobile android game and when the player touches the screen to jump there is a delay, this doesnt happen in unity but only when i export it to mobile, it happens on about 3 phones ive tried some old and some new so i dont think its a spec problem, i do have alot of instantiate and destroy but it still delays before the game even gets there, any way i can lower the delay?

snow warren
astral basin
#

but i cant

#

on the pc it runs smoothly

#

the problem is after im building into mobile

#

does it matter if i used get mouse click instead of get touch?

astral falcon
astral basin
#

after building or using the unity remote thing?

astral falcon
astral basin
#

alr ill look into it thanks

void fable
#

Hi I am following this tutorial https://www.youtube.com/watch?v=JFtfyw5u6ro and I am halfway, but suddenly I got these errors and I have no idea how to fix them. I know what the error implies, but it is not the case in this code and it wasn't a problem before. These are the three codes that Ive been using with this tutorial ( i havent changed any other code ) https://hastebin.com/share/zunehidazo.csharp (gamecontroller) https://hastebin.com/share/iroleribor.csharp (spriteswitcher) and https://hastebin.com/share/porakagepo.csharp (spritecontroller) ( i put them in 3 different files to keep it from being confusing) thanks in advance

In this video you will learn how to create and animate sprites in visual novel style using Unity!

Discord server: https://discord.gg/gRMkcyNhwa

Previous part: https://youtu.be/YHwM7d20Gqo

Google drive project: https://bit.ly/3J33zQ4 - for educational purposes only

Music credits:
Chillpeach - Purple
Chillpeach - Vanilla Candy
Chillpeach - ...

▶ Play video
alpine glen
astral basin
alpine glen
astral falcon
astral basin
void fable
void fable
#

What does error mean?

void fable
marble hemlock
marble hemlock
astral basin
void fable
marble hemlock
#

i think what its saying is that you have something called GameController and SpriteSwitcher as variables, but unity may already have a class with those names

void fable
marble hemlock
#

that or you have duplicate scripts

void fable
void fable
polar acorn
marble hemlock
#

find the copy
Destroy the fake

void fable
#

Omg youre right i do have duplicate scripts, i have no idea how that happened

void fable
#

yall are life savers!!!!!!!

marble hemlock
#

now its time for me to have a meltdown over an extremely minor bug

marble hemlock
#

WHAT HAVE I DONE TO YOU

marble hemlock
#

im getting bullied by a bool this is silly

void fable
#

I wish I could help, but i know less than you. Have you tried asking chatgpt?

astral basin
#

find another way to do or smt

marble hemlock
#

honestly i dont even think this is a code issue
at first i thought it was but i think it might just have something to do with the gameobject itself

#

im starting to wonder if i put the wrong thing in the field

void fable
astral falcon
astral basin
marble hemlock
#

yes