#💻┃code-beginner

1 messages · Page 211 of 1

rare urchin
#

after all

#

dont put a blame on me

oak nimbus
#

can you show me your code that acheived that?

rare urchin
#

wooo

queen adder
#

Im about to steal

#

This mans code

rare urchin
#

im suck code but still choose game for my project

minor patio
queen adder
#

haha yes indeed

queen adder
minor patio
#

freedom of exchange, & all thinksmart

rare urchin
#

but idk why first time it work. i didnt add Charecter controller

queen adder
#

And game programming is on the more impressive side of programming

rocky canyon
queen adder
rocky canyon
#

not sure that get/set is still required for it to work.. but i just didnt remove it

rocky canyon
#

the callback should be enough OnMyStringListModified()

frigid sequoia
#

Oh, I know why it was happening now

queen adder
#

Is there a way to prevent the private keyword from being auto put on methods ? I tried google but to no avail

rocky canyon
#

b/c code running too fast

teal viper
#

Wdym by auto put?

frigid sequoia
#

I was trying to get the component of a component, that was what was null

frigid sequoia
#

What I don't get is why that ends up spawing the prefab without the refencenced component

queen adder
#

I didnt even know there was a intellisense file / settings.json

sterile radish
#

hi, im making a tower defense game and i was wondering how would i check if an enemy is in range of my tower in my "UpdateTarget" method and not in my "TargetClosest method". the problem with the target closest method is that the "findgameobjectbytag" method returns gameobjects randomly and not in an orderly list which is why im trying to change it.
https://hatebin.com/qnbfgortoc

queen adder
#

Vector3.Distance() is my first guess

rocky canyon
queen adder
#

Thats why i like it here always learning new stuff

#

but yeah roshi i think u just need to check which gameobject has the shortest distance to ur tower

oak nimbus
cosmic dagger
queen adder
#

I know how to change the default template

rocky canyon
#

the one added would be on the bottom

queen adder
#

But spawn showed me the way i got it figured out

oak nimbus
rocky canyon
#

pretty sure its always the last index

frigid sequoia
oak nimbus
#

say I add 4 items to list, then remove item at index 2 next item added to list will go to i ndex 2 no?

rocky canyon
#

ummm not sure tbh

queen adder
#

my default template is now

using UnityEngine;

public sealed ClassName : Monobehavior
{
void Awake()
{
}

}

rocky canyon
#

i dont know how list reorder themselves if im honest

oak nimbus
rocky canyon
oak nimbus
#

i think it depends on size of list

frigid sequoia
oak nimbus
#

large lists fill in the holes small lists reorder when items are removed iirc

sterile radish
verbal dome
#

List.Add will put it in the end of the list

rocky canyon
frigid sequoia
cosmic dagger
queen adder
#

Yeah i dont see why the list would be static when ur going to have multiple instances of the same tower probably

rocky canyon
#

ohh no, not statics again 😅

queen adder
#

Ikr

sterile radish
#

oh yeah thats seems dumb now that i think about it my bad guys 😭 (thank you for the help btw!)

cosmic dagger
#

leave static for extension methods . . .

queen adder
#

Whats with the sudden obsession lol?

#

Or events

#

I use static events everywhere

rocky canyon
#

iono, people see static and like OHH i can access that anywhere!

#

thats awesome, ill use it everywhere

queen adder
#

Yeah i was obsessed with them at first to

oak nimbus
cosmic dagger
#

they go HAM with static after finding out it can be accessed from anywhere . . .

rocky canyon
#

lol facts

queen adder
#

But quickly realized ur not supposed to use them like that

rocky canyon
oak nimbus
#

oh wait yo u cant do those in editor scripts can you?

rocky canyon
# oak nimbus coroutine maybe?

possible.. im sure theres a better approach to all of this. but as i dont know much about editor scripts i kinda cheated and copy and pasted some of it

frigid sequoia
# sterile radish oh yeah thats seems dumb now that i think about it my bad guys 😭 (thank you fo...

Then there are a few ways you can go, but I would have a recount of each enemy for how advanced they are in the track (which the enemy itself should track) and a recount of how far each enemy is from the tower. You could have these datas in two different List (that you could sort to get easily the highest and the lower) or however you find more manageable; just make sure that you can easily access the closest enemy and the most advanced

rocky canyon
#

idk what ur use-case is..

oak nimbus
rocky canyon
#

but i dont think u can have editor scripts in ur build at all..

#

not sure thats a problem for u

queen adder
#

Oh thats right

#

Lmao

rocky canyon
#

thought this was a tool/ ease of use type situation

queen adder
#

Went thru all the work and ur code wouldnt even show up in ur final build lmao

oak nimbus
#

I think I need to just render the list in the inspector myself manually with my own GUI code tbh

rocky canyon
#

ya, editor scripts are for the developers

queen adder
#

Honestly russel

#

I think ur overthinking this

cosmic dagger
#

editor scripts are only for development . . .

rocky canyon
#

same.. whats ur actual use..

#

what is your goal in all of this..

queen adder
#

Why not just give them there appropriate Ids somewhere else

cosmic dagger
#

wait, what is the issue?

queen adder
#

Because u cant even use the editor scripts when ur game releases

#

When the list changes in game then what?

oak nimbus
#

im making an editor tool

rocky canyon
#

^ this.. he wanted a callback for when he added to a string list thru the inspector..

oak nimbus
#

there is no list in the game

#

this is all editor code

rare urchin
#

can yo recomend me any way to script this?i will make player pick up cpu but first player must Pull that lock by click then player can pick up cpu and attach to socket. just use normal if else?

oak nimbus
#

ok ok

queen adder
#

Then whats the point of the editor code if u arent going to use it in game?

verbal dome
rocky canyon
#

TIL.. theres Editor Coroutines 👀

verbal dome
#

Yep. I usually use async instead tho

queen adder
#

Async scares me

cosmic dagger
queen adder
#

especially inside of unity

rocky canyon
oak nimbus
#

ok so I am g oing to make a long post e xplaining my use here give me 5 mins

queen adder
#

I can almost gurantee it wont be worth it in the end

rocky canyon
#

im thinking its probably one of them.. X Y problems..

#

where theres probably a better solution all together than what we're thinking

queen adder
#

Facts

#

But to be fair i dont know ur project or the full scope of what ur trying to do so i could be wrong

rocky canyon
#

ive never heard of UYI toolkit

#

so imma look at that while i wait

oak nimbus
#

I have a scriptable object

public class SublimeEditorPrefabRegistry : ScriptableObject
{
    public List<SublimeEditorPrefabRootData> prefabs;
}


public class SublimeEditorPrefabRootData
{
    public string name;

    public List<SublimeEditorPrefabData> prefabData;
}

public class SublimeEditorPrefabData
{
    public int poolSize;
    public SublimePeerType peerType;
    public GameObject go;
}

This is only ever lives in the editor this data holds both info used by the server and t he client. however t he client doesn't need to know about the server data, a nd the server doesn't need to know about the client data.

So all of this is baked into 2 seperate json files one for the client one for the server

I want each instance of SublimeEditorPrefabRootData to get an ID generated when I add it to the list via the inspector

#

later on in the game

#

the data is deserialized into classes

rocky canyon
#

sooo much relevant information! thanks for typing it out 👍 im surely these guys can tell u exactly what u need to do now

queen adder
#

Why not just give the items in the list IDS when the game starts

oak nimbus
#

because i generate a class when the json bakes

#

