#💻┃code-beginner

1 messages · Page 629 of 1

tribal wave
#

-# i am VERY stupid

cosmic quail
#

spawning an object

tribal wave
cosmic quail
tribal wave
#

thanks

orchid fern
#

hi i am still a beginner in unity can someone help me make a save system?

If anyone can help please contact me privately!

low warren
#

hey guys
i am stuck in a bug for around two or three weeks
i can't wall jump after another wall jump
here you can see that i can't jump after colliding with the other wall
idk why

slender nymph
#

show relevant !code

eternal falconBOT
low warren
slender nymph
#

that is one of the sites you can use, yes

low warren
#

i don't see any share thing

void notch
#

Strange! Maybe double check if you have any unused using statements, I would expect code stripping to strip out parts you don't use. Or set it to high ( Project Settings --> Player --> Optimization). See image for reference. If this doens't help I would suggest #🌐┃web

low warren
orchid fern
#

hi i am still a beginner in unity can someone help me make a save system?

If anyone can help please contact me privately!

slender nymph
cloud walrus
#

Guys i need help fixing this bug:

What I'm trying to do in details:
So i made the script Ball_mover which moves the ball directly towards the player, and it did work well at first without any bugs but later on when i add physics to the ball (aka Rigidbody) it started bugging

Anyhow to fix that?

low warren
slender nymph
#

okay so what debugging have you done? or are you just saying that you've just tried random shit and expected to find a fix?

void notch
low warren
low warren
void notch
#

There's a lot to debug. Check if all the booleans are correct in the first place. But I would suggest just re-write it a bit simpler so you understand it again.

low warren
#

or no?

void notch
#

There's code that says: canWallJump = false in your wallJump() method. So very likely that has something to do with it.

low warren
#

nevermind let me try it

void notch
#

If you always want to wall jump, just remove the boolean canWallJump 😄

cloud walrus
slender nymph
#

you need to show code if you want help with your code

eternal needle
cloud walrus
#

okay here's my code

using UnityEngine.UIElements;

public class Ball_Mover : MonoBehaviour
{
    [SerializeField] Transform player;
    [SerializeField] float moveSpeed = 1f;
    Vector3 playerPosition;
    void Start()
    {
        playerPosition = player.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, playerPosition, Time.deltaTime*moveSpeed);
    }
}```
slender nymph
#

yeah, it also appears that everything by the Y for both position and rotation is constrained on the rigidbody

cloud walrus
slender nymph
eternal needle
#

if you want physics, you have to move via physics too. Use the rigidbody and AddForce in the direction that you want

slender nymph
#

that is when physics is updated

steady flame
#

wow thats a lot of information

cloud walrus
low warren
#

okay i found a thing
when I'm colliding with the other wall
IF I press the arrow key of that direction(left OR right) the player WILL jump

eternal needle
cloud walrus
candid goblet
#

set a varible to accest you rigid body, and access it velocity in your code witha vector3

slender nymph
steady flame
#

I downloaded it and imported it and now i imediatly i got 3 Errors:

#

@rocky canyon

rocky canyon
# steady flame

ya, i fell off into a rabbit hole,
i'm actually still working on it.. i figured it'd be nice to wire up my character controller and pause menu stuff to the rest of my UI and have it ready..

steady flame
#

wdym?

rocky canyon
#

i just added the confined bit.. to demonstrate it beter

limber flower
#

ive downloaded a movement script on unity from 2019 that comes with an example player prefab, but when i use the prefab it just falls through any objects i put it on top of and the controls dont work, or if i put the movement script on an object with a rigidbody, it just floats while still not being controlable, my input keys seem to be correct, im not sure what i need to do to get this to work

slender nymph
#

perhaps check the asset's documentation to see what setup is required to make it work

limber flower
#

all it has is a readme that says you can either use the prefab or use put the movement script on an object to do the camera control yourself

#

i checked the issues tab on github and none of the solves for similar issues worked for me

slender nymph
#

then either link it so someone can look at it since nobody here is psychic so we cannot possibly know what you're using or what its requirements are or post an issue on the github or anywhere else the asset author accepts support requests

limber flower
#

heres the github

slender nymph
#

are the objects that you put the prefab above on the default layer or are they on a different layer?

limber flower
#

all of the objects in the parent prefab are on default

#

and the objects below yes

slender nymph
#

i did not ask about the objects in the prefab

limber flower
#

yeah i misinterperated it but everything is on the default layer'

slender nymph
#

then you probably need to look at the layer mask on SurfPhysics to make sure it isn't set to None or something

#

otherwise you should be asking the asset author for help

limber flower
#

ill put an issue request

wintry dew
#

When is an Abstract class useful in c# nowadays? I previously thought they were useful for standard implementation but you can do that with interfaces, so any methods without implementation are just the same as "abstract" methods in an abstract class right?

#

Are they only good for having inheritable variables?

slender nymph
#

depending on your needs an abstract class can possibly be interchanged with an interface instead, but abstract classes are strictly for inheritance and can contain variables as well as properties and methods, can have non-virtual/non-abstract methods that contain behavior.
interfaces can only define properties and methods, and while you technically can add default behavior to an interface method in most cases you really shouldn't

wintry dew
#

i see so its just better practice to not use interfaces for "is-a" relationships

#

and overall more troublesome

cosmic quail
grand badger
eternal needle
wintry dew
#

Yeah it's just a medium of classifying a group of scripts so they can be accessed as a group

undone pier
#

does this code mean 'yield return null' is stepped into once per frame?

public IEnumerator Test()
{
    while (true)
    {
        yield return null;
    }
}
wintry quarry
undone pier
#

I see. Thanks both

worn spade
#

anyone know the problem here?

wintry quarry
#

!Ide

eternal falconBOT
worn spade
wintry quarry
#

that's one part of the instructions

#

do all of them

worn spade
#

i think its this

wintry quarry
#

If that's one of them, you have to do it, yes.

worn spade
wintry quarry
#

don't ask me, read the instructions

slender nymph
worn spade
#

at this point all packages are being downloaded

slender nymph
#

sounds like a waste of space, but alright

slate roost
#

if (hit.distance <= Mathf.Abs(velocity.y) + skinWidth)
This if statement is coming back false, even though the debug says otherwise? any idea how I can fix this?

#

wait I'm dumb, I was comparing the debug in reverse!

well, now I have a different problem

#

I'll try doing < || Mathf.Approx
but if anyone knows a better solution, I'd welcome it!

white girder
#

Any way to make logs not stack up like this?

humble marsh
#

This took me too long to figure out. Anyone else happen to figure this out?

public bool isEmpty() {

return !( amount == 0); 
slender nymph
slate roost
#
float _compVelocityY = Mathf.Abs(velocity.y) + skinWidth;
if (hit.distance < _compVelocityY || 
    Mathf.Approximately(hit.distance, _compVelocityY))```
hmm, this did not work, its still coming back false... anyone know how I can fix this?
obtuse ether
#

hi just coded smth for a bullet that makes it move torwards the player

#

and flip the sprite depending on its x velocity

#

but is there a way for me to just make it point straight at the player?

#

i know the vector pointing to the player im just not sure how to turn that into a direction for the gameobject

humble marsh
#

Quaternion.Lookrotation to get a rotation, transform.lookat(playerpos) to make it just look at player

teal viper
#

That would probably make it look on the z axis, which is not what you want in 2d.

obtuse ether
obtuse ether
#

im now trying to figure out how to fix that

teal viper
#

That's not gonna work. You could keep the bullet sprite orientation with it's x axis and assign the direction to transform.right

#

Actually, nevermind that. It might flip the sprite to the back face.

#

You could keep flipping the sprite and assign the transform.right toPlayerDir or -toPlayerDit depending on the flip state.

timber tide
#

LookAt should work, no? Just use z as world up

obtuse ether
#

i should prolly start learning more abt those

timber tide
#

oh wait is this topdown or sidescroller

ivory bobcat
obtuse ether
obtuse ether
#

i think learning how rotations work is gonna kill me

polar acorn
#

You can actually just assign a value to transform.right like it was any other direction variable and the object will point in that direction

obtuse ether
obtuse ether
#

oh my gosh

#

it was that easy

calm shoal
#

im trying to open a script but it does this can someone help

obtuse ether
#

😭

teal viper
obtuse ether
#

my mind is going to kill itself now but thanks for the help

