#💻┃code-beginner
1 messages · Page 211 of 1
can you show me your code that acheived that?
wooo
im suck code but still choose game for my project
"liberate"
haha yes indeed
Itll be super rewarding in the end
freedom of exchange, & all 
but idk why first time it work. i didnt add Charecter controller
And game programming is on the more impressive side of programming
https://hatebin.com/heqewqmvqy LIST_TEST.cs
https://hatebin.com/blgqkgylbk LIST_TEST_Editor.cs // has to go in Editor folder

not sure that get/set is still required for it to work.. but i just didnt remove it
awesome thank you so much
the callback should be enough OnMyStringListModified()
Oh, I know why it was happening now
Is there a way to prevent the private keyword from being auto put on methods ? I tried
but to no avail
b/c code running too fast
Wdym by auto put?
I was trying to get the component of a component, that was what was null
What I don't get is why that ends up spawing the prefab without the refencenced component
they removed the embeds 👀
I didnt even know there was a intellisense file / settings.json
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
Vector3.Distance() is my first guess
i didnt either 😄 i know about templates.. didnt know intellisense used settings like that
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
Ok so yeah this works, but is there a way to get a reference to the object that was just added?
do you mean all of your methods or the default template for when you create a new script?
I know how to change the default template
wouldnt u just be able to grab the last index
the one added would be on the bottom
But spawn showed me the way i got it figured out
would it alwasy tho?
pretty sure its always the last index
You probably don't want to make a list for each tower of each single enemy spawned with a FindObjectsByName
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?
ummm not sure tbh
my default template is now
using UnityEngine;
public sealed ClassName : Monobehavior
{
void Awake()
{
}
}
i dont know how list reorder themselves if im honest
same here tbh thats why im not using indexof
default templates are the best.. no need to remove the comments and random using statements
i think it depends on size of list
Probably the range of the tower should be marked with a trigger collider that checks for any objects with the proper tag that enter it and add those to the list of possible targets (and remove them when they leave)
large lists fill in the holes small lists reorder when items are removed iirc
okay thank you! this list should be static and on the script that controls my tower's targetting correct?
No
List.Add will put it in the end of the list
ya, it seems like from what im reading they always are added at the end.. unless u use Insert to insert them at a specific index
The list should not be static; you are meant to update it constantly
you should not use FindGameObjectByTag, instead, create a trigger collider and add enemy GameObjects to a list when they enter (remove when they exit), or use a physics overlap method to grab all of the enemies within range . . .
Yeah i dont see why the list would be static when ur going to have multiple instances of the same tower probably
ohh no, not statics again 😅
Ikr
oh yeah thats seems dumb now that i think about it my bad guys 😭 (thank you for the help btw!)
leave static for extension methods . . .
iono, people see static and like OHH i can access that anywhere!
thats awesome, ill use it everywhere
Yeah i was obsessed with them at first to
yeah i saw that but the problem is, the code in the custom inspector is called before the item is actually added to t he list D:
they go HAM with static after finding out it can be accessed from anywhere . . .
lol facts
But quickly realized ur not supposed to use them like that
ohh, thats unfortunate.. might could use some sort of workaround to wait until its finished being assigned.. not sure how off hte top of my head..
coroutine maybe?
oh wait yo u cant do those in editor scripts can you?
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
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
you could use the callback in the regular monobehaviour do the actual coroutine
idk what ur use-case is..
i t hink I need to rethink my approach
but i dont think u can have editor scripts in ur build at all..
not sure thats a problem for u
thought this was a tool/ ease of use type situation
Went thru all the work and ur code wouldnt even show up in ur final build lmao
I think I need to just render the list in the inspector myself manually with my own GUI code tbh
ya, editor scripts are for the developers
editor scripts are only for development . . .
Why not just give them there appropriate Ids somewhere else
wait, what is the issue?
Because u cant even use the editor scripts when ur game releases
When the list changes in game then what?
im making an editor tool
^ this.. he wanted a callback for when he added to a string list thru the inspector..
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?
ok ok
Then whats the point of the editor code if u arent going to use it in game?
EditorCoroutines package allows this
TIL.. theres Editor Coroutines 👀
Yep. I usually use async instead tho
Async scares me
@oak nimbus you can do that with the new UI Toolkit. i'd use that for making editor tools, imo . . .
especially inside of unity
w/e Random Says is better than my solution.. i can almost gaurantee it @oak nimbus
ok so I am g oing to make a long post e xplaining my use here give me 5 mins
I can almost gurantee it wont be worth it in the end
im thinking its probably one of them.. X Y problems..
where theres probably a better solution all together than what we're thinking
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
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
sooo much relevant information! thanks for typing it out 👍 im surely these guys can tell u exactly what u need to do now
Why not just give the items in the list IDS when the game starts
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
I may be stupid but u cant just give them ids when u serialize the class?
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
i think this is my best solution so far ima give it a look
ya, not sure i should be helpin u at all considering im just a humble peasant, in terms of where ur at 😄
i just dont want to remake a bunch of editor tools in ui toolkit if i can avoid it
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 . . .
And then u can check what IDs are available via the callback and repopulate the IDs when a list item is removed
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:
This is the code that manages the bounce: https://gdl.space/egusinepuv.cs
Yeah this wont work either, it doesn't provide a way to get the object in the list and has the same issue the code spawn provded does the callback is called before the item is actually added to the list so I cant just get t he last item added to the list cause it technically didn't happen yet.
im just gonna code my own UI for rendering the list.
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).
I mean, what is it meant to do after attacking once?
Keep attacking.
Have you loop time on the attack clip?
How do I do that?
That's the animator STATE not the animation CLIP
They are different
Click twice
Oooooooooh
Also, this is not really a code question, there is a specific channel for animation
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
How do I hide the mouse cursor?
Like for a FPS game.
Thanks
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
See posts, photos and more on Facebook.
Dont crosspost
sorry @rich adder
post the video
no use this
https://streamable.com/
You need to actually post some code or a description of how it's currently set up too
you should not dox yourself like that
what do you mean?
huh ? you have personal conversations open
in a video, you should not be showing that lol
lol no worries, just saying it for you
okay!
poste the code too?
are you folliwing a video?
Yes!
that gravity is wrong
Looks to me like your ground is at an angle
But those video clips aren't really helpful
Learn How To Make an Endless Runner Game From Scratch With Blender And Unity. All code is written entirely in C#. https://play.google.com/store/apps/details?...
you have direction.y += Gravity * Time.deltaTime; twice
they don't have that in the video it seems
Okay
In this tutorial, we will implement a simple jump & gravity mechanic for our player.
● Project files on GitHub: https://github.com/Chaker-Gamra/Endless-Runner-Game
● The Whole Playlist: https://www.youtube.com/watch?v=DxKIuyOjwPw&list=PL0WgRP7BtOez8O7UAQiW0qAp-XfKZXA9W
●Get The Game:
https://play.google.com/store/apps/details?id=com.chakergamr...
look the video
Your code is saying no matter what if im not pressing up arrow smoosh me down
copy it like the video?
if you're following a video copy it exactly like the video lol
they just told you how. you did not copy the code from the video correctly. make sure your code is exactly like the video . . .
is yours not on the ground? I can't tell from the vid game cam angle
It is I fixed it @cosmic dagger
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
Somebody helped me with that @rich adder
they made it worse
Okay
you should not mix transform.position teleport, with controller movement. Also that Lerp is HELLA wrong
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?
:doubt
only scripts derived from MonoBehaviour can attach to a GameObject . . .
Send me script? @rich adder
do you want to learn how to make a game or not ?
i do @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
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
@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
fix any console/script errors you might have
show the script you are trying to add
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
nothing special about XR really
hmm alr
you could screenshot the console window
hmm have you tried directly dragging the script onto the gameobject?
any warning or errors?
well it says its not the same file nam
ah yes that would do it
i believe there is information being left out . . .
when i fixed it it still does the same thing
Your filename must match class name, show that they match
what is this infamous script?
Also, just to mention, capitalization matters too
i deleted it to write a new one. i will send the new one in a min
i question your tactics. you could have sent the original for us to see . . .
well in my degree if something is wrong redo it
Asking for code help without code is like going to a car repair shop without a car
then ask questions if i keep getting same results
yes does degree not have common sense
?? elaborate on what u are saying?
lets hope ur scripts dont get very long lol
seems like it was all a big waste of time, coming to a channel to ask for code help never showing the code then deleting it
🤷♂️
well sorry for wanting to re write my code just to make sure it wasnt a coding problem ☠️
they only said that if you posted the code for us, we could have told you if it was a coding problem. that's why we're here . . .
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?
yeah its called hiring gig
Hmm might do that instead planning on making a realistic vr game. However don’t really have the time
It's worth learning, but frameworks and helpers make it go fast
apple vision pro?
It does but getting a degree doesn’t help when the coding u learn ain’t c
No I’m on quest 2
can we make games for the apple vision pro yet?
ohh cause now seeing big ramp in vr because of apple hype
sdk is out already
i believe its restricted to Pro plans and Enterprise
Yup
Hmm couldn’t u also use ai to help generate code as well
yeah, good luck with that being somewhat accurate . . .
If you get too stuck on VR, drop the code in #🥽┃virtual-reality and I'm sure one of us can help. If you do go for frameworks, some are better than others, and it depends alot on the game you want to make.
Some are pretty badly coded though
if you know what you're doing it can be a helpful tool, but it's not going to make all your code yet for anything more complex than like snake at this stage
spambot is worth nothing more than a funny conversation
mehh copilot can be arguably considered an actual useful tool than that garbo
i use it for writing method summaries in my packages and unit tests, that's all . . .
copilot can only get you so far
and no i mean github not the new BS mS put out with the same name
that's nice
yup
how can i make a player jump only once when holding the spacebar?
set a bool, and don't reset it until the spacebar is released . . .
could i use context.performed or i think its context.entered instead?
yeah you want performed
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 . . .
.cancelled should tell you when its released
i tried using public void OnJump(InputAction.CallbackContext context) { if (context.performed) { JumpAction = context.ReadValueAsButton(); } }
i think thats very wrong tho lol, it only reads if its true or false if its performed.
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
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
Then you should be set
Just add to ur y velocity when the button is pressed and make sure ur grounded
so your saying i need to add JumpActionCancelled = under the JumpAction = right?
and then if its true I can jump again?
nre?
null reference exception . . .
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
Oh u want them to constantly jump if theyre holding the button?
the opposite
So currently if u hold the button they jump again as soon as they touch the ground?
it basically reads it, goes to jump, then resets what it knows and reads the input agian
yea
its a state machine its alot 😮
I tend to not use them (Controversial I know)
But whats ur current code looking like
once i started adding crouch and sprint i said noopeee i seeee the iceburg
Haha yeah i feel u
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)
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
Are you using Send Message?
show script
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);
}
}
}
}
Whats calling the Jump method Bear?
Show the TakeDamage method
Sorry I'm very new to this. What does that mean?
the playerHealth ?
You are calling a method TakeDamage on the object playerHealth
The error suggests that you haven't implemented it.
the jumpstate
Ur ide should be telling u that tho
ahh
!Ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Oh. My player health script. Hold on.
they generated the method in code editor, but never did anything
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yup Osmal got it
use one of these websites instead
throw new NotImplementedException();
Haha lmao
You have a duplicate TakeDamage. Remove the other one
looks like a duplicate . . .
yes
either idle, walk, or sprint state
remove the one with the throw new NotImplementedException();
Gotcha
remove the unnecessary one . . .
different signatures thats why no error in health script
Okay. Removed it. Now there's an error in my damage code XD
also, you can condense OnTriggerEnter from DamageOnce . . .
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out PlayerHealth playerHealth)
{
playerHealth.TakeDamage(damageAmount);
}
}
cast it or just change it from int to float in method playerhealth script
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
cast the variable or change the parameter type of the method . . .
All u need to do is check if u grounded and if u are call the jump method
sorry, if hasJumped is true.
i promise i started with that, and there were so many issues;
Just check ur current y velocity if its greater than zero ur jumping if its less then ur falling
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
Ah i see
Was there anything else u needed help with? Are u still jumping while space bar is held?
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
Oh good point
i didnt want to mess with the rigidbody and gravity, but i did fix it
the jumping is still happening
Again
cool cool
im writing the code now, but what is the code for when the button has been let go?
Is it UnityEvents?
Input.GetKeyUp
Hes using the NewInput System
oh
yea
If ur using UnityEvents u have to change ur code
wym
Are u using them?
Show me the NewInputSystemValues class
it has broken code in the jump rn, but above the if statement was all it had beforehand, just reading the input
if(context.ReadValueAsButton.WasPressedThisFrame)
ahhh
thats the equiv to the Input.GetKeyUp
i want to keep it versitile so i could have my wife play on controller
I like the new input system but its overly complex imo
but yea, you should read as value..
U do that inside of InputAction class inspector or whatever its called
thats the proper way
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
thats the whole thought process behind the new input system
is u can create functionallity that will translate from kb to gamepad, etc
That part of it is super cool
and change things super quickly
And relatively ez
assign new schemes etc
yea, but i got it workin, and i think its fine if i set the threshold to 100 or just leave it
ya, im behind in it tbh
also i want to see if i could ever make this vr too haha
i still use basic Input code to prototype
i have made vr before, but nothing crazy
Whats the error message
oh wait
context.action.WasPressedThisFrame();
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
Show the code? Are u checking if ur grounded

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
Share the entire code
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.
When u call jump ur not checking if u were grounded
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
U need to check if ur grounded when ur setting the velocity
wym
hahaha
Where's that code in?
Yeah bro this is spaghetti
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
Yeah but u have to jump around 4 classes to see whats going on
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
Its not the statemachine itself thats the problem
One thing that is a red flag for me is that you don't return after switching a state, meaning several states could be switched to on the same frame. If there is any logic for state switching, it would potentially run for several states.
yea i forgot this was the first out of 4 revisions from the tutorial i got it from
Its just hard to follow and work thru the code
But i degress
Whats in ur playermovement class
i get what your sayin, atm i understand it, but im just putting out fires left and right
That's a lot of switch states but I don't see return statements.
Maybe just share all the scripts properly. !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You don't need to share all of them. Just the relevant ones.
The spongebob references are making me feel old
is it really this much just to get movement up and running correctly? or am i just not used to it?
i get there are easier ways, and yes this is haha, but i figured id want something scaleable
State machines become handy when you get a lot of states
Beyond just walking and crouching.
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
Its fine
Where's the state machine even? I don't see anything about it in the controller..?
I think ur problem is the way ur setting the HasJumped Boolean
Why not just check everything on the jump event
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.
its not a controller just a rigidbody
He doesnt mean the component
It controls your character, so it's a controller.🤷♂️
ooo
'one step forward and two steps baaack,
yall about to give me a heart attaahaack'
I think the state machine was a plain class initially, was it not?
Was it a MonoBehaviour from the very start?
yes
It was a MonoBehaviour?
i think, the PlayerStateManager class has Monobehavior
The question is, wether it had(*wether it is to word it correctly) it in the tutorial?
yea i set it up exactly how he had it, its that apple falling off a tree state machine tutorial
He didnt have a jump method?
Okay then.
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
I wouldnt code a state machine like this
so now i am stuck with the knowledge of how to make states, but not really how to make a state machine in genereal
You should really only Get State information when another class is requesting it
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
What's the issue anyway? This conversation dragged for so long that I didn't even see any initial info on the issue.
His jump isnt working
Hes using the New Input System...Unity Events he has Input Class that listens for the events
That's not very helpful. What exactly isn't working? Does the code not run? Does it run but not as expected?
the second part of this video where im moving and jumping
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?
i was going to replace it with the above code
What about it? It looks fine to me on first glance. Can't see the logs on mobile.
U should really just try and set the state inside of OnJump()
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?
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
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
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.
Debugging is a skill you learn, the actual coding you'll do is trivial work 90% of the time if you understand the language already.
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
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).
Post in #↕️┃editor-extensions along with your code
will do ty!
yea its getting cumbersome. and thats only movement. then i have to figure out wtf to figure out next
realizing what i did wasnt right
That is learning
Its good to get comfortable with rewriting your code
yea, i was just hoping the 5th time was the charm :.)
One good way of learning is looking at other people's project/code. You can probably find some on GitHub or the asset store. Or just looking through different tutorials that implement a feature you're interested in.
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.
speaking of other peoples code, I wanted to look inside a finished game project and see how crazy it looks. I get ocd when i have like 3 scripts in the same folder. I get nervous when i have alot of scripts
Maybe look at some unity samples. I think there was that open source project by unity where they implemented a lot of stuff.
ill check it out, itll give me a good idea
This is part of our animation scripts for npc and the second one is part of the entire character folder.
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?
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
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
Ok thanks a lot tho
just set it to null
I did that but it doesn't seem to be working
lemme get a screenshot hang on
Doesn't work
.Equals is a comparison method not a setting method
Okay, what method would I use instead?
none just =
how can i make it show the box collider and allow me to edit it
im trying to add it to the prefab
this is a code related channel
which channe; shall i go to
are you doing a unity learn project?
yes
enabling gizmos with this button may help
ahh good catch
yeah its also missing the gizmos button on the component itself
Blue means on, grey off
If that doesn't help then I don't have more ideas
is there no way i can visualise what collider im putting 
make a new project
You downloaded the learn template though right?
i have the worst setup for now
so there is 0 chance of this working
on this project
not our problem kinda
if you downloaded a learn template, I think they want you to follow through certain steps
might be custom inspector messing with it
I’m switching back to unreal this killing me
only way to know is testing a new project
Sup, i have problem, i want it to move/shake slowly, but even with RB its fast, whats wrong?
offtopic is not allowed aswell
still offtopic
do you need help with anything?
or do you have any code related question?
it says anything
you surely read the #📖┃code-of-conduct after joining the server right?
btw..
If it doesn't fall under fixing or improving somebody's code as a beginner Unity developer, it's off topic
ok..
how to hide this in vs code?
remove the extension, indent rainbow
who use vsc in Unity 🗿
a lot of people?
it runs better
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?
You shouldnt be changing the SO at runtime, use the SO to provide the base stats then modify the object which received the values as you want.
If you are randomly generating it, I dont think you need SO then but you could create an instance at runtime
you can clone your SO base for each item, that way each one has it's own
I dont believe I could do that since it would be impossible to serialize
not impossible
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?
well currently i dont have random item generation and am serializing a guid to then regenerate the items at start
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
well your SO shouldn't have such data
SO should be just constant data container, that doesnt change
Item stats should be on different class
SO's are fine to change at runtime, jsut not in this case due to the use case
usually i do ItemData scriptable object and ItemStats and just store the base stats on item data and assign them to itemstats in start
i will use the SO to have a "base item"
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
my plan is to just save all the items to json
and have it be rebuilt at start
you cannot serialize SO btw
instead of having a database ingame to hold every isntance of every time of item
if that's what you are planning to do
gl
that's still not a serialization
I had a similar problem of not wanting to save every item because of random value, so I instead just opted to not have random values lol
Well not at all. You are saving a string that the SO just happens to have as well
and rebuild
that has nothing to do with SO serialization
you just made save/load system for the guid
yes i know, so's are just simple to do so since they persist in the asset folder
really? what's this then, a figment of my imagination
https://assetstore.unity.com/packages/tools/utilities/scriptableobject-pro-218340
idc about some random assets im talking about built-in solutions
I think they meant by default, of course it's possible to write code for it
he always has to advertise his asset when talking about SOs 😄
yes, because you are always so definitively wrong
lol
sure xD
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?
It really is a lot easier that way, but as mentioned above you could also create instances for your SO. If you truly wanted to keep going down that path
or you can buy steve's asset
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
yeah i feel like that would get messy very quickly and prone to data loss
you don't need to buy my asset, you can roll your own, it's not that difficult
sure but what if you have 100 of the same items
that have the same SO hooked
you cannot make unique item stats with such approach
well i wouldnt be serializing the SO from now on, it would just be a reference on the "item Instance" wrapper
yup
right now I don't have random stats implemented, thats what im trying to achieve
so I have to restructure
Imho if you design with the idea that scriptable objects are immutable life is a heck of a lot easier
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
idk I use scriptable objects fine for inventories
i want random stats as in Diablo 3, path of exile style
not just number variations
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
no, totally no
the items are completely random from a pool of prefixes/suffixes with a general base item
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
each item can have up to X random affixes from a pool, and each affix can have X statistics frmo a range
like there are probably quadrillions of variations possible for each item
yup
Ah
The instance would be the same instance. If you lose reference to it at any given time, you may find that all references to the SO are of a new different instance.
@native seal May I DM you?
sure
Any person who doesn't run windows and doesn't want to spend money on JetBrains
oh ok
there is always monodevelop
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
this is a code related channel @torn gyro
with no luck
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
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
not FMOD related
dynamic rigidbody. rb.velocity = new Vector2...
ok where i ask ?
You need remove * Time.deltaTime
whats f mod
the asset you are using?
oh uhhh
https://paste.ofcode.org/BQfkR9PT5xPCXmAMn7WBM3 Lasso() is the method you wanna look at
lol
already got it
its regular file
wheres this FMOD place u speak of
its all wrong
You dont put deltaTime on the rigidbody at all
Oh okay, didn't know that. Why not?
stop spamming the channel already
FMOD is a asset
because rigidbody is already on fixed time step
Doing * Time.deltatime makes it so I can only walk in one direction
do you know what deltaTime is?
vaguely
what is it then you think?
It's something to do with time since the frame started? I remember watching a video on it but I never finnished it
Okay, it's the interval in seconds from the last frame to the current one
yes its used to keep thing consistent through diff fps change
Yes, I know that
You just learned it lol
I knew what it did, just not exactly where the value came from
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?
I don't know why it does, but that's the only thing I changed, and then I could only walk in one direction. Pretty easy to assume that was why
show current code
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?
SerializeField
👆
this isn't the updated code
Thanks
I sent it
what is the value the bool when its walking in one direction
I'm sorry, could you rephrase that?
your bool , your if statement
when you are saying its walking in one direction, what is the value
lassoed
It's negative both ways, because the character isn't lassoed
walking doesn't change that
then your groundwalking is wrong
Why?
You know what? Nevermind, I'll figure it out on my own.
why does the unity code suggestions in vs code suck so bad even after I installed unity code snippets?
how so?
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.
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
Installing snippets won’t give you actual autocomplete
vs code is much faster than vs, i tried it today
They’re just random blobs of code you can insert
i have the unity extension installed too
even .setactive wont auto complete
Cool, now follow the rest of the instructions !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Take it from the top and ensure that you’ve done everything
I use VSCode on my Mac. It works great.
yeah then you did not configure it fully
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.
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
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
and for the three characters that aren't currently "up", you have a few options:
- Deactivate the button entirely
- Make the button non-interactive
- Ignore the button press in your code
did you reference the correct camera
theres also a settign form it in inspeector
I need to change it at runtime
I did
where are you calling the method
on start
try awake?
this might be an issue
does the object disable itself?
nope
use debug.log to see if its even called
I know it is called
how?
how
since other code in the same if statement is executed
show script
that deosnt make sense
https://gdl.space/daxexecexo.cpp most of it is irrelevant
the ConfigurationManager part is a config file loaded from a json that determines whether the skybox should be enabled or not, among other things
on it
got it to work, thanks 👍
can smb help me with an error message i have in an unity project?
mate, you gotta post the error
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
are you trying tobuild?
you provided no context to where and how you got this error 🤷♂️
cuz i dont know
give the start point an offset ?
so who wrote the code ?
AI, cuz i dont know anything bout coding
umm Yea I rather not waste time fixing broken gpt code. Its also against community rules #📖┃code-of-conduct
oh, ok. mb srry
I suggest you actually learn properly with course !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks
can you create a button in your script that can be clcked from the inspector and manually runs a method?
yes, but is it worth the time ?
Custom inspector basically or you can find third party tool
Do you actually want to do this at run time? Or just always have it as that colour...?
yes, often is
sometimes a [ContextMenu] will do 🙂
actually at runtime, since I need to pick change between solid color and skybox depending on what config is loaded
seems like it works now, at least in playmode in unity, will try to build it
This is the easiest and quickest way.. it'll show up in right mouse click on the component title
[ContextMenu("My method")]
private void MyMethod() { }
often it will, but it depends on how often you're going to be pressing the button 🙂
true, i personally enjoy messing with Custom editor/inspectors
Odin Inspector (IIRC) adds a [Button] attribute, which does it with just that
ya i think there is also naughty attributes for free
i was just wondering
i dont think i need it yet but
i feel like it would be helpful
yup
why is there no red underline on the mistakes of my code in vsc?
because you did not configure it like the guide
how many times you need to be told
i did
@rich adder would you like to test the you were helping me with other day 🙂
if its #1180170818983051344as webgl perhaps lil later
clearly not. or it would be working 
!vscode
Yup it's there
Here it is
A common problem with vscode. The configuration with Unity breaks often . . .
been decent recently , the updates are making ok
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 . . .
what is rider
another IDE
Another — better — IDE, but it's a paid subscription . . .
free if you're student
Though VSCode isn't really an IDE, but yeah . . .
ok this question is gonna sound really dumb
tradeoff for speed
but how do i run a coroutine from another script
i would make a public method that calls the coroutine in that script instead
how do you call method from another script
Do you have a reference to the script with the coroutine?
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));
}
}
}
Then use the reference to call it, though I'd do with navarone said and call a method that starts the coroutine . . .
how would i do that
StartCorountine(<methodyou wan to call>)
i already have that though
no, you do not.
_playerPickupText.StartCoroutine(PlayerPickup(weaponname));
how would i fix this specific line to be in line with syntax
_playerPickupText.PlayerPickup(weaponname) is the method you want to call
public class A{
public void Foo(){
StartCoroutine(Bar())
}
private IEnumerator Bar(){
}
}
public class B{
A a;
void Method(){
a.Foo();
}```
so how do you call method from another script
_playerPickupText.StartCoroutine() is not a thing and is why you're having errors.
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");
}
}```
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
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
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
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);
}
}```
What do you mean being limited?
inventory.Capacity = 5;
why are you using Capacity property
that's why its limited to 5
im not using it //inventory.Capacity = 5;
ah
nvm i just figured out the problem
then what do you mean by being limited
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
but I have another question do you guys know why the list count is always 1
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
it has to be, i dont have any other list
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
same behaviour
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
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
If i erase this now it debugs correctly
it stops
whenever the list size is bigger than 1 it stops debugging
however if I erase the code above it debugs correctly
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
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
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 🤦♂️
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?
Yeah I’ve actually used them in this scenario to update the list of displayed items when the inventory is changed, but I’m still wrapping my head around the syntax, registering them and passing in arguments. Have literally just this minute started watching some more guides on them to figure out how to properly use them in my situation
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
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)
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
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
its unity having a stroke and leaking memory
i havent started anything yet but can i click play when this warning is active
and does is affect my work
you can ignore it, but if the editor eats all your RAM a quick restart should fix it
ok ty
is your OnTriggerEnter2D being called at all?
did you debug it?
yes
how?
put a debug log in it
and it disappears
and show the results
but it doesnt reappear
IEnumerator RespawnCooldown(int seconds)
{
Debug.Log("respawn coroutine!);
yield return new WaitForSeconds(seconds);
gameObject.SetActive(true);
}
see if it prints
starts but doesnt end
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