this way I can do something like sublimeNEtworkInstantiate(NetPRefab.Player,

#

where netprefab.player is an integer

#

that is assigned by codegen

#

i got it all working

queen adder
#

I may be stupid but u cant just give them ids when u serialize the class?

oak nimbus
#

no because the ids need to be assigned when the object is added to the list that way if an item is removed from the list the id can be repopulated into the collection of available ids

#

this is essentially a bunch of hoops im jumping through so that gameserver code and client code can reside in the same project without server code being included in client builds

#

I understand yall think this is an XY problem but I have a giant network library that is working and is in production in a live game

#

and im just trying to reduce the chance of a mistake being made by someone manually assigning the ids

#

so I w ant them to generate when an item is added via the inspector

oak nimbus
rocky canyon
#

ya, not sure i should be helpin u at all considering im just a humble peasant, in terms of where ur at 😄

oak nimbus
#

i just dont want to remake a bunch of editor tools in ui toolkit if i can avoid it

cosmic dagger
#

i just started messing with it and need to figure out how to use SerializeReference with it, but they have callbacks you can subscribe to that check if a field has changed . . .

queen adder
#

And then u can check what IDs are available via the callback and repopulate the IDs when a list item is removed

frigid sequoia
#

Ok, so I have been unable to fully fix this for a while now and I am not sure it is a problem of logic by my part or it is bound by the randomness of the order of execution of the scripts; but I have a script (the one I shown before) that casts prefabs of lasers when it collides with a wall; it works fine but has a mayor issue and it is that after a certain number of bounces it starts to run a frame behind what it should. As shown in the image:

oak nimbus
#

im just gonna code my own UI for rendering the list.

sullen gazelle
#

Okay so there's this spider I got off the asset store. And I have it set up to follow the player and attack when in range. The only issue right now is that it will walk to the player, attack once it's in range, and it will just freeze up until I leave it's range (then it starts following me again.) It won't go back to it's idle state, it won't attack again, nothing until I leave the range. I think it has something to do with my transitions. I have them all set up the same way (I'm planning on doing jump and idle later).

frigid sequoia
sullen gazelle
#

Keep attacking.

frigid sequoia
#

Have you loop time on the attack clip?

sullen gazelle
#

How do I do that?

frigid sequoia
#

Select the clip

#

In the inspector it has a box for it

sullen gazelle
frigid sequoia
#

They are different

#

Click twice

sullen gazelle
#

Oooooooooh

frigid sequoia
#

Also, this is not really a code question, there is a specific channel for animation

sullen gazelle
#

Oh.

#

Well thank you.

frigid sequoia
#

You are welcome; I can already see you will have more questions about how to set up an animator controller, such as I did, seems frustrating but you will figure it out

untold saddle
#

How do I hide the mouse cursor?
Like for a FPS game.

summer stump
#

This was the first link when I googled "unity hide cursor"

untold saddle
#

Thanks

uncut shard
#

Hi folks, I am trying to make a game like Subway Surfers 3D. My capsule player needs to fall down from the top to the bottom. Like showed in the second video how can I fix it? I tried Chat GPT code didnt' work

uncut shard
#

sorry @rich adder

rich adder
uncut shard
#

I cant

#

file is too big

#

Check the Facebook link

north kiln
#

You need to actually post some code or a description of how it's currently set up too

uncut shard
#

Sure

#

@north kiln

#

The first one is mines and the second is the tutorial video

rich adder
#

you should not dox yourself like that

uncut shard
#

what do you mean?

rich adder
#

huh ? you have personal conversations open

#

in a video, you should not be showing that lol

uncut shard
#

Okay sorry!

#

I will make sure next time

rich adder
#

lol no worries, just saying it for you

uncut shard
#

okay!

rich adder
#

poste the code too?

uncut shard
#

I also tried Chat GPT it did not work

rich adder
#

are you folliwing a video?

uncut shard
#

Yes!

rich adder
#

that gravity is wrong

uncut shard
#

Okay

#

What should it be?

tough lagoon
#

But those video clips aren't really helpful

uncut shard
rich adder
uncut shard
#

I am at part at adding tiles

#

Okay @rich adder

rich adder
#

they don't have that in the video it seems

uncut shard
#

Okay

uncut shard
#

Okay where should it be after update or after key up arrow

#

@rich adder

rich adder
#

Your code is saying no matter what if im not pressing up arrow smoosh me down

uncut shard
#

Okay how can I dix fix that

#

fix

rich adder
uncut shard
#

Yes

#

@rich adder

rich adder
uncut shard
#

but its not falling right

#

How do I fix that

#

It should fall like in the video

cosmic dagger
# uncut shard How do I fix that

they just told you how. you did not copy the code from the video correctly. make sure your code is exactly like the video . . .

rich adder
#

is yours not on the ground? I can't tell from the vid game cam angle

uncut shard
#

It is I fixed it @cosmic dagger

rich adder
#

ohmy the longer i stare at this code, the worse it gets

     transform.position = Vector3.Lerp(transform.position, targetPosition, 80 * Time.fixedDeltaTime);
    }

    private void FixedUpdate()
    {
        Debug.Log("i am moving");
        controller.Move(direction * Time.fixedDeltaTime);
    }```
whyyyy
uncut shard
#

Somebody helped me with that @rich adder

rich adder
uncut shard
#

Okay

rich adder
# uncut shard Okay

you should not mix transform.position teleport, with controller movement. Also that Lerp is HELLA wrong

lucid nova
#

Hey guys i have a query, i made some c# script file to help me generate a jungle terrain floor. however when i try to put this script file on top of terrain it doesnt add. any reasons why?

uncut shard
#

I fixed it @rich adder

#

Still doesn't work

rich adder
cosmic dagger
uncut shard
#

Send me script? @rich adder

rich adder
uncut shard
#

i do @rich adder

rich adder
#

then sending you a script will not teach you anything valuable

#

learn to fix what you have, if you don't understand it then take a proper structured course on !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

lucid nova
#

@cosmic dagger i believe i have done that however when i type in teh name of teh script file to add component nothing showing up

rich adder
#

show the script you are trying to add

lucid nova
#

i dont have any script errors. it says no errors. i might just re write it again. mainly using unity to create vr games. do i have to write the code differently to satisfy that i am using XR? mainly just trying to build a map rn

rich adder
#

nothing special about XR really

lucid nova
#

hmm alr

rich adder
lucid nova
rich adder
# lucid nova

hmm have you tried directly dragging the script onto the gameobject?

lucid nova
#

yeee i have quite a bit and it doesnt latch itself obto teh object

#

onto the object*

rich adder
#

any warning or errors?

lucid nova
#

well it says its not the same file nam

rich adder
#

ah yes that would do it

cosmic dagger
#

i believe there is information being left out . . .

lucid nova
#

when i fixed it it still does the same thing

rich adder
#

Your filename must match class name, show that they match

cosmic dagger
#

what is this infamous script?

tough lagoon
#

Also, just to mention, capitalization matters too

lucid nova
#

i deleted it to write a new one. i will send the new one in a min

cosmic dagger
#

i question your tactics. you could have sent the original for us to see . . .

lucid nova
#

well in my degree if something is wrong redo it

verbal dome
#

Asking for code help without code is like going to a car repair shop without a car

lucid nova
#

then ask questions if i keep getting same results

rich adder
#

yes does degree not have common sense

lucid nova
rocky canyon
#

lets hope ur scripts dont get very long lol

rich adder
#

🤷‍♂️

lucid nova
cosmic dagger
lucid nova
#

ik... i wanted to make sure it wasnt a coding error hence me stating i will brb with another code sample

#

hmm could i just buy a package and use that btw instead of coding it?

rich adder
#

yeah its called hiring gig

lucid nova
#

Hmm might do that instead planning on making a realistic vr game. However don’t really have the time

tough lagoon
#

It's worth learning, but frameworks and helpers make it go fast

lucid nova
#

It does but getting a degree doesn’t help when the coding u learn ain’t c

#

No I’m on quest 2

spare mountain
rich adder
#

ohh cause now seeing big ramp in vr because of apple hype

rich adder
#

i believe its restricted to Pro plans and Enterprise

tough lagoon
#

Yup

spare mountain
#

huh

#

whaddayaknow

lucid nova
#

Hmm couldn’t u also use ai to help generate code as well

cosmic dagger
#

yeah, good luck with that being somewhat accurate . . .

tough lagoon
#

Some are pretty badly coded though

spare mountain
rich adder
rich adder
cosmic dagger
spare mountain
#

copilot can only get you so far

rich adder
#

and no i mean github not the new BS mS put out with the same name

rich adder
#

Yeah take this json and write me a c# class model

#

menial secretary tasks

spare mountain
#

yup

vale karma
#

how can i make a player jump only once when holding the spacebar?

cosmic dagger
vale karma
#

could i use context.performed or i think its context.entered instead?

rich adder
#

yeah you want performed

cosmic dagger
#

you can use an action (event) that calls a method which sets a bool in your jump script. one action for press and another action for release . . .

#

you can also use context; make sure it's performed . . .

queen adder
#

.cancelled should tell you when its released

vale karma
#

i tried using public void OnJump(InputAction.CallbackContext context) { if (context.performed) { JumpAction = context.ReadValueAsButton(); } }

queen adder
#

theres also

#
{
    context.action.WasReleasedThisFrame();
}```
vale karma
#

i think thats very wrong tho lol, it only reads if its true or false if its performed.

queen adder
#

I believe it depends on how ur action is set up via the inspector

#

Like so

#

you would use context.ReadValueAsButton() if ur action was set to a button action type in the Input Actions

vale karma
#

yea the spacebar is set as a buttontype

#

once it reaches past a certain value it is either true or false. works well so far

queen adder
#

Then you should be set

#

Just add to ur y velocity when the button is pressed and make sure ur grounded

vale karma
#

so your saying i need to add JumpActionCancelled = under the JumpAction = right?

#

and then if its true I can jump again?

queen adder
#

No i wouldnt do it like that

#

Are u using UnityEvents for the PlayerInput?

vale karma
#

yea i got the full movement setup already, hold up ill show u

queen adder
#

Oh so ur good tho right?

#

Except the NREs but thats another thing lol

vale karma
#

nre?

queen adder
#

Null reference exception

#

The Red Stop signs in ur console

cosmic dagger
#

null reference exception . . .

vale karma
#

yea lol, but i cant figure out a way to get the player only to jump once while in the jumpstate, but then carry that knowledge over to the next state if your holding the key still

#

as i say it i think i found an answer lol

queen adder
#

Oh u want them to constantly jump if theyre holding the button?

vale karma
#

the opposite

queen adder
#

So currently if u hold the button they jump again as soon as they touch the ground?

vale karma
#

it basically reads it, goes to jump, then resets what it knows and reads the input agian

#

yea

queen adder
#

That shouldnt be happening

#

Send ur current code?

vale karma
#

its a state machine its alot 😮

queen adder
#

I tend to not use them (Controversial I know)

#

But whats ur current code looking like

vale karma
#

once i started adding crouch and sprint i said noopeee i seeee the iceburg

queen adder
#

Haha yeah i feel u

vale karma
#

heres the gist. theres like 5 or 6 more states tho

sullen gazelle
#

Hi all. I'm having an issue with recieving damage. I made a cube in my scene. I gave it some code in Visual Studio that should make it so when I walk into it, I take 2 damage. I put the "is trigger" on the cube. And I get this in the console.

NotImplementedException: The method or operation is not implemented.
DamageOnce.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Damage Once.cs:15)