eternal falconBOT
obtuse ether
ocean loom
#

hey guys, im working on a 2D game for a project, and i wanna add an ability where the character shoots and when the bullet collides, the character transform position = collision transform position. However this only works when the prefab is added to the hierarchy, and not when i instantiate the bullet. Can someone help me with this

calm shoal
versed light
slate roost
#

and that seems to work ok, gonna do some playtesting with it

versed light
#

then just add a 0.0001f epsilon to skin width

#

eg
velocity.y <= Mathf.Abs(velocity.y) + skinWidth + 0.0001f

slate roost
#

I'll try that, that seems less messy than what I did

versed light
#

the <= should not always be false due to imprecision issues though

calm shoal
# ocean loom

ok so it was the installer it gave me, which one do i choose there is a bunch

versed light
#

usually imprecision issues is for == more so than <=

#

unless you're dealing with very small velocities and skin widths

calm shoal
#

what visual studio is best for unity?

rich adder
#

read the description

calm shoal
#

oh ok

#

what is this😭

rich adder
calm shoal
#

ok

ocean loom
calm shoal
#

i did that

#

i downloaded it how do i get it in unity now?

rich adder
#

mate all the steps you need are in the link

#

follow them carefully

calm shoal
#

how do i fix this?

rich adder
#

you can't put Non-Components on gameobjects

calm shoal
#

then how do i get the script to work on the camera?

rich adder
#

make it a monobehavior ?

calm shoal
worn spade
slender nymph
rich adder
#

you likely have compile error

eternal falconBOT
rich adder
#

also this ^

slender nymph
slender nymph
slender nymph
#

if you had gone through all of the troubleshooting steps then your visual studio is working

worn spade
#

what module are u supposed to install?

#

In the Add modules to your install step, select Done.

slender nymph
#

why not read the instructions and find out?

#

actually wait, those are part of the instructions for installing unity. are you just not comprehending the instructions you are reading?

worn spade
#

vas

#

no visual studio is trolling

#

thats about it

#

reinstalled both same problem

slender nymph
#

no, you're just not bothering to pay attention to the actual instructions

worn spade
#

vsc on the other hand

worn spade
slender nymph
#

prove it. open visual studio and screenshot the entire window with the solution explorer visible

worn spade
slender nymph
worn spade
#

how

slender nymph
#

or did you mean that as "yep, i did not bother going through the page you linked to me"

slender nymph
slender nymph
#

no you didn't. i can very clearly see in your screenshot that you did not complete the troubleshooting steps

worn spade
#

what exactly did i not do

slender nymph
#

why don't you bother reading the fucking instructions instead of lying and saying you did

worn spade
#

because i can tell u exactly what ive done

#

i have read the instructions and ive done them the ones that apply to me..

slender nymph
#

and i can tell you exactly what you didn't bother doing, and that is to read the troubleshooting instructions that i linked to you

worn spade
#

Connect Unity and Visual Studio and use Visual Studio Tools for Unity to support writing and debugging for cross-platform development.

#

these 2 right?

slender nymph
#

specifically the first one, yes. because that also links to the second but also the first one has troubleshooting instructions for if it is still not working after completing the typical setup steps

#

so fucking read them

worn spade
#

step 1 run

#

if that doesnt work read it again

slender nymph
#

step 1 for you should apparently be "learn to read"

worn spade
slender nymph
#

bullshit

worn spade
#

its like i actually did the steps its nuts

slender nymph
#

then what was the first troubleshooting step it told you to do

worn spade
#

idk what u told me

#

i dont even know u

slender nymph
worn spade
#

the US is changing alphabet

#

u need it more

slender nymph
worn spade
#

then what was the first troubleshooting step i told you to do

#

is what i read

#

my bad man

slender nymph
worn spade
#

b for monkey

teal viper
worn spade
#

some shit like that

#

then download visual studio, with all the packages ez

teal viper
#

That's not all the steps. There are steps specifically for when you've set it up, but it still doesn't work.

worn spade
#

i know thats not 10/10 compared to the fucking configuration

#

what am i missing

#

packages are pre installed

#

true or false

teal viper
worn spade
#

oh yeah i did that one 55 times

slender nymph
#

you do realize that your screenshot earlier proved you didn't even do step 1 there, right?

teal viper
#

Did you regenerate project files? Via unity? Did you regenerate project files via VS?

worn spade
#

no i clicked on the button that says regenerate files

#

or something like that

#

no visual anything after being clicked

#

still restarted 69 times

teal viper
worn spade
#

alr

teal viper
#

And yes, it seems like you don't have the unity workload either.

worn spade
#

yeah i was right

#

it was something like that

teal viper
#

Follow all the steps and take a screenshot at every one of them.

worn spade
#

im not going to reinstall

teal viper
#

You don't need to reinstall. If it's installed already just take a screenshot

worn spade
rich adder
slender nymph
#

obviously not since that would actually fix it

rich adder
#

that will tell you for sure if you do or dont have the Workload

teal viper
worn spade
#

the other link that talks about workload?

teal viper
worn spade
#

no i didnt

#

what the fuck is workload

teal viper
worn spade
#

its not even in the title why would it be relevant

teal viper
#

Is everything relevant supposed to be in the title..?

worn spade
#

maybe

teal viper
#

Here's a quote from the page. Now go read it properly

Select the Workloads tab, then select the Game development with Unity workload.
worn spade
#

oh classic

#

i remeber that one

rich adder
worn spade
teal viper
worn spade
rich adder
worn spade
rich adder
#

Checkbox selected doesnt mean much if it shows Install size rather than gained space size or 0

worn spade
rich adder
teal viper
# worn spade

You don't need all of them, but ok. now the next screenshot. The correct VS selected in the external tools in unity.

rich adder
#

also never a good idea to configure IDE with Errors in the compiling. As mentioned in the troubleshooting steps

teal viper
# worn spade

Great, now follow the "if you are experiencing issues" steps. All of them. In order. No skipping.

junior basin
#

Hey there, I was wondering how one might go about rotating this "beak" object around the beakPivot parent? Currently it's rotating fine, but I haven't managed to get it to rotate as a pivot to the parent if that makes sense. If you need me to elaborate on anything further just lemme know, thanks!

#

BeakPivot is positioned at the opposite end to where the BeakTip is on the cylinder btw

rich adder
worn spade
# rich adder done what exactly?

If you have compiler errors, if possible comment out those files so Unity can compile code.
Ensure the Visual Studio Editor package is installed and updated in UPM (com.unity.ide.visualstudio).
Regenerate project files via Unity.
Close VS.
Select regenerate project files in EditPreferencesExternal Tools.
Reopen VS via AssetsOpen C# Project.
Regenerate project files via VS.
If an assembly in the Solution Explorer is marked as (incompatible), right-click it and select reload with dependencies.
Restart your computer.

rich adder
worn spade
#

ye

rich adder
worn spade
junior basin
rich adder
# worn spade

solution explorer in VS, did you do the Reload With Dependencies

#

show it

worn spade
#

thats the 1 thing i didnt do

rich adder
#

so why did you say you done everything

#

makes no sense

worn spade
#

didnt think it applies to me

rich adder
#

pleaase dont say such stupid things, you were specifically instructed to follow ALL the Steps

#

if you here to just troll find another server..

worn spade
#

yeah bro im having the time of my life trolling rn

rich adder
#

it would be lot less frustrating to you and everyone involved if you actually learned how to follow a step by step instruction without claiming "it doesnt apply to you" when its part of Troubleshooting

rich adder
#

make a video if you must

worn spade
#

restart time

slender nymph
#

congrats, it is configured after that

#

if only you'd followed the instructions earlier when i told you to you would have been done a long time ago

rich adder
# worn spade

ya you didnt check solution explorer again after you did that..

#

but is configured

slender nymph
#

i don't even understand how they thought that step didn't apply to them since it was clear from their earlier screenshot that the project was marked (Incompatible) and that is like the main thing mentioned for that specific troubleshooting step

rich adder
#

ya I always think troll but there is that Hanlon's razor part

worn spade
rich adder
worn spade
slender nymph
#

instead of making assumptions about everything you should read the information presented to you

teal viper
worn spade
teal viper
#

Also sharing the whole !code could be helpful

eternal falconBOT
slender nymph
#

look at your using directives

#

that's where your initial error was

worn spade
#

idk what that is

rich adder
#

