#💻┃code-beginner

1 messages · Page 805 of 1

grizzled steppe
#

Is it better to make your own animator or use the build in?

unreal veldt
#

hello guys, new here!

silk night
grizzled steppe
#

I'm making my own rig system that uses pivot points for anims and a centralized root part for raycasting the character collisions

silk night
#

Are you doing this for a learning/asset creation point or just reinventing the wheel for the sake of it?

grizzled steppe
#

learning mainly

#

It's my first ever made physics thing

silk night
#

well then use the standard animator until that doesnt work for you anymore

grizzled steppe
#

I can also set ground types too and plan on adding a friction setting for them

tall lava
#

is there a way to differentiate wall tiles and ground tiles in a tilemap for game logic?

grizzled steppe
#

In terms of what?

#

Texturing or hitbox?

#

Could use collision layers

#

or tag

#

or check if the surface position is below a certain threshold of the player

tall lava
#

oh, sorry I should've been more detailed, I'm trying to do it for hitboxes, so the player can jump when touching a ground tile but not when it's touching a wall tile

solar star
#

@silk night just fyi if youre interested. unity6.3 didnt fix my problem, but i tested with a RigidBody + CapsuleCollider instead of a CharacterController, and this works perfectly. time to rewrite my movement code I guess sadblob

tall lava
naive pawn
grizzled steppe
#

Is it a whole mesh or individual?

rich adder
#

you'd have to Tag them your own way by using scriptable tiles

tall lava
#

I'll look into that, thank you for the help!

grizzled steppe
#

Anyone know what causes camera to skip randomly?

naive pawn
#

not without more info, no

grizzled steppe
#

I'll send the script I made

#

private void UpdateCamera()
{

        Transform target = (CameraOffset <= 0.1f) ? Neck : Character;
        Quaternion rot = Quaternion.Euler(pitch, yaw, 0f);
        float OffsetX = ShiftLockOn ? 1.5f : 0f;
        Vector3 OffsetFix = new Vector3(0f,CameraOffset <= 0.1f?0.25f:0f,CameraOffset <= 0.1f?-0.125f:0f);
        Vector3 offset = rot * (new Vector3(OffsetX, 0f, -CameraOffset) + OffsetFix + HumanoidCameraOffset);
        GameCamera.rotation = rot;
        GameCamera.position = target.position + offset;

        bool showHead = CameraOffset > 0.5f;
        Neck.gameObject.SetActive(showHead);

        if (Input.GetMouseButton(1) || CameraOffset <= 0.1f || ShiftLockOn)
        {
            yaw += Input.GetAxis("Mouse X") * sensitivity;
            pitch = Mathf.Clamp(pitch - Input.GetAxis("Mouse Y") * sensitivity, -80, 80);
            yaw%=360;
            pitch%=360;
        }

    }
rich adder
grizzled steppe
#

This is latest update too cause I tried to see if it was update related

radiant voidBOT
grizzled steppe
#

The camera works but for some reason it randomly skips to some random rotation and jumps

radiant voidBOT
rich adder
grizzled steppe
#