vale karma
#

i wish i could implement another state machine with grounded in it. so things like that could already be factored further in the code without having to call it a bazillion times

rich adder
#

show script

sullen gazelle
# rich adder Are you using Send Message?

public class DamageOnce : MonoBehaviour
{
    public float damageAmount = 2.0f;

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            // Assuming you have a player health script attached to the player GameObject
            PlayerHealth playerHealth = other.GetComponent<PlayerHealth>();
            if (playerHealth != null)
            {
                playerHealth.TakeDamage(damageAmount);
            }
        }
    }
}
queen adder
#

Whats calling the Jump method Bear?

sullen gazelle
rich adder
#

the playerHealth ?

verbal dome
#

You are calling a method TakeDamage on the object playerHealth

#

The error suggests that you haven't implemented it.

vale karma
#

the jumpstate

queen adder
#

Ur ide should be telling u that tho

verbal dome
#

Probably looks like this

rich adder
#

ahh

queen adder
#

!Ide

eternal falconBOT
sullen gazelle
#

Oh. My player health script. Hold on.

rich adder
#

they generated the method in code editor, but never did anything

queen adder
#

Oh i see

#

!code

eternal falconBOT
rich adder
#

yup Osmal got it

queen adder
#

use one of these websites instead

rich adder
#

throw new NotImplementedException();

queen adder
#

Haha lmao

verbal dome
#

You have a duplicate TakeDamage. Remove the other one

queen adder
#

Mans was ahead of the game

#

also bear what triggers the jumpstate?

cosmic dagger
#

looks like a duplicate . . .

sullen gazelle
rich adder
#

yes

vale karma
#

either idle, walk, or sprint state

rich adder
#

remove the one with the throw new NotImplementedException();

sullen gazelle
#

Gotcha

cosmic dagger
rich adder
#

different signatures thats why no error in health script

sullen gazelle
#

Okay. Removed it. Now there's an error in my damage code XD

cosmic dagger
rich adder
#

cast it or just change it from int to float in method playerhealth script

vale karma
#

i have code that determines the speed of the movement in the air based on the previous states speed. i think i can do the same concept with a hasJumped bool. so i can make it false to start, change it to true under the NewInputSystemValues script when the space bar is pressed, and the false when the cancelled action has happened. then in the jumpstate i can write an if statement determining if the number of jumps is 1, if so then dont respond, if not then jump

cosmic dagger
queen adder
#

All u need to do is check if u grounded and if u are call the jump method

vale karma
#

sorry, if hasJumped is true.

#

i promise i started with that, and there were so many issues;

queen adder
#

Just check ur current y velocity if its greater than zero ur jumping if its less then ur falling

vale karma
#

the problem with just that is your still grounded even after pressing spacebar, for quite a few frames. and also, if your walking up a slope your velocity is greater than 0. I do have a falling script allowing it to change states once grounded and is falling.

#

basically most ways of doing it would allow the states to change rapidly between eachother bc in a sense both where true at the same time

queen adder
#

Ah i see

#

Was there anything else u needed help with? Are u still jumping while space bar is held?

rocky canyon
#

the key to that is applying gravity the entire time ur grounded and then zeroing it out just as you start a jump..

#

that helps the whole flickering thing

queen adder
#

Oh good point

vale karma
#

i didnt want to mess with the rigidbody and gravity, but i did fix it

#

the jumping is still happening

queen adder
#

Again

rocky canyon
#

cool cool

queen adder
#

Whos calling Jump

#

Wheres it being called from

#

When u press space

vale karma
#

im writing the code now, but what is the code for when the button has been let go?

queen adder
#

Is it UnityEvents?

rocky canyon
#

Input.GetKeyUp

queen adder
#

Hes using the NewInput System

rocky canyon
#

oh

vale karma
#

yea

queen adder
#

If ur using UnityEvents u have to change ur code

vale karma
#