this is nonsense

worn spade
teal viper
rich adder
worn spade
#

the guy did it flawlessly

rich adder
#

its not good to copy code when you dont even know the basics of formatting

slender nymph
worn spade
#

yeah its been tampered with recently, fuck the code isnt the whole configuration of IDE supposed to fix MonoBehaviour?

slender nymph
#

your errors on previous lines are causing that error

teal viper
worn spade
teal viper
#

Even if you have a perfectly working chair, when break it's legs, you can't use it properly, can you?

#

Or if you put it upside down

worn spade
teal viper
worn spade
#

trueing

worn spade
#

is what it was meant to look like

#

thx for helping man im really grateful

teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

teal viper
#

Ideally right now, before continuing with whatever you're doing.

worn spade
teal viper
#

You can get this done in a week or two.

worn spade
teal viper
#

Not sure what you mean by that?

worn spade
#

not forced to leave my room type shit

#

is this the basics u was talking about?

teal viper
junior basin
#

@rich adder I realise I was a bit weird in my wording but it's all sorted now, thanks for getting my brain to work though 😁

amber spruce
#

anyone know how to format numbers so if the number would be 1000 then its 1K or if its 1000000 1M and so on and stuff preferably would be able to just keep going and stuff

rich adder
cedar prairie
#

Why doesnt my mesh stick to my ragdoll?

rich adder
cedar prairie
#

cheers

amber spruce
# rich adder You could set your own threshold then return the suffix for it, iirc you can als...

so i was actually able to get chatgpt to do it for me partially sadly it still wont be endless but it should be basically endless because unless someone finds a way to edit the save data no one will get enough money to get more then it has rn

but my issue im having is the way it rounds up and stuff so i have it once it starts using abreiveations to display for example 9.8K but it displays that when your at 9750 so i dont think that is the right aproach since it will not give the most acurate numbers

#

got any ideas

#

should i add another number at the end so it would be 9.87k or change it to only switch to 9.8K when it reaches 9800

#

or smth else

teal viper
tulip herald
#

!code

eternal falconBOT
nimble apex
# worn spade

before u do coding, i strongly recommend u to download rider

#

its a very very useful coding tool

#

and its completely free

rich adder
nimble apex
worn spade
#

having fun doing the educational course

rich adder
worn spade
nimble apex
#

yeah plz tell me ur still a student and under learning

worn spade
rich adder
#

"its not the tools that make an artist"

nimble apex
#

🤔

slender nymph
nimble apex
#

🤓 👍

rich adder
#

are you getting a commission from jetbrains lmao

nimble apex
#

its better than visual studio and vsc in my opinion , anyway i dont have commission nor financially supported by jetbrain

rich adder
#

they can use rider and struggle with the same lack of basics regardless, the editor doesnt mean anything in your learning

nimble apex
#

ofc, but after they learnt the basic and wanna get their hands dirty, thats the moment it gone useful

worn spade
#

what does that icon mean bottom right

nimble apex
#

oh thats cinemachine

worn spade
#

does it have any functions

rich adder
#

you're jumping way ahead of yourself

nimble apex
#

its a better camera with more function than the old one, but its way more advanced topic

#

if u really wanna have a learning step or learning curve , in a very simple manner

C# basics > unity editor basics (QWERTY / creating objects) > intermediate C# skills > advanced unity skills > extensions

#

colliders, rigidbody or any stuff like that is around basics

rich adder
#

the unity pathways are the best to get foot in the door, they cover most of those

nimble apex
#

yeah

nimble apex
# worn spade

u know what, ignore that little icon first unless the lectures teaching it, follow the path in unity learn

if u encounter some more mysterious icons u can ask here

cosmic gorge
#

!code

eternal falconBOT
worn spade
#

is there a way to always use wasd in scene view instead of mouse controls

cosmic gorge
#
Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

Super quick question, how come when creating a new rigidbody variable, you have to specify that "rb" is getting the rigid body component when you've already specified "Rigidbody rb;" at the top??

#

or just any component variable for that matter

eternal needle
rich adder
cosmic gorge
rich adder
eternal needle
cosmic gorge
#

my head is gonna explode

#

sorry im very new to this

rich adder
#

no 0 is 0

eternal needle
#

you should really look into c# basics then first and follow an actual tutorial, plus do examples to wrap your head around it

rich adder
#

null is default for reference types
if you want more understanding , look up Reference Types vs Value Types

cosmic gorge
cosmic gorge
#

saying "Rigidbody rb;" doesnt assign the component to rb, it just tells unity that thats where the variable is being stored??

rich adder
cosmic gorge
calm adder
#

Hello! Quick question, const means that a variable can only be changed when its first created

nimble apex
rich adder
#

only on the initializer

nimble apex
#

after that u cant change

nimble apex
# cosmic gorge okay that makes a lot more sense now thank you

if u wanna distinguish null and 0 quick , heres the rule , 0 is something and null means nothing

0 is a number right? no matter how u understand it, it is a number/value, so its related to number types, lets say int(eger), or float, or double, yeah it can also be a char/string , but u need to know it is a value, it is NOT nothing

0 or 0.0f is the default value of number types , because of special reasons, in C# those simple types cannot be nulled, they must always have a value , so if u dont do anything to integers/floats, they will still get a 0 , and it means they have a value

as for reference types, like those rigidbody, they dont need to have something at first, they can be empty, because u can "reference nothing" and C# allows it

#

u will get null reference tho if u try to use the value 💩

rich adder
#

well string is reference type
(basically an array of chars)

nimble apex
#

string is quite special here, because C# allows string to have nothing

#

oh that make up the whole thing lol

rich adder
#

but yeah they have value semantics
aka they are immutable, can be compared by value with ==

eternal needle
#

i would really avoid just dumping information like this, to just let them learn from an actual resource. Even just bringing up int? to say we can ignore it is going to confuse them more. Plus I don't think char[]{0}; is even valid syntax

#

Ive never really seen these kind of teachings benefit the person more than just letting them go and learn properly. Strings werent even the topic of discussion

rich adder
#

this is a code channel

worn spade
#

anyone know where i can find some scenes to fuck around in maybe environmental or something

rich adder
timber tide
#

Unity provides templates

worn spade
#

wait theres more?

worn spade
boreal umbra
#