⁨⁨```cs
private void UpdateCamera()
{

        Transform target = (CameraOffset <= 0.1f) ? Neck : Character;
        Quaternion rot = Quaternion.Euler(pitch, yaw, 0f);
        float OffsetX = ShiftLockOn ? 1.5f : 0f;
        Vector3 OffsetFix = new Vector3(0f,CameraOffset <= 0.1f?0.25f:0f,CameraOffset <= 0.1f?-0.125f:0f);
        Vector3 offset = rot * (new Vector3(OffsetX, 0f, -CameraOffset) + OffsetFix + HumanoidCameraOffset);
        GameCamera.rotation = rot;
        GameCamera.position = target.position + offset;

        bool showHead = CameraOffset > 0.5f;
        Neck.gameObject.SetActive(showHead);

        if (Input.GetMouseButton(1) || CameraOffset <= 0.1f || ShiftLockOn)
        {
            yaw += Input.GetAxis("Mouse X") * sensitivity;
            pitch = Mathf.Clamp(pitch - Input.GetAxis("Mouse Y") * sensitivity, -80, 80);
            yaw%=360;
            pitch%=360;
        }

    }
#

I'll be turning my camera in game and for some reason it just skips to some random rotation value

rich adder
#

that modulo lookin sus

#

also input should always be captured before anything

grizzled steppe
#

So move the if above all of it?

rich adder
#

Transform target = (CameraOffset <= 0.1f) ? Neck : Character;
this is probably part of why it "snaps"

grizzled steppe
#

Cause of the switching?

rich adder
grizzled steppe
#

I changed the top line to neck

naive pawn
rich adder
naive pawn
#

in the update loop, doesn't matter where

#

lateupdate is still in the update loop

rich adder
#

oh ok then

naive pawn
#

though, i don't think it's been stated what message this method is called from?

naive pawn
#

yeah you didn't say what message this method is called from

#

could still be an issue if it's in FixedUpdate, but in that case the issue would be that the entire thing is in fixedupdate

rich adder
#

I think I saw earlier mentioned "LatestUpdate" idk if they meant LateUpdate

#

I think that pivot switch is what might be causing it too look "twitching" though

grizzled steppe
#

Yeah late

naive pawn
#

similar for OffsetFix as well

grizzled steppe
#

So Should I use the neck of the character?

#

It seems the issue was the pivots changing

#

Now to make a raycast thing so camera can't clip through walls

deep fractal
#

I have 1 question and that is how to fix this error in the code. Otherwise I am a beginner and I want to learn how to make games in unity.

frail hawk
#

flappybird yeah

pure cypress
#

Hey guys, I ran into this error I was wondering if anyone knows how to resolve it.

radiant voidBOT
# rich adder !input
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

pure cypress
rich adder
pure cypress
rich adder
#

!vs

radiant voidBOT
# rich adder !vs
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)

pure cypress
fickle stump
#

Hi o/
I'm looking for a way to pause my charakter from moving/stopping the player from giving any movement imput while there's a pop up (like a journal). I can remember that there was some way I can make this work but can't remember 🫠

naive pawn
#

you could check for that state yourself, you could disable the input action/map/asset, there's quite a few ways

fickle stump
#

Oh neat there's a way i can disable any input action from the new input system?

#

I'll look that up cheers

swift crag
#

I disable the "Player" action map while a menu is open

#

make sure it gets turned back on, of course 🙂

#

i put all of that logic into a single controller that decides things like "are we in a menu right now?"

fickle stump
#

That's actually Smart. My first thought was putting that in the movement script, because obviously we're handling movement here. But I'll probably be referencing a lot, since there's multiple situations in which the player will not be able to mvoe

#

Thank you blobnod

fickle stump
fickle stump
#

I am stupid. I made the checkState private, meaning I wasn't able to access the information from the skript 🤦‍♂️

grand snow
#

That would give a clear compile error

fickle stump
#

Sorry I have to ask again.
I'm currently setting up a Collectables and a CollectionTracker.
In the Collectables I have the Interaction logic, where I want to increase the amount in the CollectionTracker by the Amount of x which is part of an SO (e.g. I have Scriptable Object Nails set to 2, so I want to add 2 to the current amount of Nails). I know how to reference a value from another script if it's only one object, but how would I do that, if I have multiple of those?

My thought was to create a list of GameObjects which contain the script "Collectables" and then access the Component/Script through the awake method. But I'm not sure if that is the correct approach and idk how to do that 😅

Collection Tracker: https://paste.ofcode.org/bsfhzaBCfuee2wHSYKxzQa
Collectables: https://paste.ofcode.org/E9cSHZzEgCXkwmHCJ6PLiZ
SO: https://paste.ofcode.org/K9pAUVw4ajLafdAVnem2ZP

ivory bobcat
grizzled steppe
#

I'm making a build system but for some reason it keeps auto deleting the cloned object when its parented to my workspace object

ivory bobcat
#

!code

radiant voidBOT
midnight tree
#

Does [SerializeReference] show the interface(reference object of it) in the inspector, right?

sour fulcrum
#

You can’t serialize interfaces if that’s your question

naive pawn
#

afaik, you can, they just aren't shown in the built-in inspector

tired python
#

i am trying to setup a currency system in my tower defense game. when ducks are killed, i want the blood text value to increase by 10. Said currency manager script is this:-

using UnityEngine;
using UnityEngine.UI;

public class CurrencyManager : MonoBehaviour
{
    public Text HP;
    public Text Blood;

    int hp = 0;
    int blood = 0;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        HP.text = hp.ToString();
        Blood.text = blood.ToString();
    }

    // Update is called once per frame
    public void SpillBlood()
    {
        blood += 10;
    }
}
#

I am figuring out whether collisions are occuring or not and then changing the value of blood in CurrencyManager:

#
using UnityEngine;

public class CurrencyAdderOnCollision : MonoBehaviour
{
    [SerializeField] CurrencyManager _currencyManager;
    // Update is called once per frame
    public void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log("Collision Detected.");
        Debug.Log("Adding blood to pool.");

        _currencyManager.SpillBlood();
    }
}
#

it ends up giving me this error

verbal dome
verbal dome
tired python
verbal dome
#

Look at the inspector of this script component

#

And if it's assigned then make sure you don't have extra CurrencyManagers in the scene

tired python
verbal dome
#

Unity automatically serializes public fields

tired python
#

damn, i was away from unity for just a month or so and i forgot about this. btw, what can i do to fix the error? should i just do smth like HP = this.HP in void Awake() or something?

verbal dome
#

Unity needs to know which Text component you want to reference

#

So just assign it in the inspector?

#

If possible

tired python
#

I can't drag the Text component in the inspector, it doesn't allow me to do so

verbal dome
#

Use the correct type, TextMeshPro or TextMeshProUGUI or something

#

Instead of Text

tired python
#

could you maybe explain to me what the person in this video did in this case?

#

apparently it's supposed to do the same thing but, he was somehow able to do it in the code itself

#

he created an instance variable(like a constructor i am assuming), then assigned this gameobject to the instance variable in Awake() and then reffered to this instance in the other script and used the function AddPoint()?

verbal dome
#

It could be done with GetComponent via code, though.

tired python
tired python
# verbal dome <https://youtu.be/YUcvy9PHeXs?t=256>

last question, i am seeing that the guy did not have to use the update() method at all, on the other hand, if i do that with my code, it doesn't rly update it. only when i copypasta whatever is present in the start block in the update block, does it actually happen.

#

oh wait, nvm, i figured it out, the function itself changes it, mb

verbal dome
#

Update is just a method that unity automatically calls every frame for your monobehaviour script

raw kelp
#

Hello all. I've been trying to set up Playmode tests.

Currently I have EditMode tests set up in Assets/Tests/Editor and Unity is able to find them. I didn't have to create an assembly definition file for this. And in this Editor folder, I'm able to reference code from my actual game folder (for example the public code in Assets/Scripts).

I have tried to create Playmode tests but it seems that it's not as easy as just creating a Playmode folder. I opened the Test Runner instead, went to Playmode, and create a new folder inside Assets/Tests for the playmode tests. It created the assembly definition file there, but I'm not able to figure out how to make it reference the code in Assets/Scripts.

This is all the information I think I have right now. Although, I'd appreciate if someone could help me ask the right questions, and also help me sort this issue out.

Thanks in advance 🙏🏻

#

And I'm not really sure if this help request is fit for this channel 👍🏻

midnight plover
raw kelp
#

I don't remember adding one myself, and one doesn't show up when I search.

Good reminder though, because I did try adding it before while I was attempting to set up Playmode tests. When I added it, I got a million (exaggerated) compiler errors because most of my other code broke.

midnight tree
verbal dome
#

Yeah they're just not editable is what I mean

midnight plover
raw kelp
midnight plover
#

As you do not have any asmdef in your Assets folder, everything has access to all Unity namespaces. But if you add an asmdef file to a folder, it will separate it entirely from Unity and you have to edit the asmdef file to include Unity stuff, for example like this:

#

I am not entirely sure, what errors you got, but they should show you, what namespaces are missing

raw kelp
#

i see. so I will have to manage these deps myself. Well, thanku 🙏🏻

deep fractal
midnight plover
deep fractal
#

ow

#

(:

#

it still doesn't work

sour fulcrum
#

What do you expect that to do

kindred temple
#

Is there a way I can automatically make this scroll area scale vertically without changing the canvas scaler's settings?

I've already done the rest of the UI with a specific setup so it'd be pretty difficult to change everything else for this one element, is there another way?

deep fractal
#

i'm watching tutorial how to create flappy bird game and this will this will make it so that when you press the spacebar it puts you a little higher than you were before

polar acorn
deep fractal
#

idk what i need to do

polar acorn
#

The message told you exactly what to do

midnight plover
#

you should go trough the unity learn tutorials probably, rather than using some maybe bad or outdated youtube tutorial. You clearly are missing basic level knowledge of coding. So either try the unity tutorials OR take some super simple c# tutorials to start with.

polar acorn
deep fractal
#

btw it's this correct now?

#

or?

sour fulcrum
#

no

tender mirage
#

No. That’s far from correct.

deep fractal
#

gg

#

idk what i need to do

midnight plover
deep fractal
#

realy

midnight plover
radiant voidBOT
sour fulcrum
#

You just had to use .linearVelocity instead of .velocity

#

as it said

tender mirage
#

Or maybe i’m remembering that wrong.

sour fulcrum
#

Which is why you have to do that

deep fractal
#

it still doesn't work

midnight plover
#

and then do what it tells you to

#

And then stop and go to some basic tutorials about c# please

harsh basin
#

Hey everyone, where can I get help on the Unity courses from Unity Learn? I'm doing the Junior Programmer course and I keep having an issue importing the asset packages, seem textures are not applied to the assets everythign is Pink. I am following the 6.3 LTS version but for Prototype 2 I resolved the issue by importing into 6.0 LTS and converting to 6.3, but this is not working for Prototype 3 assets. Anyone know how to resolve or how I could correct manually?

radiant voidBOT
polar acorn
# deep fractal idk what i need to do

Read the error message. It's very clear about what to do. It's literally just plain text instructions. Actually try to interpret the words in front of you instead of smooshing your keyboard and hoping it works.

deep fractal
#

thanks anyway

polar acorn
#

Programming isn't magic. Words mean things like they do in any context

#

You can just read the messages and they say what to do

midnight plover
tender mirage
#

You become what you eat afterall. If you get spoon fed, you’ll become a spoon. And a spoon can’t program.

polar acorn
#

You know, that succinctly summarizes something I have struggled to convey to people for years.

I'm gonna yoink that for my metaphor toolbox

midnight plover
#

Discussable if you get fed with or by a spoon tho 😄

tender mirage
#

If it helps you convey what you're feeling towards people then go for it.

tender mirage
#

spoons fed you.

midnight plover
#

So spoon inception in that case?

#

Sorry mods, we are running offtopic 😄

tender mirage
#

I take full respoonsibility. I'm sorry for this.

sour fulcrum
#

And who gives a fork about teaching spoons 😅

twin pivot
#

forking nobody, thats who

restive bone
#

Hi everyone, I'm a beginner Unity developer and now I'm working on a small iOS project. This game is about "chasing" falling musical notes. I have 2 gamemodes

  1. In Main menu hit Play - random song and random instrument - play
  2. In Concert hall - select an instrument - choose a specific songs for that instrument - play
    I have a list of songs that appears for being chosen and a list for random songs that I don't want to appear anywhere just to be there to load random songs when button Play is pressed. I don't know what I'm doing wrong, but I can't implement this. If anyone here can help I will share the github link to see the code and to understand exactly what's in there. Thanks
wintry quarry
#

as well as what if any debugging steps you've taken and their results

sour sun
#

Hey guys, I've just started with Unity - I am programmer, so in this way It is fine, but what I am a bit confused is a documentation. For example - I want to create a game menu, just some simple one and test the capabilities, but when I dug into the official documentation there is nothing. Woirking with UI Builder is simple as well as styling, but what I did not find is the handling the UIDocument with code. I have found a lot of videos how toi create menu, but I want to follow official docs. Why there is nothing, or am I blind? Can you help me to find some good material how to handle / create a simple game menu like - working with windows, quit the app etc? Thank you!

restive bone
naive pawn
restive bone
sour sun
keen dew
#

learn.unity.com has the official tutorials for using the methods and components in practice

queen adder
#

Hey guys im working on gamepad support and trying to implement my gamepad to work like a cursor. But, for some weird reason my virtual mouse doesn't point at ui (can't highlight) and clicking doesnt seem to work. This is the code im using:

    private void UpdateMotion()
    {
        if (virtualMouse == null || Gamepad.current == null) return;

        Vector2 stickValue = inputs[0].action.ReadValue<Vector2>();

        stickValue *= cursorSpeed * Time.unscaledDeltaTime;

        Vector2 currentPosition = virtualMouse.position.ReadValue();
        Vector2 newPosition = currentPosition + stickValue;

        newPosition.x = Mathf.Clamp(newPosition.x, 0F, Screen.width - padding);
        newPosition.y = Mathf.Clamp(newPosition.y, 0F, Screen.height - padding);

        InputState.Change(virtualMouse.position, newPosition);
        InputState.Change(virtualMouse.delta, stickValue);

        bool isPressed = inputs[1].action.triggered;

        if (previousMouseState != isPressed)
        {
            virtualMouse.CopyState(out MouseState state);
            state.WithButton(MouseButton.Left, isPressed);
            InputState.Change(virtualMouse, state);
            previousMouseState = isPressed;
        }

        AnchorCursor(newPosition);
    }

While in my inputactionasset i've tried to set point to the position of the virtual mouse and for clicks to be on the virtual mouse left button and also the gamepad button. Im really not sure why it wont work. The event system is also set up with my custom ui input module.

wintry quarry
#

And what do you mean by "custom UI input module"?

queen adder
solar hill
#

would be far easier if you shared the scripts related to your issues

naive pawn
solar hill
#

rather than your whole github repository

restive bone
solar hill
#

you wrote the scripts..?

tiny bloom
#

is adding/removing components to game object at runtime considered bad practice or bad for performance?

restive bone
#

A part of them and a part were wrote with qwen.ai help

shell sorrel
solar hill
solar hill
#

but nobody is here to fix and clean up ai code for you

shell sorrel
#

has some overhead but unless you are doing it many times a frame sure its fine

restive bone
solar hill
restive bone
tender mirage
#

Not to be rude. But i really wouldn’t recommend using ai.

No proper structure, no code.

shell sorrel
#

using it will not help you actually learn things

#

all it will do is toss you in the deep end before you can swim

tiny bloom
# frail hawk explain why and how

so i have a base class called BossAttack, and another called BossBrain
each bossAttack has public variables that allows u to modify like how much damage u wanna apply, how fast, how often it happens...etc
and then bossbrain searches how many BossAttack exist on boss GameObject and execute them one by one

so when boss goes to phase 2, i remove one of those attacks
add another new ones
and make the ones left deal more damage and happen more often

the reason i went with this approach, is because i was able to modify values in the inspector so it's better for design

and now i can kinda create new bosses or make some bosses interchangable as long as they have the animations required for each attack i add

solar hill
#

its one thing to use ai, whatever, but its a completely different thing to rely on it so much you have no clue whats actually being done in your own project

#

youre actively hurting yourself in the long run.

shell sorrel
restive bone
#

Ok so no one can help me here...even if I used ai

tender mirage
#

It's more like no one wants to help somebody that's using ai.

tiny bloom
shell sorrel
tiny bloom
shell sorrel
wintry quarry
queen adder
#

Im really not sure what it is due to

#

I've set up point, a custom control scheme with the virtual mouse but it just won't detect ui

#

Here is my full code

wintry quarry
plain oar
#

i need help making a knife like people playground that stbs into objects and can be pushed in and can only be pulled out the opposite way it was pushed in

#

im making a combat game ive got every other weapon but stabbing tools

solar hill
#

help with that specifically

plain oar
#

i dont know where to start

solar hill
#

well you start off by breaking your problem down

plain oar
#

ive got the knife sprite with a rb2d and a collider (it is 2d game)

solar hill
#

first find the mvp of your concept

#

then break that down into its basic individual challenges

#

thats step one

plain oar
#

ive got the knife to drag eith the cursor in a 2d space so first i need the knife to stick into a 2d square with a rigidbody

queen adder
wintry quarry
#

i would try:

  • The default actions asset in the input module
  • Using the built in virtual mouse
queen adder
#

Ive tried it but still nothing.

#

Clicking only seems to work when the ui is selected but highlighting never works

#

For both custom and unity's solution

slow idol
#

is it that performance heavy to frequently pass structs with many variables stored in it?

naive pawn
#

"that performance heavy" is a vague question

#

"many variables" is also very vague

#

it's more work the more copies and the more variables you have, multiplicatively, but it's a few instructions worth

#

unless you have millions of copies and thousands of fields, it's not going to matter. there will be other things much slower

balmy vortex
#

hey so like just to sanity check myself rq, onStart() only gets called at the very start when the project opens as soon as the script is enabled right?

#

and onEnable just comes after that?

frail hawk
#

onEnable comes before

balmy vortex
#

oh wow ok

#

is there like any specific reason for that or

naive pawn
#

OnEnable is when it becomes enabled & active
Start is the first frame it's enabled & active

frail hawk
#

is something not as you expected or why the question

grand snow
#

Awake to init self, Start to access other things post init

slow idol
#

if i have a physics-based player, should i run the movement in fixedupdate or update?

wintry quarry
kindred blade
#

what does transform.translate mean 0-0

wintry quarry
#

Generally you do things that interact with the physics engine in FixedUpdate

wintry quarry
#

Which is a fancy word for "move it"

kindred blade
#

and transform is its position?

wintry quarry
#

No

#

The Transform is the component responsible for the object's position, orientation, scale and parent/child relationships in the scene

kindred blade
#

ohhh alr i get it now, ty!

slow idol
#

last weird/short question: how could i move a rigidbody at a constant velocity while updating it in fixedupdate AND update?

fallen snow
#

Hey uh, I need help making a script that is basically able to exactly copy maya's orient constraint. I'm making a physics based game and I'm trying to animate my character with a custom rig in-engine. to do this I need to be able to mimic maya's orient constraints and my attempts so far have been really dire.

The character I'm making is a physics based mechanical android and part of their design includes hinge/gimbal joints, which are nested joints for different axies. (think that's the plural of axis) For some reason Euler doesn't like this and while I understand code somewhat I'm very much artist brained and find it extremely difficult so if anyone does try to help sorry if I'm not totally a whiz.

In this gif hopefully you can see my shoddy attempt in unity, and how the maya version using the native animation constraints works perfectly.

If this isn't the right channel to discuss this please redirect me!

grand snow
fallen snow
#

AI assisted because I suck at coding

grand snow
#

er well firstly if the rigs are the same then you could directly copy local rotation over

fallen snow
#

Yup! I've been doing that

#

but euler issues causing flipping

grand snow
#

You want to avoid working directly with euler angles

fallen snow
#

and also the fact there's nested joints. apparently unity's parent system doesn't like that but they're essential for the design

grand snow
#

you are working with local rotation so that doesnt matter. Local position and rotation is directly relative to its parent

#

Id try to just use rotate towards and use the local rotation quaternion as is

fallen snow
#

The 'bones' animation type rig I made and all the individual meshes of my character are all zeroed out so they should all have the same local orient

ashen trail
#

this is a script attached to an object, when I move my mouse its position changes, but i cant see it.

any reason why?

grand snow
fallen snow
polar acorn
ashen trail
#

because on the objects inspector its showing a changing position

polar acorn
#

So, the numbers are changing but the object is not visibly changing position?

ashen trail
#

yah

polar acorn
#

Or is it moving just fine but not where you expect it to be?

grand snow
#

why make it complicated? i gave the answer

ashen trail
#

i thinks its something with camera position not being converted to world position or something

#

ima figure it out

polar acorn
grand snow
#

🤷‍♂️

ashen trail
#

k it tracks now, still cant see it but ima try to fix that on my own

#

thanks guys

grand snow
ashen trail
#

it is 2d

#

figured it out

#

thx

fallen snow
#

Hey! so that rotate towards advice has helped, it seems a lot smoother. and I don't think I see any massive flips? But the joint's later down the heirarchy do seem to be acting strangely...Like a sentient IK controller with a crack addiction.

grand snow
#

Share code again on a sharing site

#

!code

radiant voidBOT
alpine ferry
#

i am trying to make it generate

#

send me a friend req if you can help

slender nymph
radiant voidBOT
# slender nymph !ask 👇

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

twilit jolt
#

sorry if this is a dumb question, but this has been making me go insane for the past 30 minutes now
i'm trying to set up some world space things that the player can click on to interact with (the mouse is unlocked in the section)

i check for the custom worldspace button component with a raycast, that uses the mouse position, and gets a ray through the main cam (i specifically added a layer just for these, to make sure nothing can be blocking the collider)

[SerializeField] LayerMask wsbLayer;
Camera cam;

void Start(){
    cam = Camera.main;
}

void Update(){
    Ray ray = cam.ScreenPointToRay(Input.mousePosition);

    Debug.DrawRay(ray.origin, ray.direction * 100, Color.blue);
    
    if(Physics.Raycast(ray, out RaycastHit hit, 100, wsbLayer)){
        if(hit.collider.gameObject.TryGetComponent<WorldspaceButton>(out WorldspaceButton wsb)){
            if(Input.GetMouseButtonDown(0)){
                wsb.onClick.Invoke();
            }
        }
    }
}

if i put this on a random cube in the world, it works
however, if i put it on a collider that is in front of the camera, and is positioned where i want the interaction area to be, it just refuses to work

i have the layer set correctly, i have the component on the object, i tried logging just about everything, and when debugging the ray, it shows up correctly intersecting the object, and i even tried moving the collider farther from the camera and scaling it up
what could possibly cause this? cus i am completely lost

grand snow
#

Normally we would wait for input and THEN raycast to look for the target

#

Another solution would be to use the event system pointer events instead if this custom solution

twilit jolt
grand snow
#

What is the collder you want to hit btw? box?

slender nymph
grand snow
tired python
#

i want only the smoke to be visible and not the squares...i have seen people somehow make the squares transparent

slender nymph
#

Are you referring to the white and gray squares? Because if those are visible that means your image isn't actually transparent

grand snow
#

google images moment

tired python
#

i imported the img from google

slender nymph
#

Yeah so you got a fake transparent image.

tired python
#

wait, so it won't work?

twilit jolt
# grand snow What is the collder you want to hit btw? box?

yup, regular boxcollider
also i already tried logging basically everything, but i went trough it all again in case i messed up the first time (with the layer being passed, nothing is hit; without the layer, it skips through the collider, and logs the name of the object behind it, which is the building you can see in the screenshot)

gonna give the event system interfaces a try also ty for the example repo, super helpful :3

grand snow
#

some silly thing must be wrong then such as a disabled collider component

slender nymph
# tired python wait, so it won't work?

Correct. It's not actually transparent so those won't be transparent.
Also it is a really bad idea to just grab stuff from Google images unless you don't plan to ever release it

tired python
#

i have photoshop so...

slender nymph
#

If it's public then it's still a bad idea. You don't have the license to use that image

tired python
#

now i need to make my own effect too? oh poop

twilit jolt
twilit jolt
slender nymph
eager stratus
#

Apparently using StopCoroutine to manually stop a coroutine from executing causes a "Coroutine continue failure". I'm told that it's harmless and, at least from my testing, doesn't seem to be hurting anything, but it's annoying seeing it in my console. How do I get rid of this?

slender nymph
tired python
midnight tree
grand snow
tired python
#

wait, is it a bad idea to have unity and photoshop open at the same time?

slender nymph
rich adder
tired python
rich adder
#

Ok so you answered your own question

upper token
#

How can I make a functional GroundCheck? One that detects when objects touch the ground (I need to know how to do this to create a jump button).

slender nymph
upper token
pliant dome
#

Is there a place where I can find official information about public class states?

#

for like state machines

teal viper
#

What class exactly are you looking at?

north scroll
#

YO

#

anyone know gitlab and know how to stop it from asking me every 2 minutes for authentification when having forked open

#

or push, imma flip tf out rn

slender nymph
#

i think that's really an issue with fork honestly, it did the same to me for github. authenticate with a token and it should stop

grizzled steppe
#

Is it better to put raycasting for character collisioning in fixed update or update?

slender nymph
#

unless you're calling Physics(2D).SyncTransforms every update, then your colliders are only ever updated on physics frames (same cadence as FixedUpdate), so it makes little difference in precision, and whether it makes a difference for performance would really need to be profiled but unless you're doing a lot of checks per frame then it makes little performance difference

grizzled steppe
#

I'm making a custom raycast character controller

slender nymph
#

yeah i figured. what i said still applies

#

just keep in mind that if that object has a collider but no rigidbody then its collider being recreated every FixedUpdate (on account of it not being moved via rigidbody) will likely be more performance costly than a few raycasts each frame

grizzled steppe
#

I don't have any collider on the player

#

It's using raycasts that fire at parts in the scene

lucid mauve
#

how could i "visualize" whats happening when i do math counts in c#? like, I needed a "fov" raycast based, there was a bunch of calculations that I couldnt comprehend why it was working ingame as I wanted

grizzled steppe
#

Debug.DrawLine(Vector3 start, Vector3 end, Color color, float duration = 0.0f, bool depthTest = true);

#

Can use to visualize raycasts

slender nymph
#

or use the physics debugger if they are 3d raycasts

tired python
#

i have an enemy collision script which is used for single target units. do i need to make a diff script for one which does an aoe attack?

wintry quarry
#

There are no absolute answers through, it really depends on the details of your game and the desired enemy behavior

tired python
slender nymph
#

i would personally use different components for each attack, but have them either inherit the same base class or implement a specific interface, then you can compose your enemies however you want mixing and matching any attacks as you see fit

tired python
#

oh...so the same script has two options, both single target and multi target attacks in it, and i can choose which one i want to use

slender nymph
#

i mean the attack itself is its own component and you put whatever one(s) you desire on the enemy so it uses the one it has assigned

tired python
#

i think you got something mixed up, it's not the enemies who can attack, only my units.

#

it's a tower def game

slender nymph
#

okay so then substitute the word "enemy" in that sentence for "unit" or whatever the fuck you want because that part isn't what is important

tired python
#

should i add an if else condition to check whether the unit this script is being attached to uses a single target attack or a aoe attack and then those different blocks of if and else handle single target and aoe attack respectively

slender nymph
#

no, make the attack component worry about its targeting

#

the "unit" or the overall controller for that object should just care about referencing the attack component and calling whatever targeting/attack methods are required (which would be dictated by the base class or interface that i mentioned before)

wintry quarry
#

And there are many good ways to do it that don't involve repeating a bunch of code that is shared.

sullen trail
#

Hey guys got a question. I am using Fishnet for my multiplayer solution (this is not a fishnet question though). I have a class, named ItemInventoryMember. I am making this a SyncVar (fishnets synchronized field) in another class.

The issue is that in my ItemInventoryMember class, I have public properties such as

        /// <summary>
        /// Gets the quantity of item occupying this <see cref="ItemInventoryMember"/>.
        /// </summary>
        public int Quantity
        {
            get { return _quantity; }

            private set
            {
                if (_quantity != value)
                {
                    _quantity = value;
                }
            }
            
            
        }

The fact that this has a private setter causes fishnet to have trouble serializing them for networking. Basically, i need to make these public setters (ie just use set) for it to work. I don't want other scripts to be able to access the setters though. Any thoughts on how I can approach?

slender nymph
#

the property itself shouldn't be serialized at all, it should be the _quantity field that is serialized. the property is really just a get and set method, so if fishnet is attempting to serialize that directly then it's a bug in that package's code that should be reported

#

or if you are decorating it with some attribute that makes it sync then you're doing it wrong, you'd need to sync the field not the propery

sullen trail
slender nymph
#

then, again, it shouldn't be trying to serialize the property at all, and just serializing the _quantity field. presumably fishnet has its own discord server you can ask for further help in to make sure you are doing things correctly

#

and you should actually let them know what (if any) errors you are getting

sullen trail
slender nymph
#

your property is already correct. again, the property itself shouldn't be serialized. the backing field should be. if fishnet is attempting to serialize the actual property rather than the field then it's a bug in their code.

wintry quarry
#

if you would like to exclude such fields from being serialized use [ExcludeSerialization] above the field.

#

You should simply serialize the field and put [ExcludeSerialization] on the property

#

so it doesn't attempt to serialize the property

#

the field would need to be public though

slender nymph
#

is its serialization really so naive that it doesn't account for full property vs auto property?

wintry quarry
#

seems that way.

slender nymph
#

that seems like a huge oversight

sullen trail
#

So i guess its a little pointless to even use the ExcludeSerialization if i have to make my backing fields public anyways ... lol

#

as in the whole point is so other code can't touch these. seems like exposing the private backing field as public is even worse because it can now be altered + would bypass any logic i was using in the property at the same time

wintry quarry
#

I mean i just think the fact it tries to serialize a public setter by default is stupid

ashen wind
#

hey I need help with my spring joint, I'm getting this error:

Skipped updating the transform of this Rigidbody, because at least one of the position vector's components is infinite. Could you have applied infinite forces, acceleration or set a huge velocity?
#

it only happens when my grappling hook hits something and pulls the player into another collider

#

as soon as the player touches the collider the forces go to infinity

wintry quarry
#

are you doing anything like moving the objects directly in your code instead of using forces etc

ashen wind
#

yes, I'm using MoveTowards to recall the grappling hook, let me see if it stops the error if I comment that out

#

yes that was almost certainly it

#

but now I'm not sure how to make the grappling hook return

wintry quarry
#

you're assigning the Transform position directly or something like that

ashen wind
#
        if (state == "returning")
        {
            rb.linearVelocity = Vector3.zero;
            rb.angularVelocity = Vector3.zero;
            sj.maxDistance = Vector3.Distance(transform.position, player.position);

           
            transform.position = Vector3.MoveTowards(transform.position, new Vector3(player.TransformPoint(hand_position).x,
                                                                                    player.TransformPoint(hand_position).y),
                                                             transform.position.z);```