wym

queen adder
#

Are u using them?

vale karma
queen adder
#

Show me the NewInputSystemValues class

vale karma
#

it has broken code in the jump rn, but above the if statement was all it had beforehand, just reading the input

queen adder
#

if(context.ReadValueAsButton.WasPressedThisFrame)

vale karma
#

ahhh

rocky canyon
#

thats the equiv to the Input.GetKeyUp

vale karma
#

i want to keep it versitile so i could have my wife play on controller

queen adder
#

I like the new input system but its overly complex imo

rocky canyon
#

but yea, you should read as value..

queen adder
#

U do that inside of InputAction class inspector or whatever its called

rocky canyon
#

thats the proper way

vale karma
#

its the same thing but converts it to a bool at a certain threshold you can set

#

kind of like a trigger to a gun

queen adder
#

Yeah

#

But for a jump that doesnt really matter. just jump as soon as its pressed

rocky canyon
#

thats the whole thought process behind the new input system

#

is u can create functionallity that will translate from kb to gamepad, etc

queen adder
#

That part of it is super cool

rocky canyon
#

and change things super quickly

queen adder
#

And relatively ez

rocky canyon
#

assign new schemes etc

vale karma
#

yea, but i got it workin, and i think its fine if i set the threshold to 100 or just leave it

rocky canyon
#

ya, im behind in it tbh

vale karma
#

also i want to see if i could ever make this vr too haha

rocky canyon
#

i still use basic Input code to prototype

vale karma
#

i have made vr before, but nothing crazy

queen adder
#

Nice!!

#

The jump is working now?

vale karma
#

nah one set

#

sec

queen adder
#

Ah to bad

#

Still got work to do

vale karma
#

it doesnt like that code

#

the Waspressedthisframe code

queen adder
#

Whats the error message

vale karma
#

oh wait

queen adder
#

context.action.WasPressedThisFrame();

vale karma
#

i got it working, but if you hold space after you let it go and your still in the air, you jump again, so i guess Waspressedthisframe can be used too

queen adder
#

Show the code? Are u checking if ur grounded

vale karma
#

what i learned in boating school today isssssss

#

ITS NOT READY MRS PUFF

queen adder
vale karma
#

yea im kinda stuck

#

its not really workin anyway i go about it

#

trying to read the buttonvalue and also if check if it was pressed this frame or released on the same input and then to get into the jumpstate you ahve to check both inputs which would be oposite of eachother wouldnt work

#

like if (jumpaction && !hasJumped) would be controlled by the same input. It would change hasJumped to true at the same time if not before JumpAction is true

queen adder
#

Share the entire code

vale karma
#

the idle state is what i changed to test the was pressed and was released code. as you can see the other sprint and walk states have the original jumping code.

queen adder
#

When u call jump ur not checking if u were grounded

vale karma
#

oh crap thats checked in this script