Hello, what code can I use to reverse the direction of movement when an object collides with a second object (it may be a bit unclear because I'm using a translator)

rich adder
#

Vector3 direction = new Vector3(1, 0, 0);
direction = -direction;

#

or multply by -1 etc

boreal umbra
#

Oh,thanks

eternal needle
bright zodiac
sour fulcrum
#

the difference is that string in a lot of contexts is treated more like a standard value non nullable type rather than an object

#

can trip people up

plush belfry
#

im trying to make a 2.5D Platformer but my jump button doesnt work when i play the game on my phone but when i try it in the phone simulator on my pc it works. The right and left movement works on my phone as well just the jump button doesnt. The problem doesnt occur because of the onGround variable not being true, I tried removing the onGround variable from the jump if statement and it still only works in the simulator not on a real mobile device. It may have something to do with the way I made the jump button I just put an image on the canvas and gave it a touch button component and mapped it to the south gamepad button and in the input system manager I added the south gamepad button to the jump action is there maybe something wrong with doing it that way or is there a better way to do it? https://paste.mod.gg/basic/viewer/cbeznexattvf/0

eternal falconBOT
rare basin
#
private Queue<ICommand> GatherCommandsAsQueueInOrder()
{
    var commandsQueue = new Queue<ICommand>();
    foreach (Transform commandEntry in _commandsParent)
    {
        var commandEntryComponent = commandEntry.GetComponent<CommandEntry>();
        commandsQueue.Enqueue(commandEntryComponent.Command);
    }

    return commandsQueue;
}

could someone explain to me, why this throws error The non-generic type 'Queue' cannot be used with type arguments?

#

it's not possible to return a Queue of ICommands?

#
public interface ICommand
{
    Task Execute(Rigidbody rb);
}
#

ah lol, i wass missing a namespace

#

nevermind

rancid tinsel
#

!code

eternal falconBOT
digital stone
#

hi, need some help, i am using a function for player movement that addforce , i want to keep the momentum and velocity constant, what is the library function in unity for that

young pewter
#

hey guys, I am having trouble using the new input system
basically, I can't make a click action work
this is my script:

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class MeleeAttack : MonoBehaviour
{
    [Header("References")]
    public Animator animator;
    public InputActionReference fire;

    [Header("Parameters")]
    public int numberOfAttacks;
    public float cooldown;

    private float timer = 0f;
    private float cooldownTime = 0f;
    private int attack = 0;


    private void OnEnable() 
    {
        Debug.Log("enabled");
        fire.action.started += PerformAttack;
    }

    private void OnDisable() 
    {
        fire.action.started -= PerformAttack;
    }

    private void PerformAttack(InputAction.CallbackContext obj) 
    {
        Debug.Log("Cooldown = "+cooldownTime + " timer = "+timer+" attack = "+attack);
        if (timer > cooldownTime) {
            if (attack >= 3) {
                cooldownTime = timer + 2 * cooldown;
                attack = 0; 
            } else {
                attack++;
                cooldownTime = timer + cooldown;
            }

            animator.SetInteger("Attack", attack);
        }
    }

    
    void Update()
    {
        timer += Time.deltaTime;
    }
}
#

these are the settings

#

what am I doing wrong?

#

It is not calling the perform attack function (the debug is not appearing on console)

timber tide
#

may need to call fire.enable. I forget

hexed terrace
#

Was just gonna say the same

pulsar dock
hexed terrace
#
protected override void EnableInputs()
{
    click.Enable();
}

protected override void RegisterActions(bool register)
{
    click.performed -= Click;

    if (register == false) { return; }

    click.performed += Click;
}
amber spruce
#

how can i make a button do 1 thing when i just click it once and do another thing when i hold click on it for like more then a second

#

(i need a button to do 2 things for a mobile game so i cant just do right click)

hexed terrace
#

Off the top of my head, I can't remember if they work with touch though.. so, test

amber spruce
#

public void OnPointerDown()
{
isHolding = true;
holdTimer = 0f;
}

public void OnPointerUp()
{
if (holdTimer < holdTime)
{
StartCooking(); // If released quickly, cook instead
}
isHolding = false;
}
so like this?

hexed terrace
#

No

#

Nothing (other than two vars being set) will happen while it is down, and start when you release

#

The below informs you how to share !code correctly

eternal falconBOT
amber spruce
#

ooohh it was 3 of those things i thought it was 2 i was super confused lol thanks

hexed terrace
#

Click will happen every time, unless you put in some check if you don't want it too

amber spruce
#

Also is there a better way of doing what I’m trying to do because I have a button that i need to click to start it but also click to open upgrade menu

#

Would it be better to add another button above it to open the upgrade menu

hexed terrace
#

With that amount of info.. I'd say yes

raw fiber
#

How do i make that the button needs to be played to the end and only then can get played again?

frosty hound
#

You have two options:

  1. Don't use PlayOneShot but instead assign the buttonClip to the audioSource directly and .Play() it. That will let you check if the audioSource isPlaying in your PlaySound() function's if statement.

  2. If you want to use PlayOneShot, then you need to also have a bool IsSoundPlaying that is set to true when you play the sound, and then set back to false by using something like a coroutine that waits the length of the AudioClip buttonClip

raw fiber
#

whats the problem and where can i set it to single or smthing

frosty hound
raw fiber
#

and where can i set active input handling to single?

verbal dome
#

The settings window has a search bar in the top right

raw fiber
#

i already searched that there

verbal dome
#

It's under the Other Settings tab

raw fiber
#

what other settings tab

verbal dome
#

In the player settings.

raw fiber
#

found it thaks

shy edge
#
using UnityEngine;
using TMPro;

public class ProjectileGun : MonoBehaviour
{
    public GameObject bullets;

    public float shootForce, upwardForce;

    public float timebetweenShooting, spread, reloadTime, timeBetweenShots;
    public int magazineSize, bulletsPerTap;
    public bool allowButtonHold;

    int bulletsLeft, bulletsShot;

    bool shooting, readyToShoot, reloading;

    public Camera fpsCam;
    public Transform attackPoint;

    public GameObject muzzleFlash;
    public TextMeshProUGUI ammunitionDisplay;

    public bool allowInvoke = true;

    private void Awake(){
        bulletsLeft = magazineSize;
        readyToShoot = true;
    }

    private void update(){
       MyInput(); 
       if (ammunitionDisplay != null){
        ammunitionDisplay.setText(bulletsLeft / bulletsPerTap + " / " + magazineSize / bulletsPerTap); 
       }
    }

    private void MyInput(){
        if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
        else shooting = Input.GetKeyDown(KeyCode.Mouse0);

        if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
        if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();

        if (readyToShoot && shooting && !reloading && bulletsLeft > 0){
            bulletsShot = 0;

            Shoot();
        }
    }
#

    private void Shoot(){
        readyToShoot = false;

        Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        RaycastHit hit;

        Vector3 targetPoint;
        if(Physics.Raycast(ray, out hit)){
            targetPoint = hit.point;
        }
        else{
            targetPoint = ray.GetPoint(75);
        }

        Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

        //spread
        float x = Random.Range(-spread, spread);
        float y = Random.Range(-spread, spread);

        Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0);

        //make bullet
        GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
        currentBullet.transform.forward = directionWithSpread.normalized;

        currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
        currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * shootForce, ForceMode.Impulse);

        if (muzzleFlash != null){
            Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);
        }
#

        bulletsLeft--;
        bulletsShot++;;

        if(allowInvoke){
            Invoke("ResetShot", timeBetweenShooting);
            allowInvoke = false;
        }
    }

    private void ResetShot{
        readyToShoot = true;
        allowInvoke = true;
    }

    private void Reload(){
        reloading = true;
        Invoke("ReloadFinished", reloadTime);
    }
    private void ReloadFinished(){
        bulletsLeft = magazineSize;
        reloading = false;
    }
}
#

getting these errors what do i do

queen adder
#

how do i fix this

verbal dome
shy edge
#

nvm im stupid lol

digital stone
verbal dome
slender nymph
# queen adder how do i fix this

make sure all packages are up to date, if the error persists after updating packages then close unity, delete the Library folder from within your project, and open unity again so it regenerates the Library folder (this will also cause a full reimport of all your assets)

slender nymph
eternal falconBOT
hollow geyser
#

Hello once again here for a question 😅

So I am creating a fp horror game in which there is a line xRotation -= mouseY;
So someone please help me to understand this line plz !

#

Hope someone will respond

slender nymph
#

you already received an answer in #💻┃unity-talk
if you need further information then clarify what you still do not understand

queen adder
#

There's always an error like this how do I fix it, thanks

slender nymph
#

that is neither a code issue nor an error

queen adder
#

so how do i get rid of it or its meant to be there

molten ridge
#

Hi, the (Lightbulp) Quick actions and refractories is not working for me. It's the very first time I'm scripting.
After I write "update" then press Tab on the keyboard, it should automatically write "private void update()"
But it just goes a few spaces forward instead. I tried CTRL+. and by right clicking it, nothing happened. The lightbulp is also not showing on the left side.
Photo for reference:

eternal falconBOT
molten ridge
#

Thanks!

fleet venture
#

I have this treatmentImage.sprite = Resources.Load<Sprite>("Assets/Art/hospital"); and the asset exists but it doesnt load, do i have to do somethign special to turn an asset into a resource?

slender nymph
fleet venture
#

ooooh okay

untold shore
#