wintry quarry
#

transform.position =

#

Yeah this is the bad part

ashen wind
#

I've been setting the spring joint max distance to "turn it off"

#

since there's no way to enable/disable spring joints

#

I suspect the position setting wouldn't be a problem if the spring joint was off

#

but I don't know how to do that

wintry quarry
#

unfortunately the way to disable a joint is to destroy it

sullen trail
gaunt mason
#

Hey everyone, I'm stuck in a Terrain Data loop. I duplicated my Terrain Data asset (DesertTerrain -> GrassTerrain) to use in a new scene. I assigned GrassTerrain to the Terrain Collider, but the main Terrain component is still stuck on the old DesertTerrain data. Clicking 'Assign' just forces my Collider back to the old Desert data. How do I force the visual Terrain component to switch to the new asset without it reverting?

In short what I'm trying to achieve is duplicate Terrain A, which would result in having Terrain A and Terrain B, and only change Texture/Material on Terrain B.

sour fulcrum
gaunt mason
#

Sorry for wrong channel, will do

tired python
#

@slender nymph is this similar to the solution you guys were suggesting?

broken meteor
#

I'm honestly quite confused by Quaternion.Slerp atm. To give more context I'm trying to create a situation where a transform smoothly rotates -45 degrees in the Y axis, only once everytime a string is the same.