#
    {

        if (inputValues.MovementAction != Vector2.zero)
        {
            player.SwitchState(player.WalkState);
        }
        
        if (playerMovement.IsGrounded() && !inputValues.hasJumped && inputValues.JumpAction )
        {
            player.SwitchState(player.JumpState);
        }

        if (inputValues.SprintAction)
        {
            player.SwitchState(player.SprintState);
        }

        if (inputValues.CrouchAction)
        {
            player.SwitchState(player.CrouchState);
        }

    }```
#

the inputavlues.hasJumped would be true, at the same time jumpaction would be true. the WasPressedThisFrame changes hasJumped before the player jumps

queen adder
#

U need to check if ur grounded when ur setting the velocity

vale karma
#

wym

queen adder
#

Nothing

#

Share the player movement class

#

This is so nested

vale karma
#

hahaha

teal viper
queen adder
#

Yeah bro this is spaghetti

vale karma
#

lol i have a script where i get just input, a script for the basic movement mechanics,and a statemachine built to change the movement mechanics based on the state its in

queen adder
#

Yeah but u have to jump around 4 classes to see whats going on

vale karma
#

its hectic now, but realize if I want to check if im in the air while im attacking, if i have above 5 health and dont have a leg injury, and i am alive, and not starving, etc... you can tell how much would go into one if statement if i dont use state machines

queen adder
#

Its not the statemachine itself thats the problem

teal viper
vale karma
#

yea i forgot this was the first out of 4 revisions from the tutorial i got it from

queen adder
#

Its just hard to follow and work thru the code

#

But i degress

#

Whats in ur playermovement class

vale karma
#

i get what your sayin, atm i understand it, but im just putting out fires left and right

static cedar
teal viper
#

Maybe just share all the scripts properly. !code

eternal falconBOT
vale karma
#

hehe...

#

im ugly and im proud

queen adder
#

Really

#

All we need is the playermovement script

teal viper
#

You don't need to share all of them. Just the relevant ones.

queen adder
#

The spongebob references are making me feel old

vale karma
#

is it really this much just to get movement up and running correctly? or am i just not used to it?

queen adder
#

Its not

#

This is over designed IMO

vale karma
#

i get there are easier ways, and yes this is haha, but i figured id want something scaleable

static cedar
#

State machines become handy when you get a lot of states

#

Beyond just walking and crouching.

vale karma
#

i just dont wanna code myself into a corner

#

but it seems ill never make it to an end of a game unless i just say F it and hardcode the rest of it

queen adder
#

Its fine

teal viper
queen adder
#

I think ur problem is the way ur setting the HasJumped Boolean

vale karma
#

its a script of its own i think

#

and yea, im confusing myself

queen adder
#

Why not just check everything on the jump event

teal viper
# vale karma its a script of its own i think

That's a pretty bad design imho. So you have a character controller that doesn't have any dependency on the state machine and then you have an external logic that modifies the controller fields sneakily.

vale karma
#

its not a controller just a rigidbody

queen adder
#

He doesnt mean the component

teal viper
#

It controls your character, so it's a controller.🤷‍♂️

vale karma
#

ooo

#

'one step forward and two steps baaack,
yall about to give me a heart attaahaack'

teal viper
#

I think the state machine was a plain class initially, was it not?

#

Was it a MonoBehaviour from the very start?

vale karma
#

yes

teal viper
#

It was a MonoBehaviour?

vale karma
#

i think, the PlayerStateManager class has Monobehavior

teal viper
#

The question is, wether it had(*wether it is to word it correctly) it in the tutorial?

vale karma
#

yea i set it up exactly how he had it, its that apple falling off a tree state machine tutorial

queen adder
#

He didnt have a jump method?

vale karma
#

all this is so much to wrap my head around. I feel like ill never make it out of the basics DX He only explained how state machines worked. i implemented the states and what they were for myself

queen adder
#

I wouldnt code a state machine like this

vale karma
#

so now i am stuck with the knowledge of how to make states, but not really how to make a state machine in genereal

queen adder
#

You should really only Get State information when another class is requesting it

vale karma
#

Like i dont get what most of what you guys are refering to, so im sure i still have no idea what i actually wrote

queen adder
#

It doesnt even really matter

#

The problem is the Jump

teal viper
#

What's the issue anyway? This conversation dragged for so long that I didn't even see any initial info on the issue.

queen adder
#

His jump isnt working

#

Hes using the New Input System...Unity Events he has Input Class that listens for the events

teal viper
#

That's not very helpful. What exactly isn't working? Does the code not run? Does it run but not as expected?

vale karma
# vale karma

the second part of this video where im moving and jumping

queen adder
#

When the Jump event is raised he sets a hasJumpedBool to true and sets another field

#

But the second field seems redundant

#

public void OnJump(InputAction.CallbackContext context)
{
if (context.action.WasPressedThisFrame())
{
hasJumped = true;
Debug.Log("true");
}
if (context.action.WasReleasedThisFrame())
{
hasJumped = false;
Debug.Log("false");
}
JumpAction = context.ReadValueAsButton();

}
#

Why are u setting JumpAction to the context?

vale karma
#

i was going to replace it with the above code

teal viper
queen adder
#

U should really just try and set the state inside of OnJump()

vale karma
#

but then i figured i am thinking of what pressing this frame wrong. instead of thinking of "have i jumped already?" the bool is actually determining "am i being pressed". So im thinking if i put hasJumped in the Jump state it would work?

queen adder
#

That does not happen

#

WasPressedTHISFrame

#

It only checks it for a single frame so ur good

#

Theres no reason to check if a jump button was released. Especially since u DONT want them jumping if the spacebar is held down

vale karma
#

im noticing theres still more bugs in my code with movement. the player cant go up a small angled wall when hes walking, but he can fly up it if hes sprinting. Ill just have to scrap this project for now, i think i bit off more than i could chew

#

how did you guys get so good at it? just years of practice im guessing

queen adder
#

Yes and no

#

Trial and error mostly

timber sundial
#

Hello! I was hoping to get help with programming a EditorWindow. I want it to debug.log some info when the button gets pressed but nothing pops up. Is there a way to debug.log without pressing the play button in unity?

#

This tool is for developing so it would be used primarly while not playing the game.

eternal needle
vale karma
#

okay, bc im getting discouraged thinking i learned something, spending 3 weeks on it, then getting stuck and realizing what i did wasnt right

#

you can ask @dlich ive been on this same concept for weeks

eternal needle
#

theres lots of ways to do movement, its not unusual to rewrite it a few times because a past way wasnt quite right. I rewrote my first one a few times then moved on from that project due to it being overscoped.
Then it also ties into stuff later in your game, like knockback, restricting movement (stuns, slows, etc).

timber sundial
#

will do ty!

vale karma
#

yea its getting cumbersome. and thats only movement. then i have to figure out wtf to figure out next

verbal dome
#

Its good to get comfortable with rewriting your code

vale karma
#

yea, i was just hoping the 5th time was the charm :.)

teal viper
#

The point is to read through it and understand how it works. And why. Why is probably the most important question. Why implement like this and not some other way.

vale karma
teal viper
#

Maybe look at some unity samples. I think there was that open source project by unity where they implemented a lot of stuff.

vale karma
#

ill check it out, itll give me a good idea

charred spoke
knotty tendon
#

When I add a ui text object it doesn’t seem to show up anywhere except for a blue text symbol. I can’t get a picture atm but does anyone know a simple solution to this?

keen dew
#

Not a code issue (#📲┃ui-ux) but there's not much to say without seeing it other than make sure the text object is in the right place and has the right size

arctic ibex
#

Anyone know how to disable the follow on Cinamachine? I have my code set up already, I just can find the function (or whatever it called) to disable it. It seems like it must be "virtualCamera.m_follow" or "virtualCamera.Follow" but I can't figure out the syntax

arctic ibex
#

lemme get a screenshot hang on

#

Doesn't work

languid spire
#

.Equals is a comparison method not a setting method

arctic ibex
#

Okay, what method would I use instead?

languid spire
#

none just =

arctic ibex
#

oh alright

#

thx

hybrid sundial
#

how can i make it show the box collider and allow me to edit it

#

im trying to add it to the prefab

rare basin
#

this is a code related channel

hybrid sundial
#

which channe; shall i go to

rare basin
rich adder
#

are you doing a unity learn project?

hybrid sundial
#

yes

trail heart
rich adder
#

ahh good catch

hybrid sundial
#

i had that

#

on

#

still the same thing

#

i just pressed a few buttons to check

rich adder
#

yeah its also missing the gizmos button on the component itself

trail heart
#

Blue means on, grey off
If that doesn't help then I don't have more ideas

hybrid sundial
#

is there no way i can visualise what collider im putting Cry

rich adder
#

make a new project

hybrid sundial
#

i dont have any space

#

it will take hours

rich adder
#

You downloaded the learn template though right?

hybrid sundial
#

i have the worst setup for now

#

so there is 0 chance of this working

#

on this project

rare basin
#

not our problem kinda

rich adder
#

might be custom inspector messing with it

hybrid sundial
#

I’m switching back to unreal this killing me

rich adder
#

only way to know is testing a new project

fringe plover
#

Sup, i have problem, i want it to move/shake slowly, but even with RB its fast, whats wrong?

vocal fable
#

pov : my coding skills

#

gifs are not allowed

#

what

rare basin
#

offtopic is not allowed aswell

vocal fable
#

well this is coding

#

or where do i post this

#

else

rare basin
#

still offtopic

#

do you need help with anything?

#

or do you have any code related question?

fringe plover
rare basin
fringe plover
#

nah i forgot about it

#

i did but forgot

burnt vapor
fringe plover
#

ok..

dusty coral
#

how to hide this in vs code?

rich adder
#

remove the extension, indent rainbow

fringe plover
#

who use vsc in Unity 🗿

rare basin
#

a lot of people?

dusty coral
#

it runs better

native seal
#

can I create randomly generated items with stats using a scriptable object base? when I edit the item at runtime, it obviously changes the scriptable object and therefore changes all instances of the item. Whats the best way to structure this?

eternal needle
languid spire
native seal
native seal
#

here is my item, I want to randomly change the "affixes" when an item is dropped, should I make a wrapper c# class to hold it?

native seal
#

from a database

#

i don't want my database to be cluttered with 100 duplicates

#

my idea is to just save the affixes in json and rebuild the items at start

rare basin
#

SO should be just constant data container, that doesnt change

#

Item stats should be on different class

native seal
#

SO's are fine to change at runtime, jsut not in this case due to the use case

rare basin
#

usually i do ItemData scriptable object and ItemStats and just store the base stats on item data and assign them to itemstats in start

native seal
#

i will use the SO to have a "base item"

eternal needle
# native seal i don't want my database to be cluttered with 100 duplicates

If you are generating an item with something that is entirely random, you're gonna have to store the random value no matter what you do. Your only other option would be storing the seed used to generate this number, but then you would also have to make sure you generate them again in order which isnt gonna be fun either

rare basin
#

than if you upgrade the item you modify the stats from ItemStats

#

not from ItemData

native seal
#

and have it be rebuilt at start

rare basin
#

you cannot serialize SO btw

native seal
#

instead of having a database ingame to hold every isntance of every time of item

rare basin
#

if that's what you are planning to do

native seal
#

yes you can

#

i do it currently

rare basin
#

gl

native seal
#

by using guids

#

and a database

rare basin
#

that's still not a serialization

native seal
#

yes

#

i know

eternal needle
rare basin
#

so why did you say "yes you can"

#

you cannot serialize SO

#

that's a fact

native seal
#

yes not directly

#

but the data is very easy to serialize

eternal needle
#

Well not at all. You are saving a string that the SO just happens to have as well

native seal
#

and rebuild

rare basin
#

that has nothing to do with SO serialization

#

you just made save/load system for the guid

native seal
#

yes i know, so's are just simple to do so since they persist in the asset folder

languid spire
rare basin
#

idc about some random assets im talking about built-in solutions

eternal needle
rare basin
languid spire
#

yes, because you are always so definitively wrong

native seal
#

lol

rare basin
#

sure xD

native seal
#

im just wondering the best way to implement this to easily allow for expansion

#

so i should use SOs for the base item, sprite, name, etc, then have a wrapper class with a constructor to add affixes?

rare basin
#

yes

#

actual item stats should be in a different class

#

not in the SO

eternal needle
rare basin
#

or you can buy steve's asset

eternal needle
#

Although you should experiment around with when SO's data reset if you modify it at all, I remember someone tested and in a build they found it reset at weird times

native seal
languid spire
#

you don't need to buy my asset, you can roll your own, it's not that difficult

native seal
#

i jsut reset so's on start and exit

#

and then save and load from json

rare basin
#

that have the same SO hooked

#

you cannot make unique item stats with such approach

native seal
#

well i wouldnt be serializing the SO from now on, it would just be a reference on the "item Instance" wrapper

rare basin
#

yup

native seal
#

right now I don't have random stats implemented, thats what im trying to achieve

#

so I have to restructure

charred spoke
#

Imho if you design with the idea that scriptable objects are immutable life is a heck of a lot easier

eternal needle
# native seal and then save and load from json

Also if you wanted to avoid saving all the random item stats as you said above, you can just have a few variants of an item. Like make a bad, average, good variant of the item and then still just save the GUID

native seal
native seal
#

not just number variations

eternal needle
#

Diablo is basically just variation is it not? Been a few years since I played but I remember the prefix would usually indicate what the stats would be

native seal
#

the items are completely random from a pool of prefixes/suffixes with a general base item

eternal needle
#

Maybe I am thinking of a different game

#

Diablo definitely had some certain things it could generate to though, not sure if it was complete randomness

rare basin
#

each item can have up to X random affixes from a pool, and each affix can have X statistics frmo a range

native seal
#

like there are probably quadrillions of variations possible for each item

eternal needle
#

Ah

ivory bobcat
languid spire
#

@native seal May I DM you?

native seal
#

sure

burnt vapor
fringe plover
#

oh ok

languid spire
torn gyro
#

hey

#

i get this error when i added a sound file to my assets
FSBTool ERROR: Internal error from FMOD sub-system.

#

i looked online whith no luch

rare basin
#

this is a code related channel @torn gyro

torn gyro
#

with no luck

arctic ibex
#

Okay, so I have a character that can move up and down on a distance collider by using the getaxisraw. Get axis raw is checked in Update, and a variable is set which i reference in FixedUpdate. For some reason when I build is it goes up and down super slowly instead of at the desired speed, and I can't figure out what I've done wrong.

#

!code

eternal falconBOT
rare basin
#

not FMOD related

potent echo
#

dynamic rigidbody. rb.velocity = new Vector2...

torn gyro
rare basin
#

idk, not in code relaetd channel

#

in FMOD server probably

rich adder
torn gyro
rare basin
#

the asset you are using?

torn gyro
#

oh uhhh

arctic ibex
rare basin
#

lol

arctic ibex
torn gyro
#

its regular file

torn gyro
rich adder
#

You dont put deltaTime on the rigidbody at all

arctic ibex
rare basin
#

FMOD is a asset

rich adder
arctic ibex
#

Doing * Time.deltatime makes it so I can only walk in one direction

rare basin
arctic ibex
rare basin
#

what is it then you think?

arctic ibex
#

It's something to do with time since the frame started? I remember watching a video on it but I never finnished it

arctic ibex
#

Okay, it's the interval in seconds from the last frame to the current one

rich adder
#

yes its used to keep thing consistent through diff fps change

arctic ibex
#

Yes, I know that

rich adder
#

You just learned it lol

arctic ibex
rich adder
#

not related..tho

#

so tell me how this would make you only walk in one direction

arctic ibex
#

Look, I'm just asking for help to figure out why the speed for my distance joint is doing weird things, and the thing you told me to do (ei. multiplying the getrawaxis by Time.deltatime) did not work. Can you help me?

arctic ibex
split dragon
#

Hi. I was faced with a choice of how to access the component: create a variable for the component: [SerializeField] "component name" "variable name" or: GetComponent<"Component name">(). Which option would be better?

rich adder
#

this isn't the updated code

split dragon
arctic ibex
arctic ibex
rich adder
arctic ibex
rich adder
#

your bool , your if statement

#

when you are saying its walking in one direction, what is the value

#

lassoed

arctic ibex
#

It's negative both ways, because the character isn't lassoed

#

walking doesn't change that

rich adder
#

then your groundwalking is wrong

arctic ibex
#

You know what? Nevermind, I'll figure it out on my own.

dusty coral
#

why does the unity code suggestions in vs code suck so bad even after I installed unity code snippets?

burnt vapor
#

Are you on Windows?

#

If so, consider using Visual Studio instead so you don't have to bother yourself with a list of setups

#

Unless you have a reason to use VSCode, obviously.

swift crag
# torn gyro whats f mod

I don’t think you were directly using FMOD here. It’s an audio system. Unity uses a modified version of it internally.

#

If you’re getting errors when you try to import an audio asset, ask about it in #🔊┃audio

swift crag
dusty coral
swift crag
#

They’re just random blobs of code you can insert

dusty coral
#

even .setactive wont auto complete

swift crag
#

Cool, now follow the rest of the instructions !ide

eternal falconBOT
swift crag
#

Take it from the top and ensure that you’ve done everything

#

I use VSCode on my Mac. It works great.

rich adder
graceful dust
#

I'm not exactly sure how to word this, but: How do you make a button the only thing clicked? Let me add an example: lets say every time you click a character attacks. When you click a butotn, the button presses, but the character still attacks. Is there a way to make the button pressable without the character attacking? Sorry if this isn't enough info/clear enough, just ask if oyu need more context.

swift crag
#

You need to handle that in your code.

#

If you have four characters and only one is allowed to attack at a time, you should be able to check whose turn it is

sullen rock
#

Hello! Im trying to change the backround type on my camera from skybox to solid color, but cant figure out how to do it

A quick google search recommended this

cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = Color.black;

but it doesnt actually seem to do anything

swift crag
rich adder
tepid summit
sullen rock
sullen rock
tepid summit
#

what is the for if i may ask?

rich adder
sullen rock
tepid summit
#

try awake?

sullen rock
#

wrong answer

sullen rock
rich adder
#

does the object disable itself?

sullen rock
#

nope

tepid summit
#

use debug.log to see if its even called

sullen rock
#

I know it is called

rich adder
tepid summit
#

how

sullen rock
#

since other code in the same if statement is executed

rich adder
tepid summit
#

that deosnt make sense

sullen rock
burnt vapor
#

Use Debug.Log and pass cam as the second parameter

#

Then, click on the log

sullen rock
graceful dust
merry plover
#

can smb help me with an error message i have in an unity project?

rich adder
merry plover
#

o9k

cerulean snow
#

Hello. This is probably has a really simple answer but how do I make so a Raycast2D starts a bit to the left or right of the character. I want to have it check if the character is about to go over a ledge

rich adder
merry plover
#

i have no idea of coding xD

rich adder
merry plover
#

cuz i dont know

rich adder
merry plover
rich adder
merry plover
#

AI, cuz i dont know anything bout coding

rich adder
merry plover
#

oh, ok. mb srry

rich adder
#

I suggest you actually learn properly with course !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

merry plover
#

thanks

stuck palm
#

can you create a button in your script that can be clcked from the inspector and manually runs a method?

rich adder
hexed terrace
rich adder
#

sometimes a [ContextMenu] will do 🙂

sullen rock
#

seems like it works now, at least in playmode in unity, will try to build it

hexed terrace
hexed terrace
rich adder
#

true, i personally enjoy messing with Custom editor/inspectors

hexed terrace
#

Odin Inspector (IIRC) adds a [Button] attribute, which does it with just that

rich adder
#

ya i think there is also naughty attributes for free

stuck palm
#

i was just wondering

#

i dont think i need it yet but

#

i feel like it would be helpful

rich adder
#

yup

dusty coral
#

why is there no red underline on the mistakes of my code in vsc?

rich adder
#

how many times you need to be told

dusty coral
#

i did

rigid valve
#

@rich adder would you like to test the you were helping me with other day 🙂

rich adder
hexed terrace
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

cosmic dagger
rich adder
#

been decent recently , the updates are making ok

cosmic dagger
#

I use it (vscode) as my IDE, and it only ever messed up twice, but I finally got around to installing Rider. I just need to configure it with Unity . . .

dusty coral
#

what is rider

rich adder
#

another IDE

cosmic dagger
rich adder
#

free if you're student

cosmic dagger
#

Though VSCode isn't really an IDE, but yeah . . .

autumn tusk
#

ok this question is gonna sound really dumb

rich adder
autumn tusk
#

but how do i run a coroutine from another script

rich adder
gaunt ice
#

how do you call method from another script

cosmic dagger
autumn tusk
#

yeah

#
using System.Collections.Generic;
using UnityEngine;

public class WeaponInfo : MonoBehaviour
{
    public string weaponname;
    public float bulletforce;
    public int ammo;
    public int maxheldammo;
    public int playerdamage;
    public float spread;
    public int shotsfired;
    public float reloadtime;
    public bool isautomatic;
    public float burstdelay;
    public Transform firepointpos;
    public Transform newfirepointpos;
    public GameObject ammoused;
    public Sprite weaponpickupsprite;
    public SpriteRenderer heldweapon;
    public AudioClip shootclip;
    public AudioClip emptyclip;
    public AudioClip reloadclip;
    public playershooting _playerShooterScript;
    public PlayerPickupText _playerPickupText;

    // Start is called before the first frame update
    private void Awake()
    {
        _playerShooterScript = UnityEngine.Object.FindFirstObjectByType<playershooting>();
        _playerPickupText = UnityEngine.Object.FindFirstObjectByType<PlayerPickupText>();
    }
    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.CompareTag("Player") && Input.GetKey("q"))
        {
            print(weaponname);

            heldweapon.sprite = weaponpickupsprite;
            _playerShooterScript.weaponname = weaponname;
            _playerShooterScript.ammo = ammo;
            _playerShooterScript.maxheldammo = maxheldammo;
            _playerShooterScript.spread = spread;
            _playerShooterScript.shotsfired = shotsfired;
            _playerShooterScript.reloadtime = reloadtime;
            _playerShooterScript.isautomatic = isautomatic;
            _playerShooterScript.playerdamage = playerdamage;
            _playerShooterScript.bulletForce = bulletforce;
            _playerShooterScript.burstdelay = burstdelay;
            _playerPickupText.StartCoroutine(PlayerPickup(weaponname));
        }
    }
}
cosmic dagger
#

Then use the reference to call it, though I'd do with navarone said and call a method that starts the coroutine . . .

autumn tusk
#

how would i do that

hexed terrace
#

StartCorountine(<methodyou wan to call>)

autumn tusk
#

i already have that though

hexed terrace
#

no, you do not.

autumn tusk
#

_playerPickupText.StartCoroutine(PlayerPickup(weaponname));

#

how would i fix this specific line to be in line with syntax

hexed terrace
#

_playerPickupText.PlayerPickup(weaponname) is the method you want to call

rich adder
# autumn tusk how would i do that

public class A{
    public void Foo(){
        StartCoroutine(Bar())
    }
    private IEnumerator Bar(){

    }
}
public class B{
    A a;
    void Method(){
        a.Foo();
    }```