Hey y'all, having some trouble atm with my coding. Currently, I want to have a random chance to have a special card pop up so the player can play it. However, this would have to be in a specific area and I don't really know how to do that. (Can y'all tell Im a beginner beginner?) Anyway lol, here's my code.
https://paste.ofcode.org/32QSFc2xZbGYFHuZwgUDziw
What I basically want is the clones of these cards (which have the buttons to do stuff attached to them) to pop up, with a random chance to be any one of them.

How would yall go about it? I cant really find any good videos to watch on going about this. Thanks. (Please @ me if you respond, thank you so much!!!)

grand snow
untold shore
thorn holly
grand snow
dusky pike
#

    private void AttachButtonToCard(GameObject cardObj, GameObject cardButtonPrefab)
    {
        GameObject buttonObj = Instantiate(cardButtonPrefab, cardObj.transform);
        buttonObj.transform.SetParent(cardObj.transform, false);
        buttonObj.transform.SetAsLastSibling(); 

        Button buttonComponent = buttonObj.GetComponent<Button>();

        if (buttonComponent != null)
        {
            Debug.Log($"Button added for: {cardObj.name}");
            
            Button buttonCheck = buttonObj.GetComponent<Button>();
            Debug.LogWarning($"Button still there? {buttonCheck != null}");
            
            buttonComponent.onClick.RemoveAllListeners(); 
            buttonComponent.onClick.AddListener(() => OnButtonClick(buttonObj));

            Debug.Log($"Number of listerners {cardObj.name}: {buttonComponent.onClick.GetPersistentEventCount()}");
            
            Button buttonCheck2 = buttonObj.GetComponent<Button>();
            Debug.LogWarning($"Button still there? {buttonCheck2 != null}");
        }
    }

produces these logs:

  • Button added for: Card_Air Boost

  • Button still there? True

  • Number of listerners Card_Air Boost: 0

  • Button still there? True

#

What am i doing wrong?

slender nymph
#

GetPersistentEventCount() does not count listeners added via AddListener. a PersistentListener is one added via the inspector

untold shore
dusky pike
grand snow
slender nymph
grand snow
slender nymph
#

it should also be set as the last sibling by default

dusky pike
#
  
private void AttachButtonToCard(GameObject cardObj, GameObject cardButtonPrefab)
    {
        GameObject buttonObj = Instantiate(cardButtonPrefab, cardObj.transform);
        buttonObj.transform.SetAsLastSibling(); 

        Button buttonComponent = buttonObj.GetComponent<Button>();

        if (buttonComponent != null)
        {
            Debug.Log($"Button added for: {cardObj.name}");

            buttonComponent.onClick.RemoveAllListeners(); 
            buttonComponent.onClick.AddListener(() => OnButtonClick());

        }
    }


    // Die Methode, die aufgerufen wird, wenn der Button geklickt wird
    private void OnButtonClick()
    {
        Debug.Log($"Button auf der Karte {this.name} wurde geklickt!");
    }

So this should produce a log, right?

slender nymph
#

when the button is clicked, yes

dusky pike
slender nymph
#

have you confirmed that the button actually works?

dusky pike
grand snow
#

im gonna guess its not sized or positioned correctly to ACTUALLY be clickable

dusky pike
#

(The Button image is the black thing)

slender nymph
#

click the event system and check it's preview window when you try to click the button (click the button multiple times to be sure since clicking out of the game view makes it lose focus so the first click in it again will be the one to give focus back)

dusky pike
#

Ahh, i found my Problem... I am building the Card Objects here:


    private void Start()
    {
        _getUnits = FindObjectOfType<GetUnits>();
        _getUnitDecks = FindObjectOfType<GetUnitDecks>();
        _getCardObjects = FindObjectOfType<GetCardObjects>();
        
        // Lade alle Karten:
        allCards = _getCardObjects.Load(cardPrefab , cardButtonPrefab);
        
        // Lade alle Units und ihre Decks:
        allUnits = _getUnits.Load();
        
        // Lade die Decks der Units:
        unitDecks = _getUnitDecks.Load(allUnits);
        
        // Sorge dafür das Units im Dropdown auswählbar sind:
        PopulateUnitDropdown();
        
        // Event-Listener hinzufügen:
        unitDropdown.onValueChanged.AddListener(OnUnitSelected);
        
        // Alle verfügbaren Einheiten:
        PopulateAllCardScrollView();
    }

(In the line: allCards = _getCardObjects.Load(cardPrefab , cardButtonPrefab);)

And "clone" theme here:

#


    private void PopulateAllCardScrollView()
    {
        // 1. Vorherige Karten aus der Anzeige entfernen
        foreach (Transform child in cardScrollViewContent)
        {
            Destroy(child.gameObject);
        }

        // 2. Falls keine Karten geladen wurden, Debug-Warnung ausgeben
        if (allCards == null || allCards.Count == 0)
        {
            Debug.LogWarning(":warning: Keine Karten zum Anzeigen gefunden.");
            return;
        }

        // 3. Alle geladenen Karten im cardScrollViewContent platzieren
        foreach (GameObject card in allCards)
        {
            GameObject cardItem = Instantiate(card, cardScrollViewContent);

            // Optional: Name für Debugging setzen
            cardItem.name = "Card_" + card.name;
        }
    }
#

That somehow removes the button Click component... how do I clone an Object with an working Button?

grand snow
#

not gonna lie i cannot understand this code

dusky pike
grand snow
#

make sure you dont modify your prefab

slender nymph
grand snow
#

OH, maybe they think the listener added in code would be copied?

rare basin
#

without even understanding it

dusky pike
#

Okay, when im loading my scene I wanna load all Cards that exist.

Those are stored here: (Normaly not part of the UI)

When i use a Filter or smth, i wanna scan all the cards there and only use "some cards"

this Code:


    private void PopulateAllCardScrollView()
    {
        // 1. Vorherige Karten aus der Anzeige entfernen
        foreach (Transform child in cardScrollViewContent)
        {
            Destroy(child.gameObject);
        }

        // 2. Falls keine Karten geladen wurden, Debug-Warnung ausgeben
        if (allCards == null || allCards.Count == 0)
        {
            Debug.LogWarning("⚠️ Keine Karten zum Anzeigen gefunden.");
            return;
        }

        // 3. Alle geladenen Karten im cardScrollViewContent platzieren
        foreach (GameObject card in allCards)
        {
            GameObject cardItem = Instantiate(card, cardScrollViewContent);

            // Optional: Name für Debugging setzen
            cardItem.name = "Card_" + card.name;
        }
    }

  1. Clears all Child Objects in the UI content container here:
dusky pike
rare basin
#

do you even understand this code? or do you just want someone to tell you directly how to fix it and/or do the code for you

dusky pike
#

im trying to learn

slender nymph
rare basin
#

then go learn with proper sources, dont learn via chat-gpt where you just copy&paste stuff without even understanding it

#

whats the point

grand snow
rare basin
#

what will you learn

#

delete chat-gpt from your learning path

#

you'll thank me later

slender nymph
# dusky pike im trying to learn

there are beginner courses pinned in this channel and the pathways on the unity !learn site are a good place to learn the engine. don't let yourself learn bullshit from a bullshit generator

eternal falconBOT
#

:teacher: Unity Learn ↗

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

dusky pike
rare basin
#

it's a nice tool when you are somewhat experienced and know how to use it and why

dusky pike
#

Only those in the content box

#

removing the line doesnt change anything

rare basin
#

helping you at this point is pointless, as you won't even understand the provided help, and noone will just re-write you the code

dusky pike
rare basin
#

just go and learn via proper sources and you'll figure it out yourself

grand snow
#

yea this isnt helping anymore

#

I will help if you can correctly describe the problem but it helps no one if you generate code with AI and even you dont know what its doing...

dusky pike
# grand snow I will help if you can correctly describe the problem but it helps no one if you...

My first Problem:

  • Im adding a listener manually per Code, but it didnt show up
  • Fixed (its just not visible in the inspector, sry i didnt knew that)

My second Problem:

  • im generating (UI) CardObjects from a json. These Objects get the mentionend listener.
  • I store them outside the UI Canvas (i know that doesnt make sense and I will defenitly change that later)
  • I use this TEMPORARY Code snippet:

    private void PopulateAllCardScrollView()
    {
        foreach (GameObject card in allCards)
        {
            GameObject cardItem = Instantiate(card, cardScrollViewContent);
        }
    }
  • To copy them into the UI Canvas.
    The Problem:

The copying seems to delete the Button component.

#
s    

private void Start()
    {
        // _getUnits = FindObjectOfType<GetUnits>();
        // _getUnitDecks = FindObjectOfType<GetUnitDecks>();
        _getCardObjects = FindObjectOfType<GetCardObjects>();
        
        // Lade alle Karten:
        allCards = _getCardObjects.Load(cardPrefab , cardButtonPrefab);
        
        // Lade alle Units und ihre Decks:
        // allUnits = _getUnits.Load();
        
        // Lade die Decks der Units:
        // unitDecks = _getUnitDecks.Load(allUnits);
        
        // Sorge dafür das Units im Dropdown auswählbar sind:
        // PopulateUnitDropdown();
        
        // Event-Listener hinzufügen:
        // unitDropdown.onValueChanged.AddListener(OnUnitSelected);
        
        // Alle verfügbaren Einheiten:
        PopulateAllCardScrollView();
    }
grand snow
rare basin
#

sorry but this doesnt even make sense what you're saying: The copying seems to delete the Button component.

dusky pike
rare basin
#

i dont actually

#

is the Button component removed from the spawned instance?

#

or what

dusky pike
#

No, the Connection between the Function


    private void OnButtonClick()
    {
        Debug.Log($"Button auf der Karte {this.name} wurde geklickt!");
    }

and the button is lost

rare basin
#

listeners?

#

unless you've added some listeners to the onClick in the prefab

#

you never add them in code after you create new instance

#

but since it's a private function, then you didn't add it via inspector

#

so you just need to add the listeners to the spawned instances

dusky pike
#

yeah i know

dusky pike
rare basin
#

it's not random at all, it's all explained in the docs

dusky pike
#

Thats fair

grand snow
# dusky pike I just dont know random stuff like that

Unity could technically copy the whole managed object (c# stuff) state (so other variables) but that could quickly cause problems.
So as long as you remember that serialized stuff gets copied and the rest is back to "default" you will be fine

ember tangle
#

Say I have two lists, one is {15, 25, 10, 50} and the other is {a, b, c, d} I want to order the first list in ascending value so it would be {10, 15, 25, 50} and I want the second list to match that reordering {c, a, b, d} How do I do this?

slender nymph
ember tangle
grand snow
eager elm
ember tangle
slender nymph
#

but why does it use two lists instead of a single list of some data structure

ember tangle
#

thats a great question

#

This may be boneheaded but how do I access specific values in a multiple item list like List<(int, char)> foo

#

if I wanted only the int

rare basin
#

why cant you just make a struct/class

#

and make List<ThatStruct>

#

or w/e

ember tangle
#

scriptable object is needed

rare basin
#

ok and what about it

#

you can make List<YourStruct> in scriptable object

grand snow
rare basin
#

or serizeable class

#
public struct MatchingIntChar
{
  public int myInt;
  public char myChar;
}

public List<MatchingIntChar> foo;
#

why do you really want to keep it separated in 2 lists

#

when you need it combined/matching

ember tangle
#

Its not a well informed decision, its just what I did to make it work. Its for a spawn table for various things.

#

Now that I need to order the one list by the other im looking for solutions

rare basin
#

just make the int/char inside 1 class/struct

grand snow
#

yea its not hard. we sort the list using a value we can easily compare in the type.

ember tangle
#

thanks for the help!

#

If only this worked ```public struct SpawnChance<T>
{
public T type;
public int chance;
}

[CreateAssetMenu(fileName = "SpawnTable", menuName = "Scriptable Objects/SpawnTable")]
public class SpawnTable<T> : ScriptableObject
{
public List<SpawnChance<T>> spawnChances;
}```

#

I'm realizing the solutions that were offered wont work because the way I implemented the spawner requires two lists newDoodad = GameObject.Instantiate(Spawner<GameObject>.RollType(levelSettings.doodadSpawnTable.chance, levelSettings.doodadSpawnTable.prefabs)); because of the generic type.

slender nymph
ember tangle
#

I feel like at that point its the same as my current setup of having every spawn table being its own scriptable object of two lists.

#

but I could be wrong.

slender nymph
#

i mean, there would still be just a single list so you aren't attempting to sort one list then rearrange the other to match the new order of the first list

mystic wasp
#

Im using a CinemachineCamera and wanna make a zoom in function using a script, but cant seem to find out how to access the lens part of the component?

grand snow
#

wont you want to change the follow distance instead of fov?

#

unless it orthographic

grand snow
#

If no worky you are on V2 and not v3

rich adder
#

ya if you're on 2 its just a public field 🤮

mystic wasp
#

where do I check which version im on

#

nvm Im on 3.1.3

rich adder
#

i assumed 3 because CinemachineCamera

#

used to be called CinemachineVirtualCamera

#

I guess "virtual" was confusing ppl :p

mystic wasp
rich adder
mystic wasp
#

perhaps Im more lost than I realized 💀

rich adder
#

eg if you want to change fov
cinemachineCamera.Lens.FieldOfView = 40;

#

etc

tawny grove
#

if i wanted to increase a sprites size without increasing the size of its other components, would i have to have it on a sepret object child on the gameObject? spriteRenderer.size doesent seem to work with 'multiple' sprites properly/I am not understanding it

mystic wasp
rich adder
#

if after that, its not working then you need to debug if the line runs at all

mystic wasp
eternal aspen
#

Hey would anyone know how to prevent the player from sliding down on edges of platform like this?

I want to keep the capsule collider because I like how it interacts with all other aspects of my game but this small issue caused by the shape of the collider is getting in the way.

rich adder
verbal dome
#

Hmm you could blend in a box collider when you stop moving

eternal aspen
ancient stirrup
rich adder
verbal dome
#

It's also possible to make a "rounded box" using boxes and a couple of capsules or circles

rich adder
#

hell you can even make the bottom a skinny rectangle

eternal aspen
verbal dome
#

You should enable continuous collision detection on the rigidbody too

#

To avoid most clipping issues

frosty hound
#

Using a flat bottom collider will cause issues when moving on seams, and other places like walking up ramps. You can consider shrinking the collider when detecting it's over "air" (raycast), and then gradually increasing it back to its former size, this would let the player fall expectedly, and then also push them away from the wall if they try to go against it.

Alternatively, you could also add force upwards to keep the player afloat, by the offset that is the bottom of the collider and the contact point?

rich adder
queen adder
#

why does my player keep falling into void when i start playing

rich adder
queen adder
eternal aspen
rich adder
rich adder
#

forgot they changed it into an enum now lol

#

make sure the rigidbody it put on it is set to Static

#

and you u have used by composite in the collider

eternal aspen
queen adder
#

Hi, I dont have any idea on how to code so I'm in need of a script that supports vr and pc walk OR two seperate scripts if possible. ty

rich adder
#

here you get help with specific problem in your code

slender nymph
eternal falconBOT
#

:teacher: Unity Learn ↗

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

queen adder
#

i need help on why isn't my cam following the player and why is it so zoomed, thanks

slender nymph
#

Target Main Camera
it's following itself

queen adder
slender nymph
#

you also need to get vs code configured 👇 !ide

eternal falconBOT
stray wigeon
slender nymph
#

show relevant !code

eternal falconBOT
eternal aspen
stray wigeon
#

rigid body is interpolated

#

the using DG.Tweening; is for rotating camera movement while doing a wallrun (it works as intended)

slender nymph
stray wigeon
queen adder
#

why does my script doesn't have target, thank you

#

Camera Follow (script)

verbal dome
#

You likely need to fix all compiler errors

#

If you are expecting to see something in the CameraFollow inpector

#

Otherwise, show your code

queen adder
verbal dome
# queen adder

Start with configuring your !IDE 👇 so you actually see errors highlighted there

eternal falconBOT
outer haven
#

Hello! I've got a PlayerController, and in this I've got my basic movement stuff like inputs, locomotion etc. I've also added swimming. Now, because it was possible for my character to keep jumping while holding spacebar, I added a coyote timer and jump buffer. Which then in turn caused my character to jump endlessly when jumping out of the water. Except, now my character cannot jump out of the water.

I was hoping that anybody could have a look into the code and advice me on how to solve this issue.

I've put all relevant code in the pastebin with descriptions.

https://pastebin.com/wBSY2DZ7

rocky canyon
#

make sure its resetting properly when exiting water

#

could possibly add a cooldown before allowing jumps after leaving the water

#

controller code is alot for someone to have to sift thru to find ur issue.. i'd suggest to do what i just mentioned.. debug those values.. find more specific of a problem and return if u can't solve it

bright osprey
rocky canyon
#

^ def should consider some sort of state-machine type pattern if ur getting into so many conditionals

#

i'd suggest a basic Enum state machine to start w/

#

break up ur code into states and use a switch statement to run each logic block respectively

bright osprey
#

it helps break down the responsibilities of your code into manageable chunks. You can also handle transitional moments easily with an OnEnter and OnExit method for each state

#

Interfaces will help this functionality if you fancy the above behaviour. Otherwise any state machine will be a helpful refactor

outer haven
#

That makes sense, it does sound a lot more managable than having everything in one huge chunk.

rocky canyon
#
    enum PlayerState { Idle, Walking, Jumping, Swimming }
    PlayerState currentState = PlayerState.Idle;

    void HandleStateTransitions()
    {

    }

    void HandleStateLogic()
    {

    }```
outer haven
#

I will make a backup of my current code (as it sort of functions) and get started on that, thanks @rocky canyon @bright osprey

rocky canyon
bright osprey
#

no worries - are you using any version control?

outer haven
#

Not at the moment, I just back up in Notepad++ and sort the code with versions.

rocky canyon
#

renaming them and going onto to PrototypeVersion<insertnumber>

outer haven
#

😂

rocky canyon
outer haven
#

I guess everyone has their own sorting systems. xD

rocky canyon
#

yessir.. i still use Github too tho

#

for my main projects

#

sometimes its not worth having an entire repo.. if i just wanna try something out

#

the ^ master project of those duplicates does have a repo

#

just not none of the spin-off projects i call em

rocky canyon
#

sometimes soemthing will catch ur eye that doesn't look or feel right..

bright osprey
outer haven
rocky canyon
rocky canyon
#

when im finally done developing i'll just get rid of the serializefields and go on my way

rocky canyon
# rocky canyon

i like to make little clips like this and go back and re-watch them

#

i also tend to notice more after the fact.. than i do when im right there looking 👀

#

lol

#

don't stress urself out tho.. character controllers are no joke..
and they don't just fall out the sky..
to make a really good one (which is the backbone of most games) it can take a while

#

multiple iterations thru-out the projects life-time

outer haven
#

Well. I've tried asking chat GPT to help me with converting everything to a state design pattern because I wasn't sure how to go about it. And it looks awefully complicated for the movement I'm going for, so it doesn't look like it's worth it. It would basically be starting from scratch all over again and throwing a week worth of work in the gutter. 😦 @rocky canyon @bright osprey

rough lynx
#

If your current design works I wouldn't sweat it

bright osprey
#

No worries! i didnt mean to tell you to throw all your work away 😂 might be worth creating a small side project and following a state pattern tutorial? if you want to take a break from the project 🙂

rocky canyon
#

if u want to start using statemachines.. gradually step into them...

#

learn urself.. chatgpt gonna try to fk u over

noble heron
#

hello

keen cargo
#

Oh yeah don't do chatgpt

outer haven
#

I will try that. It looks a lot more versatile way to code. But for now I just wanna fix my current code so it functions first. xD

noble heron
#

im kinda new to using unity

rocky canyon
#

don't sell ur car to buy gasoline.. yaknow?

rocky canyon
keen cargo
#

ChatGPT will give you one of these:

  • a somewhat good answer, if the request is simple
  • a bad answer that works
  • a horrible answer that doesn't work
  • way too complicated of an answer that may or may not work
rocky canyon
#

the problem with chatgpt is over-reliance..

keen cargo
#

That too

rocky canyon
#

not really it's fault.. but if it makes a mistake.. it needs u to point it out to it

#

b4 it runs off on a tangent

rough lynx
#

Never really understood the appeal of state machines for stuff like character controllers. It just seems like you're intentionally impeding yourself but maybe I'm just being shortsighted

#

Why limit yourself to very specific states

rocky canyon
#

a good statemachine is scaleable

#

and u can add states.. EASIER

#

than w/o one

keen cargo
#

State machines have their place and time, if there's a lot of states to work with then it's absolutely useful

rocky canyon
#

if u dont have a statemachine.. if u go and add functionallity.. u need to go and add it EVERYWHERE in the script..

#

if u have a good statemachine.. u could add it w/o worrying.. b/c the rest of the class could care less if that state is there or not..

outer haven
# keen cargo ChatGPT will give you one of these: - a somewhat good answer, if the request is ...

I've used chatGPT to debug in the past for this code. But I learnt to back up my code a lot because it often sends me around in circles. That's what's happening right now with the code I got too.. because the code itself works right now, except the ability to jump out of water. Because I've got a jumpbuffertimer and coyotetimer and I've had to switch the way the game handles spacebar presses while swimming.

rocky canyon
rich adder
cosmic dagger
outer haven
rough lynx
#

That's amazing 👏

rocky canyon
#

the lite version can walk, sprint, and jump

#

thinking of 86in the jump eventualy

rocky canyon
#

i finally figured out the bare-bones basic Enum type statemachine.. and then everyones like..
Ohh have u heard of State-less state machines.. u should try those... or better yet.. what about Behaviour Tree's?

#

point being.. they're not the simplest things imo.. and i definately wouldn't start out my journey by using chatgpt

rough lynx
#

Stateless state machines is a crazy name to have

#

So contradictory

rocky canyon
#

-# disclaimer: ChatGPT

#

not sure how true all this is.. but since im here.. figured i'd see what it had to say about them

outer haven
#

Fair enough. xD And well. I'm using a little bit of chatGPT to fill in the gaps I don't know, but the deeper I go, the more I don't know. Lol

rocky canyon
rocky canyon
#

its mostly to refactor.. and to write boilerplate code now-a-days

#

but if ur smart about it.. its just a tool like anything else

outer haven
#

I know the basics of C# so far, I've also done some stuff in Python. But these scripts for my game are my first time writing scripts that are this big.

rocky canyon
#

went from 1500 lines of code or so down to 7-800 after a few refactors..

#

ever heard of the SOLID principles?

outer haven
#

I haven't before, no 😮

rocky canyon
#

heres a few sources.. the reason i ask b/c the first one.. and probably the most important for beginners is.
Single Responsibility

#

you want ur classes to stick to doing (1) thing.. thats MY job
if ur classes are doing more than (1) thing.. or are referencing many different scripts/systems..
it may be too much for a single class

outer haven
#

That actually makes sense. I feel like the current script actually has a few things scattered around a bit too much.

rocky canyon
#

if u keep it in ur mind while u code.. its a bit easier..

#

like here.. you can see that i have many different components all technically on my character controller..

#

each one doing its own thing... that way i don't have to worry about every little mechanic I have falling apart say i accidently break (1) or more of the other scripts

#

Composition is what its called i believe.. (when u have multiple classes on a single object)
each doing a single thing.. but together adding up to the total functionallity

rocky canyon
noble forum
#

Hi

#

How do i block raycast to something below the UI element

#

This doesnt work

rocky canyon
noble forum
rocky canyon
#

as long as u know its fine..

rocky canyon
outer haven
rocky canyon
#

i typically use an Image component.. stretched to fill the canvas
and transparent.. (then i'll use the canvas sort order to put it on top of w/e im trying to block off)

noble forum
#

I did the same as you showed way before

#

the problem is, it works for other UI

#

but not for other raycasts

noble forum
rocky canyon
#

not sure what that is..

  • you can scale it and position it however u want *
#

if u need it to block some things and not other things.. then change the sorting layer where its above the things u want to block and below the things u dont

noble forum
#

but i can still click on chesspieces and cards

rocky canyon
#

hmm.. not sure.. it was just a guess tbh..

#

what is it that ur trying to do anyway?

#

do u just need certain things to not be interactable?

noble forum
#

It is preview of the card

#

when active, i want nothing else to be interactable, besides few things that are children

#

fastest way to do so is to block raycasts

rocky canyon
#

i guess that makes sense

noble forum
#

It works for UI butttons like you see on the right, i can't click end turnn

#

but i can still click on chesspieces

rocky canyon
rich adder
noble forum
#

i mean what allows to move pieces

rocky canyon
#

yea, 3d raycasts care not about ur UI

rich adder
#

nah

#

only if you use Ipointer interface + physics raycaster instead of Raycast

rocky canyon
#

i'll need to make note of that..

noble forum
#
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                clickPosition = hit.point;
                OnInputRecieved();
            }
        }
    }

    public override void OnInputRecieved()
    {
        foreach (var handler in inputHandlers)
        {
            handler.ProcessInput(clickPosition, null, null);
        }
    }``` I believe it was this
rocky canyon
#

i have a feeling i'll be trying to remember that

#

or needing to atleast

#

u just need to toggle off ur 3D/Interactive raycast script

#

when u have ur cards pulled up or w/e

noble forum
#

yea, i can, but isnt there a way to just block all world space by UI?

rocky canyon
#

that'd be a nice easy way that i think i would do

rocky canyon
#

sitting in the path of the raycast lol

#

the image/canvas does work pretty good to block other UI elements tho ^ like something like this

rocky canyon
# noble forum ```private Vector3 clickPosition; void Update() { if (Input.GetM...

just do something like this:

public GameObject uiPanel; // Assign this in the Inspector
private Vector3 clickPosition;

void Update()
{
    if (uiPanel.activeSelf) return; // Prevent detection if UI is open

    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            clickPosition = hit.point;
            OnInputRecieved();
        }
    }
}```
noble forum
#

i did already, but thanks XD

rocky canyon
#

if that UI panel is Open -> return(skip rest of code)
if that UI panel is Closed -> run the GetButton/Raycast code

noble forum
#
    private Vector3 clickPosition;
    void Update()
    {   if (cardWrapper.isPreviewActive)
    {
        return;
    }
        else if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                clickPosition = hit.point;
                OnInputRecieved();
            }
        }
    }

    public override void OnInputRecieved()
    {
        foreach (var handler in inputHandlers)
        {
            handler.ProcessInput(clickPosition, null, null);
        }
    }```
