#archived-code-general
1 messages · Page 436 of 1
I know what you said but I think you're mistaken in thinking that just because it looks smooth when there's no damping that there's not a problem.
I'm basically looking for whether you're using a Rigidbody without interpolation here
This is my player controller script:https://pastebin.com/zUPGfSZF
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
can you show the inspector for the Rigidbody2D on your player
wow that fixed my problem, thank you very much
Would it be better to add an onclick listener and pass the ID that way?
isn't that what you're doing already?
I'm using lamda
to add a click listener
Ah...
Did you try adding those additional log statements?
I forgot what I was going to add when I started posting the code lol
However
I undid all my edits and tried again with is and now it works
Thanks for the help
I noticed that when I set my camera lans further away from the player, the player sprite has less pixel. When zooming in, we can clearly see a differance. Is there a way to fix this?
Lans? Lense?
Is it not an orthographic camera?
when I set to orthographic, the same problem happen.
Camera Inspector:
Cinemachine camera inspector:
i mean what kind of zoom are we talking about here
your monitor only has so many pixels
if you zoom out or in we will see more or fewer pixels representing the same number of pixels in the sprite
leading to more or less detail
ok so the best thing to do is simply reduce the size of the original sprite as my camera at my default distance is too far to see all the pixel of my sprite
I don't know what your goal here is so it's hard to say what the best thing to do is.
the zoom at the top, when I increase it I can see the sprite has less pixel when the cameramachine settings is further away
yeah because it's literally zooming in on the game view
keep it at 1x to see what it actually looks like
What's the purpose of that scale slider?
the game is not going to render extra pixels due to you zooming in on the game view
mostly to confuse people from what I've seen 😆
I've never found it to be of any use, more of an annoyance if I accidentally zpom in
lol
smells like a legacy feature that they never got rid of
the best use is to allow you to see the full game view when your game view is smaller than the resolution it's set to.
you could set game view to 4k and it will render at that resolution even if the game view window itself is smaller
which is useful for testing ui layouts and stuff
a very niche case, but I get it
alrighty so in the middle of my changing from 2d raycasts to 3d, i noticed that Raycasts dont have a fraction method like Raycast2d.
i'm wondering what is the alternative to it?
or other than that what would be the math to recreate this?
i considered Raycast.distance would be close, but im thinking it doesn't result similar to fraction
The scale can be useful when developing some shaders for example, and you need to inspect individual pixels
hit.distance / maxDistance would be the equivalent
yeah that's the only time it's been any use to me
sounds like you just need to normalize the distance then
I'm actually blown awaay someone is using RaycastHit2D.fraction lol
I really seems like it's a feature that doesn't really have any need to be so easy to accidentally zoom in with
thank you very much 🙂
What's that?
huh
I think I see the use, honestly if I needed that kind of thing it's something I'd probably write myself
I wouldn't have thought such a thing exists
is there a way to change an animation clip's speed in runtime? assuming no multiplier parameter
the simplest way is with a parameter on the Animator
yeah but assuming i cant do it that way (because i cant in my specific context of modding), is there any other way?
huh, didn't know modding was considered forbidden/bad-to-talk-about here, my b
#📖┃code-of-conduct mentioned here yes
ic, well atleast my question doesnt really relate to modding, im just trying to work with the limitations of it lol, but ill stop talking about it thanks
yeah changing the animator's speed might be my only way of doing it even if it also changes every other animation's speed 😔
I am trying to make it so that a light lights up everything on the players screen, then eventually is pitch black as the player gets lower. To do this I am changing the inner radius from 11 to 0, then outer radius from 11 to 0. However, when I try to lerp, it doesn't work, but setting to a constant value, such as 0 does. Anyone know why this is happening?
Code that updates light: https://hst.sh/abotutabum.cs (method is run on Update)
Mathf.Lerp(11, 0, Mathf.Min(transform.position.y + 20 / -50, 1)```
this looks super suspicious
Why?
several reasons
Log it
one: magic numbers
so I'll explain it
two: transform.position.y + 20 / -50 order of operations means this is y + two fifths
every time
which is almost certainly not what you want
oh, do I need to add brackets?
yes
this is transform.position.y -1
if(transform.position.y < -10)
{
if(transform.position.y < -20)```
this is also odd
oh I see
Yeah
I could remove that else statement though and just use Mathf.Min again
Ok, it works now!
The secret is to just put everything in paratheses
I hate how vs tells you to remove them. Like no?
so in the middle of me working on changing from 2d to 3d. i think i can keep my 2d rigid body since im not really using it much, but change the colliders and the raycasts mainly and that should be enough to make it interact with 3d colliders.
you can't use a 2D rigidbody with 3D colliders
ah
well i guess i can make a script to swap them out and pray it doesn't break much lol
almost thinking of just forking this and using it to be a whole new project instead of redoing all of the colliders and everything else
and just have 2 projects instead of 1 huge one
Sounds like a nightmare
yeah, i already knew i might end upcrying when i decided to tackle this XD
I mean having two projects sounds like a nightmare
oh, yeah that too
Ok so I got some good advice and started taking on shadow volumes through the CPU rather than compute shaders. And it's sorta kinda working but the detection of silhouette edges (which is outlined with a blue debug line) where a lit face (which has a green line) and an unlit face (which has a red line) meet is proving to be a massive headache and I'm sure that I'm doing something wrong. Any help would be greatly appreciated. 
https://paste.mod.gg/lqwmvryhvuhy/0
A tool for sharing your source code with the world!
possibly cured code warning!! Is there a way to get a name of a variable that was passed in via ref, from code?
I have something like the code attached, and I want to swap my newGO.name = comp.GetType().Name;to use the name of the variable instead, without passing in the name of the variable every time. Is this easily achieavable without a lot of really ugly reflection?
maybe you want to use FieldInfo to start 🤔
that seems like too much for this little piece of code... I'll just go through the hassle of using an optional argument 🙃
you cant have it both ways 🤷♂️
true
There's a caller attribute that does it for you, not sure if it's available in Unity's C# version though.
oooh that's more like it!
if you mean this: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/caller-information
that's not quite it
you know that code, as written, will blow up if the T script is missing, right? I assume you meant to create a new GameObject child and use AddComponent
yea already swapped to TryGetComponent
this is a super dangerous snippet btw, if you ever have A with a serialized ref of B and B with a serialized ref of A, then a missing A will probably result in the editor crashing
Yeah, caller expression seems to be closest to what you want but it's only available in C# 10+.
likewise with any self-reference or reference to same type which is unassigned
I'd say just do the optional argument, it's not worth the magic even if it's possible.
nameof() and its all good
Name of will always return comp
Yeah, and caller expression basically does that for you
But it's not available in Unity and probably not a good idea anyways.
what is this quickview window called, in VS? i am trying to find a way to change the size, but i cannot recall the name to do a search
its only me or others also have problems with SerializedDictionary ?
Im using Unity 6000.0.41f1 and every time when i look to script that have SerializedDictionary it looks like this (1 pic.)
When i reset this script it back to normal (2 pic)
and then i can use crtl+z and it back to how it should looks like in first place.
Unity has a SerializedDictionary package??
more like there's one for unity
https://openupm.com/packages/com.audune.utils.dictionary/ ive used this one before
never got much use out of it as shortly after using it, I figured a Dictionary wasnt actually something I needed to use at the time
for the 5 minutes it was in use, it worked very well!
i use it for randomize sounds before moving to free wise
ah ok this is Audune.Utils.Dictionary; and im using AYellowpaper.SerializedCollections; so this is something on my side, okay! 😄
hey does anyone know what code to use to force quit a vr game on a meta headset? (android)
I already have some code from the unity website thing but idk if it works, and I cant go on vr to check anytime soon
map mode
I want to stream live the android's camera over an API, anyone knows how?
Hello all! I am currently making an angrybirds-esque game and I have this code set up. I am trying to make it such that there cannot be more than 1 ball on screen at any time AND ensure that all balls are despawned before initiating the Game Over. I am having trouble because of a specific sequence:
- I shoot 1 ball from the launcher, all is well, except for the fact that
IsBallInAiris stuck as being true - I attempt to shoot a second ball, but nothing spawns.
I have it set such that, when a ball is destroyed, the projectile handler is listening and sets IsBallInAir to false when it receves that Unity Event. So I have no idea why the boolean IsBallInAir is stuck being true.
The only place in the script that sets IsBallInAir to be true is LaunchBall(), which is called by OnRelease(), a method that listens to when the user lifts their finger off of the touch screen. OnRelease() is definitely only being called once.
https://paste.mod.gg/amvrizxbyzit/0 - Ball.cs
https://paste.mod.gg/jkrdneaadeco/0 - Projectile Instance Handler.cs
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
!code
you have debugs around, you should print out more values or use the debugger and figure out why IsBallInAir isnt being set when you think it should be. Also are you following a tutorial/using AI for this? parts of this code is extremely questionable yet the code itself uses stuff that implies you should be pretty sufficient with debugging
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
I hadn't started asking AI until after I was stumped.
I definitely rushed out this code, so that's probably why it's questionable
Do you even do anything with OnBallDestroyed??
The crux of the problem isn't that IsBallInAir isn't being set, it's that IsBallInAir is being set to true somehow even after OnBallDestroyed() is called
if i were you, id honestly reconsider the entirety of that ball class. im pretty sure AI wrote most of that for you
and read the bot message, that code is really hard to read in discord
I guess I just write similar to ai lol cause that entire class was my doing
I'm thinking I might just overhaul the ball class to work using a state machine
I am not very good at writing those so this'll be fun
I am pretty sure the destroyed event never gets fired also, the object will have been destroyed by then, should be firing right before destroying
you're making very simple logic into extremely complex code, and seemingly not even using most of it. i thought AI wrote it because you have generic classes and events that seemingly arent used
the monobehaviour instance will still exist untill gc'd so the event should still work (but persistent subs may stop working)
You dont need a state machine here, it will just complicate things more. your only "state" is really a bool, if the object exists or not. You could even just store the last launched projectile, and check if its null because you're destroying it anyways. no real need for events but it is cleaner if you want to change functionality later
Even when passing this?
yes. this will equate to null thanks to the unity overload BUT its not really null
weird to begin with imo
Destroy(gameObject);
gameObject == null; //true!
ReferenceEquals(gameObject, null); //false
i dont even think its subscribed to, but i skimmed through and really cant be bothered looking line by line in that discord format
yeah thats what I looked for too but its UnityEvent he probably does it through inspector
Sorry, lemme try to fix it.
that is correct
they dont have a method which accepts ball as a parameter though
yea not that we can see anyway
I wonder why it doesn't say that that's a problem on compilation?
What are you subscribing to it?
its not a compile issue, but i dont know how unity events actually work since i dont use them. i dont know how you've assigned it in inspector is all
Posting code
still, please just rewrite that code lol. consider this #archived-code-general message
this type of problem id honestly say is #💻┃code-beginner . i just didnt suggest it initially because your code had generic classes so i assumed more complex stuff was going on
we can also just keep the rest in the thread since this probably wont be quick
if you're only subbing to the ball's destroyed event in the inspector, when you create a new ball it will have a new event that's not subbed to. You need to sub to it programmatically
ball.destroyed.AddListener(BallDestroyed);
I would think that, but the very first instance of the ball spawned at runtime (via OnPress() calling SpawnBall()) works perfectly fine. It's the SECOND time Press is invoked that OnPress() refuses to spawn a ball because IsBallInAir is stuck being true
that's why this is more complicated than #💻┃code-beginner
going to the thread 👉
lets
It is normal that when creating a shader it comes by default with 20 or 19 errors ?
are there any discords to higher 3d modellers and animators etc? for commission
ok final question regarding converting from 2d physics to 3d.
lets say i just switch everything to 3d, but i still have my 2d colliders on stuff, is it possible for 3d colliders to detect 2d colliers in some shape or form or even detect them the same way that 2d colliders detect (like when they ignore z axis)
if i can at least make 3d colliders detect eachother the same way 2d does, i can possibly make a tool to convert 2d collider points to 3d
i seemed to have an idea how i can keep both things within the game though
hey im sorry to ask such a generic question but im having issues rigging avatars to users in XR. They keep t-posing at the origin
is there a trick to it?
lol im in the middle of trying to learn this one too, i wish i can help buddy
where is the code question
#🏃┃animation
same here where is code question ?
#💻┃unity-talk
im using building blocks networked avatar - as far as i can tell it should work but no idea where to start
that's why im asking the question relating to "general coding concepts" lol
like you know how using Physics.Raycast can detect 3d colliders
and Physics2d.Raycast can detect 2d colliders. (well in my case i used Physics2D.LinecastNonAlloc)
i was wondering if it's possible in code to treat a 3d raycast to ignore the z axis the same way a physics2d.raycast would?
not really, that's just not how they work
physics2d raycast "ignores z" because it doesn't even have a z component
physics2d is strictly working with X,Y
strcitrl
lol
new string function unlocked
ah yeah, that's understandable... the only thing i can think of (and it's not a great idea) is to simply do a really long linecast across the z to fake it lol.
what exactly is the usecase here
switching from 2d physics to 3d.
yeah but whats the problem
why did you want to mix 2d colliders and 3D
most 2D / Vector2 positions are compatbile with Vector3
Unity is a 3D engine no matter what you do anyway, its just the Physics that changes
I'm working on a Unity player selection system where players can create a new profile with a name and age, and their level is assigned based on the age. The data is stored in a JSON file and loaded when the game starts. At the end of each level, if the player has accumulated enough points their level should be updated, the level updates in the JSON folder but when the user goes back to the main menu 2 things happen.
a) All of the players from the players list are gone
b) Once restarting the game the players do appear but whilst in the JSON file their level has updated, inside the game their level has increased to 4 for some reason.
See video and code below.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
well at first the game was mainly a 2d platformer, but i had an idea to start giving it 3d movement for some parts of the game, but i want to switch to it seamlessly. while it's going to be on a railed path, i can't simply place 2d colliders on the z-axis and expect the 2d rigid body to pick it up. so im using 3d colliders
the problem is this idea is pretty late into the project and i have like guesstimated like 4000 2d colliders as prefabs. and changing all of them to 3d would be tedious (unless i get some sort of epiphany and is able to make a tool to switch them)
but yeah, seeing as i cant treat 3d colliders the same way as 2d, i'll just approach this differently
i can't simply place 2d colliders on the z-axis and expect the 2d rigid body to pick it up
can you elaborate on this?
specifically, what do you mean by placing them on the z axis
yeah just make them all 3D colliders if you plan on doing 3D
well since unity is a 3d engine even though in using 2d physics, i can just move the 2d prefabs i made on the z-axis, but since they're 2d colliders and 2d rigid bodies and raycasts, they wont take account of the z axis for things like ground detection.
I think they mean that Colliders in 2D does not rotate on the Z axis
so if they move on Z they cant interact with 2D
you could use 3d raycasts?
they wouldn't have rb collision though as you said
(not saying it's a good idea though)
you have to switch everything to 3D colliders and physics.ray funcs
im confused what the issue is right now
what im saying is you could have the 2d stuff (as in, objects that present 2d rbs and colliders) use 3d raycasts (and i guess vice versa)
they just want to mix 2D and 3D and that wont happpen, the next best thing is converting to 3D colliders
those two don't interact , different physics
that's not what im saying
yeah i was thinking of keeping the 2d rigid bodies and use 3d raycasts to pick up the 3d colliders since i dont really use the 2d rigid body for much. i was planning to explore it, but im already preset to swap in a 3d rigid body.
what would 3D raycasts be for though
object, in 2d, with 2d colliders and rb, has script that uses 3d raycasts to understand the 3d colliders and rbs
Ohh I see what you mean
but they want to move some 2D object on the Z axis from what I gatheer
i don't know if that's a good idea though; all im trying to say is that that seems possible
yeah since physics3d is pretty much same as 2D, I would just get rid of 2D altogether and stick to 3d imo
yeah, i definitely thought of that but. when you got like 4000+ already made 2d colliders (for prefabs) it makes me question my sanity a bit lol
yeah im still not quite sure what you're trying to do lol
if i got no choice i will though... (probably finally pick up watching one piece while i go through converting all of them)
at the same time, i considered just making it a new project. but i'll update on what i manage to do
guys am new to unity and i got a probleme really annoying , like my mouse get of the scene like the cursor go right and he came of the other side of my screen and The W D S Q not working i tried to change in Shortcut
what?
wym what
I mean, I read your sentence and have no idea what you are trying to say.
oh
thank you very much for the inputs btw
lemme explain
on that topic I have this game that's played on a 2d surface rendered in 3d, I want to use 2d physics. I was wondering if it's possible to change the physics axis
doubt it
I see
Unity is just using the box2d engine so whatever they got there
its a 2d engine so probably stuck xy defacto
I might have to do it the other way round of attaching 3d models to the 2d objects where Z is up
I didn't know unity is on box2d though
ya
2d = box2d
3d = physx
Also, newest 50 series cards don't support PhysX now right? Is that a problem for unity games
I haven't seen unity games as affected but mirrors edge is just unplayable
ill just send u the clip i made it from my phone cuz when i clip with my pc the mouse invisble
Oh also Havok is there if you have a pro license
Oh havok comes with unity too?
just the binary so you don't get the sourcecode but its still an amazing physics engine
any discords to find unity modellers?
not this one, !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
I'm working on a Unity player selection system where players can create a new profile with a name and age, and their level is assigned based on the age. The data is stored in a JSON file and loaded when the game starts. At the end of each level, if the player has accumulated enough points their level should be updated, the level updates in the JSON folder but when the user goes back to the main menu 2 things happen.
a) All of the players from the players list are gone
b) Once restarting the game the players do appear but whilst in the JSON file their level has updated, inside the game their level has increased to 4 for some reason.
See video and code below.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
well the players in the player list goes away when you hit the players.Clear(); when you hit LoadPlayers() on your first pastebin.
also from what im seeing if the age is probably returning a number that makes the game just returns a value of 4. from what i see in the
public int AssignLevelBasedOnAge(int age) ```
is the age not within that numbered variable? what happens if they are younger than 3?
i think where it returns 4 is from this here
{
if (age >= 3 && age <= 5) return 1;
if (age > 5 && age <= 7) return 2;
if (age > 7 && age <= 9) return 3;
return 4;
}
the return 4;
if they're under 3 then no profile is created
is there anywhere that stops the profile from being created if they are under 3?
theres nothing directly stating that i dont think but that is just what happens when you create a user under 3
ah, it looks like it will also just return 4 since nothing was specified for it 🤔
Yep correct, profiles under 3 will have level 4, since the 3 if statements won't be satisfied it'll hit the very last return instruction
OH i see what's going on
is it because "return 4;" is not under an "else" ?
so despite what is changed prior, it will just go back to 4?
I dont think it does because if you enter someone over the age of 9 it will return 4 and assign level 4. when under 3 is added it is not added to the player list nor the json
not specifically that, no
ah ok.. yeah i think i understand, return makes the script stop at that point so that's why that part is fine.
the problem is the second time round, when i click on the main menu, the player list dissapeas. However if i restart the game the player is shown (because it was updated in json) as level 4.
i think i have an idea why it sets as level 4 but im confused why the player list doesnt appear (maybe the loading of players from json file is not working?)
does anyone knoe how to fix?
fix what?
on the video
when i click to go back to menu the entire player list dissapears and players are loaded , also when the game restarts. eg when i stop and replay the game, the new player has a level of 4 instead of 2
share !code with the sites below, book mark them if you must.
pastebin is no good
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
https://paste.mod.gg/pyyzcwqgbjae/0? (Player selection)
https://paste.mod.gg/mlowytubfjwq/0 (Coin manager)
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
You have multiple warnings in your console from what I see in video..did you address those
those are debug warning i have put to see if each thing works
I know what they are but it seems to be printing the else statements
like "No player data found."
yeah what i was trying to make the old buttons clear and then reload the new buttons (so that the level displayed is updated) but it says that there are no buttons to clear making it seem that the buttons were cleared by something else before it. also the no player data found was because i deleted the json file to shwo a clean start
I wrote a progress bar script that does work, but wondering if i could get any help having it change based on the current score variable?
Still new to c# and learning, Thanks!
Progress bar https://paste.myst.rs/yl20e5aw/history/0
Score script https://paste.myst.rs/in87usrg/history/0
something to debug then
you're going to have a maximum score?
That's mainly for when the player reaches for example 100 score it allows them to shoot
so the bar will be full after say 100
so all you want to do is use Score value in that?
Yeah so just as the score increases the progress bar moves up until value 100 for example
thanks
yeah so just assign the Current value to Score
btw there is also #💻┃code-beginner channel
Thanks 🙂
what do you think is the best way to implement cooldowns into a game
The question is too vague
i've seen coroutines, timestamps and quarternion uses
would u say any of em is superior to the others
Quaternions??
Yeah I know what a quaternion is I don't have any idea how they are related to cooldowns
Quaternions represent rotations
some snippet i found online
The time stuff is the cooldown
The quaternion has nothing to do with it
That's just the rotation it's spawning the object with
ye i should reread stuff
Some example of the way I do it
you could probably get rid of the boolean but I kept it for some reason
other than that just set some CONST value for your CD, assign it to your timer on ability use, and remove Time.deltaTime each frame that passes while ability on Cooldown (and make sure ability cannot be used, e.g. why I have a bool here)
arguably if jumpCDTimer > 0, MC cannot jump so boolean redundant, but you get the idea
Fyi I call JumpLogic() (the method seen above basically in the last two screens), every frame in Update()
is this like a good way to organise code
i just have 10 stray if statements floating around
wdym?
How to properly post !code (large code blocks and discord inline)
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
making it into functions instead of stray if statments
i mean it makes sense because if something breaks u know roughly where to go tbf
Well ultimately it's more readable if your "main" (e.g. Update() here let's say, core logic) only calls a few functions and you can understand what your game does every frame in a snapshot
I'd say
How should I have done it?
At the beginning you can have "stray" if statements and whatever honestly, just remember to refactor after prototyping basically for future readability
At least that's the way I go about it
Sometimes I know from the start so I write the function directly
anyways what does the f after the numbers do
Using one of the format suggestions provided by the bot.
#📖┃code-of-conduct would very much appreciate it
makes it a float
is there a point to do such when the variable is defined as a float?
Try it and see
float x = 1.5
see what it does
The docs https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals
Not really in the case with zero but for consistency purposes (and when you've got some other non-whole number other than zero).
if (!canJump) {
return;
}
// Handle Jump CD Timer
if (!canJumpTimerComplete) {
jumpCDTimer -= Time.deltaTime;
if (jumpCDTimer <= 0f) {
canJumpTimerComplete = true;
}
}
// Handle Jump Input
if ((Input.GetButtonDown("Jump") || Input.GetKeyDown(KeyCode.W)
|| Input.GetKeyDown(KeyCode.Z) || Input.GetKeyDown(KeyCode.Space))
&& isGrounded && canJumpTimerComplete) {
rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
canJumpTimerComplete = false;
jumpCDTimer = JUMP_CD;
}
}
``` cs
oooooh
I feel like this is more readable though
The indents gets weird with the backticks
add cs after ```
The picture is less editable and can be obscured on devices with smaller displays.
and the pictures get cropped if u send more than one
An illustration; I want to get the closest point to my capsule collider's "foot" region, the center of the bottom circle, within some acceptable range, say an extra 0.1 units.
Physics.OveralapSphere will return the collider i'm touching, but the ClosestPoint method will only work on boxes, spheres, boxes, or convex mesh which mine is not.
If I do a spherecast with radius Capsule.radius + 0.1f, any Raycasthits that return will be zero since they overlap, so I can't iterate through those.
I could spherecast from inside the capsule collider and point it in a given direction with some distance but then you ignore all the parts of the bottom capsule that aren't covered by that spherecast.
Should I do simple raycasts in idk how many, like 32 directions to check hits then find the closest one and only then spherecast along that direction if I want the exact point? Seems a little jank but I guess it wouldn't be expensive to run. No expanding spherecast method sadly.
Are there other possible solutions?
could you use ClosestPointOnBounds?
I dont think there is a spherecast solution here if it can ever start with overlapping the object. Even the all/nonalloc methods
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.SphereCastAll.html
For colliders that overlap the sphere at the start of the sweep, RaycastHit.normal is set opposite to the direction of the sweep, RaycastHit.distance is set to zero, and the zero vector gets returned in RaycastHit.point
im not too sure you'd be able to use it considering .point is assigned the 0 vector.
I guess it at least tells you something was hit 🤔
https://github.com/Gentlymad-Studios/NewGraph?tab=readme-ov-file anyone got any experience with this library?
Curious if it’s any good for custom abstraction, in lieu of graph foundation or whatever it was. Is there even a release date on that?
There isn't
Idk if this is the right place to ask this but.
Are banner ads supposed to be super small? For some reason my banner ads are tiny in any portrait mode that is not 16:9
so an update. whileim notdone, i have managed to make it work with 3d colliders so far. i havent swapped out the rigidbody2d yet though, but im unsure if i need to do that yet
I am attempting to make the player die when their health reaches 0, and I want to teleport them to their original position. For some reason teleporting them to the world origin, without disabling any scripts or anything, is preventing them from being able to walk, the debug shows that the values are being set, but the player isn't moving.
This is my code: cs private void Update() { if (shSystem.healthSys.health == 0) Die(); } void Die() { for (int i = 0; i < inventory.items.Count; i++) { if (inventory.items[i] != null) inventory.Drop(i); } transform.position = origin; }
The code that drops all the players items upon death is working fine, but for some reason setting their position to the origin prevents them from moving.
because you're setting the position to the origin every single frame
Update runs every frame
there's no reason to use Update for this
The check for health <= 0 should happen at the time that your character loses health
instead of just having a public health variable you should use accessor (get and set) methods, or a TakeDamage method, or use a property.
This way you can control that whenever the health is reduced, you check if the character has died
then you don't need to be checking every frame.
The player class is sort of a branch class where I have the intersecting functionality of the player. Are you saying that I should just check if the players health is 0 whenever I lower the health. Why would I need to replace the public health variable?
Why would I need to replace the public health variable?
Having a public health variable means you can accidentally write code that reduces the health and doesn't check if the player died
by using an accessor method or property you ensure there is only one place in your code where health can decrease
and therefore only one place where you need to check if the player died
Are you saying that I should just check if the players health is 0 whenever I lower the healt
Yes. Something like this @dense estuary
// private so nothing can touch it.
private int health;
// We only change the health varaible through this property
public int Health {
get => health;
set {
health = value;
if (health <= 0 {
health = 0;
Die();
}
}
}
public void TakeDamage(int damage) {
Health -= damage;
}```
So the problem is that my health and stamina are mixed together, similarly to how its set up in LOCKDOWN protocol, when the stamina is empty and the player keeps running, it starts to drain the health. This is my script at the moment: https://hastebin.com/share/geyujaxire.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm not sure how that's a problem
The health mainly drains slowly via a Mathf.MoveTowards() method.
Oh wait, your right.
So the Die method would also lie in the HealthSystem class, so I would need to give the health system access to some of the classes the player class has access to, in order to make dying disable some of the player scripts.
I would use events instead
public event Action OnDeath;
void Die() {
OnDeath?.Invoke();
}```
then your player script can subscribe to OnDeath
and do what it needs to do
this way you keep all of the references pointing the same direction
the health system won't need to know anything about the other scripts
I would probably also use an event for every time healthj changes in general
then you can use the Observer Pattern for UI elements etc to show the current health
What does that mean?
Also the UI uses a custom shader to display the Health and Stamina.
it doesn't matter how it displays it
doesn't change anything
The observer pattern is a pattern where the script responsioble for displaying the health would simply subscribe to an event, like a OnHealthChanged event
and update itself whenever the event is fired
this way the health script doesn't need a reference to the "displaying health" script
basically just leveraging an event like this
in this case you'd put it right in the health proeprty as well:
public event Action<int> OnHealthChanged;
int health;
public int Health {
get => health;
set {
health = value;
// let observers know the health changed
OnHealthChanged?.Invoke(health);
if (health <= 0 {
health = 0;
Die();
}
}
}```
this is the beauty of having the single access point for changing the health variable
now we know that whenever we change the health:
- We always do the death check
- We always update the UI
if you use a public variable it becomes a mess
I've never used events before, how would the player class "subscribe" to OnDeath or OnHealthChanged?
void OnEnable() {
shSystem.healthSys.OnDeath += DeathHandler;
}
void OnDisable() {
shSystem.healthSys.OnDeath -= DeathHandler;
}
void DeathHandler() {
Debug.Log($"Detected that the player has died");
}```
like this
So in practice I would use it like this?
yes although I would probably just make a function likecs public void Reset() { this.health = this.baseHealth; } on HealthSystem to reset the health
That makes sense, although, I am curious, why did you add the this before each variable?
That makes sense, thank you, you were very helpful for me, I am going to rewrite a lot of jumbled code with events.
Hi, the code you see above leads to the player teleporting to the origin for one instant, then teleporting back to where they originally were, which is very confusing.
This is what I mean: https://streamable.com/s0n0kb
Its like the rb is setting the position to a position that was determined just before the player died. Possibly caused by the event being out of sync with the Update method.
has anyone used I2 lately? and if so the google side of it - I cannot get it to install the service to connect to google sheets, it seems it was updated at some point google side and it simply doesnt work now?
read the reviews, there's something about a problem with google in a couple of them (which I think is the same).. there's a link to a solution
How can I change the sprite of a UI Image from another script? I'm trying to access it (from another MonoBehaviour in the same scene) via
GameObject.Find("BG Image").GetComponent<Image>().sprite;
But that gives me the error
ArgumentException: GetComponent requires that the requested component Image' derives from MonoBehaviour or Component or is an interface.
Am I missing something? Is Image not a Component?
Image is very much a component you are probably using a type from System that happens to be called the same. Do you have using UnityEngine.UI in your script ?
UnityEngine.UI.Image is a component; that specific Image sounds like it isn't
try hovering over it to see where it's being pulled from
It's UnityEngine.UIElements.Image
That is not a component
Well, that's slightly unintuitive. But using UI.Image did the trick, thanks^^
You are mixing up the old UI system and the new UIToolkit
Ah, I see. I'm still kinda new and bad with UI stuff.
If you are using a Canvas you need to use the things in UnityEngine.UI
Just forget about UIElements
Or better yet since you are new, forget about the canvas and learn UIToolkit since that is the future
not really a problem for my project more of a question but im using Random.Range(0, array.Length) and it's showing the random range as an int, which to my understanding excludes the last number as it says MinInclusive,MaxExclusive, but it's outputting the last item on the list at times, i guess my question is does .Length inherently +1s itself in cases like this?
I hope I explained that properly ;v
sorry not list, it's an array
.Length inherently +1s itself
...what?
it would not lie about the length, no
in cases like this
theLengthgetter wouldn't know (nor care) about what kind of case it's used in, it just does its job
the last item of the list is supposed to be accessible
Length isn't a valid index
if you have an array of length 3, you would have 3 elements at indices 0, 1, 2
right
but when i use random.range with ints, it says it's maxExclusive, meaning it excludes the last number, and i know its done this before because i use Random.Range(0,2) as a coin flip. But when I use .Length, it does output the last number, which is where im getting confused.
length is 3
it's not gonna output 3
it outputs at max 2, which is the last element of the array
but it does for me is what im saying
it outputs the value Length?
wait
ohhhhhhhhhhhhhhhhhhhhhhh
god i forgot arrays start at 0 thats embarrassing
haha
do you know how to read sets in range notation? (eg. [0, 5))
that might help internalize it
yea yea, sorry its been a long day
(also heads up that the float random is max inclusive, the int max being exclusive is kind of an outlier likely specifically so you can just easily plug in a collection length into it without worry)
yeah ive seen float randoms are max inclusive, it was an issue i wasnt aware of for a while
so an array of 3 would output 0,1,2 and then exclude 3
for ints
your wording might be enabling your downfall
1-based lists/arrays/etc (for example in lua) have indices in the range [1, Length], like in normal counting
0-based structures (in most languages) have indices in the range [0, Length)
i am not very good at explaining things 😔
taking that sentence literally an array of 3 would output 3 assuming it's just an array containing 3
[start, end) happens to also be the range that Random.Range uses for ints
well that would be arr[Random.Range(0, arr.Length)], rather than Random.Range(0, arr.Length)
an array containing the first three numbers would output 1,2,3 because it's (0,3) for the index where [0] = 1, [1] = 2, [2] = 3
smh 0 not being the first number, what is this blasphemy
yeah, i just forgot it starts at 0, which is crazy considering how many lists im using right now. i think im just tired
you'll get used to it with experience 😉
maybe they are programming sesame street 😛
ah, ah, ah
is there a way to add a static method to a class like Color?
I want to create Color.Uniform(myParam) for creating colors with the same rgb values without copying and pasting the same things 3 times
I have ColorExtensions for it right now, and I know I can add it when operating on an object (via using a this Color color parameter)
YOu can make a static method in another class, or add an extension method
but I want to add it to the Color class directly
those are your two options
Extension method would look like:
public static class MyExtensions {
public static Color Uniform(this Color c) {
return c; // do whatever you need here
}
}```
And you would use it like:
```cs
Color x = Color.red;
Color y = x.Uniform();```
not possible in C#
best you get is extension methods
Why? You would use the extension method in an identical way
no I wouldn't, I need an object to exist to use an extension method
While I want to use it as a shortened version of the constructor
It can't be done
sth like this
public static Color Uniform(float rgbValue, float alphaValue)
{
return new Color(rgbValue, rgbValue, rgbValue, alphaValue);
}```
🙃
you have to make your own static class:"
public static class MyColorStuff {
public static Color Uniform(float rgbValue, float alphaValue)
{
return new Color(rgbValue, rgbValue, rgbValue, alphaValue);
}
}```
Then call it like `MyColorStuff.Uniform(..)`
¯_(ツ)_/¯
If by multi cursor you mean the text editing feature, yeah it's essential
it's a great feature
It takes like maybe 10 minutes to learn, and it easily pays it back in everyday's work. Everyone should learn it.
I've seen people who open up Excel to do text editing in cells with formulas and stuffs for repetitive code, then after they are done they copy it back into IDE. Could've just done the same thing with multi cursor directly.
regex is more flexible, multi-cursor is faster & easier to do directly
maybe regex feels faster / easier because I have more exp. doing it
Yeah most cases don't need regex's flexibility and can just be done with multi cursor, and done faster.
in VSCode, do you have to spam CTRL+D to select all identical wording (?)
The only time I still do regex is if I need complex conditional matching/doing it across multiple files which multi cursor doesn't allow.
Ctrl + Shift + L selects the same word in the whole file and inserts a cursor for every one of them.
Ok it's good
This specifically
Pretty much for multi cursor you just need to learn and get familiar with (VS Code shortcuts in parentheses, but other IDEs should all have similar shortcuts):
- Insert a cursor above/below (
Ctrl + Alt + Up/Down arrow) - Insert a cursor on the next matching word (
Ctrl + D) - Insert a cursor on every matching word (
Ctrl + Shift + L) - Insert a cursor on every line (
Shift + Alt + I) - Navigate by word (
Ctrl + Left/Right arrow) - Navigate to start/end of line (
Home/End)
For VS Code specifically: - The command "Emmet: Evaluate Math Expression"
- A bit niche, but you can use an extension/a snippet to add the cursor number for every cursor.
The first parts are the ones that everyone should know, takes little time to learn and will get use out of them every day. The second parts are a bit niche but very useful in some situations, eg you can use it to generate a sequence of numbers some values apart, open a spritesheet and shift all coordinates by a certain amount, etc.
middle click + drag also lets you do multi cursor or select an area
Not sure if this is a "general" issue or an "advanced" issue but
I want a mechanic in a game i'm making for a class where if the ball collides with the player, the player respawns at a certain point
when i test, the game recognizes that the player and ball have made contact, and so the player should respawn...but the player doesn't respawn
both the player and ball have rigidbodies and colliders, but the ball bounces off the player instead of the player respawning
not exactly sure if this is a scripting issue or a physics issue
which object is this script attached to
From the logs it looks like... both?
also if they're bouncing off it sounds like you're not using a trigger collider, but your logs are logging which implies you are using at least one trigger. Do your objects have multiple colliders?
only 1 has the script, it's the player
your logs seem to disagree with that
This implies that some object with the script is interacting with the player
in other words, is not the player itself
unless PlayerArmature is not the player
Can you show how the hierarchy is set up and which objects have which scripts?
i'm using a player armature from a 3rd person asset package from the asset store, so it has its own collider, but i added another (box) collider just to make sure that the script would work
the ball only has a sphere collider
nope, only 1 has it
which is confusing me too
YOur logs imply that whichever object the script is on is colliding with the playerarmature.
My guess is you have multiple Rigidbodies in the player hierarchy by accident
and so maybe the parent object which is empty is getting moved
and the armature itself is not getting moved
because it's a separate Rigidbody
you would need to show screenshots of how everything is set up to confirm
here's the inspector and hierarchies
why do you have both a Rigidbody and a CharacterController here
anyway you should type this into the search field in the hierarchy:
t:PlayerRespawn to make sure there aren't extra copies
private void tween_camera(Vector3 axis) {
System.Action<ITween<float>> circleRotate = (t) =>
{
transform.rotation = Quaternion.identity;
transform.Rotate(axis, t.CurrentValue);
};
float startAngle = transform.transform.rotation.eulerAngles.x;
float endAngle = startAngle + 90;
// completion defaults to null if not passed in
transform.gameObject.Tween("RotateCircle", startAngle, endAngle, 0.35f, TweenScaleFunctions.CubicEaseInOut, circleRotate);
}
```Heyo, I have a tween library, but I can't seem to figure out why it doesn't work properly if i remove the```c#
transform.rotation = Quaternion.Identity```I'm trying to rotate on top of the current rotation, but the identity resets the rotation that's why I tried removing it, but it breaks the tween completely
also the CharacterController is why your coder doesn't work
the CharacterController came with the package, but it didn't work when i didn't have the rigidbody (and still doesn't work)
you can't teleport a CC with transform.position without disabling it first
here's a video example of the issue
"it didn't work" is pretty vague - but it basically sounds like you don't fully understand how to use this packaged character and you're slapping bandaids on it
that are ultimately going to make things worse
I don't, you're right
I assumed that the CharacterController wasn't enough
because the player wouldn't respawn and I added a rigidbody, which didn't fix the issue either
no copies
yopur main issue is this
your secondary issue is that your object is all kinds of messed up with a bunch of competing components that do the same thing in different ways and will conflict with each other
ah that'll definitely make it worse then
the player will just fall through the floor if i disable CharacterController
you would only disable it exactly at the moment you teleport
cc.enabled = false;
transform.position = whatever;
cc.enabled = true;```
I want to condense the scripts into a single script, I just haven't gotten to that yet
although the scripts attached to the player are only for destroying and enabling objects (enabling as in they appear because they were initially disabled)
i'll give it a shot
I have a weird issue where I'm doing a null check on an interface and instead of returning null, it's returning "null"
oh my gyatt it worked
thank you very much
show code and show where you're seeing that
ah I found why. The reference is in another scene, and the scene is unloaded
https://paste.mod.gg/cyyukirzhnlg/0
Somebody care to help me get rid of some bad practice? This is just a small interaction foundation
A tool for sharing your source code with the world!
is there something specific you're looking for?
the main things id point out is use non alloc versions whenever you can
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.html
and the input being processed in HandleInteraction isnt ideal. you'd typically want to use the new input system too
I've heard that often, what is so appealing about the new input system compared to the old one? I think the old one is much easier to implement.
there is more functionality built in like double taps. its more flexible, and setup through inspector which is arguably better for when you want to make changes to how input works
I suppose you're right if I'd ever need to make changable input settings, it would be easier, and that double tap function would also save me time
I'll definitely look into it, buut what about no alloc versions? I don't follow
i linked the non alloc version, you simply dont allocate an array every single frame
I see, I'll have a look at it
So it's pretty much the same to the eyes, but it's more performant?
if you do also use the legacy input system, one thing im not a fan of is having the actual Input.Get... stuff randomly throughout the code.
if you look at HandleInteraction, it doesnt do anything if Input.GetKeyDown(KeyCode.E) is false. So you could keep this purely in Update, where you dont even call HandleInteraction if they weren't pressing E
yes
Its not gonna change your life here but its just something you should get used to using. I wouldnt call it a micro optimization either
Yeah as I said, I just want to get rid of bad practice in the beggining
It's better to do it now than later, I had a hard time when doing js cause I made the same mistake when I was younger, so I pretty much ended up with a ton of bad habits that made everything harder
using the keyword "new" in update or code that is called often is generally bad (unless its a struct) because it triggers garbage collection and will cause lagspikes
reason's kinda off here
i didnt look through the actual logic to see if there are bugs but from skimming through otherwise the code is fine. id change those 2 things above and try to change line 64 where you kinda have a magic number of adding (0, 0.05f, 0) to the position. If you have large interactable objects, its possible that 0.05 does nothing
Maybe store the actual highlight location on the interactable object
garbage collection happens anyways, but if you create a lot of reference type objects that you don't use for long, then you get a lot of garbage to collect
new is fine if you need it; check if you actually need it
I already have a script for this, I made up a little shortcut that will just get the lowest point on the mesh or gameobject and return the vector 🙂
I just haven't put it to use as I just changed this current script cause I found some faults
You could probably handle it very simply. The interactable has an empty game object on it as a child which acts as the point where the highlight should be
Yeah but considering I'll have a ton of them, I just wrote a script for it to save some time
Thats how id do it at least if interactable objects would need it placed in weird locations. But this is also a non-existant problem potentially if they all have similar structure
if you need to use "new" in code you call multiple times though then its a good idea to store it in a variable, right? unless that code is called multiple times but very rarely in which case storing it in a variable might be a bit worse, idk
you use new when you need to create a new object.'
do you mean lowest point or highest? because your code adds a small direction upwards
Ah i get what you mean, i was imagining an arrow or something
Oh, I
if you call new multiple times, you're creating multiple objects
I'll have that eventually, but until then this works fine
Ok then yea what i said probably doesnt apply. i think what you did with position + 0.05f is actually fine then
I'm actually very happy how it turned out tho, I made it very easy to implement in all objects that are interactable, so I just add the interactable script to it
Something I had issues with was getting the correct raycast for this though, I used spherecheck in the beginning, and then moved onto just rays but took me a full day to find OverlapSphere in the docs 😦
Luckily turned out just as expected;
depends on your needs. i don't think you can really generalize this advice
nice
When i wrote mine, i implemented it with a raycast but it was a bit awkward because it was 3rd person perspective. It really just depends on the game. I think overlap sphere is best for your case, and possibly a raycast after if you want to not interact through walls
Yeah, a clean raycast works perfectly but not for this sadly
But overlaysphere was exactly what I was looking for, spot on 🙂
I was saying you could raycast as well after getting the closest object, to make sure the player can actually see the object
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
(You were told this already)
Yup I am going to do that eventually, I'll have a grid based building system and such, so I need that
It'll be pretty easy to implement luckily
For items, I won't be doing drops, it'll all be in menus so no item drops, is there any point of doing scriptable objects for items? I've only seen scriptable objects be used to physical objects
what kind of items do you have?
The point of the SOs is to have the item data stored in one centralized, serialized, referencable location
whether or not they're physical seems immaterial
So it's like a preset or a container basically?
I'm guessing this saves a ton of performance if you're dealing with a large scale of objects
its a way to avoid making a separate script for each item
I would want to use this for my trees then I think
can you put trees in your inventory or something?
if they're just placed in the level then use a prefab, not scriptable objects
I have prefabs right now
scriptable objects are useful for stuff like items in your inventory, i dont see how they would help with trees
and you cant save performance with scriptable objects
I wouldn't agree, I just read the docs and it strongly disagrees with you too
how does it save performance with your trees?
You wouldn't have to duplicate the tree data across multiple instances, u reference to a single scriptable object that contains the shared data, as it avoids copying information
alot of memory saved
what data do they have? isnt it just a model?
Obviously not, in my sitation they are going to be animated, they are harvestable as of right now, they also contain a script for item drops
Hello, wanted to code a simple debug tool for controller input so I decided to use Unity's UI Graphic Class as I found it easiest to do simple task of just rendering lines on just UI itself, it displays all and well except for the fact I can't call AddTriangle for the lines separately in same OnPopulateMesh function without having to connect them (I want them to be separate), might use separate class for this but prefer to be in same one.
Main Issue I've been encountering is UpdateGeometry in FixedUpdate causes too much lag for the entire game loop. Am I supposed to be using SetAllDirty and if so, where should I call it from? Same function that draws the vertices? Update? Or OnPopulateMesh? The documentation does not leave information on what SetAllDirty nor it's similar functions exactly do.
protected override void OnPopulateMesh(VertexHelper vh) {
vh.Clear();
leftRectWidth = _leftPanel.sizeDelta.x;
leftRectHeight = _leftPanel.sizeDelta.y;
// Draw the vertices for each point
for (int i = 0; i < pointsX.Count; i++) {
Vector2 point = pointsX[i];
float angle = 0f;
Color vertexColor = xColor;
DrawVertices(point, vh, angle, vertexColor);
}
for (int i = 0; i < pointsY.Count; i++) {
Vector2 point = pointsY[i];
float angle = 90f;
Color vertexColor = yColor;
DrawVertices(point, vh, angle, vertexColor);
}
// Draw a line between the vertices
for (int i = 0; i < pointsX.Count - 1; i++) {
int index = i * 2;
vh.AddTriangle(index, index + 1, index + 3);
vh.AddTriangle(index + 3, index + 2, index);
}
for (int j = 0; j < pointsY.Count - 1; j++)
{
int index = j * 2;
vh.AddTriangle(index, index + 1, index + 3);
vh.AddTriangle(index + 3, index + 2, index);
}
}
Have you tried just calling it once? Does it need to be constantly updated?
Usually UI stuff only needs to be rebuilt when there's a change
Updating it on runtime to change the position, does in editor but not on runtime without it
So, I've replaced UpdateGeometry with SetVerticesDirty and does the same thing without causing as huge performance loss so there's that, so all that's missing is separating the lines, if I try to put them together in single for loop, it draws a line between last X points and first Y point.
Yeah was going to suggest that
https://docs.unity3d.com/Packages/com.unity.ugui@3.0/api/UnityEngine.UI.Graphic.html
These docs a little better
Quick question, is there any better way to store values into a 2d array than just writing the 60-ish lines of code to set each value individually, since 2d arrays arent available in the inspector like 1d arrays are
!code and you should actually describe what problems you're having instead of just pasting code and hoping people know what you want
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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're attempting to call Initialization in the base class but the base class is MonoBehaviour and that doesn't have that function
hi bro its me again hahahah
That first one, you also likely dont want new on a method declaration
i built a new code
yea i removed
and someone knows the "Flip()" error?
What is Flip()
{
if (isFacingLeft)
{
transform.localScale = facingLeft;
}
if (!isFacingLeft)
{
transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}
}```
ohhh i know
its bc its protected
Is that in the same script
nah its another
should i put in the same script?
So in the script you're trying to call Flip() from, there is no such thing as Flip()
I almost feel like this would be AI code if you are using new and protected in your method declarations without even understanding what they are
And a base class
ye no one used protected
No, actually. This is a continuation of a conversation in the other Unity server that kept getting interrupted by some chode who kept spamming "JUST ASK GPT" every other message
exactly
So they didn't use AI for this one. Presumably it's a bunch of IDE auto-corrects
Amazing
The player can have the collider (Hurtbox) in gameobject child? And if so, how can detect the collider?
And the tag is object "Player"
It would be in the base class for a reason, so all deriving classes can access it
Although protected would still let you access from derived
i learned the protected at school since then i forgot the use of it hahahaha
i inserted the flip() inside the same script now i just have the monobehaviour error with the initialization() function
should i do like instead of "public class PlayerMovement : MonoBehaviour" should i put "public class PlayerMovement : Character"?
Is PlayerMovement supposed to be an child object of Character?
yes
Then you should probably make it one
then put "public class PlayerMovement : Character"?
Yes
thanks bro i still hav a question
what and how am i suposed to put a variable not null here: if (horizontalInput > 0 && character.isFacingLeft)
i declared character like this
protected Character character;
And where did you assign a value to it
isnt ``` character = GetComponent<Character>();````assigning a value?
Does that run before you attempt to check character.isFacingLeft?
Does it run at all?
can i send a video here?
Yes, if it fits
nevermind bro i just replaced the Initialization() to Awake() in every occurence and then its working
Hi, I am using an event to check when the player is dead, then once they are, I make them drop all their items and teleport to their spawn location. Its like the rb is setting the position to a position that was determined just before the player was teleported.
This is my code:
DeathHandler-https://hastebin.com/share/ikuhaxasow.csharp
Health-https://hastebin.com/share/hijeramelo.csharp
This is the issue: https://streamable.com/s0n0kb
I fixed it by using rb.MovePosition instead of setting transform.position
hey yall, im making a photography game, and im able to save the render texture to a file, basically im also using that render texture in a scope shader for the viewfinder. but as you can see the entire render texture is way larger than what im able to see out of the viewfinder. is there a way to crop the output of this image?
public IEnumerator TakeScreenShot()
{
yield return new WaitForEndOfFrame();
Camera camOV = filmCameraLens;
RenderTexture currentRT = RenderTexture.active;
RenderTexture.active = camOV.targetTexture;
camOV.Render();
Texture2D imageOverview = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false);
imageOverview.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0);
imageOverview.Apply();
RenderTexture.active = currentRT;
// Encode texture into PNG
byte[] bytes = imageOverview.EncodeToPNG();
// save in memory
string filename = fileName(Convert.ToInt32(imageOverview.width), Convert.ToInt32(imageOverview.height));
path = Application.persistentDataPath + "/Snapshots/" + filename;
System.IO.File.WriteAllBytes(path, bytes);
Debug.Log("Click");
}```
heres my code for the photo
I'd just change the UVs/material settings instead of fooling with the texture itself
cant rly do that, this shader works in mysterious ways
the image is projected a super far distance away so unless youre literally right next to the eyepiece you wont be able to see all of the texture
also the render texture needs to be square for it to work, and i dont want square images for the camera
Hi, I'm working on an Android app, I want to build it but I get this error and it seems like there's something duplicated but I don't know what I should delete, I'm using admob and google signin with firebase
->#📱┃mobile but if you search the project for google-signin-support do you find a file anywhere?
its either included as a file and or declared as a gradle dependency (preferred)
Yes, but I only find one with the .aar extension
So I don't know why it says there is a duplicate
what thing included this file?
Normally plugins now do NOT include libs like this but declare dependencies for external dep manager to setup via gradle
check your Assets/Plugins/Android/mainTemplate.gradle file to see them all listed. (force android resolve first)
So should I delete these files and leave only the mainTemplate.gradle line?
the implementation blah line should have a comment pointing to these so these should be kept.. but how are there 2 of some 🤔
.aar
.pom
.aar.md5
.aar.sha1
.pom.md5
.pom.sha1
Hmm should only be one version then But the error states the same aar was included again 🤔
!vscode
Is there a way to make my button, after it is clicked & deactivated, return to its original color when i bring it back? It changes color on hover
Hi. I'm trying to recreate the portals from Valve's "Portal". The player should be able to stand with a part of their body in the portal without teleporting through it. To recreate this, I thought of removing the triangles from the meshcollider of the surface that the portal is placed on to allow the player to pass through this part of the surface, but I have been repeatedly unsuccessful in making it work. Could you help with this?
Here is my current code:
void CreatePassableArea(Collider wallCollider, Vector3 position, Transform portalTransform)
{
MeshCollider meshCollider = wallCollider as MeshCollider;
if (meshCollider == null) return;
// Create a new mesh instance to modify
Mesh originalMesh = meshCollider.sharedMesh;
Mesh modifiedMesh = Instantiate(originalMesh);
// Calculate portal bounds in the wall's local space
Vector3 localPosition = wallCollider.transform.InverseTransformPoint(position);
Vector3 localSize = wallCollider.transform.InverseTransformVector(portalTransform.lossyScale);
// Create bounds with small depth (adjust as needed)
Bounds portalBounds = new Bounds(localPosition, new Vector3(localSize.x, localSize.y, 0.1f));
// Process triangles
List<int> newTriangles = new List<int>();
Vector3[] vertices = modifiedMesh.vertices;
int[] triangles = modifiedMesh.triangles;
for (int i = 0; i < triangles.Length; i += 3)
{
Vector3 v1 = vertices[triangles[i]];
Vector3 v2 = vertices[triangles[i+1]];
Vector3 v3 = vertices[triangles[i+2]];
// Check if triangle center is within bounds (more reliable than all vertices)
Vector3 triCenter = (v1 + v2 + v3) / 3f;
if (portalBounds.Contains(triCenter))
{
continue;
}
newTriangles.Add(triangles[i]);
newTriangles.Add(triangles[i+1]);
newTriangles.Add(triangles[i+2]);
}
// Apply changes
modifiedMesh.triangles = newTriangles.ToArray();
modifiedMesh.RecalculateNormals();
modifiedMesh.RecalculateBounds();
// Assign the modified mesh
meshCollider.sharedMesh = modifiedMesh;
}
I would suggest using the Physics.ContactModifyEvent.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.ContactModifyEvent.html
What that lets you do is get a callback when a collision is about to occur and then you can check if that contact point is within the portal and ignore it.
Though if the player is not using collision events and is instead a character controller using physics queries, you'll need to do something similar in that code too.
Dumb it down for me boss
if something needs to happen when you click, the interface for that is
IPointerClickHandler
Interface to implement if you wish to receive OnPointerClick callbacks.```
the description provided with each one, is self explanatory
using UnityEngine;
using UnityEngine.EventSystems;
public class Example : MonoBehaviour, IPointerClickHandler
{
//Detect if a click occurs
public void OnPointerClick(PointerEventData pointerEventData)
{
//Output to console the clicked GameObject's name and the following message. You can replace this with your own actions for when clicking the GameObject.
Debug.Log(name + " Game Object Clicked!");
}
}```
adding the IPointerClickHandler interface to your class, gives you access to the OnPointerClick method
which gives you the function of detecting a click
look through all those interfaces, pick out the ones that apply to your use case, which sounds like clicking, deselection, hovering, and that should give you what you need
It may not fully help but i know some videos explain more how portal actually manages collisions when you are close to a portal. Speedrunning resources may explain this is useful detail 🤔
My idea would be to just ignore the collider completely if I'm somewhat touching the portal
otherwise voxelize all the surfaces and chip away at that
Hello, I am doing a deckBuilder with the UIToolkit. Is it possible to disable the scroll of the ScrollView when I want ? Because when I drag a VisualElement it also scrolls the scrollView. thx
I have a problem, I'm still confused on how to make the player look left and right so I added this camHolder.rotation = Quaternion.Euler(0, newRotation.eulerAngles.y, 0); and it works but it stutters alot as you can see. The rigid body interpolate is on, the camera is not a child of the player that has the rigidbody and the camera is a child of CamHolder. Any ideas on how to fix/do it properly?
from your setup it looks like you have multiple things affecting the rotation here. you are changing the camHolder.rotation which is seemingly the parent object of the camera. then also the camera's X rotation is constantly changing as well
also that one line of code isnt really enough to say anything
I remove that, I can only look left and right how would I do it properly and look up and down with no stutters?
https://paste.ofcode.org/AeADSe9AXnFTNhaKBqrQKe
camera rotation should probably be in lateupdate or fixed
you should really just use cinemachine. there are a few things kinda questionable about this code, like if this isnt parented to your player object, it shouldnt even be doing what your video shows. meaning there is more logic somewhere
it doesnt look like the issue is looking up and down even. it looks like when you're moving it stutters
this is on the cam holder
not sure if im just blind but your video shows the camera is looking left or right with the player. the code youve shown doesnt do that. the camera rotation code being in update doesnt help also.
have you confirmed that its stuttering when you look around because it really looks like its more when you move. do you have interpolate on your rigidbody?
you should really just use cinemachine
I tried it before it was a hassle to setup and when I did it. It really didn't eliminate the stuttering.
@leaden yoke I agree with bawsi that nothing you have shown would rotate the camera left/right, unless it is a child of the rigidbody
well yea you'd have to configure it so that it updates at the correct time. at least with cinemachine thats just a dropdown so you could basically brute force the correct answer
Double triple check that you don't have any extra scripts affecting the rotation
I'm saying I don't know how to. I'm still confused on how to make the player look left and right I did say at the start I was confused
I only have 3 scripts..
Do you still have some cinemachine component active?
Show the inspector of the camera, cam holder, and the player
ah it was the line they removed, that they showed in the initial message that rotated left or right
Oh i see
I wonder if the cameraPosition.position is not actually interpolated even though it is a child of the rigidbody
I doubt it, but that would make sense regarding this issue
how would I interpolate it? and will that fix my issue?
For testing purposes, try replacing the line in lateupdate with something like cs transform.position = cameraPosition.parent.position + new Vector3(0, 1.7f, 0);
It changed the camera's position.
Include your previous camera rotation code that you removed. Do it in lateupdate, not update though.
Move around, look around and see if the same issue from the previous video still exists
this? camHolder.rotation = Quaternion.Euler(0, newRotation.eulerAngles.y, 0);
Yes, that
Someone with experience let me know if this is okay to do or if there is a better way to do it. My idea is having a game with different levels, when you complete the level you are in, you are teleported to the next level, and the level you were is deactivated. The problem I see with this is, I would have to have the amount of if statements of the amount of levels I have in the game and I am checking if the condition is met for each one and then I have to teleport the player to each cordinated of the next level. Hope it makes sense.
I get this error.
You made it work in Update before, so surely you can make it work in LateUpdate now
#💻┃code-beginner nothing about this requires you to have if an absurd amount of if statements based on the number of levels. you should look into arrays/lists
What is newRotation
would this work?
No
if you arent familiar with c# basics, please just use cinemachine lol
At this point yeah
how would I set it up in cinemachine?
this really isnt even #archived-code-general level either
in cinemachine there are a ton of options u can change in inspector
wtf I didn't even realise I was in code - general lol
it depends on the camera you use, but there should be a dropdown somewhere about when the camera should update
alright I will take a look into it
would I do anything script wise?
probably not but you'd likely have to move that rb rotation code to the player, which it should be anyways. Im not too familiar with the first person cinemachine cameras but they really arent that hard to play around with
Ok I will take a look. Will it really make the "Stuttering" go away?
if you set it up correctly
a ton of people use cinemachine, its not like everyone is putting up with stuttering.
Would these settings be good?
OH SHIT. THERES NO STUTTER WHEN WALKING/LOOKING AROUND
Most normal Unity way to handle something basic like existance :D
Scene is apparently a struct not a class so it can't be null
If you ask for a scene that doesn't exist or isn't loaded you just get a default Scene struct which will not be valid, and yeah since it's a struct it can't be null.
Really what they should have done is used the TryGet pattern like Dictionary.TryGetValue etc.
how do ppl to collaborate in unity if the cloud storage is only 5go?
is there not a double precision waitforseconds ?
for audio timing in a coroutine? or is it just not possible with frame timing
meh
no matter what you will still be subject to deltaTime when using WaitForSeconds, it makes no sense at all to have an overload that accepts a double for that
mmk
What is it that your trying to do with audio where any other data type like float might not be good enough for your usecase?
Ah, I see
trying to align action to the drop
WaitForSeconds is not precise in any case. It waits for the next frame after the indicated time has past
if you do WaitForSeconds(1) it will never happen at exactly 1 second
how about a hack for the fact timeSamples resets to 0 after a clip loops?
without having to bounce it back and forth between two audio sources (already doing that, but i'm using it to queue the next chunk of the track)
or is that the easiest hack
"hack" for what, you havent exactly described what it is you're trying to do or what timeSamples is in this case
Audio sources. When you play a clip you can get the precise elapsed time of the clip based on timesamples / frequency
However if it loops back to start that value stays at 0
The hack I know of is to juggle clips between two audio sources but if there’s a way to get the accurate value another way I’d prefer that since I’d have to rewrite a bunch of stuff to juggle a loop of the same clip
For musical timing basically
The resetting to 0 seems to be a bug
i havent messed with that enough to know if thats actually a bug, where it stays at 0. timesamples being the current playback position would make sense if it were 0 when the clip restarts.
If you just want the elapsed time, could you not just have your own timer and add deltaTime? it seems your timer is longer than the audio clip anyways
Could probably mark the end time and modulo the clip duration with current dsptime
Audio time is super super finnicky though might not line up perfect
Thing with timesamples is it’s the audio source most accurate indicator of elapsed time in the clip and it’s an integer
Idk shit let’s try it
Is there any sort of built-in functionality for creating a rendered polygon given a bunch of vertices, or do I need to create a custom mesh using some sort of triangulator algorithm? Trying to make one of those filled in stat bubble thingies
void MoveAim()
{
if (playerController.targetedEnemies.Count > 0)
{
Transform targetedEnemy = playerController.targetedEnemies[0].transform;
var constraintData = headAim.data; // Store current data
constraintData.sourceObjects.Clear();
constraintData.sourceObjects.Add(new WeightedTransform(targetedEnemy, 1f));
headAim.data = constraintData; // Reassign modified data
rig.weight = 1f;
headAim.data.sourceObjects.Add(new WeightedTransform(targetedEnemy, 1f));
rigBuilder.Build();
} else
{
if (!isBuilt)
{
var constraintData = headAim.data;
constraintData.sourceObjects.Clear();
headAim.data = constraintData;
headAim.weight = 0f;
rig.weight = 0f;
rigBuilder.Build();
isBuilt = true;
}
}
}
could anyone help here
im using multi aim constraint from animation rigging
but the target isnt updating
I believe that "stat bubble thingy" in math is called a "radar chart" or "radar graph" (there may be some tutorials on that specific approach), im not a expert with mesh generation but I believe youd have to create a new Mesh from a vertices array, AFAIK, TextMeshPro works in a similar way for generating the letters, alternatively, maybe you could use a shader to draw the vertices array, though im not sure if there would be a technical name for that kind of shader (maybe compute? Vertex displacement?)
That's the fuckin word for it, thank you. I knew it had a name but I couldn't find anything. Now that I have the name of it I'm finding loads
One of these things ought to work
can someone help me for my homework. i am genuinely so confused
Nobody will help if you don't have a question, you have to have shown you have tried
Do you have compile errors
i am just restarting my code and will try to figure it out.
I'd also say its probably a good idea to speak to your teacher about the assignment, if youre struggling with it, I'm sure they can give some better guidance
i did lol they havent responded in like 16hrs
That doesn't answer my question but it does show you haven't configured your !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
• :question: Other/None
do you not see them in person?
its online
ah
i did unity last semester but i never did the code, i just focused on other stuff
an immediate problem there is the code doesnt end with a }
C# does things like that, a little different to python, so it's an easy mistake
if your course has any teaching material for C#, it couldnt hurt to go over that again
And also configure your IDE
!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
• :question: Other/None
A properly configured compiler will always catch little things like this 
oops, didnt spot the command used earlier 😆
hi guys
can i use a shader in the script and get its result as a texture?
probably is possible, but how do i manage to do that?
Hello! I'm currently trying to create a building system, where my builds are decoupled from the player controller. Is it alright to run event.invoke every frame in a update, or should i just return the transform of the build object to a variable in the player class and edit that.
tried searching up performance impact of event.invoke and im getting nothing real good
are you talking about a C# event? should be fine
MB.Invoke isn't good
Yeah you should be fine invoking every frame, its normal to do so
thank you for the help nav. is it same performance as if i was to do class.method(vector3) every frame?
micro-optimising 😉
There might be slight overhead.
doesn't it all become the same in IL ?
i just wanted to know it wasnt like a lag machine during runtime.
Should probably not worry about it.
If you need to optimize something, use the profiler
anyway the difference are so small you shouldn't worry it
thank you guys.
Also, worry about optimization way later. After everything works
You can! I can't help answer in more detail rn (very tired 😆) but look into RenderTexture and ComputeShader in the documentation
You'll most likely want a RenderTexture here
ok but how i apply the shader on the render texture?
Write the render texture to a compute shader, write code in shader which writes color onto the texture
The output render texture can be used like any image texture like any regular texture
that allows you to copy data from one texture and write it onto another
Blit() is used for fullscreen effects mainly
You wouldn't really need it here
If I'm understanding what you want to do correctly
I used it to write images onto a render texture so they can be used in a shader
And you also use it to copy from one rtex to another rtex
Yeah, but tbh I'm not sure what they want to do anyways lol
They haven't described their end-goal

And I said "mainly" based on what I've seen others do. Not on what you've done lol So in my experience, I'm not wrong
Ive seen blit used in a number of situations
I only gave those examples as they were the first that came to mind
You said mainly, implying the main usage is that
But yeah, it's the fastest way of copying pixel data
it is
Failed to resolve project template: Failed to decompress [C:\Users\ABC\AppData\Roaming UnityHub Templates\com.unity.template.urp-blank-17.0.9.tgz].
😫
i can't do this
Again, I said "mainly" as it relates to my experience. Not my fault if you assumed but alright then 😄 Have a good day folks
@subtle herald
what is solution
The hell? Idk lol
Don't just start pinging random people
If someone is online who can help then they will, just relax and wait
when i make new project this show
Try Google, plenty of stuff comes up if you copy and paste your exact question lmao
Can I create a project from Google?
What? No....... that's not at all what I said nor suggested.
I'm asking you if you tried searching for a solution to your problem with Google?
hmmm no just gpt
Oh... nice. Yeah, this is where my assistance ends. lmao
Dude stop pinging me. If you're just going to default to AI and not listen to what I say then I'm not going to help you.
Don't rely on AI, rely on you.
Alright, that's an easy block.
Is there a way to find if a point is within a Mesh/MeshCollider?
you can use Collider.ClosestPoint. If the point is within the collider it returns the same position you passed in:
public static bool IsPointWithinCollider(Vector3 p, Collider c) {
Vector3 closestPoint = c.ClosestPoint(p);
return closestPoint == p;
}```
(works for any type of 3D Collider)
Wow nifty, thank you!
for basic multiplayer procedural maps (similar to like lethal company or something) should I have them all in one scene and just delete the old map and generate a new one if I want to go to a new map? or should I have them all in separate scenes?
lethal's moons are not really procedural
but lethal has
SampleShipRelay (the scene with the ship, always loaded)
The Moon Scene (one per moon, additively loaded and unloaded on lever pull/leaving the moon)
and the interior is generated via a plugin called Dungen in the moon scene
interior is
ye
Unless your interior isn't dependent on living alongside the "moon" i would personally suggest the way lc does it
otherwise you may want to additively load both the moon and interior as seperate scenes
hey guys, my game is running super bad, and i thing its to do with vsync but i have it turned off on all graphics settings
like theres no vsync but it still takes so much processing power, whats causing this?
this is a profiler attached to a build, btw
and ultra is the graphics setting for the build
based on unity document, object pool's collection check performs only in editor
but to be frank im not seeing any UNITY_EDITOR symbol around this checking
so how is unity going to disable the colelction check in build ?
It's not necessarily vsync. It could be a GPU bottleneck.
Can you take a screenshot of the GPU module alongside CPU?
/// <param name="collectionCheck">Collection checks are performed when an instance is returned back to the pool. An exception will be thrown if the instance is already in the pool. Collection checks are only performed in the Editor.</param>
this is really frustrating... i dont see where this collection check has been disabled in Player Build
looking at the GPU usage it seems to be the painterly image filter im using
not much i can do about that apart from turn the iterations down, ty though
Well, you could try optimizing that filter/pp effect. Not much I can tell without knowing the whole context.
Or seeing the profiler data.
Assuming that's the actual code and not a decompile or something, it seems like the checks would be there even in a build.
Ah, actually, m_CollectionCheck sounds like a relevant flag. It could be false outside the editor.
And that could be toggled off from anywhere. Maybe even C++ side.
its defo the kuwahara filter
keep in mind this performance is v exaggerated because i have the profiler attached, its around 60fps normally but it probably should be higher than that
All you can do is have a look at the filter implementation then.
It seems to be running 22 times per frame too. Is that expected?
ah no definitely not
its meant to run once per frame
ill have a look at it a bit more closely 😅
or, twice i guess because its running on the main camera and the camera object (im making a photography game)
Hi
How could I make instances of the same scriptable object have different values? The inventory system for my game is set up like a tree, the base is ScriptableObject, then ItemSpec, then (type)Spec's (like upgradeSpec or consumableSpec). In my game each item is worth calories, so you can keep a creature satiated, but I don't know how to make it to where different instances of the same item have different calories.
This is the code for the ItemSpec: https://hastebin.com/share/wucilefuxo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the classes like UpgradeSpec derive from ItemSpec
have you created instances of your SO yet? this is something you literally just assign in inspector
if you created 2 upgradeSpec or consumableSpec, you can already assign them different values for calories
These are instances
My issue is, I want it so when one of these items is spawned in, it is given a set calories between a min and a max, and it keeps that set amount until it is fed to the creature.
when you spawn the object, (i assume InWorldItem), it should read or be passed the values of your SO. youve already assigned a variable speed increase. if you look at other instances of your SO, they aren't the same value
this is just your data container, you dont spawn a SO into your scene. you use it to pass data to whatever needs it
Right, sorry, I have the data stored in the InWorldItem (the ItemPickup script on the InWorldItem).
There will be multiple instances of these instances in the scene
And I need a way to make each of those items have their own random amount of calories between a min and max.
Like this
Two of the same ItemSpec, in the scene.
If I were to store the min and max on the itemSpec, I would need to find the amount and store it in the ItemPickup script, but then that brings the issue of storing the chosen amount in the item.
which part are you struggling with here? do you understand how the SO can be used to hold data and pass it to your objects?
this part you can have a method in your SO which generates a random number between min and max. it doesnt need to store it but can just pass it when the game object is spawned
I understand that, I want the generated number to be different for each in world instance, the two Upgrades in the screenshot would have different generated values.
how are you currently spawning the ItemPickup objects? and can you share the code for it
just so i can write an example
https://paste.ofcode.org/drYhwXg9vuWSGz74dWJ9e
I'm trying to make throwing objects a possibility with tutorials but I'm missing something fundamental in the understanding of what I am looking at in Google so, I 'd love some help here!
you'd have to say what you specifically struggle with here, although this code really is a mess. all these get components and controlling what happens to other objects is extremely fragile and hard to debug. a component on your object should have control of these things and should be called through a method. this would move logic to your "pickable" objects but also remove the need for using tags to determine logic
The commented bit at the bottom is how I was attempting to have things thrown but it would leave objects stuck in the air with no physics or ways to make the object pickable whatsoever if that helps.
I just whipped up a basic spawning script: https://hastebin.com/share/uhinoravov.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
truthfully id scrap all the code there and remake that logic. setting the collider and rb info should happen purely from the object thats being picked up. You could use a base class to handle this for every object that can be picked up, then derive from that class when objects need more functionality.
I don't really know what the goal is here though so it's hard to suggest much more. you should almost never have this structure of
cubeItemHeld = false;
sphereItemHeld = true;
nothingHeld = false;
sphereBool = true;
Yeah, that's very much me being a beginner as I try to finish a thing for a remote class. If I wasn't on a time crunch I'd look into that because I am very aware of how Chaotic this code looks ^^'
I would move the spawning logic to the SO, but either way something like this in ItemSpec
public virtual void Spawn(Vector3 position, Quaternion rotation)
{
ItemPickup instance = Instantiate(inWorldItem, position, rotation);
instance.SomeMethodToAssignValues(calories, isBig, etc);
}
and at the same time u can generate that random value
the above was for u
Oh, alright.
Then the inworld items have different calories, but I'm not sure how I can make sure those different values stay with the item when the player picks them up.
if you want something a bit more flexible and this being a tutorial you said, you could hold a reference to each specific object in the tutorial scene and then compare that. Depends though if the object with this code is in scene too, since prefabs cant reference scene objects
[SerializeField] SomeComponent myCube;
then when you GetComponent<SomeComponent >() you compare if its the cube. at least this moves you away from tags.
Then just take into account what i said about having a component on the cube itself set the rb.isKinematic and collider.enabled
you would just assign that through a method, you can already run code in a scriptable object. so you just do something like
int randomValue = whatever random method you choose and pass that as a parameter
Also, the isBig variable is meant to stay on the item, if the item is marked as big then the Inventory class prevents the player from picking up more items while it is in hand.
Wouldn't that lead to both in-world instances having the same random value though?
well the inventory class shouldnt be referencing your SO specifically to read the data. the SO should tell the ItemPickkup that it is big.
and no both in world instances wont have the same value, because you would generate a random value everytime to pass through the parameters. this random value isnt stored on the SO, its only passed to the spawned object
If its passed to the spawned object, would I need to make a separate list for the calories? This is my Inventory script: https://hastebin.com/share/imafotokoz.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Would I need to make a seperate list to store the calories from the in world items?
no, the items be told what the calories are and thats it
i suggest you try this and just see how it works. you quite literally just pass it a value through a method when its spawned
I know I can store the calories in the ItemPickup, but my inventory script stores the items the player is holding like this:
How does the Inventory script know how many calories the item is worth?
it doesnt make sense for the inventory to store a list of SO. this is just your data container
you should probably make a new class containing only the info you want stored
and then ItemSpec can also create this new class passing it to ItemPickup
the alternative to this would be making unique instances of your SO at runtime using instantiate which honestly is much worse in my opinion. because you also need to manually destroy them
then you need to look into when to actually destroy them which is not a fun thing to solve
You mean I could make an serializable base class that has empty variables that can be set by the ItemSpec class?
yea, itd also remove repeated variables from ItemSpec and ItemPickup so i end up doing this anyways a lot of the time
Would it be bad for this base class to also hold a reference to the ItemSpec its spawned from?
the parameters become a lot simpler, and in ItemPickup its just also holding its own reference to ItemData
public ItemData itemData;
public virtual void Spawn(Vector3 position, Quaternion rotation)
{
ItemPickup instance = Instantiate(inWorldItem, position, rotation);
instance.SomeMethodToAssignValues(itemData);
}
the itempickup? it can definitely do that. that just depends if you really have a use for it. Right now ive been writing the examples as if the SO is spawning the object but if you were spawning the ItemPickup elsewhere, then itd make sense. on awake it could read the values
just a difference of reading the values vs being told the values
Because, the Items Use functionality is stored in the itemSpecs, so I would need to keep a reference to the ItemSpec.
The Use functionality is actually stored in the classes that derive from itemspec
you might want to be careful with that, since item spec is an SO. if your methods ever need to know state then you'd be modifying data on an SO
I just modify the data of the player class using the data on the itemSpecs.
idk what you use the method for, but just an example, you'd have no current way to code "on the 3rd use, this item gives the user +5 health!". because you cant store how many times it was used on the SO, or every single item would be reading the same value
if you never need to store data like that then its fine
you'd have to store it somewhere other than the SO, and possibly pass it to the SO as a parameterif needed
Parameter as in the get set thing for a variable?
as in when you call some Use function
you pass it a value
Yeah, I pass it a reference to the player script
The radars scan speed is stored in the player script, so when I use a speed upgrade, it multiplies the speed stored in the player class.
(to be pedantic, that's an argument)
(to be pedantic, isn't that passing a value via an argument?)
(the value is the argument, the variable on the other side is the parameter (holding the argument as its value))
i wasnt specifically referring to the variable declared, i quite literally meant it like "you give the script a value"