gaunt ice
#

so how do you call method from another script

hexed terrace
#

_playerPickupText.StartCoroutine() is not a thing and is why you're having errors.

autumn tusk
#

ok you just dont call the coroutine

#

makes sense

hidden sleet
#

Was hoping to clarfiy a couple things that have had me a little confused. I have here a script for a UI slot of an inventory, which when clicked should spawn an item into the world. I am refactoring it at the moment so I don't need to check the scene to spawn stuff, but I was curious about that Inventory object. As is, I was worried that having that there would mean that every single UI slot has it's own inventory, holding every item in my inventory, wasting memory. But is that actually the case? I'm not too sure how memory management works in this scenario. Is it the case that the actual inventory is held elseswhere, and this just references that, or is each slot actually holding the inventory in it?

public class InventoryUiSlot : MonoBehaviour, IPointerClickHandler
{
    public InventoryItemSlot CorrespondingInventoryItem;
    public Inventory inventory;
    public void OnPointerClick(PointerEventData eventData)
    {
        Scene currentScene = SceneManager.GetActiveScene();

        switch (currentScene.name)
        {
            //Get the item placer and inventory manager to retrieve the user's inventory
            //Then place the item in the world
            case "Roam":
                break;

            case "Recycle":

                if (CorrespondingInventoryItem.item is RawItem)
                {
                    itemPlacer itemPlacer = GameObject.Find("CraftingManager").GetComponent<itemPlacer>();
                    itemPlacer.placeItem(CorrespondingInventoryItem.item.objectPrefab);
                    UpdateUiElementOnClick();
                }
                break;

            case "Build":
                itemPlacer buildItemPlacer = GameObject.Find("BuildManager").GetComponent<itemPlacer>();
                buildItemPlacer.placeItem(CorrespondingInventoryItem.item.objectPrefab);
                UpdateUiElementOnClick();
                break;

            default:
                break;
        }

    }