rocky canyon
#

that's how i always handle that stuff

noble forum
#

Also for some reason i heard that using things like public CardWrapper cardWrapper all over the code isnt good. Why?

rocky canyon
#

its better to have hands-on with the code and know its blocking it

#

than just hope something will do it

rocky canyon
#

ive seen both sides of the argument tho.. (no clue why or whats better)

rocky canyon
#

I've used classes as tags/layers...

if (Physics.Raycast(ray, out hit) && hit.collider.TryGetComponent(out MyInteractable interactable))
{
    Debug.Log($"Hit interactable: {hit.collider.gameObject.name}");
}```
with `MyInteractable.cs` being just an empty class i attach to gameobjects.
im not 💯 sure thats the same thing tho
noble forum
#

I mean, this part is tutorial code that i expanded now to 2x its lenght, i was asking about the refferences, why aren't they good?

noble forum
rocky canyon
#

Object Oriented Programming

rich adder
rocky canyon
#

the sound u make when someone knee's u in the stomach

noble forum
rich adder
#

"wrapper class" You're pretty much creating an object for it

rocky canyon
#

never knew it had pillars.. got me something to read! 🌈 🌟

rich adder
#

Inheritance < Interfaces

median mortar
#

Hey guys, having a problem when switching scenes with cinemachine.
Having three scenes

1. Systems (Persistent with MainCamera and Cinemachine Brain)
2. MainMenu (3 Cinemachine Cameras)
3. Gameplay (1 Cinemachine Camera)

Starting with Systems and MainMenu, everything works fine and I can transition between all 3 Cams.
Loading Gameplay and unloading MainMenu

SceneManager.UnloadSceneAsync("MainMenu");
SceneManager.LoadSceneAsync("Room1", LoadSceneMode.Additive);

and loading back into MainMenu

SceneManager.UnloadSceneAsync("Room1");
SceneManager.LoadSceneAsync("MainMenu", LoadSceneMode.Additive);

I can't transition between the Cameras anymore.
GameObject with Main Camera / Cinemachine Brain stays persistent via DontDestroyOnLoad though.

#

Thinking over it, this could be more a cinemachien question so I'll ask it there 😄

timber tide
#

Probably need to tell cinemachine to search the scene again for those virtual cameras

#

Hmm they may actually subscribe via a singleton actually when they awake(), or well that would be the more reasonable way

hexed nymph
#

Yoooo how can I configure my IDE??

rich adder
eternal falconBOT
dusky pike
#

I have a Problem with my UI Dropdown Menu clicking on the white menu bar blocks my raycast system from reaching the tiles underneath

But when my dropdown menu is open, no matter where i click, it reaches the tile underneath it

#

Opening the dropdown works just fine

rich adder
#

UI doesnt block raycast

#

You have to specific check your cursor is on UI
and if it is you return

dusky pike
#

but when i click on the arrow again to close it i click on the tile beneath

wintry quarry
#

And you'll get the blocking behavior for free

dusky pike
#

I thought "Raycast" target would be enough?

wintry quarry
#

Only if you're using the event system for clicking tiles

dusky pike
#

(and it also works always, except when i open the drop down)

rich adder
#

yes because UI doesnt block the Physics.Raycast

#

only if you use a Physics Raycaster on the camera then it uses Event System for ray as with UI and its covering it that way works

dusky pike
#



    public bool IsMouseOverUI()
    {
        return isMouseOverUI;
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        isMouseOverUI = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        isMouseOverUI = false;
    }

i tried doing it this way

wintry quarry
#

Yes that's... part of it

rich adder
wintry quarry
#

But this is wrong overall

dusky pike
#

No

wintry quarry
#

The actual tile handling should use that stuff

dusky pike
#

My tiles a 3D objects

wintry quarry
#

Not just setting some UI bool

dusky pike
#

fair

rich adder
wintry quarry
rich adder
#

put this component on the camera, then you need to handle the clicks on the Tile itself

dusky pike
rich adder
#

it knows cause of the PhysicsRaycaster uses the same raycast (Event System) as Graphic Raycaster so it will just work ™️

rich adder
#

hover and whatever else

dusky pike
#

Ah nice thanks!

stray wigeon
#

Hey, this chat usually helps a lot, so I want to ask here first. If i follow this tutorial: https://www.youtube.com/watch?v=IVj7-usBxHo&t=30s Could this be used to create a trail of blood that my player leaves behind? The thing is, I want it to be dynamic so the player not only bleeds but the game sees what asset/what angle the player is standing on so the blood stays on the said asset depending on what part of the player is touching it and what angle the asset is at. Kind of like splatoon paint, but that spawns from the player at all times. Imagine shooting a paintball at something. Or is this too hard of a task for a beginner and I should forget it? Or the trail that Super Meat Boy leaves behind when he touches something but in 3D

Also, this is nothing too realistic, I'll just slap on a super low effort pixel shader on top of everything at the end...

Today we are going to see how to create a procedural Blood effect (no textures). We are going to use VFX Graph to spawn the blood and manipulate it's motion and then we use Shader Graph to create the Blood Shader.

I used this blood effect here in the Toxic Waterfall : https://youtu.be/uOhWT6TxZgE

Enjoy!

Would be awesome if you wishlisted ou...

▶ Play video
rocky canyon
verbal dome
#

Particle system + spawn decals on collision is probably the easiest way

#

Havent used VFX graph's collisions enough to comment on that one

stray wigeon
#

Thanks for the replies! Are there maybe any guides close to what I am trying to achieve that I can check out?

verbal dome
#

The unity manual probably gets you started

#

So that's a google

#

I dont know how you learn best 🤷‍♂️

rain tartan
#

I can't find the help channel in this discord so appologies. I'm wondering how to "unfreeze" time in the editor?

#

None of my particle systems will play right now

#

I used to be able to preview my particle systems by clicking "restart" here

#

but now nothing happens. Playback time stays at zero

verbal dome
rain tartan
#

ok

#

thx

rich adder
#

you will need to code that in

#

raycast onto the surface hit then apply the decal projector with a slight offset

#

you can use particle system too but Decal Projectors can be pushed to GPU unlike particle system (performance boost when spawning a lot)

#

VFX graph doesnt work well because it runs on the GPU while unity collisions are processed in physics / CPU so they cant interact

rocky canyon
#

yea, probably raycast be ur best bet.. esp w/ all the weird edge-cases u were trying to describe

#

can get normals and stuff and angle ur projectors how they need

mystic wasp
#

Is there any specific tutorial anyone recommends or has in mind regarding procedural generation with rooms?

faint agate
#

Hey guys, I have a grappling gun that has a grapple wire you can physically see. The problem is 2 of them are coming out. I can see the second in the editor so its definitely being executed by script.

#

Ill send the script, give me a moment

rich adder
faint agate
#

The one attached is the wire I can see in the editor. The wire offset of the gun is what the script is doing

mystic wasp
#

alright ty, I had that one in mind but wanted to double check before I commit to it in case anyones done it b4 🙏🙏

faint agate
faint agate
hasty cape
#

anyone know how to use snap points in unity 6 i cant find anything online...

#

im trying to snap food onto a tray

hasty cape
#

i dont mean how to position objects

#

i meant stuff like socket interactors

#

but the using snap points

rich adder
graceful jasper
#

does SetActive(false) immediately stop the execution of code? if i have a method that returns some data after setting the game object its on to false, will that return still execute?

slender nymph
#

No to the first question

polar acorn
graceful jasper
#

awesome, thank you