Right now the behavior seems to only have like one frame of the slerp doing anything or maybe its not doing anything at all, in testing there is a very rough estimate of ~0.01 change in rotation for all values.

I have tried quite a few things, the rotation its-self works without slerp, I'm a java programmer learning c# so I assumed the problem was that I needed to clone each variable, but this was not the case, I've also tried some other configurations to no avail. I have also searched my problem online and I did not see anyone with the same problem as me.

If anyone could help me resolve why my slerp isn't doing anything that'd be amazing 😅

            Quaternion oldLowArmRot = lowArm.rotation;

            if (dir.x < -15 && dir.y < 0)
            {
                if (orientation != "uR")
                {
                    lowArm.Rotate(new Vector3(0, -45, 0));
                    lowArm.rotation = Quaternion.Slerp(oldLowArmRot, lowArm.rotation, Time.deltaTime * 14);
                    orientation = "uR";
                }
gaunt mason
broken meteor
gaunt mason
tired python
slender nymph
tired python
#

something like this

#

and i got this as an answer

#

ain't no way i am using this things code though

wintry quarry
#

Also I have no idea what that sentence about being a Java dev and "cloning" each variable means

broken meteor
#

'preciate it, i'll be back if it some reason doesn't work though

wintry quarry
slender nymph
rich adder
gaunt mason
#

@rich adder Not sure what the emojis are for. If the AI suggestion isn't a fit for the problem, feel free to explain why, otherwise it's just childish.

sour fulcrum
#

we dont suggest ai around here as it's pretty bad at helping people

rich adder
gaunt mason
#

I wasn't only recommending it, I was offering to choose the right one, and see what can be done. It wasn't "just use AI" and ignore the problem...

rich adder
#

"use the right one"
"you just have to give it the proper context"
"get better at prompting to get good results"
yada yada

sour fulcrum
#

"just know what your trying to learn so you know when it lies to you" 😛

gaunt mason
sour fulcrum
#

just a heads up that most of the server feels this way

slender nymph
#

we've all heard all the lame promotions for AI already. you can proselytize elsewhere.

gaunt mason
#

Didn't know it hurts your ego so much

rich adder
#

just take a hike and stop being a bozo

candid wraith
#

upto folks whether or not they want to use AI, but saying that someone's personal choice not to want to use it is childish is strange imho

gaunt mason
#

I said the response was childish, not the perosnal choice

rich adder
#

joined the server today, probably knows nothing about unity here to just try to rage bait

frosty hound
#

Before this turns into the usual conversation, let's make a thread.

#

Otherwise, we can move on from the same responses we all have heard many times before.

#

Sorry, we're not playing "get the last word in". Thanks.

tired python
#

holy 💩

frosty hound
#

If you want to debate AI, please make a thread.

ivory bobcat
# broken meteor Ah, that would make sense then lol, I'm going to have to rethink how Im structur...

You can opt to use a coroutine if the control flow only encounters this situation in one frame but you are wanting it to operate through multiple frames therafter:```cs
if (dir.x < -15 && dir.y < 0)
{
if(!finished)
return;
if (orientation != "uR")
{
StartCoroutine(LowArmRotate());
orientation = "uR";
}
}

private IEnumerator LowArmRotate(float duration = 1f)
{
    finished = false;
    var initial = lowArm.rotation;
    var target = ...;//todo
    for(int progress = 0; progress < 1f; progress += Time.deltaTime/duration)
    {
        lowArm.rotation = Quaternion.Slerp(initial, target, progress);
        yield return null;
    }
    lowArm.rotation = target;
    finished = true;
}```
tired python
#

how do i search for other components attached to a gameobject without using something like GameObjectToSpawn.transform.GetChild(0).GetComponent<EnemyCollision>();

#

the value of the position sometimes ends up making me redo a part of the code everytime i add something new

#

I don't want to use find either cus it searches through all the gameobjects present in the hierarchy which is costly

tired python
slender nymph
#

what does that mean

tired python
#

u know what, i am a moron, ofc that would work

tired python
slender nymph
#

ah, well unless you want to do annoying Find or GetComponentInChildren calls, a serialized field on a root component is the best idea

slender nymph
#

the way i suggested is the best way

tired python
#

cus the get component in children thing is srsly gone case scenario

#

why don't they just remove these stuff...

#

oh...cus projects which are using them won't work anymore

sour fulcrum
#

GetComponentInChildren usage can be appropriate sometimes

tired python
tired python
#
void OnParticleCollision(GameObject other)
    {
        Debug.Log("Particle Collision Detected.");
        Destroy(other);
    }

I want the gameobject which is colliding with the particle to be destroyed, not the gameobject the particle system is attached to

#

how do i achieve that?

#

one way would be to just place this code onto the gameobject which is colliding with the particle, but i don't want it to be managed by that gameobject. I want it to be managed by the unit which the particle system is attached to

verbal dome
#

I thought other would already refer to the other gameobject that you hit?

#

Does the particle system have a collider and is hitting itself or something?

tired python
#

it's just one particle tbh, which is growing in size overtime

tender mirage
sour fulcrum
#

Not really tbh, getchild(0) is super assumey and flimsey which isn’t worth the potential cost there imo

#

if process time mattered you’d do things in a way where you wouldn’t need to do this period

long wraith
#

What is this server about

verbal dome
#

A game engine

median hatch
#

just learn before you learn with AI bro trust me

twin pivot
midnight plover
twin pivot
#

Oh i didnt see that XD, thanks for the info tho

silk night
# median hatch just learn before you learn with AI bro trust me

yes, learn in a traditional way until you have some sense of when the AI could be halucinating and you research further, you dont need to know any topic 100% but you will quickly get a sense of how things work and that will make you able to spot when the AI is being funky

west quail
#

how optimized actually are raycasts?

#

can i just run a bunch every frame or on FixedUpdate without much fps loss?

sour fulcrum
#

do not worry about raycasts

frosty hound
#

What even would be the alternative if someone said they weren't. Use the things the engine provides.

west quail
west quail
#

i can use something different but easier with raycasts so gonna go with them

inland crystal
#

I suspect some people might see 'raycast', get mixed up with 'raytracing' and worry about efficiency but they're really not on the same level

frosty hound
#

It's more than beginners forget computers can do lots of things, fast. It's hard to imagine in our brains such large calculations so naturally the assumption is that it will cause "the lag"

#

You see the same questions in other things like "too many if statements" or "are loops going to lag"

sour fulcrum
#

Tens of thousands also chilling tbh

rich adder
#

Ya I did 70k one time and you can see it a bit in profiler but definitely not as much as rendering / meshes do

sour fulcrum
#

It was at the 500k-ish where i needed to ideally move to the raycastcommand shit

twin pivot
#

They really optimized the shit out of raycasting huh

midnight plover
#

I think this should go into something like #💻┃unity-talk , as its just about personal experience in the overall scope of projects, neither code nor unity related specifically. Also talking about AI is happening over there anyways and has been discussed to extent already

minor swallow
#

Okay ill move it over, sorry about that

minor swallow
#

In rendering I have fog on. Is there a way to disable it in certain volumes? Or disable the fog in rendering and make fog as a volume? I have pretty big contrast between some rooms in my scene and I want to be able to control the atmosphere more

rich adder
sour fulcrum
#

HDRP specifically has that but of course it has a lot more too

minor swallow
#

I know it does change a lot but would it break my game using regular urp

sour fulcrum
#

A lot changes yeah

wintry quarry
low copper
#

I've got an issue with "No Camera" flashing on my screen. To reproduce, I go into my AR scene which is required to have maincamera disabled so it can use XROrigin. I have a additive UI scene with a button on it. This UI scene is used on a lot of scenes. When I click the button it unloads all current scenes and then loads the new one async. On the next scene I have code that enable main camera in Awake(). I don't know how to get rid of that gap as I don't think I want the UI scene controlling cameras.

midnight plover
low copper
#

AR is only small part of the game

midnight plover
#

Ah, got it.

wintry quarry
low copper
#

It will just be black?

wintry quarry
#

it's probably not a big deal

#

yes

#

try it

low copper
#

Ok...that is no big deal. I'm thinking I can also have camera controller in the UI...maybe I dont' need to restrict that.

#

I'm going into an inventory page. I know I will always want main camera

midnight plover
#

you could also hook your main cam to the xr cams state. When it switches off, maincam switches on and vice versa with a simple event.

low copper
#

That sounds like an interesting idea...I already have the events setup

echo ruin
#

Is it not possible to manipulate a component if it's part of an array? Or is there something I'm missing?
I'm trying to animate an object by manually setting the SpriteRenderer.sprite in an array, and while debugging, it shows that the correct sprite has been assigned the SpriteRenderer component. However, in-game, it still shows the standard sprite.
I figured I'd ask here instead of the animation chat, since I don't use the animator component
https://puu.sh/KI7FR/74103512a5.png

frosty hound
#

You can change the sprite whenever/wherever you want. Being part of an array has no bearing on that.

echo ruin
#

That's what I was thinking too

frosty hound
#

Why it's not showing, could be any number of things. Possibly overridden elsewhere in your code to be the standard sprite? Could be you're looking at the wrong sprite? Could be that this component isn't on the sprite you're looking at?

wintry quarry
echo ruin
#

For testing purposes, I only have that one object in the entire scene. At least the only object with a SpriteRenderer. I'm curious if it's even possible to have any SR components if it's not even attached to an object?

naive pawn
wintry quarry
#

how many elements in your array? Which element is this one?

echo ruin
#

Index 0. Only object in the array

wintry quarry
#

Ok and check that it's actually the object in the scene, and not for example, a prefab reference

naive pawn
midnight plover
echo ruin
#

Yeah. It's a ECS-like system. All other "components" work just fine. The object correctly moves when index 0 is processed. It shows the correct stats when I debug [0]. The only thing I can think of is that the animation part is handled from a different script

#

But I suppose the references should be correct

naive pawn
naive pawn
wintry quarry
#

Or just checking the inspector in UnitManager and seeing what it's pointing to

naive pawn
#

or check in this object with the debug inspector

echo ruin
#

It seems to have assigned the Unit(Clone) correctly to the SR array

midnight plover
#

Ah, you already debugged it, okay

midnight plover
echo ruin
#

No

#

I'm trying to animate manually by just assigning the sprite to the sprite renderer

pastel cave
#

I've heard the new unity input system is "awful". I've certainly felt a little resistance but my usecase was... farily unorthodox, do people agree with this? If so, what makes it awful? I'm looking to make a local multiplayer game and it seems... okay for this usecase...

naive pawn
midnight plover
midnight plover
wintry quarry
#

(i disagree)

pastel cave
naive pawn
naive pawn
pastel cave
#

It's not something I nessicarily expect it to cover

naive pawn
#

well you're in luck, it does

midnight plover
polar acorn
minor swallow
pastel cave
#

Thank y'all

echo ruin
#

!code

radiant voidBOT
midnight plover
pastel cave
naive pawn
#

it's pretty hard to confirm or dispute an opinion that just says "X is good/bad" when no reasoning is provided

pastel cave
#

Fair enough.

naive pawn
#

can't read their mind, maybe they just didn't like it based on vibes lol

pastel cave
#

At minimum it's nice to confirm that people do use it for local multiplayer, which likely means it's good enough for me

naive pawn
#

input system can be used for all input, it's effectively a superset of the old system

midnight plover
#

I guess, most people not based on tutorials, are using it nowadays, because its just way easier to handle when setup (my opinion)

echo ruin
naive pawn
#

most tutorials you'll see with still be using the old system, given that, well, there's years and years worth of input manager tutorials, and only a few years worth of new input system tutorials

pastel cave
naive pawn
#

no clue tbh, i didn't get that far before learning the new system

pastel cave
#

I see

naive pawn
#

there's a controller 1/2/etc config in the input manager, maybe it's that

pastel cave
naive pawn
#

this might be useful to you (at least in comparison if nothing else) #🖱️┃input-system message
as an example of "input system can be used in a lot of ways"

naive pawn
#

just gotta be familiar enough to make that translation

red igloo
#

Hey, So I am trying to add a raycast from the player so it follows my mouse, The ray is being cast from an empty game object in my player which is following my mouse input. My issue is its not accurately following my mouse. This is a feature I am adding where you can throw the ball is this a dumb way to do it? If I cast the ray from the camera that's not really going to work. Any ideas?

Script: https://paste.ofcode.org/Q6hTsk24G6nn2ekv7XerKS

midnight plover
red igloo
#

wtf obs is not showing the game window odd..

naive pawn
red igloo
naive pawn
#

cool, so you just aren't showing the bug then lmao

ivory bobcat
#

We'd need to see how this reacts to the scene from the game camera (scene view)

naive pawn
#

how do you know it's not accurately following your mouse if you don't show where it is in relation to your mouse

#

draw some gizmos to see in the gameview

#

also, in terms of ui/ux - how do you plan to resolve depth exactly? as in, what's the intended behavior
eg, if you have your mouse on the edge of the player, should that go towards the camera, parallel to the camera plane, away from the camera?

midnight plover
# red igloo

you want to raycast against the 3d world from your cameras position to get a hitpoint that you can use to visually attach the end of your line to it. right now you are going from your switcher into whatever is RayTarget.forward, which is basically some local direction not in world space

echo ruin
#

Honestly just me being stupid. The code worked correctly, but I still had an animator component on the prefab which, I assume, was overriding the sprite change

naive pawn
midnight plover
echo ruin
midnight plover
#

glad you fixed it

echo ruin
naive pawn
#

you could have a similar thing with maintaining indices with lists, or even with dictionaries

#

just without preallocation

#

but i don't know the context/usecase, so maybe that preallocation makes sense /shrug
-# not a recommendation exactly, just thinking out loud

ivory bobcat
# red igloo Hey, So I am trying to add a raycast from the player so it follows my mouse, The...

So from what I can see, you've cast a ray from the player in some forward direction relative to rotation acquired from look input; which is acquired from look action. This can probably produce syncing issues and the drawn ray will not be relative to the mouse position on the screen. The ray direction is definitely moving when the mouse moves but perhaps you should take a different approach.. like cast a ray from the screen-camera to the scene and simply make your object look-draw-a-ray to wherever your mouse had been pointing to relative to the screen. Otherwise, it is moving relative to the acquired input action - just not relative to the object, it would seem.

echo ruin
#

I'm really just trying out different systems to get a broader understanding of coding in general

naive pawn
echo ruin
#

Not that I'll stick to this pattern. Just thought it would be interesting to try. Also hence the reason I'm animating manually. It's a challenge

naive pawn
#

i mean like, what happens if you need a new one but availableIndices is empty thinkies

echo ruin
naive pawn
#

not really

#

you can do the same with a list

#

a list is just a wrapper for an array that sometimes makes a new array

echo ruin
#

You'd still have to change some of the logic.
unit[i] attacking unit[unit.target[i]] changes if another element in the list is destroyed or removed

naive pawn
#

you don't have to remove it from the list, same way you're handling it with the array

echo ruin
#

But if I want to remove it from the array...

#

What exactly are you trying to get at?

naive pawn
#

however you're "removing" it from the array, you can do the same with a list

naive pawn
# echo ruin What exactly are you trying to get at?

my point is i see 2 potential issues to these arrays, and changing them to lists would eliminate those issues while introducing a minor third one (that can be tuned to be less impactful, depending on usecase)

echo ruin
#

I think I already stated that I'm doing this as a way to learn.

#

I'm not doing it for efficiency or performance

naive pawn
#

ok, 1 of the potential issues of the arrays was perf. the other is functionality

#

what happens if you need a 1001th element? 1000 is arbitrary
a list lets you dynamically handle the amount requirements

midnight plover
#

😄 Just keeps on going

fresh fern
#

i am a beginner coder and i am making various side projects to increase my skillset. i try to replicate arcade games (because i have been suggested to do that a lot) and i am currently doing pong. it is a nightmare! could anyone give me some tips? i have tried doing it by using the bouncy physics material on my ball, i have tried making the bouncing myself with basic code, but everything i try has at least one major bug/ flaw that just destroys it all

echo ruin
#

Isn't that irrelevant without the context?
If I want a game where I need more than 1000 objects, sure. I'm practicing, so array lenght is arbitrary and it's not really important

naive pawn
#

you're learning, right? so i'm trying to give an opportunity to learn how to make extensible systems without arbitrary numeric restrictions

echo ruin
#

I've been working with lists up untill now

#

Lists, Dictionaries, Staks, Queues

#

I thought I'd try the old fashined way

naive pawn
#

fair enough, but making these lists would be 2 lines of change

#

and it wouldn't affect the overall logic of maintaining indices

#
  stack availableIndices
- array entities
+ list entities

  new:
-   return availableIndices.pop()
+   if !availableIndices.empty():
+     return availableIndices.pop()
+   else
+     entities.push()  // or reserve more and push to availableIndices
+     return entities.size() - 1

  // exact same code for removal & retreival
echo ruin
#

I don't see what it is you're not understanding. Why are you so persistent on changing something I'm doing for fun?

naive pawn
#

...huh? this wasn't an attempt to win you over to lists

midnight plover
#

sounded like

echo ruin
#

I didn't come here to ask for improvements or changes. I had a bug and wanted to see if anyone could help me find the issue

naive pawn
#

i can get not wanting to change just because you aren't interested. but the previous reasons you gave just weren't relevant

midnight plover
naive pawn
#

i'm here to help people learn, and i'm trying to show how lists would be pretty much drop-in while giving a little improvement.
you gave reasons for not using lists that weren't correct, so i disputed those.

echo ruin
#

Where was I wrong?

naive pawn
#

i'm not trying to convince you to use lists. i'm just trying to show how they can be used here

midnight plover
#

guys..., you wanna use a thread for this?

fresh fern
#

Well when i use the physics material the ball eventually slows down

#

And when i do it with code, it sometimes goes into walls

fresh fern
midnight plover
naive pawn
# echo ruin Where was I wrong?

#💻┃code-beginner message -> you wouldn't have to change the retreival or removal logic, you can maintain indices in the same way as you are with the array - by just not touching them

i realize my replies here could be somewhat condescending.. that's not my intent, sorry if it comes off that way

fresh fern
#

Some slow some fast

fresh fern
#

I think it was with velocity

midnight plover
#

Maybe show your code, as we are in a coding channel 😉

fresh fern
#

But i deleted all that code to use the physics material

midnight plover
#

Oh, well

#

😄

fresh fern
#

Nevermind

#

I will try again from scratch

#

Thanks for replying

fresh fern
#

To make physics update more often

#

I thought it was always a 0.02 sec or something?

#

That would be very useful

naive pawn
# naive pawn ```diff stack availableIndices - array entities + list entities new: - re...

i guess my real point is - this is an opportunity to learn about analyzing for restrictions and making future-proof/extensible code. i don't know if you're already experienced with that and thus don't care in this learning instance, since i'm not in your head. it's your choice whether you want to use that opportunity or not, but if you present objections that don't apply then i'm going to dispute them

fresh fern
#

Though more resource intensive

echo ruin
# naive pawn https://discord.com/channels/489222168727519232/497874004401586176/1468995122006...

Okay. I'm not sure you read the code I pasted.
The target[] array is an int array. A unit having a target means that it's acting towards an index corresponded to the array. If a unit is moving towards target[5], and I want to remove target[4], nothing will happen to [5] because that unit's data is attached to that index in an array. If I unit.RemoveAt(4), suddenly the corresponding indices will shift down, and the unit will now target what was previously target[6].
That's what I mean by "changing logic". I understand that you can change things up. I could allocate an identity int within one of the struct. I could use a dictionary with ints as keys. But that's essentially changing the logic

naive pawn
#

how are you "removing" with the array currently? just saying the index is available, or also setting it to null?

you can do the same with the list.

echo ruin
#

public bool[] indexOccupied;

naive pawn
#

using a dictionary with ints also doesn't change the logic, just the underlying data structure

naive pawn
# echo ruin ` public bool[] indexOccupied;`

sure, you can make a list for that too. my point is- you don't have to change the logic at all.
a list is a thin wrapper around an array, you can use the list like an array plus the "resize" operation.

echo ruin
#

Unless I want to remove things from it...

naive pawn
#

you can "remove" things in the same way as you are removing from the arrays you already have

#

RemoveAt removes the data and the slot. here (in the current array case, and changing the array to a list) you just remove data and not the slot

echo ruin
#

So now we've moved the utility of lists to be equal to that of arrays, if I know I wont pass the array size

naive pawn
#

the benefit being pre-made dynamic allocation. this was my entire point, yes.

#

that's what i meant by it being "drop-in" for this usecase

echo ruin
#

I don't often ask for help in here. It can be a bit dreadful trying to ask for something and it's often met with "Why would you.." or "Why don't you.." with something completely unrelated to the context I bring

naive pawn
#

is it that it sounds condescending?

echo ruin
#

It's that there's a persistence with getting a point across rather than to just meet the people where they're at with their questions.

naive pawn
#

it's a pretty effective thing to point out something that might not be ideal and challege the assumptions that wrote that solution (in general)

naive pawn
#

that's what i'm trying to do here

#

that's what "why are you doing X" is intended to get at - it's easier to build off of reasoning once it's verbalized

echo ruin
#

If I say I want to learn to do a design revolving around arrays, it doesn't help if I'm being told to use something other than arrays

naive pawn
# naive pawn the benefit being pre-made dynamic allocation. this was my entire point, yes.

maybe this would clear it up -
the main "issue" (not really an issue in the specific case, but something that could be improved) is the static allocation.
dynamic allocation would solve that "issue", making it more generalized
that's what lists are, dynamically allocated arrays, with a bunch of extra operations. you don't need those extra operations, so you can just ignore them

#

you could do dynamic allocation yourself if you wanted too, that's also a pretty nice thing to learn

#

and again - i'm not telling you to not use arrays. i'm pointing out that lists could be used here.

#

lists are just a thin wrapper around arrays. the change i'm suggesting would have 90% of the use still treat it as an array.

echo ruin
#

I'm well aware of what lists are. Thank you

midnight plover
#

Can you guys either go into a thread or just stop? This is getting frustrating to read along... everyone made their point.

echo ruin
#

I apologize if I sounded a bit hostile. It wasn't my intention.

red igloo
# ivory bobcat So from what I can see, you've cast a ray from the player in some forward direct...

This is what I have got, The ray from the player is following the ray from the camera went and tested it out and it does follow but its not accurate at all.

using UnityEngine.InputSystem;

public class AimFromMouse : MonoBehaviour
{
    [Header("References")]
    [SerializeField] private Camera mainCam;
    [SerializeField] private Transform playable;

    [Header("Ray Settings")]
    [SerializeField] private float rayLength = 100f;
    [SerializeField] private LayerMask aimMask;

    private RaycastHit hit;

    void Update()
    {
        CastCameraRay();
    }

    private void CastCameraRay()
    {
        Vector2 mousePos = Mouse.current.position.ReadValue();
        Ray cameraRay = mainCam.ScreenPointToRay(mousePos);

        Debug.DrawRay(cameraRay.origin, cameraRay.direction * rayLength, Color.cyan);

        Vector3 origin = playable.position;
        Vector3 direction = cameraRay.direction;

        Debug.DrawRay(origin, direction * rayLength, Color.red);

        if (Physics.Raycast(origin, direction, out hit, rayLength, aimMask))
        {
            Debug.Log("Playable ray hit: " + hit.collider.name);
        }
    }
}
ivory bobcat
# red igloo This is what I have got, The ray from the player is following the ray from the c...
    private void CastCameraRay()
    {
        Vector2 mousePos = Mouse.current.position.ReadValue();
        Ray cameraRay = mainCam.ScreenPointToRay(mousePos);

        Debug.DrawRay(cameraRay.origin, cameraRay.direction * rayLength, Color.cyan);

        Vector3 origin = playable.position;
        Vector3 target = cameraRay.GetPoint(rayLength);
        Vector3 direction = (target - origin).normalized;
        float distance = (target - origin).magnitude;

        Debug.DrawRay(origin, direction * , Color.red);

        if (Physics.Raycast(origin, direction * distance, out hit, rayLength, aimMask))
        {
            Debug.Log("Playable ray hit: " + hit.collider.name);
        }
    }```Player direction is incorrect
#

This would have them pointing to the same point some distance away relative to the ray length.
Ideally, you'd normally do a ray cast first to see if there are objects in the way and would use that hit-point as the target for both the camera and player rays.

red igloo
#

I am still not understanding why its not accurate? my mouse will be on for e.g. a wall and there are no debugs but if I keep moving up then the debugs will happen. Do I need to adjust the camera ray as well?

#

do both hit points need to be touching? I mean like the tip of the ray do they both need to be touching?

ivory bobcat
# ivory bobcat This would have them pointing to the same point some distance away relative to t...
    private void CastCameraRay()
    {
        Vector2 mousePos = Mouse.current.position.ReadValue();
        Ray cameraRay = mainCam.ScreenPointToRay(mousePos);

        Vector3 target = cameraRay.GetPoint(rayLength);
        Vector3 origin = cameraRay.origin;
        Vector3 direction = (target - origin).normalized;
        float distance = rayLength;

        if (Physics.Raycast(origin, direction * distance, out hit, rayLength, aimMask))
        {
            Debug.Log("Camera ray hit: " + hit.collider.name);
            target = hit.point;
            distance = (hit.point - origin).magnitude;
        }
        Debug.DrawRay(origin, direction * distance, Color.cyan);

        origin = playable.position;
        direction = (target - origin).normalized;
        if (Physics.Raycast(origin, direction * distance, out hit, rayLength, aimMask))
        {
            Debug.Log("Playable ray hit: " + hit.collider.name);
            target = hit.point;
            distance = (hit.point - origin).magnitude;
        }
        Debug.DrawRay(origin, direction * distance, Color.red);
    }```
slender sable
#

Where is there an 4, and why??

ivory bobcat
slender sable
#

Its C#

solar hill
#

for help with unity

ivory bobcat
#

!csds

radiant voidBOT
solar hill
#

also your second image litterally explains this

slender sable
naive pawn
solar hill
#

actually

#

it is wtf

ivory bobcat
solar hill
#

is this ai generated?

#

this looks one of those "learn programming apps" which are almost entirely ai generated

naive pawn
#

maybe it's just desynced - the code was changed the description wasn't updated or vice versa

slender sable
solar hill
#

this server and channel are for unity specific issues

naive pawn
spare summit
#

Hi I was just wondering if it was possible to detect if an object is colliding with an object based off of a tag and when it does it reloads the scene. Except both objects have the same tag so I want the main object to not be detected but rather the other object. If that makes sense XD
heres wat my code looks like so far.

using UnityEngine;
using UnityEngine.SceneManagement;

public class InsideObject : MonoBehaviour
{
    private string currentScene;
    public string[] tags;

    private void Start()
    {
        currentScene = SceneManager.GetActiveScene().name;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        foreach (string tag in tags)
        {
            if (collision.gameObject.CompareTag(tag))
            {
                Debug.Log($"Collided with {collision.gameObject.name} (tag: {tag}). Reloading scene.");
                SceneManager.LoadScene(currentScene);
                return;
            }
        }
    }
}

basically the issue I'm coming across is that its reloading the scene because the object with the script has the one of the tags in the array. I want to detect for the other objects not the main one.

ivory bobcat
naive pawn
naive pawn
spare summit
naive pawn
#

up to your design. i'm honestly not sure what the situation/context is

red igloo
frail hawk
#

sounds like a XY problem, maybe explain what you are doing @spare summit

#

or what you want to achive

spare summit
#

so basically I'm having an issue with my crates that they get stuck inside of eachother. I want to detect that and then correct it. Thats basically the idea I have with fixing the bug. But I can't figure out how to detect the crate with out detecting the main crate itself

#

@frail hawk

#

the reason why this is happening is the system I have with the movement script where it stops the movement script from working if a crate is next to another crate. But this created the bug I show in the video and I've kinda been putting it off for some time now

frail hawk
#

do you know this: Physics.IgnoreCollision

#

research it might be what you want.

ivory bobcat
#

Likely the mask isn't correct and you're firing off way into the back ground

spare summit
#

how would I make sure an object stays on the grid in play mode. Like the object doesn't go into whole numbers they only stay on .5's like 2.5, 3.5, 5.5 that kinda thing

ivory bobcat
ivory bobcat
grand snow
red igloo
#

Ok so for some reason the issue was the ray lenght I set it to 200 and its literally working now but this feature is for throwing a ball I want to have a max distance. The ray lenght value 5 was perfect but if I lower it then the issue will reoccur The issue was the layerMask I removed it and its now working

hard tapir
#

Hello, I am making a platformer game with rooms.
I would like my player to switch to another room smoothly (keeps reletive pos and velocity) when it touches an object. Ive tried and failed to make a script but I get an error when I use it.
If someone can tell me whats wrong with my script or give me a link to a source that explains how to do this it would be greatly appreciated

#
using System;
using UnityEngine;
using UnityEngine.SceneManagement;

public class switchRooms : MonoBehaviour
{
    [SerializeField] int switchTo;
    static string switchToText;
    GameObject switchedTo;
    [SerializeField] GameObject player;
    static bool switched;
    static Vector3 playerPosition;
    static Vector3 playerVelocity;
    int goToRoomsInScene = 0;
    int goToRoomIndexTracker = 0;
    GameObject[] goToRoom;


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Awake()
    {
        GameObject[] allObjects = FindObjectsOfType<GameObject>();

        foreach (GameObject obj in allObjects)
        {
            if(obj.name.StartsWith("goToRoom"))
            {
                goToRoomsInScene++;
            }
        }

        goToRoom = new GameObject[goToRoomsInScene];

        for (int i = 0; i < allObjects.Length; i++)
        {
            if(allObjects[i].name.StartsWith("goToRoom"))
            {
                goToRoom[goToRoomIndexTracker] = allObjects[i];
                goToRoomIndexTracker++;
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (switched)
        {
            for (int i = 0; i < goToRoom.Length; i++)
            {
                Debug.Log(goToRoom[i].name);
                if (goToRoom[i].name == switchToText)
                {
                    switchedTo = goToRoom[i];
                    Debug.Log(goToRoom[i].name);

                }
                Instantiate(player, new Vector3(switchedTo.transform.position.x + Math.Sign(playerPosition.x), switchedTo.transform.position.y + Math.Sign(playerPosition.y)), Quaternion.identity);
                player.GetComponent<Rigidbody2D>().linearVelocity = playerVelocity;
                switched = false;
            }

        }
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if(other.gameObject.tag == "Player")
        {
            playerVelocity = player.GetComponent<Rigidbody2D>().linearVelocity;
            playerPosition = player.transform.position;
            switched = true;
            switchToText = $"Room {switchTo}";
            SceneManager.LoadScene(switchToText);
        }
    }
}
wintry quarry
wintry quarry
wintry quarry
#

Also: switchRooms is not a good class name for several reasons:

  • Class names should be nouns not verbs. This is a component in the scene that may do something. "room switcher" would be better.
  • Class names in C# should use PascalCase- so RoomSwitcher for example
wintry quarry
hard tapir
#

Instantiate(player, new Vector3(switchedTo.transform.position.x + Math.Sign(playerPosition.x), switchedTo.transform.position.y + Math.Sign(playerPosition.y)), Quaternion.identity);

wintry quarry
#

Which makes sense because it's very possible in your logic there for it to have never been assigned to anythiong

#
                if (goToRoom[i].name == switchToText)
                {
                    switchedTo = goToRoom[i];
                    Debug.Log(goToRoom[i].name);

                }
                Instantiate(player, new Vector3(switchedTo.transform.position.x + Math.Sign(playerPosition.x),```
#

If this code runs and the if statement does not get entered, you will still have switchedTo as null

#

and then you're trying to get the position on a null reference, bad.

hard tapir
#

I see, thank you! have a great day

naive pawn
# hard tapir

for future reference, use mp4 so it embeds in discord

tender mirage
naive pawn
#

true

midnight plover
naive pawn
#

dropping mp4 was not part of that message

midnight plover
#

😄

#

you are one of a kind 😉

tender mirage
#

Yeah, mp4 is more universal. I was moreso refering to how common mkv files were

#

since they're often exported from recording sessions

midnight plover
#

totally agree, just wanted to state, that there is rather one standard than trying to cover more not so frequently used formats for broad device support. Thats all 😄 Not gonna start another discussion here

polar acorn
#

The thing is, there's no such thing as an mp4 format. It's a file type that contains many kinds of video encoding. It's actuall the h.264 encoding that makes it embeddable. The file type doesn't actually matter, the encoding matters

topaz hatch
#

What is the proper syntax for wanting to check if a compared value is greater than a negative number? Currently with this script the cube rotates up to the max value, rotates the other direction, but does not reverse course again once it exceeds the stated negative value (min Rot)

` if (reverseRot == false)
{
print("Rotating to the right");
transform.Rotate(0,0, rotationSpeed * Time.deltaTime);

if (gameObject.transform.eulerAngles.z >= maxRot)
{
    print("I am at max rotation.");
    reverseRot = true;
    return;
}
return;

}
else if (reverseRot == true)
{
print("rotating to the left");
transform.Rotate(0, 0, -rotationSpeed * Time.deltaTime);
if (gameObject.transform.eulerAngles.z <= minRot)
{
print("I am at minimum rotation.");
reverseRot = false;
return;
}
return;
}`

naive pawn
#

it being negative doesn't have an effect in the comparison

#

the issue might be in reading the eulerAngles though. that's typically not regarded as reliable afaik

#

it's not the canonical representation of the rotation

wintry quarry
naive pawn
#

store the current rotation amount yourself and only set it to the transform, don't read it back

naive pawn
red igloo
midnight plover
naive pawn
#

the human psyche is such a weird thing

topaz hatch
#

Why would simply saying "If X rotation is -90 go in reverse" also not work?

polar acorn
#

it might be 270

ivory bobcat
naive pawn
polar acorn
#

Basically, you should only ever write to euler angles, not read from it

#

Because you could literally do:

eulerAngles.z = value;
Debug.Log(eulerAngles.z == value);

and get false

naive pawn
#

(pedantically - you can read from euler angles if you just store the Vector3 yourself, but not Quaternion.eulerAngles or Transform.eulerAngles)

ivory bobcat
#

I mean, if you really want to look at it you can but it shouldn't be thought to be the value that is actually used by the Transform component.

polar acorn
#

When you do transform.eulerAngles, it will compute a possible euler angle expression that represents the orientation. There's an infinite number of euler angles values for any given rotation, so you can't depend on that being a specific one

topaz hatch
#

Gotcha. I'll do that when I get back. But that makes sense.

wintry quarry
red igloo
wintry quarry
inland lark
#

what's a good 2d top down engine to use?

wintry quarry
solar hill
#

considering you are in the unity server

inland lark
solar hill
#

no, you dont need it

#

this is just an asset to make making these kinds of games faster and easier ig?

#

but as a beginner i would highly recommend you go the manual route

wintry quarry
solar hill
#

it does nothing you can do on your own

#

it has some good example projects and i guess it can be useful in some situations

wintry quarry
#

moving platforms, an advanced room system, persistence, smart input management, progress management, collectibles, a loot system, kills manager, destructible crates, keys and chest/doors, and more. Also achievements, dialogues, progress management, save and load, and tons of other useful stuff!
This stuff is all so bespoke as to most likely be useless.

#

it's trying to be a "do everything" asset

solar hill
#

but its really not needed

#

and its overhyped just like their "feel" asset

wintry quarry
#

oh are these the guys behind Feel? I actually considered buying that a while back

solar hill
#

kind of

edgy tangle
#

That’s kind of underrepresenting it. A lot of it is tween-based but it also has components to simplify particle system and audio handling. Overall I think it’s a very good tool if you don’t want to bother with cooking up solutions for every little piece of feedback you want to give to the player

#

I agree though on their “game engine” assets. Seems like it would pigeonhole your designs

unique spear
#

Guys pls help me 🙏 . I don't know why this code doesn't boost player's speed:
private void OnCollisionEnter2D(Collision2D collision)
{
grounded = true;
if (sliding)
{
if (collision.gameObject.CompareTag("enemy"))
{
Debug.Log("sliding into enemy");
rb.linearVelocityX = rb.linearVelocityX * 10f + side * 25f;
}
}
}
(side is a variable that when the player presses 'D' it has the value of 1, 'A' -> -1)

solar hill
unique spear
solar hill
broken meteor
unique spear
solar hill
#

i think it might be a physics issue actually

unique spear
solar hill
#

if you hit the enemy and collide with them, then you set your velocity to some high number, the physics solver might be applying some sort of opposing force to slow you down

ivory bobcat
solar hill
#

to prevent you from phasing through the enemy

unique spear
solar hill
#

have you tried using addforce?

#

instead of changing the velocity directly

unique spear
solar hill
#

bruh that would be something to mention first

#

means youre failing somewhere in the 2 conditionals

#

youre either not setting the sliding bool to true, or your collision object doesnt have the enemy tag

#

add another debug under the if "sliding" and see if that triggers properly

wintry quarry
#

Or OnCOllisionEnter2D just isn't running at all

unique spear
#

the sliding works just fine

polar acorn
unique spear
#

i figured it out! after the player touches the enemy, the enemy's tag switches to "deadEnemy" and it probably is doing it faster than the if statement can check the tag. Sorry guys for trouble, I'm such a dumbahh, thanks for your help!

wintry quarry
hallow sun
#

Quick question, does base.Function() call the previous inhertiance or the first?
For example, would this print "1 2 3" or just "1 3"?:

public class BaseClass : MonoBehaviour {
  public virtual void Function() {
        Debug.Log(1);
    }
}
public class SecondClass : BaseClass {
    public override void Function() {
        base.Function();
        Debug.Log(2);
    }
}
public class ThirdClass : SecondClass {
    public override void Function() {
        base.Function();
        Debug.Log(3);
    }
}
polar acorn
#

This is something I'd probably need to run to know for sure, but thankfully you've got a perfectly reasonable example. I'd just slap that into a project and tryitandsee

slender nymph
#

yeah definitely tryitandsee
but it would indeed print 1 2 3. base.Function() would call the previous version of the method in the inheritance line

wintry quarry
#

ThirdClass base.Function will call SecondClass Function

red igloo
# wintry quarry you need: 1. A plane raycast (unlimited range) to find the point the mouse is pr...

Sorry for the late response, I have been trying to figure this out and this is what I have so far. I never really used plane.raycast so I don't know if I did it right but as you can see it doesn't follow the mouse properly and when I move the cursor infront of the player the ray doesn't go in front of the player.


    private void CastRay()
    {

        Plane playerPlane = new( -mainCam.transform.forward, mainCam.transform.position + mainCam.transform.forward * 10f);

        Ray mouseRay = mainCam.ScreenPointToRay(Mouse.current.position.ReadValue());

        if (playerPlane.Raycast(mouseRay, out float distance))
        {
            Vector3 targetPoint = mouseRay.GetPoint(distance);

            Vector3 direction = targetPoint - playerSwitcher.currentPlayer.transform.position;

            if (Physics.Raycast(playerSwitcher.currentPlayer.transform.position, direction, out hit, maxRange, aimMask))
            {
                Debug.DrawLine(playerSwitcher.currentPlayer.transform.position, hit.point, Color.red);
            }
            else
            {
                Debug.DrawRay(playerSwitcher.currentPlayer.transform.position, direction.normalized * maxRange, Color.green);
            }
        }
    }


wintry quarry
#

My understanding was you essentially had a 2.5D game and you wanted the player to be able to aim only on the gameplay plane

#

but now in this video I see the player walking in 3D space

#

So what's the actual goal here?

solar hill
#

maybe they are missunderstanding what 2.5d means in this scenario? UnityChanHuh

wintry quarry
#

When I say "2.5d game" I mean 3d art that can only move side to side and up and down like an original 2d mario sidescroller just with 3D art

solar hill
#

when i personally think 2.5d i imagine a game that uses 2d sprites in a 3d enviroment

#

to me it just sounds like youre describing a 3d sidescroller

solar hill
#

or paper mario

wintry quarry
#

The point is the gameplay happening on a 2d plane

#

Anyway I need a description from @red igloo about what this game mechanic is supposed to be doing and how they want it to work

#

If as a player my mouse is on the floating cube in this picture, what should happen? What if it's on the wall that's in shadow on the left, or the wall in shadow deep in the distance?

red igloo
red igloo
wintry quarry
#

will it be thrown at the cube? Will it be thrown up and to the left of the player on the same plane the player is at?

wintry quarry
#

Imagine extending the cyan line out to infinity. We need to decide where along that ray the "throw target" is

#

Should it be whatever physical object we see that is closest to the camera along that ray?

#

So in this case, the back wall?

#

This screenshot maybe shows it even better.

pure pine
#

halo

balmy vortex
#

is there any reason as to why I can't or shouldn't grab UI objects as gameObjects in serialized fields?

wintry quarry
#

Can you show exactly what you are trying to drag and where you are trying to drag it to?

balmy vortex
#

oh no I mean like is it bad practice or?

#

cuz like actually doing it works fine

wintry quarry
#

That's how Unity works

solar hill
#

how are you defining the field?

#

can you show the line of code

#

and what exactly youre trying to drag into it

red igloo
pure pine
#

when i write Lander.OnUpForce += Lander_OnUpForce; it should auto create a function with that name and add a bunch of stuff to it (following a tut) but for some reason that isnt working for me , its not autocompleting it and i have to write that function myself , why?

wintry quarry
#

so you mean the nearest physical object on its path?

#

Or what?

radiant voidBOT
pure pine
#

already did those

#

its not all ide , its just this one thing

wintry quarry
# pure pine already did those

It isn't supposed to automatically make the method. What it should do is give you the option to auto create it in the little light bulb context thing that pops up

#

The tutorial person may also be using a different IDE that makes the experience a little nicer

wintry quarry
wintry quarry
pure pine
wintry quarry
wintry quarry
pure pine
#

ig imma write everything

wintry quarry
#

And passing in the sender as an object is just silly

pure pine
wintry quarry
#

ok? That's not related to the point i was making

pure pine
#

i thought telling u what im trynna do would lead to u proposing a better way

#

sorry

wintry quarry
#

I'm just saying the delegate type they chose for the event is silly. In fact you're not using any of the arguments at all so System.Action would have been fine.

#

(this would be something you have to change in the LangerControls script as well as here)

#

anyway I'm not sure why your IDE isn't helping you out here

pure pine
#

alr thanks for the hlep

#

imma take a C# course cus rn im not understanding anything

wintry quarry
red igloo
# wintry quarry I'm not asking about rays (yet), just about what your desired gameplay behavior ...

Ok so what I want is a throw player feature so right now I have a separate script where the main player which is a ball when entering the trigger zone near the capsule and presses E you switch to the capsule player and the ball disappears. This script that I am doing now will allow the player to throw the main player (Ball) by holding right mouse button. I am going to add a aim feature where it shows you where your about to shoot the main player.

wintry quarry
wintry quarry
#

Is this a language barrier problem? Are you not understanding the question I'm asking?

#

The #1 most important part of software development is being able to explain what it is exactly that you want, in detail.

#

Without that we can certainly write some code that does something, but it might not be the thing you want it to do.

red igloo
strange jasper
#
    void Update()
    {
        for (int i = 0; i < LegIKTargets.Length; i++)
        {
            Vector3 target = transform.position + legOffsets[i];
            float distance = Vector3.Distance(LegIKTargets[i].position, target);
            if (distance > legThresold) {
                GroundLeg(i);
            }
        }
    }

Why doesn't my distance check work?

polar acorn
#

My guess would be that distance > legThreshold is never true. Log both values and see

strange jasper
polar acorn
#

Did you log distance? Is it the value you expect it to be?

strange jasper
#

nope, it gradually increases, its at 9 even when the current leg position is the same as the target

polar acorn
#

So, if distance is what you expect it to be, and legThreshold is what you expect it to be, then it appears it's working fine

strange jasper
#

distance should be 0 if my legs are at the target

#

since the leg would be no distance from the target

polar acorn
#

Okay, so then go one step back: Log LegIKTargets[i].position and target and see which one isn't what you expect

strange jasper
#

i think its because the target and leg arent on the same y

grand snow
#

Id upgrade to a debugger for something like this

wintry quarry
#

I guess the second raycast is to see if it will hit any obstacles on the way towards that point?

dreamy lance
#

im fallowing a tutorial for making a hex based grid and ive gotten to the part in the tutorial where they make a auto genorating mesh for it but its super hard to fallow along and it looks like the skip parts of the code does anyone have an recources for this ?

valid stone
#

I'm sorry I know other people are asking questions here too and my one is relatively petty can I still ask it?

#

It's time to sleep anyway so let me ask tomorrow and not interrupt anyone rn

solar hill
#

huh

#

youre allowed to ask questions freely here

#

you arent interrupting anyone...

cosmic dagger
kindred blade
#

what do these mean "()"

solar hill
normal perch
#

👍

kindred blade
solar hill
#

you are probably better off learning these things from some sort of c# tutorial

#

because these are the very basic of the basics, language agnostic as well

strange jasper
#
IEnumerator GroundLeg(int leg)
    { 
        RaycastHit hit = new RaycastHit();
        Vector3 localOffset = legOffsets[leg];
        Vector3 target = transform.TransformPoint(localOffset);
        Vector3 startPos = LegIKTargets[leg].position;
        // Create a ray from the target downwards for the leg
        Ray ray = new(
            target + transform.up * rayCastHeight,
            Vector3.down
        );

        if (Physics.Raycast(ray, out hit, rayCastDistance, rayCastLayerMask))
        {
            float elapsed = 0f;

            while (elapsed < legDurationMove)
            {
                // Parabolic leg movement with animation curve
                elapsed += Time.deltaTime;
                float t = Mathf.Clamp01(elapsed / legDurationMove);
                float height = curve.Evaluate(t) * stepHeight;

                Vector3 pos = Vector3.Lerp(startPos, hit.point, t);
                pos.y += height;

                LegIKTargets[leg].position = pos;

                yield return null;
            }

            LegIKTargets[leg].position = hit.point;
        }
    }

Hi again, small problem, why aren't my spider legs affected by the rotation of the spider? like for example I face my spider against a wall and its legs don't move to the wall

shell nacelle
#

is it worth it to use a kinematic rigidbody for more control over my player

#

2d platforming game btw

tired python
#

why does spline animation mess with the z component when neither the map nor the scene have different z components?

rich adder