    public void UpdateUiElementOnClick()
    {
        inventory.RemoveItem(CorrespondingInventoryItem.item, 1);
        CorrespondingInventoryItem = inventory.GetItemSlot(CorrespondingInventoryItem.item);
        if (inventory.invContainer.Contains(CorrespondingInventoryItem))
        {
            gameObject.GetComponentsInChildren<TextMeshProUGUI>()[1].text = CorrespondingInventoryItem.count.ToString();
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private void OnDestroy()
    {
        Debug.Log("The ui slot was destroyed");
    }

}```
fierce shuttle
# hidden sleet Was hoping to clarfiy a couple things that have had me a little confused. I have...

Assuming that you assign the inventory from somewhere else, each slot is then holding a reference to the 1 source of "inventory" in memory, so each slot is not reserving extra memory of your entire inventory, just a object that points to your inventory - though if your refactoring, personally I wouldnt have a slot even know about the inventory, in my mind, a slot should just need to display info its given (perhaps a scriptable object, serialized class or just params in a function), and maybe hold a reference to an item its displaying - a inventory manager could be the part that holds your entire inventory and feeds that to slots, that manager can handle things like dropping, stacking, moving between slots, etc, this way slots dont need "parent references" to do its job imo

hidden sleet
#

Thanks for the clarification. I'm trying to figure out how to do that to a degree, I don't want classes doing much more than it's name implies but I'm having difficulties figuring out how to go about it. Been trying lots of different ways but my inexperience is making it tough to figure out

stuck palm
#

how could i create a UI element on the top of the screen that has information on it? like when a new patient spawns it creates a card with the patient data on it? I was thinking making use of a queue or a stack to just add data on the end

#

my problem is how i would create a new card

#

or how i would access the stack

candid gorge
#

Hey can someone help me out please, I'm really confused idk why my list size is being limited when Im not even using my inventorysize variable

using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{
    public List<GameObject> inventory = new List<GameObject>();
    public int inventorySize;

    private GameObject activeObject;
    private PlayerController playerController;

    public int currentObject = 0;

    // Start is called before the first frame update
    void Start()
    {
        playerController = GetComponent<PlayerController>();
        //inventory.Capacity = 5;
    }

    // Update is called once per frame
    void Update()
    {
        currentObject = playerController.currentEquip;

        //Debug.Log(currentObject);

        foreach (GameObject item in inventory)
        {
            if (inventory.Count == 1)
            {
                currentObject = 1;
                activeObject = item;
                activeObject.SetActive(true);
            }

            if(inventory.Count > 1)
            {
                if (item != activeObject)
                    item.SetActive(false);

                else
                    return;
            }
        }

        Debug.Log(inventory.Count);
    }
}```
burnt vapor
rare basin
#

inventory.Capacity = 5;

#

why are you using Capacity property

#

that's why its limited to 5

candid gorge
rare basin
#

ah

candid gorge
#

nvm i just figured out the problem

rare basin
#

then what do you mean by being limited

candid gorge
#

if inventorysize = 3 for example, the list doesnt go beyond that, but is because i'm using another script for that and i didnt remember nvm

#
{
    GameObject item = Instantiate(prefab, objectPosition.transform);
    inventory.inventory.Add(item);
    Destroy(gameObject);
}

else
    return;```
I'm using this
#

thats the problem

rare basin
#

inventory.inventory.Count

#

huh?

#

use some better naming conventions please

candid gorge
rare basin
#

then that's not that list

#

you are logging

candid gorge
#

it should be

#

because when its empty it shows 0

rare basin
#

but its not

#

code doesnt lie ;p

candid gorge
fringe plover
#

!code

eternal falconBOT
candid gorge
gaunt ice
#
void Update(){
    currentObject = playerController.currentEquip;
    //Debug.Log(currentObject);
    foreach (GameObject item in inventory){
        if (inventory.Count == 1){
            currentObject = 1;
            activeObject = item;
            activeObject.SetActive(true);
        }
        if(inventory.Count > 1){
            if (item != activeObject)
                item.SetActive(false);
            else
                return;
        }
    }
    Debug.Log(inventory.Count);
}
```what if inventory.count>1 and item==activeObject
candid gorge
#

same behaviour

gaunt ice
#

btw debug.log accept second argument that tell you which object it is logged

#

and recommend: instead of log the Count only you should use string interpolation to have a meaningful text (instead of a single number) or using debugger
also log the count before any early return

candid gorge
#

rn I'm just trying to check how many objects does the list have because that chunk of code doesnt seem to work

#

but for some reason the count caps at 1 no matter how many objects does the list have

candid gorge
gaunt ice
#

is the debug.log keeps flooding your console

#

or stop at some point while playing?

candid gorge
#

it stops

#

whenever the list size is bigger than 1 it stops debugging

#

however if I erase the code above it debugs correctly

gaunt ice
#

ok
when the count of list == 1, the activeItem is the first item in the list ---- 1
after you propagate the list so Count>1 ---- 2
since the first item is active item so early return ----- 3

foreach (GameObject item in inventory){
    if (inventory.Count == 1){ -----  1
        currentObject = 1;
        activeObject = item;
        activeObject.SetActive(true);
    }
    if(inventory.Count > 1){ ------ 2
        if (item != activeObject)  <-----first item==activeObject, so false
            item.SetActive(false);
        else
            return; ----- 3
    }
}
candid gorge
#

ohh i see

#

damn thanks

#

i didnt think that

gaunt ice
#

!code

eternal falconBOT
fierce shuttle
# hidden sleet Thanks for the clarification. I'm trying to figure out how to do that to a degre...

Maybe you can look into events and delegates, they are a nice way to have scripts get notified when something specific changes, you could also look into properties so you can display data to other classes but not allow them to change it - for example, your manager could hold a list of UISlots, and subscribe a "OnSlotClicked" event, when that slot gets mouse input, it can fire that event passing itself as a reference, and the subscribed function from the manager would be called knowing the slot that was clicked, it can then update that slot as needed

trim aurora
#

Hi folks - I'm trying to simulate some "flapping" rotation mechanics while just experimenting with some code, but something's not working. Basically, I want a constant clockwise torque on a 2d object which gets an impulse counterclockwise torque upon a "flap" click, simulating a very basic flight movement. However, when I run the below, the rigidbody seems to just get stuck on the lower or upper bound of my LimitRot() method. Any ideas why?


void Update()
  {
    LimitRot();
    myRigidbody.AddTorque(torque, ForceMode2D.Force);

    if (Input.GetMouseButtonDown(0))
    {
        myRigidbody.velocity = Vector2.up * flap;
    
        myRigidbody.AddTorque(impulse, ForceMode2D.Impulse);

private void LimitRot()
{
    Vector3 playerEulerAngles = localTrans.rotation.eulerAngles;

    playerEulerAngles.z = (playerEulerAngles.z > 180) ? playerEulerAngles.z - 360 : playerEulerAngles.z;
    playerEulerAngles.z = Mathf.Clamp(playerEulerAngles.z, minZRot, maxZRot);

    localTrans.rotation = Quaternion.Euler(playerEulerAngles);

#

Sorry for all the edits! Just getting used to the inline code function 🤦‍♂️

scenic urchin
#

Is it possible to set variables of a script not to be saved when a prefab is changed and saved? I have these prefabs that I'd like to keep some variables different on each object, is it possible?

#

If Unity follows general c# behavior, setting the variables as nonserializable should do?

hidden sleet
#

Also going through and changing some things so my classes aren’t as messy and I utilise inheritance more, so everything is a bit of a mess at the moment

fierce shuttle
# hidden sleet Also going through and changing some things so my classes aren’t as messy and I ...

It may help to create a second script to try some new things in, so you have less to look at, and just focus on getting logs to happen through events and pass info through the events to update the logs, then you have a simplified example you can reference to scale up to your current inventory, I often do something similar when picking up new things, though I usually go a step further and also do them in a separate test project, just to remove complexity in my main project (though version control is another way to manage that potential problem)

hidden sleet
#

I’ve gone and made a separate class for the new implementation so I don’t lose where I was at with the other one, but it’s mostly down to the fact that im throwing stuff at the wall to see what sticks

fading rapids
#

what is this?

wooden minnow
#
public class CollectableDoubleJump : MonoBehaviour
{
    public PlayerController1 controller;
    private void OnTriggerEnter2D(Collider2D collision)
    {
        controller.canJump = true;
        StartCoroutine(RespawnCooldown(3));
        gameObject.SetActive(false);
    }
    IEnumerator RespawnCooldown(int seconds)
    {
        yield return new WaitForSeconds(seconds);
        gameObject.SetActive(true);
    }
}```
why doesnt this work? object doesnt respawn
undone rampart
fading rapids
#

and does is affect my work

undone rampart
fading rapids
#

ok ty

rare basin
#

did you debug it?

wooden minnow
#

yes

rare basin
#

how?

wooden minnow
#

i can double jump

#

when i hit it

rare basin
#

put a debug log in it

wooden minnow
#

and it disappears

rare basin
#

and show the results

wooden minnow
#

but it doesnt reappear

rare basin
#
    IEnumerator RespawnCooldown(int seconds)
    {
        Debug.Log("respawn coroutine!);
        yield return new WaitForSeconds(seconds);
        gameObject.SetActive(true);
    }
#

see if it prints

wooden minnow
#

starts but doesnt end

rare basin
#

does it print?

#

the debug log

wooden minnow
#
    IEnumerator RespawnCooldown(int seconds)
    {
        Debug.Log("started coroutine!");
        yield return new WaitForSeconds(seconds);
        gameObject.SetActive(true);
        Debug.Log("Ended coroutine");
    }``` it printed start, didnt print the end
rare basin
#

okay

#

what's your timescale?

#

WaitForSeconds is timeScale dependant