#💻┃code-beginner
1 messages · Page 693 of 1
yeah i really hate forums
oh thats gpu shader
if u need forum answers you go to a forum website lol
#1390346827005431951 does technically have a general thread ( #1390355039272439868 ).
Nope. Awake and OnEnable do
gotcha
is vscode better than studio for unity stuff
no, nothing is really objectively better than anything else in this space
is it subjectively better
...you do know what subjective means, right
yeah it means im asking you lol
(most people use studio)
i heard vscode has that one good HLSL plugin that makes it tolerable
Vs also has an hlsl extension
yo does having no material also work
or do i have to assign a material to the rb and give it no friction
-# think you replied to the wrong message btw
i did but its just to ping him
i have no idea what you're talking about
remember u told me bout the rigid body stuff
not particularly
yo am i tweaking wtf
For you, the day Bison graced your village was the most important day of your life. But for me, it was Tuesday.
I'm trying to change my sprite's color, but the function is not being called. I have the Player Input component attached, and everything is set to the right setting(i've checked a 100 times, im pretty sure everything is correct but i could be wrong)
This is my function:
public void ChangeColor(InputAction.CallbackContext context)
{
if (context.performed)
{
if (renderer == null)
renderer = GetComponent<SpriteRenderer>();
Debug.Log("Changing color");
currentColorIndex = (currentColorIndex + 1) % colors.Length;
renderer.color = colors[currentColorIndex];
}
}```
put log outside if statement
It works now, thank you.. 😅
ohhh so everything else got called too ?
yep
but why does it work without the context.performed?
I usually use events so for me works fine with that, perhaps print/log the state thats in when that function runs to see what extact state context is in
i know, the action had a "Hold" interaction thingy.
Debug.Log(context.phase) see whats happening
it says "Performed"
interesting..wonder why its not in the if statement
is it normal that intellisense stops working inside #ifconditional compilation ?
Is there any way to keep working on the code with color/intellisense without having to always comment out the conditional ? a bit annoying to work with like this
I usually write the code first, then wrap it in the conditional compilation
yeah I fear thats what I have to keep doing, google doesn't seem to have any answers on this..
just annoying going back to the file to add stuff having to comment it out then put it back
first world issues 🥲
Half a question for my own behalf and half a suggestion, at that point would an assemblydefinition be preferable?
I would assume if you have a LOT of libraries / scripts and don't want to always having them Reload every tiny change you make to unrelated assemblies
its also puts you in to compartmentalization mode
No i meant for your thing
you could scope that monoscript to only android builds right?
what ide? this doesn't happen for me
VSCode
oh yeah, you're vsc on mac right?
I think so but dont have enough experience with it to know for sure, but its only 1 script anyawy
yeah this doesn't happen for me, for both defines that exist and don't
eg. for my little package my editor scripts are in a editor assembly definition so their all in the context of being in editor
oh wait hold on, i was testing with smaller regions
interesting, I might need to revist this.. these are just build processor scripts
i tried doing the entire file and intellisense did break
yeah mine wraps the whole code
Yeah could totally be overkill for your usecase, Just might be a more intentional route Unity wise (or not who knows 😄)
ah i think i found it?
if the define doesn't exist, then that code basically doesn't exist, so intellisense isn't provided
asmdef might work here if I just put the Platform to IOS only. / Android . Ill look into it again
oh so its like code doesn't even exist until its IOS per se?
bummer.. Luckly these files wont be touched much just curious if it was normal that it does this to intellisense in case i use others like if Unity_Editor
i imagine it'd break to have something like this if unincluded(?) regions were processed
class C {
#if A
public K<T> k;
#else
public K k;
#endif
}
hmm makes sense that only works if its UNITY_EDITOR, otherwise its as if it wasnt there
i mean, it looks like it should be && if anything, which would similarly not work
not sure though
i didn't find any matching settings for "symbol" or "region" unfortunately
yea..idk..good ol // will do for now lol
does someone know what can cause moving a 2d sprite feel stuttery? im using rb.velocity to move it if that helps
private void Move()
{
if(Mathf.Abs(playerControls.Land.Move.ReadValue<Vector2>().x) > 0.1f)
{
rb.linearVelocityX = Mathf.Lerp(rb.linearVelocityX, playerControls.Land.Move.ReadValue<Vector2>().x * maxSpeed, acceleration * 100 * Time.deltaTime * Time.deltaTime);
}
else
rb.linearVelocityX = Mathf.Lerp(rb.linearVelocityX, 0, deceleration * 100 * Time.deltaTime * Time.deltaTime);
}```
camera is not connected in any way, this is my move function which is the only part of my code that should be relevant. could it be because of Mathf.Lerp?
test it out without the lerp
i dont think thats the problem
still stuttery :(
it may not be the current issue, but it is an issue nonetheless
do you have small gaps on the ground? might want to use smoother collider on the player
but atleast i know i do thinks wrong that arent really related to my main problem as it always is haha
in the air, havent implemented gravity yet
but you do seem worried about stuttering which is a result of that "differences across frame rates"
guys i need a little help making a APK of my game
and im stuttering at 500 frames as i only have like 3 sprites in my test scene
oh okay
okay, but my point is you do seem to be worried about it stuttering so your whole "gotcha" moment with that screenshot is moot because using lerp incorrectly can lead to further stuttering
anyway, we need more context for the current issue
still that obviously isnt the root of the problem as its still stuttering without using lerp
can you clarify what you need exactly?
jesus christ are you just here to argue or to get help? i have already conceded that it is not the cause of the current issue. i was merely pointing out that it would cause further issues.
i'm done attempting to help here. so good luck.
can you please explain what you are doing on the first if statement and why you have it there
im checking if the player is moving or rather slowing down so i can apply acceleration when im speeding up and deceleration when im slowing down as these are 2 different values
you shouldnt be using Time.deltaTime on rigidbodies
it's being used in the incorrect lerp, not on the velocity itself
i thought you were done?
oh true thought they said they removed lerp
oh fuck off, i was responding to someone else
i did to test where the cause lies but i still used deltatime there
yea using it in the lerp itself okay/needed , it was still used wrong though . You don't multiply it with a constant, the number has to increase each frame/step
can you show a video
stutterring can be many things, might help to see whats actually going on
there are so many things that can make it stutter
also you should always show your code in context, we didnt even know how Move was called
ideally rigidbody move calls should be done in FixedUpdate (unless its an Impulse mode)
called it with Update and FixedUpdate, at the moment its in fixed update but it seemed like it worked the same
yea thanks for helping i think im heading to sleep. cant wait until i open unity tomorrow and 100 errors appear out of nowhere
it seem so but once the framerate start switching up you will notice it will move different
yea youre probably right
hello, I'm writing a basic character controller script and look script using the new action input, I move the player based on the camera's X axis movement and for some reason whenever I move the character itself the camera will start drifting on the x-axis. is there an obvious reason for this? I can provide my code if needed.
👀 👉 👈 I'm trying coding but everything I look at looks like a random mix of words...
So does English
where are people pulling all these random words from
👀 Can i get a finger in the direction where someone can teach basic coding that will help me in unity projects?
The documentation mostly
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Is someone using this bot on a the other end? Swear i also saw it say something about blender even though no one did the ! Thingy
The bot message still stays if you delete your message after the fact
So there's a stinker deleting their messages, Is this you?
I don't know if cleaning up a message purely intended just to summon a bot message is a "stinker"
working on an old project and i have no idea what the + 0.2f could be for, any ideas?
It adds 0.2 to that number
obviously, i mean what purpose could it serve
Well, which parameter of raycast is that?
i do not know
like i said old project i have a very loose idea as to what anything is for
So, how about checking the documentation and seeing what parameter that is?
Yoooo Im making a button that when you click on it changes its function but for some reason it doesn't work
be more specific than "doesn't work" and show what you tried
void Start()
{
but = GetComponent<Button>(); //this works
but.onClick.AddListener(JoinPlayer); //this doesn't
}```
You're still going to have to be more specific than "doesn't work"
When I click to test the game, the script gets the button component (that has no listeners) and then I try to add some but the game ignores that
How are you determining it isn't
{
if (PlayersHelper.playerCountHELP >= 2) //this is when you click on the button
{
but.onClick.RemoveListener(JoinPlayer); //but still the game doesn't recognize this command
but.onClick.AddListener(DeletePlayer); // this too
}
else
{
but.onClick.AddListener(JoinPlayer); // this too
but.onClick.RemoveListener(DeletePlayer); // this too
}```
What do you mean by "doesn't recognize this command"
Add listeners in Update is not a good idea by the way
this is when I start the game but it ignores the 2nd line on the Start function
(the one that says "this doesn't"
For one, you have an error in your console you should address.
For two, runtime added listeners aren't going to show up in the inspector
The game ignores that part of the code
Again, how do you know
because when I click on it doesn't do what I want
Just for clarity, a runtime error can cause all sorts of things to go wrong.
If it's a compiler error, you won't be running the latest up-to-date of the application.
What's the actual issue btw? Is there an error?
So what makes you sure the issue is that these lines aren't running or that the functions simply do not do what you expect? You haven't shown what any of these functions do, or what the error you're getting is
what I want is switch the "joinplayer" to "deleteplayer" but when I do it the game keeps the "joinplayer" function and ignores the line of code that removes the "joinplayer" and the line that adds the "deleteplayer"
So, it does have JoinPlayer? That would mean the one in Start works
I'm pretty sure the code isn't ignored. Instead you've likely got an error or the behavior simply isn't what you're expecting.
this is the error, but unity let me start the game anyways
Okay, that one is ignorable, you can clear that and it should stay gone for a while
How about using some debug logs to see what code is running and when
I did
{
if (whoAreYou == "P2")
{
Debug.Log(whoAreYou + " has joined!");
playHelp.playerCount = 2;
PlayersHelper.playerCountHELP = 2;
p2text.text = whoAreYou;
but.onClick.RemoveListener(JoinPlayer);
but.onClick.AddListener(DeletePlayer);
}```
the debug works
Show the logs?
everything here works, except the last 2 lines
If you get the debug log, those lines are running
this code is what the button does when you click on it
How about instead of these tiny piecemeal windows into what's happening, you just post the full !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 knowww but the last two doesn't, like in the inspector does not show the "deleteplayer" on the button
instead shows "joinplayer"
The inspector does not show runtime added callbacks to a button
Ohhhh but the game still does the "joinplayer" function instead of the "deleteplayer"
Show the full code. It's pointless to keep up this game of 20 questions until then
A tool for sharing your source code with the world!
Do not add listeners in Update. It's going to add a copy of the function every frame
And try putting a log outside the if statements
see if the functions are called
okok
If the idea is simply to make the function toggle every time you hit it, why not just have one function and read a boolean in it, then toggle the boolean when you want to swap?
I actually did that but it give me a bug on the game that I tried to solve it everyway possible and doing this solved it
And this apparently didn't solve it either so maybe don't make things infinitely more complicated for no gain
Still, consider not doing this callback swapping and just use a boolean instead
I think the problem was that I thought that the inspector will show the changes lol
Yeahhh but that didn't work either but I'll try it next time
thanks anyways!
So maybe try solving the problem instead of rewriting the entire system to be slower and harder to get working
its been like almost a week and now im able to code an interaction system by mself finally 🙏
thats a big step! congrats
thxx, ill def need help with scriptableobjects tho as i want to have a pickup system
im having an issue where my character has the "in air" tag no matter what, and when i fiddle with the values to try and correct that, it has the grounded effect when its way above the ground, any ideas?
A tool for sharing your source code with the world!
maybe a floating point error?
When you say "tag" do you just mean your grounded bool is true/false?
yes that
what would i do about that
when using == to compare floats use Mathf.Approximately
but personally i just try to avoid using floats as much as possible
Presumably your Raycast parameters are just not tuned correctly
A good way to debug this is to use Debug.DrawRay/Line to visualize your Raycast
Then you can actually see in the scene where it is and why it's not giving you the expected results.
That will be very helpful yes
Can't test that right now but I'll do that when I get back
im trying to figure out how to create a hotbar with working slots + scriptableobject holder
this is SO HARD
my brain just shuts off
does any1 have any good place to go to, to better understand the structure of it?
how about getting a so with an array of objectsand have the hotbar as some sort of holder
What i did so far is making an Item[] array to hold item type
{
public Transform hand;
public Item[] slots;
public int currentSelectedIndex = -1;
private GameObject currentEquippedItem;
void Start()
{
}
void Update()
{
for (int i = 0; i < slots.Length; i++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + i))
{
EquipItemAtIndex(i);
}
}
}
public void EquipItemAtIndex(int index)
{
if (index < 0 || index >= slots.Length) return;
if (slots[index] != null)
{
Destroy(currentEquippedItem);
}
}
}```
this is how far ive come in 20-30 minutes without chatgpt and its breaking my brain
Try Googling a few tutorials. This should be quite popular as a topic so I would expect there to be some tutorials on it.
I'm making a 2d shader to change a noise texture to water, but after I add the material with a shader to the image with the noise, masking no longer works... I have very limited knowledge with shaders and am slowly going insane. Any fixes anybody knows of?
You'll need to implement the masking functionality in your shader.
How do I do that?
I would usually just make this a subclase wihtout asking but considering it seems I may be overusing it... should I create a subclase for specific the gear slot for weapon and off-hand that use a slighty different logic or do I just work it out on the same class?
There is a specific channel for shaders, but as I far as I know, that should work without any extra work
Are u sure u are using the right layers???
It works when I dont have the shader/material on
how do i use this, is it a line of code i put in my script or just something i can turn on in unity?
This is mine working with no issues. I dunno
It's a line of code yes, look it up in the docs
You can also turn on the physics query visualizations
That's a thing that exists too
need a lil help im adding an edge collider at runtime how would i make it ignore all layers other than the 'enemy' layer
Put it in a layer that you set up to ignore the layers you want
u can set up layers to ignore others?
so like that
if I have a static variable, is there any way at all to set that using the inspector? I want to have a static ScriptableObject but I'd rather not load it in during Awake if possible
Sample the mask texture in your shader and discard the pixel depending on the value.
Though, I'm not 100% sure. If unity uses stencil buffer for masks, you might need to specify stencil test value.
i truned on the options that im pretty sure are supposed to make me see ray casts, but i dont see the ray in scene or game view, how do i fix that?
I've commonly had scriptableobjects be stored on a major singleton that i can always count on existing then use a static property to access it statically, eg.
public class ContentManifestCollection : ScriptableObject
{
[SerializeField] private PlayerManifest playerManifest;
[SerializeField] private CardManifest cardManifest;
[SerializeField] private BiomeManifest biomeManifest;
[SerializeField] private ScriptableColorPresetManifest colorManifest;
[SerializeField] private SpriteManifest spriteManifest;
public static ContentManifestCollection Contents => ContentManager.Instance.ContentCollection;
public static PlayerManifest Players => Contents.playerManifest;
public static CardManifest Cards => Contents.cardManifest;
public static BiomeManifest Biomes => Contents.biomeManifest;
public static ScriptableColorPresetManifest Colors => Contents.colorManifest;
public static SpriteManifest Sprites => Contents.spriteManifest;
}
If I have something like this, is there not a way to assign to that slot, each its own gameObject? Do I have to go one for one?
Cause that's something that wastes me a lot of time considering how often I do it lol
Is there a special type of raycast or reference to use for the camera?
I want to make a script that tries to see if there are any objects between the player and camera.... and if there is... then turn the mesh renderer off of that object until it no longer touches the raycast
correct, but if your doing it often enough it might be a sign your workflow might need some prefabs or something
You can quite literally just get the camera world possitio as an origin for a raycast lol
But there is also a specific method depending of what you are doing
What do you mean? I am supposed to do single button first and then copy it over and over?
First I make sure the UI actually shows as I want to before making it work
a specific method? can you elaborate on that?
cause I don't think simply just one raycast would work for this.... could be wrong but I haven't really used raycasts for many things before
For what you are seeking you probably just want to use :
As the origin of the raycast
so what, just do a simple normal raycast with that position as point A to point B being the player to determine the distance?
private void Update()
{
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
MyInput();
if (grounded)
rb.linearDamping = groundDrag;
else
rb.linearDamping = airDrag;
}
@frigid sequoia you might want to re-read their question
or actually not sure how its phrased
are you trying to shoot just one raycast out or a lot?
how can i convert my code (top) into something that uses the below function
oh i misread it, apologies
what is the code down below meant to be used for?
@marsh canyon you probably want a boxcastall
Making meshes do what you want can be as hard as you want it to be. The base is raycast from camera to player, if it hits something, trigger the hide effect
its just an example of Mathf.Approxmately
You probably want to get all the targets in the way tho, not only the first one
i see that but what do you need it for
im trying to see if an error im getting is caused by a floating point error. and someone reccomended using Mathf.Approximately, i just want to know how to impliment that function in the lines of code i sent
Floating point error does not occur when you are using a margin as big as 0.2 lol
idk someone reccomended it
ok well from what the documentation says all it does it output a boolean value depending on if 2 floats are similar (ie 1.00001 and 1.0) not sure this is what you need
i see
use some debug.log's to find errors
though it depends on what's happening cant' do much without such info
ok so the boolean "readyToJump" becomes true very inconsistently
which is supposed to be activated when a raycast that points directly down crosses a "whaIsGround" layer
i'd say change the 0.2f to a public / [SerializeField] float so you change it in the inspector cause i think the problem is it's too close to the player so any height makes it no touch the ground
eg
[SerializeField] float GroundCheckDistance = 0.1f;
well if i could see the ray i would know whats happening
but i cant figure out how to enable physics debug
just use OnDrawGizmos()
eg
private void OnDrawGizmos()
{
Gizmos.DrawRay(transform.position, -transform.up * GroundCheckDistance);
}
though i don't think these have a range limit
might be wrong
is that to fix the problem overall, or make the ray visible
that'd just make a visable ray when in scene view
do you know why this isnt working?
as i said before the problem is your Physics.Raycast isn't long enough so when you go on an incline it doesn't reach
which i why i recommended changing the 0.2f to a public float with a name instead of a magic variable
it doesnt reach the ground on flat ground consistently
right so increase it
ive increased it to twice the player height and it didnt work, and decreased it to really short and it worked, i just want the visualization so i know whats happening when i change things
wait this script is a component of the same one that would have your player collider yes? though if that LayerMask is set properly it shouldn't matter
never used this so not sure
its from the same one in this link
not to nitpick at something else but using a box collider for a player isn't recommended
if you try to go up a ramp it'll be a corner pushing on a angled wall, normally you should use a capsule
what was the cmd to trigger the docs bot here ?
!docs
nice thanks
i see, i will do that then
also we can't see if the grounded bool is active or not in the inspector add a public or [SerializeField] before it
same with readyToJump
hard to tell for which one isn't working when neither show in the inspector
so readyToJump is working fine, but grounded turns on and off constantly if i make any movement, even camera movement
could it be the collision detection?
on the rigidbody, i've never used continuous since it's never really worked for me
Mmmm, I don't find anything missing, does it not point it out?
always stuck to discrete
when i switched to capsule colider just now it makes the character shake violently when it bumps into anything
freeze rotation for x and z is on
nah best it'll do is this where the script used to be
I love when scripts just dissapear when I rename them lol
wait so when you do increase the value it works or does it still do the off and on thing?
increasing player height (adjusts how far the ray should be) it still is on and off but its off more often, which should be the opposite of what it does
and decreasing playerHeight makes it almost always off but occasionally on for seemingly no reason
i doubt this'll work but what if you try -transform.up
instead of Vector3.down
functions identically
grounded seems to be tied to camera movement for some reason
why though :/
thats the question
what if you turn off interpolation on the rigidbody?
all that did was make the grounded bool true less often
and the continuous what if you try discrete?
i changed that back when you said to and didnt notice anything different
ahh alright
ok so what i though Continuous is meant for fast moving things
but collisions still affect the camera which isnt good
which the player i doubt is meant to be
does the camera have a collider?
it does not
but its tied to the player which does
camera holder contains the camera, and gets teleported to camera pos
teleported?
its position gets set to the object camera pos when the game is running
camera holder controls up and down motion and camera holder is just attached to the player which is turns left and right
right, could the camera being in the same object thats getting moved/teleported be the issue?
well the player character shouldnt get rotated when it runs into a colider anyways
that's normally why i turn all three rotations off on the rigidbody
Ok, so here is a extremely weird question, like, if I am filtering gear... ah what do I do with the stuff that is being filtered? I like just.... hide it?
i guess if its a capsule you dont need y right
So let say I have this and I want to JUST show weapons, do I still keep all the rest on scene but just like dissabled?
pretty sure the constraints are just for physics based things and if you handle rotation through transform it wouldn't be physics based so the 3 rotations would be freely affected by outside collisions
oh ok
if setting the objects to inactive makes only the weapons fill the other spots then what's the harm?
as i learn more about unity i realize that i definitely picked the wrong tutorial to learn movement and camera controls
well preferences of every person does have it's affects
That it can lead to eventually to like scene with A LOT of dissabled objects, it's that ok?
Shouldn't I keep it cleaner?
what's the reason for only wanting to show weapons?
100% of my learning of unity has been fixing all the things that are bad that i got from that tutorial
So you click on a slot and it just shows whatever is relevant to equip on that specific slot, the rest is hidden
An auto filter basically
i see is there a lot of items to where it'd be more worth it to delete and spawn the new items versus just showing and hiding them? cause it's actually recommended to keep objects hidden in a "pool"| and just show them over spawning them in cause spawning a lot of Objects will have frame spikes
I have no freaking clue what would be more efficient honestly
I have to keep track to all that is in the inventory forever anyways
what i would do is have an invisible inventory , and when you open the ui inventory it just shows you what things from your invisible inventory that fit the filter
So keep making and unmaking it seems kinda dumb
Just do it however you want tbh. The best way is gonna be stuff your not interested in rn anyway
see you get it, heck there's much more advanced stuff that devs spend ages working on where all it is, is hiding and showing objects that arent in use instead of spawning new ones
ok i genuinely dont know how this code works, because even when the player height is set to zero, which should make the ray that checks if the character is grounded very short, i can still occasionally jump
Maybe you should check the code for jumping instead of the check of the one that check if you are grounded
Anyways you should send a debug that tells you when you are grounded
again as i've said just put a public before the 2 bools
i did
i can see when grounded is true
and nothing i do to the values that grounded supposedly uses to calculate if the character is grounded changes how grounded works
alright well besides the raycast this is your jump code, where the readyToJump restricts your jumping to once every 0.25 seconds at minimum
You are probably too focused on the values when probably the error is not on the numbers but in the logic
Are you 100% of the time grounded while not jumping?
could you record a video of this or something
sure
I mean the boolean obviously
oh ok then yes i can always jump when the boolean grounded is true
sorry tired
don't blame you it's 1am for me and i got work at 7 (in 6 hours) 😭
it is not always true when im not jumping, but it is always not true when i am way above the ground
if im only a meter or so off the ground it is sometimes true and sometimes not
im trying to send that video
Yeah, then the bool is doing weird stuff, and it has nothing to do with the numbers
Would be way easier to see with the Debug.DrawLine but....
If you are totally still it's always true?
And log whenever a value is assigned to it
It could be a faulty ground detection logic
no im saying it is not always true when im not jumping
I mean TOTALLY still
ohok
Sometimes walking can change the result
so if im perfectly still the value doesnt change, if i walk around or look around the value rapidly switches
again trying to send that video
Depeding it the ground is not even, something gets in between the raycast or you just have the raycast on the wrong object and it's shooting to infinity cause of animation
its just a perfectly flat box
sorry its so short its very hard to keep it below 50mb
Absolutely nothing is clear from that video.
Anywas, you should debug properly.
Yeah, I got it clear still
could you send an updated paste bin of the code cause it looks like the raycast/grounded bool only returned true after the camera was facing nearly horizontal, though it was hard to tell cause 60% of the video was loading
Note how the rotation in Y is changing while u move?
Yeah, you are sending the raycast to random places
Not the ground
The rotation and scale of your root player should NEVER change
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
A tool for sharing your source code with the world!
ehh i have the rotation on my player objects move but i also handle my raycasts differently
It should always rotate inside a parent item that does not
isnt y where its facing? so if its pointing down it wouldnt be affected by the y axis
Cause then it does weird stuff
i wish to know who gave the tutorial so i can give them a piece of my mind this code hurts me 😭
i will find it
Very fast tutorial to make an FPS character in Unity in less than a minute!
PasteBin link for code: https://pastebin.com/RXZ1dXgw
GitHub link: https://github.com/dustinmorman/FPSControllerTutorial
Link to my Upcoming Game - Survive the Uprising: https://store.steampowered.com/app/1984690/Survive_the_Uprising/
Link to the Discord - https://dis...
you're using a character controller?
the version in the pastebin is significantly modified from the one in the youtube video
am i?
idk thats what the tutorial told you to use
i havent watched it since march
never used one so i have no input on it
what makes it a character controller instead of not that
character controller is a script built in unity that does some extra things
Hi, i was analizing my melee attacks for, the player AND the enemy, (method is similar) for the animation events/update, yet i stumbled with the issue that, if is locked in one frame is too....odd, and if i put it for a lot of frames, it damages per frame wich is not the idea, so, how i can make my method of melee only trigger, when has already been triggered?
{
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(meleePos.transform.position, MacheteRange, 0f, victim);
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out ValeriaController enemy))
{
enemy.TakeDamage(meleeDamage);
}
}
}```
what is the alternative
oh this is not the video i dont think
maybe it is
well the problem with it is it sucks for slopes and doesn't use physics but it does have a built in ground detection that i think just uses collisions and not raycasts
im just going to go to sleep and see if i can figure this out in the morning
ay i get sleep yippee
Im not sure how you have it setup but it sounds like you put an animation event per frame. it'd make more sense if you had a "start attack" and "end attack" event. Then use either update, fixedupdate, or a coroutine to call this function.
All you need to do though is just check if the enemy was damaged before, store the damaged ones in a list. Everytime you start a new attack, clear the list
im more worried rn abt the enemy ones, yet, how the return works?
i think i MIGHT be cooking?
just
what if i did this
{
if (ValeriaHasBeenhit) return;
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(meleePos.transform.position, MacheteRange, 0f, victim);
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out ValeriaController enemy))
{
enemy.TakeDamage(meleeDamage);
valeriaHasBeenHit = true;
}
}
}```
what if i did this
and then
{
ValeriaHasBeenHit = false;
}```
another event with this
it is a bad idea?
now you have a melee attack that can hit at most one enemy. if thats what you want, sure
it hits the player
but i mean, the way i hit all my enemies is similar
cuz all my enemies share the same base
with the same health value
i just hit that script
and substract that value, until they die
atleast have worked till now
but now im wondering if is a good idea
it doesnt matter what it hits, ideally you wouldnt have different logic between the player and enemy in terms of how a melee hit works. The logic is the exact same, the only difference could be like checking what layer its on, or searching for a specific component, or reading a component value to know what "team" its on
it would just be
{
if (DemonHaveBeenHit) return;
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(meleePos.transform.position, MacheteRange, 0f, victim);
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(meleeDamage);
DemonHaveBeenHit = true;
}
}
}```
yeah exactly, thats what i do
...just slighty more complex
but my issue is
this, bool, return, thing. It is good?
so then if your player has the same logic, you suddenly can hit only one enemy
but i mean, my enemies use the same base
to wich it gets hurt
the hurt area is on the base
and the player detects the base
in theory all enemies use the same, so it would be like...one...enemy?...
so yes?
i have no clue what this means either. it doesnt matter what it using this function. you just have to know that whichever character is attacking via this method can only hit one target per attack
why, exactly? thats what i dont follow
i thought were about the script name thing
but now, you may be refering to another thing
wich...i can't see
i mean, you mean, i use this method, and i touch 3 guys, three inherite from the same fella
what would happen?
follow the logic line by line, follow it 3 times if you need. lets say some event calls your code to start performing melee attacks for X frames. first it resets so ValeriaHasBeenHit = false happens.
next meleeAttack is called. Lets just assume Physics2D.OverlapBox finds a Collider2D (this method also only returns one collider). You damage the target, valeriaHasBeenHit is set to true.
For all the next frames meleeAttack is called, ValeriaHasBeenhit is true, so you return.
ooooooooooooooooooooooooooooooooooooooooooooh, so the thing is, i should make the bool thing, work, on the Target, not on the attacker
makes sense
no, then an enemy can only be hit once. I never said to do this either
i want it to be hit once
until the method reset damage is set
mmm, it should better use a timer
yeah, a timer
Or just do it properly like i initially suggested and have a list of enemies that were already damaged
is...is actually..very simple, just check if the attack is melee, do the bool thing, and put a timer, if the timer goes zero, the bool returns to false and can keep get it ass kicked
oh right
the issue is...i dont know how
one change you likely need to make is using the 2nd declaration of OverlapBox so you can have a list of enemies to hit during a single check. https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Physics2D.OverlapBox.html
google how to make a list in c#. then how to add to a list. then how to check if something is in a list
JUST, for know, why this method is less likely than the list one? just asking
Can I like.... add a item to an ordered list on a specific possition instead of recalculating the whole sorting?
Like let's say inventory is ordered by descending item rarity. And I want to add an item I know the rarity of, can I not just tell the List to place it within the items of the same rarity as it comes in?
Like, sort this only item in particular and forget the rest of the list?
use the SortedList class
But that, like... has to be sorted still right?
Like, I can sort it by a bunch of values but I have to call it right?
if you want the items sorted then its gonna have to be sorted. Doing it yourself will likely just be worse compared to using built ins
there are data structures specifically for keeping objects sorted as they are inserted. you dont want to manually sort the list everytime
So if I do this, if I add an item with the same gearRarity it automatically gets sorted between the rest of the same rarity?
Like I would still have to call the list to sort it by gearRarity anyways right???
I mean, I can always do a list of lists and have a list of each rarity
it would yes but you would need to implement a custom comparer on InventoryItem. Also you wouldnt be able to add the same item, if the comparer returns 0 then it'd probably error as well.
Maybe you could get away with just using List.Insert(index, item) to insert items at a specific position. You would just need to search through and compare the rarities.
Or realistically if the list is small enough you could sort it every time a value is inserted. Just implement a custom comparer on InventoryItem
btw, what diferences are of using a List and a HashSet?
i mean cuz investigating i stumbled with some ppl discussing abt it
you might just want to google the differences though truthfully I wouldnt worry about a hashset unless you really have performance concerns.
https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-collections-generic-hashset{t}
the main thing you'd want to know is that it cant have duplicate elements, like a dictionary. you'd really have to be using a large list, a lot per frame, to ever notice a difference in performance between the two also
btw, this is how it should be?
{
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D[] hitEnemy = Physics2D.OverlapBoxAll(meleePos.position, MacheteRange, 0f, victim);
foreach (Collider2D hit in hitEnemy)
{
if (hit != null && !alreadyHit.Contains(hit))
{
if (hit.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(meleeDamage);
alreadyHit.Add(hit);
}
}
}
}```
makes sense
i mean, for what i saw, in theory this analizes the list, then analizes each fella on it, and checks if has the hit
or atleast thats what i think i did
logic looks fine at first glance. you could optimize by using OverlapBox still and the 2nd declaration
public static int OverlapBox(Vector2 point, Vector2 size, float angle, ContactFilter2D contactFilter, List<Collider2D> results);
though if you dont understand it, i wouldnt lose hair over trying to change it before testing your current setup.
oops I pasted the 3rd declaration, didnt realize the physics 2d has one that takes a list and one that takes an array. The 3D physics overlap functions only take arrays 🤔
I quite literally just was checking that
Hashset better for searching specific items very fast. List better for iterating over all the items
Yeah the list is basically an "endless" inventory, so yeah, it's meant to be big
Searching for a specific index to insert it manually seems like even more costly in resources tbh.
I think Imma go for a list of lists, seems reasonable
makes sense
a dictionary of lists would be a bit easier to associate Rarity to List
Mmmm, not really much different than to just get the rairty straight from the gear.gearRarity
Any advantage to using a dictinoray there?
you're likely going to be looking up the list by its rarity, to know which list to insert items to. it just seems to make more sense with what your goal is
I guess, but can also just add them in order so I know which is which without the need of an fixed index lol
🤔 this would force you to have a fixed index per list. Think about it like this: when this class receives an item, how do you know which list to put it inside the List<List<Item>>. You need to correlate this rarity with the index
Or just use a Dictionary<Rarity, List<Item>> myDict; and do myDict[item.rarity] to get the list
My AddItem method would pass the whole item, then the rarity would be checked, being an enum that basically can be used as index for the list of lists, then I just add the incomming item to the relevant list which is the one with matching Index on the list of lists
Just out of curiosity but in order to do what are you sorting your items by rarity?
So the thing you are likely to want to equip (aka, the better items show first)
So you want to go from Rarity to Index, so you know which list to access. Or... just use a dictionary and skip the needless step
There is not even a step, there, like... an enum is already a index
Can you elaborate?
Ah... the ideal would be that inventory holds all the items that you can equip, once you click a slot, it shows everything that can go in that slot, ordered by rarity, you can them click to swap it with whatever you have equiped right now
There is not much to it, really
an enum is an enum, not an "index". it can be converted to int sure but you need to explicitly do so. anything that wants to access this list will need to do so
how do i shorten a variable name?
at the moment, I have this:
var FOV = CinemachineCamera.Lens.FieldOfView;
but wont initializing it as "var" and then modifying FOV modify the variable indirectly? so i'd just be changing a copy?
you either make a property or a method which sets the value for you
yes right now you'd just be changing FOV, a float, which wont affect the lens field of view
Can I change the size of a sprite in pixels?
(Something like transform.localScale.inpixels = )
Realized it doesn't need to be in pixels, I just want to change the width and height to a fixed one, like 1F, 1F
I'm still not sure what you're asking.
Can somebody help me with this? I am new to coding and this code was working normal and now it keeps giving me this error. I didn't change anything. I have no idea whats going on.
You can always get the size of a sprite relative to the viewport and then calculate the scale based on that
What's a PickupDetector?
There does not seem to be a class called PickupDetector
Unity is suggesting that "it isn't a thing".
It's for detecting objects to pickup. I just don't know why it suddenly stopped working.
That works for me, but how 😮
Can you prove that it's something that actually exists and not something Unity thinks you've made up?
At this point it believes you do not have anything called PickupDetector.
hi, sorry i've never heard of this before. could you provide like documentation or give an example perchance?
I have a video of it working.
Show where you've defined PickupDetector. Working or not working doesn't really matter. It's saying that you're trying to use the type PickupDetector but it doesn't know what that is.
Ohhh i see.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties a property would essentially be a way for you to get or set CinemachineCamera.Lens.FieldOfView .
it'd be the same as creating a method void SetFov(float ...) and float GetFov()
I guess maybe what you want..? not sure
UpdateFov(ref float fov){
fov = whatever; // fov here will "refer" to whatever you passed in and will update that variable outside of this function if you assign something to it
}
UpdateFov(ref CinemachineCamera.Lens.FieldOfView); // the ref will allow the function to change this variable on the camera
note: it wont work on properties
Do someone know that why nothing is happening when I click any button?:
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenuController : MonoBehaviour
{
public void OnStartClicked()
{
Debug.Log("Start button clicked!");
SceneManager.LoadScene("GameScene");
}
public void OnNothingClicked()
{
Debug.Log("Nothing button clicked!");
}
public void OnExitClicked()
{
Debug.Log("Exit button clicked!");
Application.Quit();
}
}
you're not in playmode.
also console not open
(just annoying cause we wanna see console not an unrelated project view)
and i think you don't have an eventsystem
rightclick in hierarchy and add an event system
I have tried doing that but nothing got printed in console when I clicked buttons in play mode
On what?
Oh sorry i mean "On what?"
the left of your scene window
look at it's tab what is it called
Hierarchy
where you modify your scene
just like how you make a new cube or a new button. rightclick inside there and create an eventsystem
theres no reason to use ref there, they already know what variable they want to update
Why do we normalize inputDirection 2 times please ?
(In the video when im on: Left - Showing normal jump; Right - if i try dashing vertically, using "Y")
Im trying to implement a simple dash mechanic but when i try dashing vertically or diagonally i get floaty, as if ive jumped,
And no matter what i do i cant get it too work.
i think you dont need to normalize the input on line 192
is it not your code?
normalization is idempotent
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
No, it's from the FirstPersonCharacter from Starter Assets
oh inputDirection is reassigned to a non-normalized vector in the if statement
yeah but normalized again 🤔
yeah, because it should be normalized...?
it's the first assignment that's unnecessary (and arguably a mistake - if the input is near zero you get a magnitude of 1)
makes sense, thanks 👍
hey
would anyone mind giving me a help over vc? I am getting a bug with the camera
you are incredibly unlikely to get someone willing to help you privately. just !ask your question
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
Hi, how i can do for this nav mesh agent don't go trought the walls?
You should set up your nav mesh to set areas that are blocked by a wall as non-walkable
It kinda does seem to avoid walls but the agent radius is smaller than the graphics of the character so part of it clips through the walls
I had a break for 2 months and I've started again. I'm going to use the new input system using input action references (What I got so far https://paste.ofcode.org/JYGMuMHR5sxnBZTDw84ums) . In the image shown I would like to know how I could convert that into the new input system cause right now that's using the old input system. Help would be appreciated.
is there any way of not having hiccupts when doing loadscene async
perhaps #🖱️┃input-system
there are tutorials for that
what do you mean by "hiccups" exactly?
Is it the loading of the scene thats hiccuping or the initialize of the scene after its loaded
seems like you've already gotten currentInput, that would be like Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"))
though, you could simplify this down with some math. now that you have a vector, you can normalize or clamp it so you don't get faster diagonal movement.
loading of the scene
i divided my city into chunks
and whenever i enter a new area i want to unload the previous one
each area has entities and collectables and stuff
but yea the spikes are a bit crazy right now
Would this be fine? well it works
sure
Since im going to be adding controller support how can I make it so when your on controller and you slightly move the stick to move I want the player to move slowly
your code already does that
next what you can do is add a blend tree
use ClampMagnitude instead of normalization
what like currentinput.ClampMagnitude ?
Yeah, the difference is, ClampMagnitude prevents it from going over 1 magnitude, while normalize will set it to 1 magnitude
there's also a Vector2 version
If it's less than 1, ClampMagnitude won't affect it
🤨 your horizontal axis goes back and forth?
because transform.right and transform.left introduce a square movement structure but they want to clamp the players movement speed by magnitude
he is not reapplying it to the same vector, he is doing it to his input, so it shouldnt go back and forth
if you were to move right and forward you would walk faster than just moving forward if you werent to normalise it
that's.. not even close to what i'm talking about
and why would his horizontal axis go back and forth then? 😄
both in the original inputmanager code and the current inputsystem code, the horizontal/x axis is used to go forwards and backwards
whats "back and forth" in this context?
- and - ?
How do I start with creating a video game?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
check the pins
come up with something you want to make and figure out how to get there
ahh, now I understand 😄
most important thing is to not try and aimlessly learn stuff because you wont get anywhere
ok thanks bro <3
pfft.. thats my day in a nutshell 🤣
I got it working! Vector2 input = Vector2.ClampMagnitude(currentInput, 1f);
whats the difference between vector2 and float2 fellas
More utility functions on vector2
Vector2 is from UnityEngine, float2 is from Unity.Mathematics
very well explained
they're from different systems
is a buffer just a line of bits
no, "buffer" is a really broad term
a buffer at its core is just a chunk of data you can read and write into
more specific buffers will have more specific data and perhaps more specific constraints
how can i rotate my plane which has forward x velocity in 2d to 45 and -45 angle based on if my mouse if at top or at down
you asked 5 questions at the same time mate
wdym
what does "if at top or at down" even mean
we have no idea what you're asking
assuming they mean top of screen = fly 45 degrees up, bottom of screen = fly 45 degrees down
and linear fading
i want to rotate my plane 45 to -45 degrees on x based on mouse y at top or bottom of the screen
does this have anything to do with velocity?
if at top -45 bottom 45
like i want a rotation of that type so that the degree of rotation is where my plane would move forward
not directly related
break the task down into sections
- get the mouse position in viewport space
- map that to angles
- apply the angles to the plane
the heck
don't spoonfeed please
im just saying this is a fairly simple task and chat gpt could probably explain the entire thing to you
do not use chatgpt unless you are already familiar with unity, it will give you wrong info you cant identify
the code had a few mistakes, it wasnt even rotating on x
That is now your task to find out, we cant do your work for you
- mouse position is given in screenspace, you can use ScreenToViewportPoint to turn that into viewport space
- there's a ton of ways to do the mapping (mostly math)
- there's a ton of ways to apply rotations (probably Quaternion.Euler)
also do clamping if you want to ignore the mouse being outside the viewport
Oh thats why you downvoted my answer, I totally forgot about that function and wouldve done that calculation thats provided here manually 😄
youre not supposed to copy chat gpt code lol
then why did you do it?
haha
Treat chatgpt as if you have a 50% chance it flat out lies to you and if you dont think you could identify the lies, dont use it yet to help you out
50% is generous lol
copilot is actually doing a fair job at completing thoughts though, chatgpt is mostly hallucinating when it comes to unity 😄
im gonna try my best.
I am using a function to change the pivot of the camera, but it doesnt work properly. there are three objects: small arc, medium arc and big arc. Whenever I click on the medium arc it works, but the other two are inverted.
forsome reason
share !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 can get the x position using Input.Horizontal in a var and change the rotation using quaternion euler but am just asking what math function could get me to co-relate them if am asking too much sry but i have tried for like an hour cant find the fuction and chatgpt script isnt working
Input.Horizontal isn't a thing
if you mean the axis, well, that'd be delta, not the absolute position
what do you mean with co-relating?
also you'd want the y position
input.getaxis bro
programmers dont like AI
what a surprise
the idea behind asking chat gpt stuff is it gives you terminology and concepts to further ask about instead of getting someone to tediously walk you through how to make a plane fly for your game (like you are doing now)
it's a great tool as long as youre able to use your brain
that gives you deltaPosition, not absolute position
wait fr?
you're missing the point
i thought input.getaxis could do
Input.GetAxis gets you the value of that input axis at that frame
oo
Input.GetAxis("Horizontal") will give you whatever value along the input's X-axis it's at right now, from -1 to 1
genAI is a tool that's really easy to misuse if you don't know what you're doing
beginners, by definition, don't know what they're doing
using faulty resources and handholdy chatbots is only a hinderance for learning
i don't care if you use AI
just don't push it on beginners and don't come crying when it doesn't work
ik thats wrong but wasnt there a MouseY input too?
Vertical
yeah, that's delta position, isn't it
no this is a different thing
now whats a delta bro 💀 what have i been doing the whole time
delta is the difference between 2 numbers
Yes, that gives you how much the mouse has moved this frame in the up/down direction
math concept
delta can quite literally be interpreted as "difference"
aight buddy just stop with that bs
start using google and docs instead of that
yeah because google is pushing their ai
click the linked source or scroll down to actual docs where there are primary sources
@naive pawn i see your point bro but i promise you its cause this guy is funny
what are you talking about
me?
no
bro i am not experienced even to a bit
that gives you an absolute value in pixels, use the function Chris gave you before to get that into 0-1 range
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ai won´t take you anywhere rn
is it more common to set public variables in scene editor or get script to find stuff in scene at runtime
"variables" is an insanely broad ask
variables
fill everything you can in inspector, if stuff is spawned at runtime you can search it later
Those are called 'fields'.
Fields should pretty much never be public. SerliazeField private fields to display them in the inspector.
those are serialized variables
there are several other uses of variables where your question doesn't even make sense
just do what works for you
the recommendation is to use SerializeField'd fields but at a beginner level it doesn't really matter imo
and don´t call your script Random
If you can set a field in the inspector, you probably should set it in the inspector. Every other method of assigning a variable has an overhead cost, but assigning it in the editor is free, it just gets created with those values already set
no reason not to learn good practices early
youre asking too much
it introduces some complexity (what's an attribute? how do i expose public stuff then? how do properties work?), imo for an absolute beginner they have other things to worry about
not really, there's already 2 other things called Random, you'll be confusing yourself
In the file
ignore the folder they are in for a sec, the script is not called random, that was the original name
ive reloaded this project like 5 times now and the component name doesnt update
the file isn't called random, but the component is
you have a class Random : MonoBehaviour in there
ahhhh
cheers
i didnt realise the class was called that lol, 100% see the issue now
kind of an unfortunate naming thing
the class and file are separate entities, but "script" can refer to either depending on context
(only in unity/this kind of context though afaik, normally we don't call classes as scripts)
Hello
I've been struggling a bit with Enums, I tried to search for answer but never got one that worked for me so I'm trying here hope this is the right channel
I have a scriptable object, that old an enum where the value can be selected in the inspector
in another scripts I'm trying to get this "selected value" to, then, start a switch statement depending on said "selected value" (integer)
I can't find a way to solve this, am I missing some basic understanding of enum ?
we dont have native class support in luau so this is all new to me
Or serialized get, private set auto properties 😄
just trying to help you so you don´t get confused later that is why i said that you should be careful with the naming. quick tip: if you rename your class inside your IDE unity will also rename the file inside unity (at least with vs2022)
solve.. what exactly? you didn't actually say what the issue is lol
thank you for bringing that up btw
field-serialized get, private set public auto properties
gotta make it longer
trueing
does monobehaviour tell unity that this is the class we want this component script to be
is that exposing the field to the inspector?
unity just looks for all classes that inherit from MonoBehaviour to make them available
It is making yur IrSeekerRendererBehaviour an extension of MonoBehaviour, which is itself an extension of Component
I don't know how to resume it better
I just don't know how to get a selected value from an enum, that's my problem
oh so class : class is an inheritance thing?
yep
Same as any field, you read it from the instance
epic
Further reading: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/inheritance
Ye
[field: SerializeField] MyType MyName { get; private set; } will serialize the backings
do you still not need public there to expose the property to other classes?
[field: SerializeField] public MyType MyName { get; private set; }
yeah
but like, you don't always do that
well yeah, only if you want it exposed
A private property with no implemented getter or setter seems like it should just be a field, honestly
could be protected 😄
or internal 😏
Yeah, protected makes sense. Private, specifically, doesn't make sense
what is an assembly when it comes to this internal keyword stuff
is that sort of like the stack of classes
it's basically just a group of files that form a self-contained unit
don't worry about it at this stage
In Unity, it's files all contained by a single Assembly Definition
https://docs.unity3d.com/2020.1/Documentation/Manual/ScriptCompilationAssemblyDefinitionFiles.html
What I don't understand is that Enums seem to be Types
which doesn't allow me to get value from the enum when I'm trying to pass it to a variable in another scripts
Then how do I get the value of my enum If I can't pass it into another variable ?
You first declare your new enum type, then you need a instance of the enum:
public enum MyCoolEnum
{
A, B, C
}
public class CoolObj : ScriptableObject
{
public MyCoolEnum coolEnum;
}
They are types. You make a variable of the enum's type and you can set that variable to one of that Enum's values
it sounds like you're conflating the type vs a value of the given type?
consider like, int
0 is of type int, but you don't really get 0 from the int, you just, get the 0
an enum type is just a set of names for a set of ints
Yeah, you make a variable of type int with a value of 0. You don't make a variable of type 0
Is this how you do a boxcast? just wanted to know if I did it right and it does work.
no errors, so yeah?
might not do what you want it to do if you pass args in the wrong order
this kind of question is what docs are for
Check the docs. If those are the values you want to pass to those parameters, then it's probably good
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Physics.BoxCast.html
probably shouldn't hardcode boxSize though
What's the point in putting field: before SerializeField?
Allows you to set it in the editor
Yeah but you dont need field for that
yes you do
properties aren't fields
Then what do you mean by set it
...set it
the field: means to apply the attribute to the automatic backing field
Sorry are you saying that the get makes you unable to see it in the editor without the field?
You cannot set a propery in the inspector without [field: SerializeField], even if it's public
Huh
for this kind of terrain how should I proceed to reduce lag ?
+ public Type field; // works
+ [SerializeField] Type field; // works
- public Type prop { get; set; } // doesn't work
- [SerializeField] Type prop { get; set; } // doesn't work
+ [field: SerializeField] Type prop { get; set; } // works
(please don't format your code like this, i'm just doing it to compare)
Ahh no wonder i was confused never tried to make a { get } be seen in the inspector
it's called a property
Sure sure
a getter is a specific component of a property
wait what's the difference between the last two even? what does adding field: do the other one doesn't?
it makes it work
SerializeField works on fields
field: before the annotation means to apply the annotation to the backing field
without it, the annotation is applied to the property
It applies SerializeField to the backing field of the property instead of to the property itself.
without automatic backing fields, it'd look something like this
[SerializeField] Type m_Field;
Type prop { get => m_Field; set => m_Field = value; }
but with an automatic backing field, you can't see the supposed m_Field, so that's what the field keyword does
the field keyword also works in the accessors, but not in unity's version of c#, iirc?
i see.. yeah
is the serializedfield of the autoprop then named (in inspector for example) the same as the prop?
probably?
Be smarter with how you render this many meshes. Thats a crazy amount of batches. are these all mesh renderers or are you using draw indirect?
props are just methods that act like fields, if you cause an error in them the stacktrace shows a get_name/set_name method, so i guess the field would be something along those lines
good enough
thx for the explanations both of you
The batch count is high sure, but the saved by batching count is crazy. Are all of those blocks separate objects or something?
yeah im asking how can I be smarter, they are all mesh renderers and individual prefabs
I wanna achieve this
yea thats a very bad way to do this. You need to use something like draw indirect to cheaply draw your cubes or at least enable gpu instancing on the materials.
You probably need to use chunks like minecraft to better manage collision and the mesh drawing
I thought unity did instancing automaticly
didnt know there was another layer of optimisation
Instancing helps, but it's not a silver bullet
yea its not good enough for this many meshes
Should look up how minecraft does it
so the idea would be to make cut the terrain by chunks and merge them as one mesh
Despite what Minecraft's aesthetic might make you think, a fully voxelized terrain made of cubes is stupidly difficult and incredibly performance intensive
yea its one method, it helps with collision and culling but how the chunk itself needs to avoid a gameobject + mesh renderer per block.
ill look into minecraft but I think its harder to achieve
https://docs.unity3d.com/ScriptReference/Graphics.RenderMeshInstanced.html and https://docs.unity3d.com/ScriptReference/Graphics.RenderMeshIndirect.html exist to let you draw many instances of a mesh with instancing data and avoid extra overhead from many go instances
open a thread in #1390346827005431951 to ask more
why does this set all line renderer positions to the exact same position ?
I bet your i / samples is int/int
haha yea its a common issue that trips me up still
anyone know why im getting this? the issue has to do with the wall touch part
Something on the line the error is on is null, but you're trying to do something with it anyway
If this is the line the error is on, either playerAttributes, WallTouched, or WallTouched.WallTouch is null
its defo either wall touched or walltouched.walltouch
So use some debug logs and find out which
when i do find out which is null what do i do from there
Make it not be null
or check for it being null before you try to use a property of it
If it is supposed to sometimes be null: Check that it's not null before you try to use it.
If it is not supposed to sometimes be null: Give it a value
ok
Yeah no I already knew that I just explained my problem like an idiot sorry
I know enum is the type, what I wanted to say is that I can't find a way to access the data of my enum variable cause VS Code keep telling me that my enum variable is a type, which is not valid in the current context
I'm just trying to get the selected value of my scriptable object instance , like I have a toolClass scriptable Object, which contain a ToolType enum, and in an other script I want to get the enum result of the Scriptable Object instance Sword (_itemReference) which inherit from toolClass
but I don't know how to do it
the solution that gave rob5300 don't seem to do the job since I want the value of the enum to be set by the scriptable object instance when user select the setting in the inspector,
maybe what I'm trying to do is not for what enum is and I'm just lacking basic understanding on how to achive my goal
Your switch statement would be a variable of type ToolType
not the ToolType enum itself
right you're still conflating the type and a value of said type
right now you're basically doing switch (int), that doesn't make any sense
wait hold on
the enum is ToolClass.ToolType...?
or what
what's the variable you're trying to read here
Looks like _itemReference is a variable of type ToolClass, and ToolClass contains an enum named ToolType
You wouldn't switch on the type, you'd want your ToolClass to have a variable of type ToolType
you can reference inner types through an instance?
The enum can be defined anywhere
No, that's why it's an error
oh, ofc. i assumed the error was just about it being a type
It's probably got multiple errors. I don't know which one would take "priority" over the other
@near junco answer this please
and I don't know if the compiler can show multiple errors on the same token
the enum is ToolType
_itemReference is just the Scriptable Object (of type ToolClass)
that doesn't answer my question
Okay, what variable do you want to check the value of?
what variable in the ToolClass class is of type ToolType that you are trying to read for the switch
ToolClass seems to have a serialized field of type ToolType. what's that field called
something like toolType?
I think i'm dumb
I keep trying to access the wrong stuff
no, you're inexperienced
we can't fix dumb, but we can definitely help fix inexperienced
I already declared my enum and I forgot about it
Yep, so you want to switch on toolType, not ToolType
(btw, convention is to name enum members as PascalCase as well)
I'm sorry I wasted your time this was such a small problem from me
yeah some people a long time ago taught me to always do the naming by starting with lowercase to avoid errors I never questioned it
but VS Code keep telling me to do Uppercase, it takes time to kill old habit
you'll get used to it eventually don't have to excuse yourself here
oh nah this was much more pleasant than.. other convos
some things are camelCase and some are PascalCase by convention, maybe you misremembered and generalized that advice
it's a convention, you are not required to do it (at least in your own hobby projects) BUT since everyone tries to adhere to these it makes it easier for everyone to read and just feel smooth ya know?
the most important thing in style is to stay self-consistent
the worst naming convention is m_ 🤮
can't check rn but when you set enums in inspector are they saved as int?
oh so you cant insert any infront
just gotta move everything else over
now where do i know that from
unity do it. old programs also do shit like b_ or i_
we have modern ide's so we dont need to name things like this anymore
Unreal still do it with their class names like AActor 😐
oh
that always read to me like people who make their discord names start with a ! so they show up first
xxXhunterXxx
i hate that class name 
it should be AnActor
🙂
you could specify backing values so the others don't move, fwiw
probably not a great idea, but doable
My brain always reads it like "Aaaaaaaa! ctor"
yeah i see.. can be easily avoided
mine thinks of A-Aron (key & peele)
there are in this server channel for helping like i publish a post and then you triyng to help me
sorry about the english
yes you can create a thread
how?
if you need help, first step is to !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
Hello people,
I am trying to drag a UI image:
public void OnPointerDown(PointerEventData pointerEventData)
{
dragStart = getMousePosition();
}
public void OnPointerMove(PointerEventData pointerEventData)
{
if(dragStart != Vector3.zero)
{
Vector3 mousePos = getMousePosition();
if (isDragging)
{
transform.position = mousePos;
}
else if (dragStartDistance <= Vector3.Distance(dragStart, mousePos))
{
isDragging = true;
}
}
}
Dragging too fast unfortunately causes the mouse to loose the ui-image, which stops the "OnPointerMove" from getting called.
any solutions to this, or am I forced to move the drag-logic into an Update method?
Setting the position directly should be as fast as it gets, and unfortunately trying to snap the transform back in the "OnPointerExit" didnt fix the issue.
Thanks for any help!
use the drag events instead of trying to do it yourself
Wow, changing from IPointerDown/move/up to these IBeginDragHandler, IEndDragHandler, IDragHandler
Did the trick, thanks!!
yay
100% agree
I cant get proper highlighting to work in .compute and .hlsl files
it works fine in .cs files
i checked the settings, error highlighting and squiggles are on for both
it just looks like this
better than plaintext but not that much better
when i instantiate a clone of an object, it no longer collides with anything
send a screenshot of the inspector of the cloned object
it looks the exact same as the original object
including the rigidbody and collider components?
yes
send a picture
wait no hang on
If I have three events, OnMovedLeft, OnMovedRight and OnMoved and I want to invoke OnMoved every time one of the others got called, is there a fancy way to "link" them?
var OnMovedLeft(...) {
OnMoved();
}
subscribe invoking OnMoved to the other ones
ah damn didn't know that works
I thought I can do OnMovedLeft += OnMoved;
but that doesn't seem to work, although it gives no errors
I guess it just adds any subscribers from one event to the other
you just need to invoke the event, OnMovedLeft += () => OnMoved?.Invoke()
right now yea you are adding the events, and i suspect OnMoved has nothing subscribed to it at that point
it seems like it's not transferring a variable
the clone doesn't have the same layermask
🤔
Not saying your wrong but doesn’t sound like the kind of thing that can happen afaik
well
i have an exact clone
and this ((layers & (1 << otherCollider.gameObject.layer)) != 0)
works for the original
but not for the clone
Not to nitpick your troubleshooting but your assuming the layermasks are different when so far what you've seemingly confirmed is that they inconsistently pass that condition
You should directly log both's layermask values in order to confirm said assumption
yeah, the last debug log returns false
no as in
Debug.Log("Original LayerMask Is: " + gameObject.GetComponent<Projectile>().GetLayerMask())
Debug.Log("Clone LayerMask Is: " + clone.GetComponent<Projectile>().GetLayerMask())
it just prints "LayerMask"
Add .value
It'll give you the layer mask as an int, but you can at least see if they're equal
im actually gonna fucking lose it, i broke it in a different way
😄
Just in general make sure to directly test/log the thing your troubleshooting so you don't invest in a false assumption
this debug log here is unideal because who knows what layers is, your assuming the clone is wrong because this failed rather than directly checking
big function called Set()
Which is called when?