#š»ācode-beginner
1 messages Ā· Page 26 of 1
If i understand correctly, say i make a SO of a bird, and make prefabs of different bird species based on the bird SO?
It depends how exactly you want to design it, but usually you can just use a single prefab and have a collection of SOs for species.
I think i got the gist of it. Tysm
It's a simple implementation idea assuming that the species prefab (components) doesn't change at all. Basically, you just load the data from the SOs for what type of species it should be and then populate it from them.
You can also make prefab variants, basically using that one specific prefab and overriding some values for when you do want to just input some data yourself. This idea works great for working on the scene, while the other idea is ideally for instantiating them directly with the SO.
There's a lot of ways about it.
whats the best way to make a 2d character check if its next to a wall?
most tutorials out there teaches how to use ray casts, overlaps circle and stuff but they always have blind spots where it wont check and covering them manually isnt very ideal, where/how can I learn the best way to do that?
Overlap shouldnt have blindspots
But if you want to use Unity's trigger collider methods: https://docs.unity3d.com/ScriptReference/Collider.html
overlaps don't have blind spots tho, it literally goes around your whole character. Maybe you mean it can get stuck on corners, etc, if checking for collisions when moving?
If so, there are some tutorials out there dealing with this
But if it's for checking stuff, if shouldn't have blind spots
Quick question for one of y'all, I made 0 changes to a script between yesterday and today and now the script is greyed out for all objects its on in the inspector. Does anyone have any ideas what that reason could be? I'm posting the inspector with a greyed out script vs non greyed. The code too. I'm sure the code is most likely idiotic since its essentially a single line but thats what (used to) works for me so I didn't want to change it. I will also post the code that is giving the error saying the greyed out script doesnt exist.
This was literally working yesterday but not today.
Didn't the name of the file change?
Or the class name
SwordDamage. Always
Are the 2 components on the first screenshot supposed to be "before vs now"? Or did I misunderstand?
No no, those were just on the same inspector of a sorta what a working one looks like (movement) vs not
And frankly I don't know where the checkmark went on the Movement script but I'm not too worried about that
Because you said "I'm posting the inspector with a greyed out script vs non greyed out", so I thought it was before - after...
Try dragging another SwordDamage script component on the GameObject to see if it appears correctly . . .
Yeah I worded it horribly
This says both SwordScript and SwordMovement. That can't happen unless you've renamed the class or file
I suggest you just remove the scripts from the object and re-add them
Oh I just noticed that. I don't know why it did that
The SwordDamage does not show correctly. Rename the script and file name of SwordMovement to be the same . . .
Damage and Movement are different scripts
I know . . .
Try reading the components. If the issue persists, share the whole script as well as a screenshot of the file name.
Make sure Movement has the same file name and class name . . .
Oh gotcha. Yes they are the same
Then drag the Damage script on the GameObject and see if it appears correctly . . .
Once again, Unity loves to do its own thing and managed to rename the class...
I have an error on every rand.Next(), how do I fix it?
SpriteRenderer Sprite;
class Random;
Random rand = new Random();
void Start()
{
Sprite = GetComponentInChildren<SpriteRenderer>();
Sprite.color = new Color(rand.Next(100, 201) / 255, rand.Next(100, 201) / 255, rand.Next(100, 201) / 255);
}
Care to share what the error is?
I don't have my computer on me, I will be able to tell after 30mins
Still getting an error when trying to now put SwordDamage onto the object. I'll put SS of the codes, filenames, and error of course, for both scripts.
And nothing on the console
class Random; what is this supposed to be
Do you have errors in your console?
no
class Random; doesn't make any sense. What is that supposed to be?
Why aren't you using Unity's Random anyway
Didn't catch it earlier, but did you change any class or file names recently. That's what the problem seems like . . .
I'd re-open unity to see if it fixes itself . . .
If you look at the top of the code SS it has the filename and I did reopen it but I'll do it again just in case
Random rand = new Random(); throws out an error otherwise.
Show us the relevant files in the project window and their inspectors. Vs code can sometimes lose sync with the project and show you things that don't exist.
Per Microsoft documentation on Random
yes
So you decided to fix that error by creating your own Random class
If you really want to use C#'s own Random class then you need using System;
Knowing what these errors were (are) would greatly help in solving the problem. My guess is it was an ambiguous error between System.Random and UnityEngine.Random?
but why use that when you have UnityEngine.Random
New skill acquired . . .
and the solution to the next issue is that you need either (float)Random.Range(100, 201) or Random.Range(100f, 200f) for the color to work properly
Didn't know that you could get future telling skills by developing your coding skills enough.
Solved my issue by deleting the SwordDamage script, creating it new and retyping. Maybe cause I didn't have a Start()? Either way its fixed so thanks yall
Start is unrelated.
I figured
Sometimes you have to recreate the script or the GameObject with the scripts attached to work. I was hoping to avoid that. Start is unrelated though . . .
Lucky enough it was my only code with 1 line of functionality
Configure your !ide first.
If your IDE is not autocompleting code
or underlining errors, please configure it:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code*
⢠JetBrains Rider
⢠Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Which is part of the problem, by the way.
Which was done when I initially installed Unity...
Judging by the screenshots you shared, this is not the case and something went wrong. Please follow the steps above
I did. And All of those setting, extensions, packages, are already installed and up to date.
Either way it doesn't make much difference to me as I don't think VSC can tell me that I need to delete my code and recreate it.
I say again, your screenshots prove otherwise. Your issue also suggests there is a compiler error which causes Unity to lose context. I expect your editor to provide this error if it's a runtim error, and I expect it to properly support the syntax of your code. It does neither.
It's required you configure your editor properly before you ask a question because your editor is made to provide you with errors it can find, and it does not do that currently
Then why does my code autofill with unity recommendations?
(genuine question not trying to be rude)
Either because it's partially configured or because it is a suggestion based on existing code
It's hard to tell with Visual Studio Code, and one of the reasons why you should not use it for Unity; setting it up is way more difficult than it should be
Most likely partially configured in that case.
I suggest you see about using Visual Studio
I just installed it, will look into it more tomorrow.
I have a Character gameobject that as a child has a healthbar gameobject
The character has a script Character that controls it's health
Do I add the healthbar as a variable (field?) in my character script and then drag it to link them?
Or do I use the GetComponent function?
Does it matter?
Generally best to inject those dependencies through the inspector whenever possible.
I usually expose fields for UI related stuff, but otherwise I'm usually just using GetComponent in their awake methods.
Why?
It's just cleaner on the editor.
For the UI however, they are usually composed of a larger hierarchy, so it's preferable that you just tell it where the references are.
If it's something that you are going to be instantiating a lot of - like say some prefabs. That's a situation where you could consider just assigning it on the editor.
Im using RecenterToTargetHeading with Cinemachine to recentre my camera. After I press the button the camera recenters as intended but after releasing the button my camera starts tilting downwards. What am I doing wrong?
You need to start by configuring your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code*
⢠JetBrains Rider
⢠Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
After that, the question might be more relevant to #š„ācinemachine
Is it ok to use the Find function when spawning a new monster so I can get it's healthbar in my combat script?
Or should I really avoid that function?
Find is useful for preload scene reference bindings like linking objects to game managers, or other similar related gameobjects. But other than that you want to reduce the amount of searching through the scene.
Ah nvm, apparently this works even if Slider is an object and not a component?
monsterHealthSlider = currentMonster.GetComponentInChildren<Slider>();
wait it is a component as well, so it's probably grabbing that
why doesnt it work :~?
Which can also be avoided by just using a singleton for these manager classes.
red squigly there
because you dont have a variable called y
ok ty
Is there a way to make a [SerializeField] read only in the inspector?
With a simple property drawer, yes. Eg. https://github.com/vertxxyz/Vertx.Attributes/blob/master/Editor/ReadOnlyDrawer.cs
Say I have if (Foo() || Bar())
Bar() isn't called if Foo() is already true right?
yes, that is correct
looking to make this code a bit more concise, and I got a little bug where Y was not handled if X was already handled. Thought it was that, but thanks for confirming it.
Any suggestions as to make this more concise? I'm not sure if method extraction using ref even makes more sense here than just duplicating the calculation code?
private void Update()
{
var screenMiddle = new Vector2(Screen.width / 2f, Screen.height / 2f);
var mousePosScreen = Mouse.current.position.ReadValue();
var deltaMouseToMiddle = (screenMiddle - mousePosScreen);
var dirMouseToMiddle = deltaMouseToMiddle.normalized;
var lookingAhead = HandleAxis(ref _transposer.m_ScreenX, deltaMouseToMiddle.x, screenMiddle.x, dirMouseToMiddle.x,
_minPercentFromCenter.x, _sensitivity.x, _minScreenOffset.x, _maxScreenOffset.x);
lookingAhead |= HandleAxis(ref _transposer.m_ScreenY, deltaMouseToMiddle.y, screenMiddle.y, -dirMouseToMiddle.y,
_minPercentFromCenter.y, _sensitivity.y, _minScreenOffset.y, _maxScreenOffset.y);
if (lookingAhead) return;
_transposer.m_ScreenX = Mathf.Lerp(_transposer.m_ScreenX, 0.5f, _smoothing);
_transposer.m_ScreenY = Mathf.Lerp(_transposer.m_ScreenY, 0.5f, _smoothing);
}
private bool HandleAxis(ref float screenPosition, float deltaMouseToMiddle, float middle,
float dirMouseToMiddle, float minPercentFromCenter,
float sensitivity, float minScreenOffset, float maxScreenOffset)
{
var percentFromCenter = Mathf.Abs(deltaMouseToMiddle) / middle;
if (percentFromCenter < minPercentFromCenter) return false;
screenPosition = Mathf.Clamp(screenPosition + dirMouseToMiddle * sensitivity, minScreenOffset, maxScreenOffset);
return true;
}
Why is this not allowed?
float b = 1.3;
because 1.3 is a double not a float
isn't a double just a larger number float?
Yes it is, that's why it's not allowed
1.3f is a float however
not quite but converting from double to float would require down casting and c# will not do that automatically
but 1.3 is tiny? why is it not a float?
Because it's a double
A doesn't have to be a large number. It just can be a large number.
the default type for numbers with decimals is double
A float has f at the end of it
hmm
If it doesn't, it's a double
that is like saying 1 is tiny so why is it an int not a byte
and then Mathf.Pow only works on floats, not doubles?
help
I must be doing something wrong
Mathf is Unityās math class for floats.
You can use C#ās math class for doubles https://learn.microsoft.com/en-us/dotnet/api/system.math.pow?view=net-7.0#system-math-pow(system-double-system-double)
Why don't you just pass a float to it then
yeah I guess that's easiest lol
anyone knows if by the time SceneManager.activeSceneChanged is called is next scene loaded and I can call scripts there or not yet
just trying to figure out if I'm doing something wrong or not
well it doesn't even compile so
yo idk if its a dumb question but i installed both unity and VS and i have configured it just like the tutorial said but now a few days later it stoped working( the autocomplt and stuff)
what am i missing here?
can someone help me my pc like 3 fps and ive waited 14 mins for code to run
This is not a coding question. Unless you know the related code you should ask a proper question in #š»āunity-talk
woudl be helpfull if you replied on how to cancel it
well I'm just smart enough to figure out to turn it into a float (which is why I was asking what a float was) š
just wondering why it's designed like that
plus i did
seems like by default it wants me to use Double, but then it forces me to use Float
š¤·āāļø
Unity compiling is not modifying your files, so you can cancel it with no risk
you are confusing 2 things. C# default is double but unity uses floats
The compiler can't make subjective evaluations like "this number is small so let's make it a float"
You have to tell it what data type to use
In the real world, most people use doubles. Floats (32 bit) are faster and more space efficient than doubles (64 bit) which is why they are used in game programming where the precision doesnāt matter that much and speed is pretty important
hey im making a undertale fangame and how to make player can only in my square sprite?
There's also very little reason to have a bigger number than what a 32-bit number allows. If you reach that limit you usually have the knowledge to extend it
is there any detection that is likey i can use it
It was just very confusing to me that you have to add the f for a float, never ran into anything like that in PHP or JS
C# uses doubles by default for literals because most computers these days are 64 bit.
Floats are more of a specialized data type now for special applications. Unity happens to be one of those
PHP and JS don't have separate data types for float and double
yo my bro please add me as a friend
???
!warn 613067723551014912 do not use this discord to randomly solicit friend requests
verletswing has been warned.
@daring sinew hello I see you are making a 2D drag racing game, I am also in the process of doing so and there is 0 info online relating to helping me make this, unfortunately you have your dms and friend requests turned off so reply to this so we could hopefully talk about this thank you
is that message okay?
I meant the one I just sent
- ⢠@ or reply to people not in the conversation. Use common sense here, please.
thanks for sending context, i was very confused and annoyed by that random ping, i can help you out.
sorry mate I was just very surprised that someone has messages about the exact topic I was looking for
And I just kinda typed really fast and pinged you my bad
Just wanted to send a thanks for your suggestion ā¤ļø I got it working in about 1.5 hours. š
i see
If you wanna talk here we can or DMs I donāt mind
how far have you gotten with your game
car mechanics, speedo/distancemeter stuff, etc
what are you capable of doing?
ahhh so youāre pretty damn good at coding then
pretty new but eh
not much tbh š Iāve got a car that accelerates and stops
but canāt figure out now to do grip
I tried adding mass or drag as online people have posted about that but it doesnāt really works
Yet to wrap my head around adding vehicles upgrades and mods
Perhaps use physics materials?
maybe Iām a mooron but I thought drag and mass was under the physics materials thing
same, but it should be simple to add more cars, unsure about upgrades/mods, idk how to make saving system yet
Yeah I saw you posting about that
I thought it was under rigidbody no?
All this stuff is actually so confusing
indeed
I was adding mass to the wheel collider
JSON reading and writing
yes, but i dont get it
how have you done gears and stuff
yes
I see, try adding a physics material and mess around with the friction values
i have manual gears done
very nice
I downloaded a 2d drag racing game on GitHub and they have car mods I think
Maybe Iāll try learn from that
i misread, i used chatgpt and edited the code a lot
i just needed acceleration, not manual gears
it honestly sucks most of the time
i had to edit the code a lot to fix it
Did chatgbt give you the gears and stuff
Itās a great tool if you know how to use it. Itās good for helping with and debugging code, but itās not good at writing it
Hello! I am watching a video and when writing a code on visual studio https://prnt.sc/MK2bGBoEad6p this thing under the code comes up to help complete the code faster, but when I'm using visual studio I am not getting the same thing under the code, without it I am usually spelling something wrong https://prnt.sc/UXPkY_spgN7v . How can I fix this?
yes, but i could have done it myself already
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code*
⢠JetBrains Rider
⢠Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Is your IDE configured?
how long have you been making this project and coding because Iām trying to get an idea of now difficult this will be
I have some amazing ideas for the game but the only thing holding me back is having the basic things coded
like driving and gears
I don't know what IDE is
I can do the rest like scenes and etc etc
@open apex
I would he happy to help either of you if necessary. Iām burnt out from working on my own projects but Iām always happy to help with other peoples work
Thank you so much bro thatās very kind of you
maybe at some point we could great a group chat or something
added you
sure
could we 3 make a group or?
Send me a friend request rq
Yeah Iāll set it up
Or you just configure the IDE you are already using
instead of downloading a different one. Though VS Community is better, you should download it via the Unity Hub if you want to use it
Community
ok
Yeah
Iām leaving collage now to catch bud
Bus***
Will send my code when Iām back so you guys can examine it if you want
Could/should I use a "ulong" instead of "double" for my experience system? numbers should all be integers
What is the largest number that the experience system needs to handle?
just download community edition then follow the steps in #854851968446365696 to set it up for unity, that's what I did
2.231.401.599.869 for now š
I mean for now even a regular int is probably fine, but I dunno where my game might go after some updates
Things like serializing can get annoying with the more exotic data types so you should really consider if you really need that big numbers or if you could change the design
so long is probably better? or just keep double?
int is better
But if that's not big enough then it doesn't matter if it's long or ulong
Double sounds better for my experience system though
don't really care about the precision that much once the numbers get really big
float is probably fine too
u can make ur own type like one int stands for how many max integer limits u reached and another as progress towards another limit lol then u can go into gazillion billion trillions or whatever
I'd rather just keep it simple lol
yea for the record my idea was stupid I found out theres BigInteger with seemingly no big catch to using it
yeah saw that somewhere as well, but still too much for my current game
If you need ints bigger than max int, then you don't really have any other options
YES MR WHITE
I think I did it B)
does it save automatically?
is there a save button?
(the settings)
I did it š
Thanks for the help yall

I had the same problem and just came to check out the unity discord server and dam. That solved my problem lol
I don't know what I would have done without the help I have got
(probably cry š )
Lol yea I spent like 2 and a half hours just setting up unity cause of the file location. I could not get a project open lol. Eventually I learnt that I coulda just changed the whole file location in 5 mins.

:DD
Is it possible to add 2 events on 1 line to a Button.OnClick.AddListener?
wdym two events ?
pauseMenuManager.forwardButtonPM.onClick.AddListener(() => StartAssigment("forward"));
pauseMenuManager.forwardButtonPM.onClick.AddListener(() => SendText(forwardText));
This is what I got now, so then is it possible to combine it by adding the sendtext part to the first add listener
to make it more compact, less lines of codes
put them in the same method instead of anonymouse function
What do you mean "instead of anonymouse function"
Make a method with the StartAssignment and SendText calls in it. Subscribe just that method.
You are creating "anonymous" functions by writing () =>
pauseMenuManager.onClick.AddListener(MyMethod);
}
void MyMethod()
{
StartAssigment("forward"));
SendText(forwardText));
}```
That's not going to work sadly with the way I have made my script
Or I would have half to remake half of my entire script
how so?
How could that be possible? You would only have to add something
StartAssignment uses a string to find the name of a key. Those strings are connected to the buttons you click on. That keyname is used in a switch case, to see which keybind has to be changed.
So have the method take a parameter of the button name
Nope
Not the button name, a string which is being used for a switch case.
try
button.onClick.AddListener(() => { MethodA(); MethodB(); });
Thanks!
how would that make any significant difference to what was suggested. Anyway you can use what SteveSmith sent,
You can't unsubscribe/remove listeners this way
I meant a string that represents the button name, like you had before....
is there a method header comment assist like in IntelliJ with Java for VS with C#? in IntelliJ typing "/**" then pressing enter sets up a header comment for you
use /// to create a summary comment
is header like above everything for stuff like author
I dont think that achieves what I want though unless i'm using it wrong
/// <summary>
///
/// </summary>
/// <param name="ok"></param>
public Test(bool ok)
this is what I mean
just write /// as he said and it will make the template for u
upon typing "/**" followed by enter it fills in all the params and return for you
use /// to create a summary comment
pretty sure that's JavaDoc-specific styling
you just have to add the descriptions
/// does that
C# uses summary comments with XML markup
VS should be able to generate the comment for you based on the method.
Before typing ///:
VSCode sure does.
After:
I should really use these...
hm maybe it's because most of my variables are declared outside the methods
well, then, yes
those aren't parameters
so they won't appear in the list of parameters
Javadoc wouldn't get those either
yeah sorry, complete dumb moment from me
ty for the "///" thing though, didnt know abt that
You can also attach these to fields
or, more generally, any class member
it goes before the attribute, which results in an annoying ordering here
yeah i find it much easier to reference those types of comments than to just spam inline ones
especially since they are readable from outside the class istelf if the method is used, at least that's how it works in IntelliJ with java
my experience is 90% IntelliJ with java so that's all i have to pull from
hopefully, fields don't require a long diatribe to explain
working within a team of people with very different styles of thinking is difficult, just trying to find ways to make communication on my methods easier
Oh yeah, definitely work on filling out those summaries.
More weird noob questions š
I have a Character script that tracks all my character stuff, like stats
There are several buttons that each increase a specific stat
Is it bad to set a reference on each button to my character script in the editor?
(and maybe get more aggressive with your access modifiers)
If you have LOTS of them, it would be worth automatically creating all of the buttons from a prefab.
nah just 3
But I see nothing wrong with having a couple of buttons you have to manually reference.
are you saying setting everything to public isnt smart 
I'm just not used to draggin stuff like you do in Unity and it doesn't make a lot of sense to me
To me it feels like I'm copying my character script on all the buttons
You're referencing the Character component.
Whenever you drag something into a field in the inspector, you're referencing it
a reference isn't a copy; it's just saying "i use that object over there"
Does it matter if I drag it from my Hierarchy or from my Project folder?
ah that make a lot of sense š
Yes. I presume you're talking about the UnityEvent "on click" field on the button?
yeah
you're targeting whatever you drag in there
If you drag a script asset into it from the Project window, you're trying to target the script asset itself
which is not what you want
Those are two different objects
You want to tell a specific instance of the player to increase their strength stat by 1
The script asset is used by Unity to track which script file is responsible for which component
So I want to drag the script reference on my character onto them?
Correct.
cool, thx a lot š
you would also not want to drag in a prefab with the character component on it
that would be less wrong (it'd indeed be the actual character component, not the script asset for the character component)
but you would be changing the stats of some prefab that doesn't even exist in your game
instead of, you know, your actual player's stats
i meant that its format is just not ideal at least for my character, i wanna check if its touching a wall and have a different checker for each side,
if I make the circle overlap too big i end up checking too far from where my character actually is, and too small makes some areas where my character may touch a wall where the circler overlap doesnt cover for not being big enough if you know what I mean,
i could make multiple overlaps to cover the height of my character but sounds a bit unpractical so I wanted to know if there was a more ideal way
thx ill check it out
Perhaps you would also be interested in using different shapes. I get what you mean about the circle being too big/small when trying to get it to work
Instead try a overlapcapsule or overlapbox
That could give you a lot better coverage the way you seem to want it.
is this how a summary should look?
/// <summary>
/// This method sets the numbers for the choices box the script is attatched to, additionally it makes sure that none of the numbers in the duplicates parameter are present in this choices box <para/>
/// <paramref name="duplicates"/> -
/// This parameter is the list of duplicates for the two other choices boxes in this column
/// </summary>
public void SetNums(List<int> duplicates) {
you should just use <param> to list the params out
I dont know where you get <para/> from. Parameter definition should end with </param> as show in the 2 examples above
<paramref> is used to reference another parameter in your text
@obtuse oar #š»ācode-beginner message
oh okay, i just let it autofill the "paramref" thing, was an option after typing "pa" lol
The entire thing should be auto-generated for you after doing ///
it did not auto generate the first time, that's odd
worked this time 
Should I put summaries on classes as well?
I suppose it's nice to explain why something exists.
You should talk with your team about what they would find useful
ic, perfect, I should have thought of that beforeš¤¦āāļø
is there a debug function for me to measure its size in game?
or some other way for me to make it match my player's size?
Gizmos.DrawSphere/DrawCube/DrawWireCube etc.
If youre talking about physics.overlap
goin through and commenting made me realize how inefficient this method looks, any ideas on improving this?
overall goal of the method, which is on a button, determine if the button is an up button or a down button. Then just adding functionality to have the numbers roll over from 0-9 since this is for incrementing a single digit box
private void OnMouseDown() {
if (Up) {
if (selection_Box_Controller.currNum < 9) {
selection_Box_Text.text = (++selection_Box_Controller.currNum).ToString();
} else {
selection_Box_Controller.currNum = 0;
selection_Box_Text.text = selection_Box_Controller.currNum.ToString();
}
} else {
if (selection_Box_Controller.currNum > 0) {
selection_Box_Text.text = (--selection_Box_Controller.currNum).ToString();
} else {
selection_Box_Controller.currNum = 9;
selection_Box_Text.text = selection_Box_Controller.currNum.ToString();
}
}
selection_Box_Controller.CheckNum();
}
Add or subtract based on the button, then set the number to that number mod 10, then set the text
would that work for negatives?
I believe so, but I've just rememberd C# doesn't actually have modulo, it has remainder so let me double check
that's a smart way to go about it though, that didnt even cross my mind lol
No, it does not. So you'd do (x + 10) % 10 to un-negative it
gotcha, thanks
private void Move()
{
Vector3 forward = transform.forward;
float currentYVel = _rb.velocity.y;
Vector3 newVelocity = transform.forward * _moveSpeed;
newVelocity.y = currentYVel;
_rb.velocity = newVelocity;
//_rb.velocity = transform.forward * _moveSpeed;
}
I am kind of confused how this method works. Can someone explain please?
What do you not understand about it
The part why we play on the y velocity
It stores the previous Y velocity and then makes sure to keep that value when it sets the velocity again
Otherwise it'd become 0
float currentYVel = _rb.velocity.y; this is where we store the previous velocity then?
yes
Why then we Vector3 newVelocity = transform.forward * _moveSpeed; do this
what is the point of setting a new velocity?
...to set the velocity
If you want to set the velocity to a vector, that vector needs to exist
That's how you assign a variable
I notice the first line isn't even used.
transform.forward is used even though it's cached as forward
So that is one extra variable that I guess is unnecessary
ah yes I know. It just felt overwhelming assigning variables that much.
Ahh okay thanks.
I didnt have to make them local variables right?
public class PlayerPreview : NetworkBehaviour
{
private NetworkVariable<int> skinColor = new NetworkVariable<int>(3, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable<int> eyeColor = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable<int> hairColor = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable<int> hairStyle = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable<int> outfit = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
[SerializeField] private Image skinImage;
[SerializeField] private Image eyeImage;
[SerializeField] private Image hairImage;
[SerializeField] private PaperDollImage hairDoll;
[SerializeField] private PaperDollImage outfitDoll;
[SerializeField] private PlayerTexturesScriptableObject textures;
public override void OnNetworkSpawn()
{
skinColor.OnValueChanged += SetSkin;
eyeColor.OnValueChanged += SetEyes;
hairColor.OnValueChanged += SetHairColor;
hairStyle.OnValueChanged += SetHairStyle;
outfit.OnValueChanged += SetOutfit;
}
public void NextSkin()
{
skinColor.Value = (skinColor.Value == 16) ? 0 : (skinColor.Value + 1);
}
public void PrevSkin()
{
skinColor.Value = (skinColor.Value == 0) ? 16 : (skinColor.Value - 1);
}
public void SetSkin(int previous, int current)
{
Material mat = skinImage.material;
mat.SetFloat("_Current_Palette", (float)current);
}
...```
when I set material properties like this it affects all instances of the prefab. i want it to only affect the calling instance instead. how do i make the material unique?
I guess so. But they make the most sense as local variables as written
Since they are only used right there, correct?
Then yeah, they should be local
Thanks a lot š
You can Instantiate a material to make a copy of it.
You can then assign that copy into the material property
I'm brand new and trying to figure out how to do referencing properly
Wondering if I can get some help?
Essentially, I have a moving platform and a player character that has an empty object at it's feet I use to detect the ground.
I want to add a script to the groundcheck to see if the object it is colliding with has the tag "MovingBlock", and if it does, to then add the blocks velocity or such to the player character's
Because atm, my character just slides off the block if I put him on one
This is the start I have at the moment
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.name == "Ground Check" &&)
{
// Add this object's velocity to player
}
}
Currently, you're checking if this object is colliding with an object named "Ground Check". Is that what you want to be checking for
thank you! so as a quick test i did this and it seemed to work:
public void SetSkin(int previous, int current)
{
Material mat = Instantiate<Material>(skinImage.material);
mat.SetFloat("_Current_Palette", (float)current);
skinImage.material = mat;
}
my concern is i'm creating a new material with every change and I assume that is wasteful af. i assume better practice is to give each prefab a unique material at the start of the scene then set them how i was before?
Ah no, that's a mistake, I was meant to put compareTag and MovingBlock
Just make it unique once
e.g. do it in Awake
got it thanks!
Hey
Hello, I am confused:
When I perform 'Physics2D.IgnoreCollision(object 1.GetComponent<CompositeCollider2D>(),object 2.GetComponent<CompositeCollider2D>(), true);' collisions always occur.
However, the same problem exists if I enter rather 'BoxCollider2D' or any other Collider2D.
Thus, only 'CompositeCollider2D' to the problem, I can however not use anything other than 'CompositeCollider2D'.
Do you have an idea?
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.CompareTag("MovingBlock"))
{
// Add this object's velocity to player
So I have the player character named "Player"
The empty object called "Ground Check" at Player's feet
And a bunch of platforms where I have made one specifically, move around and given it the tag "MovingBlock"
I want "Ground Check" to detect the tag, then copy the movement of the block and add it to the Player so that they don't slip off and can just stand still
First off, if you want this to be firing constantly while the platform is in contact with this object, you should use OnCollisionStay instead of OnCollisionEnter, which fires only once when they start colliding.
Then, you could get the velocity of the collision object and add it to the velocity of your player.
Do yall know that in the 2d pokemon games you can tap any direction slightly just to change the direction the player is facing wihtout walking?
how can i implement that into my player code?
using System.Collections;
using UnityEngine;
public class Player_Control : MonoBehaviour
{
public float MovementS;
public bool MoveIsTrue;
public Vector2 input;
private Animator animator;
public LayerMask SolidObjLayer;
public LayerMask InteractableLayer;
private void Awake()
{
animator = GetComponent<Animator>();
}
void Update()
{
if (!MoveIsTrue)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
if (input.x != 0) input.y = 0;
if (input != Vector2.zero)
{
var PlayerPos = transform.position;
animator.SetFloat("MoveX", input.x);
animator.SetFloat("MoveY", input.y);
PlayerPos.x += input.x;
PlayerPos.y += input.y;
if (IsWalkable(PlayerPos))
{
StartCoroutine(Move(PlayerPos));
MoveIsTrue = true;
}
}
}
animator.SetBool("MoveIsTrue", MoveIsTrue);
}
IEnumerator Move(Vector3 PlayerPos)
{
while ((PlayerPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, PlayerPos, MovementS * Time.deltaTime);
yield return null;
}
transform.position = PlayerPos;
MoveIsTrue = false;
}
private bool IsWalkable(Vector3 PlayerPos)
{
if (Physics2D.OverlapCircle(PlayerPos, 0.2f, SolidObjLayer | InteractableLayer) != null)
{
return false;
}
return true;
}
}
Sorry idk how to put code in discord
!code
š Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
thx
Thanks for the info on the Stay š
In that case then, my first thought is
collision.gameObject.velocity but I can't use that since it says that the GameObject doesn't have a definition for velocity.
How would I go about referencing for the Player and the thing it is touching?
Sorry for these stupid questions, I'm really new
GameObjects don't have any property named velocity. What "velocity" means depends on how you are moving
if you're using rigidbodies, Rigidbody has a velocity property
using System.Collections;
using UnityEngine;
public class Player_Control : MonoBehaviour
{
public float MovementS;
public bool MoveIsTrue;
public Vector2 input;
private Animator animator;
public LayerMask SolidObjLayer;
public LayerMask InteractableLayer;
private void Awake()
{
animator = GetComponent<Animator>();
}
void Update()
{
if (!MoveIsTrue)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
if (input.x != 0) input.y = 0;
if (input != Vector2.zero)
{
var PlayerPos = transform.position;
animator.SetFloat("MoveX", input.x);
animator.SetFloat("MoveY", input.y);
PlayerPos.x += input.x;
PlayerPos.y += input.y;
if (IsWalkable(PlayerPos))
{
StartCoroutine(Move(PlayerPos));
MoveIsTrue = true;
}
}
}
animator.SetBool("MoveIsTrue", MoveIsTrue);
}
IEnumerator Move(Vector3 PlayerPos)
{
while ((PlayerPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, PlayerPos, MovementS * Time.deltaTime);
yield return null;
}
transform.position = PlayerPos;
MoveIsTrue = false;
}
private bool IsWalkable(Vector3 PlayerPos)
{
if (Physics2D.OverlapCircle(PlayerPos, 0.2f, SolidObjLayer | InteractableLayer) != null)
{
return false;
}
return true;
}
}
```cs
Listen, I realized I didnāt put my Collider2D in the composite. Have a good evening and I apologize.
Do yall know that in the 2d pokemon games you can tap any direction slightly just to change the direction the player is facing wihtout walking?
how can i implement that into my player code?
Oh right
So basically, the block is just moving between two waypoint objects that I created. So it is using transform.position and Vector3.MoveTowards
This is the waypoint code I have on the block
public class WaypointFollow : MonoBehaviour
{
[SerializeField] GameObject[] waypoints;
int currentWaypointIndex = 0;
[SerializeField] float speed = 1;
// Update is called once per frame
void Update()
{
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
{
currentWaypointIndex ++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
}
}
You using the new input system or the old input manager?
Sorry for stupidity but how do i check that?
Do you have a action map in your project?
@sand stump
Or input map, forgot what it's called
So it looks like you're going to have to use math to figure out this object's velocity since you're basically doing consistent short-range teleportation every frame
Does an object with rigidbody that is standing still on the ground has a negative y velocity? because of the gravity?
It should, so it remains in contact with the ground instead of hovering just above it
Do you have a window that looks like this in your project?
hmm okay. is it common practice to store the y velocity before doing something to preserve it?
You would have to actively choose to use the new input system.
so, by default, you will be using the old one.
Not the words you usually wanna hear š
But yeah, I would be open to trying methods for this, but the last method I had involved making the player a child of the block so it would move with it.
That caused issues with transformations though and the player model would just stretch out
Okay, so what I would personally recommend is to use the input system, you do that by installing the package for it in your package manager
ok , imma install that one sec
But, if you don't wanna do that for whatever reason, basically what you want is to make the first like, 0.1 second of holding a movement key just change the players direction, and if they hold that key, they will start moving
You could use Rigidbody movement for the platform as well as the player.
I'm not sure I'd leap straight for "learn the new input system"
So wheres the package manager?
I would go and look at some docs on how you cna do that
I gotta go back to work so you'll have to ask someone else, apologies
All you need to do here is to add a slight delay before your movement input actually causes the player to start moving.
Its ok buddie, have a nice one
void Update() {
bah
ipad keyboard moment
actually, I won't write out code just yet.
LoL relatable
The big idea is:
Ok dw
i think my shift key isn't working..
If the move input is zero, reset a counter to a small value (maybe 0.2)
If the move input is non-zero, subtract Time.deltaTime from the counter
Use the move input to rotate the player
If the counter is less than or equal to zero, use the move input to move the player.
Ok i think i got it
Yeah
In that case, you probably want to move instantly if you're already facing the right direction
exactly
Perhaps by setting the counter to 0 if, on the first frame that you try to move, you're already facing the direction you want to move
Ok, ill search on how to do that
is there any way that i can reference a scriptableobject and make adjustments to one of its fields without changing the base asset, similar to a prefab?
You could create a copy of it with Instantiate
this is all done at editor time
Dont matter
Or use ScriptableObject.CreateInstance<___> with whatever type
are you trying to make a new asset?
Just remember to DestroyImmediate it in OnDisable or something, so it doesnt leak
if you don't want it to clone an existing one and instead be whole-cloth new
i want to make the adjustments at editor time though, so how would i serialize and save these changes so it takes affect at runtime?
You want to save it to a diffeeent asset?
think of how you can drop prefabs into a scene but modify some of the fields without changing the values on the base prefab
sort of like that
dont know if its possible with SOs
The instantiated SO needs to be saved somewhere
Not sure if it gets serialized if you put it on a field on a gameobject, maybe try that
hmm ill have to experiment then
Instantiate, modify, assign to a serialized field
at least with the way that i know how prefabs work is that if you reference a prefab then make modifications to that prefab via inspector, it serializes ONLY the changes and fetches all the other values from the base prefab
Ah yeah, SO does not support that really
ahh alright
It would be dope though
yeah thats pretty much what i was wondering since ive never seen that behaviour
yeah for sure
maybe ill work on a plugin for that in the future
The closest I have seen to that is the Volume framework
Where you can override or not override parameters
havent seen it before
huh, ive never seen it, is it on URP?
that workflow i mean, ive used those assets ofc

https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.1/manual/VolumeProfile.html
I think it can be used for custom stuff too, not just post processing
I might look into it myself too
huh, cool
hello, i want to start coding again, i updated my visual studio, but idk what to download now so i can edit / make C# scripts for unity. thanks for help
Stop crossposting
You were given the resource to figure this out twice
#archived-code-general message
Read it.
dw prettyy soon they gonna post another in #archived-code-advanced
is there any benefit to a switch statement vs if else when there's only two options? like for a single bool
no
iāll do that only if Iām expecting my if to become a big switch case in future
How does Rigidbody.MovePosition work? Does it teleport my rigidbody there with all the colliders? Does it stop my rigidbody early? does it move other things out of the way etc?
negative
all i see is that moveposition normally moves things smoothly
thank you
2D or 3D?
but itās hard for me to see if colliders are getting moved as a result of MovePosition, or afterwards in physics simulation step
2D
are you having an issue or something ?
Iām trying to figure out how different steps will work together in terms of script execution order
i have a motor which moves a platform, and the platform moves an enemy. And these happen on different parts of a frame, so I want to understand how they affect each otherās calculations
my main issue right now is if the enemy falls onto platform while it is moving down, they donāt connect. He stutters in the air (like the platformās collision held it at its old position), and platform keeps moving.
so it is super janky
make a prefab variant
hmm how does it move down?
MovePosition
made my red cube fall onto a white cube with MovePosition
lift is parented to motor, and motor uses MovePosition
well, here is where it gets tricky: When the enemy is in contact with the lift, I move the enemyās transform
hmm already higher drop it moves weird
Ohhh
I basically calculate how much the lift has moved since last frame, then transform.Translate by that amount.
RB.moveposition doesnāt work for me there
Translate might be messing with the accuracy of positions of the rbs
and the lift doesnāt have a defined velocity (since it is just moved by moveposition), so I canāt copy velocity differences over
Is there some code to go along with this?
there is a lot of code. Iām sparing you the details
I have like 4 relevant scripts here, all of like 300 lines
We would only need to know the implementation of movements
but it all comes down to a few critical lines at the core
Else we're guessing without being able to see what's actually happening
enemy has a ReferenceFrameHandler component, with early execution order. ReferenceFrameHandler uses Transform.Translate to move the enemy by how much the lift has moved last frame. And it usually works really well
motor moves by MovePosition
Lift is parented to motor
i tried all sorts of things to set parents etc, joints, or rigidbody.MovePosition to couple the enemy motion, but nothing really worked. Only moving the transform worked.
idk maybe using synctransforms after using translate will work
i would love if there were just a joint that just sent movement of one object to another, while not contraining it
It would be some custom game physics and not necessarily Rigidbody/Kinematic physics.
switch statements are kind of weird in general
despite looking like separate blocks (because you have many statements that end in a break, and you indent them all), it's all one big block
bool what = Random.value < 0.5f;
switch (what)
{
case true:
int x = 3;
break;
case false:
int x = 3;
break;
}
This will cause a compile error because x is declared twice in the same block
you can scope within a case to avoid that
bool what = Random.value < 0.5f;
switch (what)
{
case true:
{
int x = 3;
break;
}
case false:
{
int x = 3;
break;
}
}
I like to do this nowadays.
Yep.
Block statement in each case. Horrific indentation, though.
I think I can configure that...
I use these to implement simple state machines.
i am a diehard K&R fan, this hurts me greatly
after a while you dont even notice the braces , it looks like intents to me š
The alternative if-statement would be: cs bool what = Random.value < 0.5f; if (what) int x = 3; else int x = 3;which can be much cleaner
Ignore obsolete stuff
python time
I rarely find switches to actually be the right choice
ohh man..that shit f me up last time , never had to use Tab so much xD
if you're not putting multiple cases together, they're pretty much just a roundabout way to write an if / else if / else if / ... sequence
Same unless I'm using some fall through (OR with if-statements)
It's a niche case that isn't ever so useful - hackish.
duff's device!
This leads to what the Jargon File calls "the most dramatic use yet seen of fall through in C".[5] C's default fall-through in case statements has long been one of its most controversial features; Duff himself said that "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against."[5]
lol
It's formatting is quite pretty though but.. it's very much like a lookup table but with all of the code jumbo'd below - the case bodies can be scoped but each expression would still be processed like chained if statements.
i changed the one line { setting immediately once I got visual studio. It drives me insane
has anyone an idea of why those two object, at the exact same place but not in the same project has not the same coordonates ?
1st one is not bugged, 2nd is
One of the two has a parent object
Inspector shows Local coordinates, always
its the same prefab, same size
yeah i know
so yeah
im gonna cry
i've been on a bug since 3 days, and now i found the problem
my targets are misplaced for absolute no reason
but only on the inspector, on the scene it is at the right place. So when i play, it get misplaced.
And if i place them correctly on the inspector, but they show misplaced on the scene. They get right placed when i play
Is this code related? If not try #š»āunity-talk Either way, make sure to provide more info. As is, it is presumed that their local positions are not the same.
but they should be
look
Is this code right?
using System.Collections.Generic;
using UnityEngine;
namespace SojaExiles
{
public class opencloseDoor : MonoBehaviour
{
public Animator openandclose;
public bool open;
public Transform Player;
void Start()
{
open = false;
}
void OnMouseOver()
{
{
if (Player)
{
float dist = Vector3.Distance(Player.position, transform.position);
if (dist < 15)
{
if (open == false)
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(opening());
}
}
else
{
if (open == true)
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(closing());
}
}
}
}
}
}
}
IEnumerator opening()
{
print("you are opening the door");
openandclose.Play("Opening");
open = true;
yield return new WaitForSeconds(.5f);
}
IEnumerator closing()
{
print("you are closing the door");
openandclose.Play("Closing");
open = false;
yield return new WaitForSeconds(.5f);
}
}
}```
The bugged spider vs The not bugged spider :
sorry for flood btw
wdym right ?
Was there an actual question?
test ? xD
np, use any of the sites from !code to copy/paste your code, save, then send us the link. it'll avoid the wall of code that scrolls up other ppls questions and responses . . .
š Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Looks like there's IK acting up on these positions. Does it really matter that the positions are different? Make sure your Move Tool (arrows in the scene view) are in Pivot + Local mode (buttons above the scene viex)
they are IK targets
but i setted them up just like in the first project
and yes it matters bc when i my spider moves, the positions are completely offset
what does pivot do ?

Makes sure the arrows are placed relative to the selected object and not its parent chain
Pivot / Local, two buttons
i'm asking why my ik targets are in a position on the scene, but its not the same as in the inspector š
is the file name and the class name the same?
Make sure that there are no compile errors and that the file name and class name match
what is class name
Ask in #š»āunity-talk or #šāanimation. It's not because of your own code
The name you gave your class
the name of the class in the script file . . .
public class Sample : MonoBehaviour
// ^~~~~~ Class Name
Any tips on where to start learning c# I have a decent experience in minecraft skript
!learn
š§āš« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
i matched the file name and class name. it says the same thing again
Show both
Make sure that there are no compile errors and that the file name and class name match
Did you save the script?
there is no errors
Show console, show code
Show the class name, and the file name. Screenshot right from the code editor with both names well in view
In one image, just to be sure
Make sure to save the script, show the console tab and show the script (code and asset)
Previous error basically suggested that they did not match or there were compiler errors
Well from what I'm seeing from earlier screenshots, the file name is Door.cs but the class name is openCloseDoor
So definitely not matching
What do you mean by loop?
Is this a different error?
the animation loops
So problem resolved?
damn whats that
Read it
This doesn't look related to the previous error.
It tells you pretty clearly what to do, check the full text of it in the console
Not code related anymore #š»āunity-talk (assign it from the inspector)
(or through code etc - preferably inspector if possible)
it says to assign the openandclose variable to the opencloseDoor script
Correct
Make sure to read and fix the error - including any other from the console tab.
so i assign it with my animation ?
just loops the animation
now i need a animatorcontroller for the animator
which when i put the animation it loops
Best to follow a tutorial if you're not sure what you're doing.
This is the coding channel, if it's not related to code try #š»āunity-talk
Anyone able to help me with GUILayout.HorizontalSliders?
i have ```cs
GUILayout.Box("Columns: " + Mathf.Round(columns));
columns = GUILayout.HorizontalSlider(columns, 3.0f, maxColumns);
but my slider is still 1-5. columns is set to 1 and max columns is set to 15
hey peeps, im trying to read an enumator from one script in another script and use its value (its a direction, Up, Down etc) to set the vector2 of the second script, but i cant figure out how to get it to work https://hastebin.com/share/ilesimolup.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
change D into d u typed in there actual enum type also its private
What's the first error say
thats not how you also make a vector 2 lol
Yea so there's a lot wrong here
new Vector2.direction.normalized makes no sense.
This is trying to access a member named direction on Vector2, then trying to get normalized from that.
Perhaps you wanted to do this?
direction.normalized
This would access the normalized property from direction, which would be valid
i know what i'd like to do but i'm not sure i can articulate it in c#
how did u end up with that even
What is it that you're trying to do then because that makes basically no sense in any language
er, well, it would be if direction was a vector2
Because they're trying to use new on a property
but it's an enumeration type
AAA
so you have a value from an enum type, and you want to create a Vector2 based on that value.
on the other script i've got an enumarator for a direction. on the script above i'd essentially like to get the direction of the enumator from the other script, and send it in that direction. i'm trying to do a projectile deflection thing
What do you mean "Get the direction of the enumator"
Okay, so you want to get this field and then turn it into a vector
So you're going to need a switch statement
or a chain of ifs at least
PlayerCombatEntity.Direction
this doesn't make much sense, partially because you didn't share PlayerCombatEntity
It looks like you've declared an enum named Direction in several different places
These are all completely unrelated types.
PlayerCombatEntity.Direction is the enum type itself. It is not a value.
Perhaps you wanted playerScript.direction .
Enumator*
Quaternion.Euler(0, 0, 90 * (int)theDirection) * Vector3.up;``` is a cute way to do it.
if you rearrange that to Up, Right, Down, Left
or add Up = 0, Down = 2, Left = 3, Right = 1
save lines of code lose lines on comments cause u gonna forget how that works 
I'm making a little voxel editor and I was wondering what's the best way I should detect the faces of a voxel to append to. I was just thinking about detecting a point on the collider, but I'm not entirely sure of the method to grab the specific face of the voxel, maybe the idea is to create a voxel with a collider for each face?
eh, one line.
You could also do
Up = 0,
Right = 90,
Down = 180,
Left = 270``` in your enum and directly use it
raycast and use the normal of the raycast hit to determine the face
with box colliders
Oh right, yeah good idea
an extension method might be enjoyable to use
public enum Direction
{
Up,
Right,
Down,
Left
}
public static class DirectionExtensionMethods
{
public static Vector2 Vector(this Direction direction) => direction switch {
Direction.Up => Vector2.up,
Direction.Right => Vector2.right,
Direction.Down => Vector2.down,
Direction.Left => Vector2.left,
_ => Vector2.zero
};
}
then:
Direction dir = Direction.Left;
Vector2 vec = dir.Vector();
another good option āļø
if only you could do extension properties
an extension method lets you create new methods you can call on an existing type
could also do the same as an implicit or explicit conversion operator
hey Fen, thanks for this, im going to try applying this to my script, thank you for the advice everyone
I think so?
you can't put operators in the enum definition and you can't put an operator in a static class
(you can't put methods in the enum definition in general)
Anyway, getting back to the original code, there were several problems:
PlayerCombatEntity.Directionis just the enum type.playerScript.directionis a field of that type, which is what you wanted- You've declared an enum named
Directionin several places. These are all unrelated types, even if they have the same name and the same values. You should just declareDirectiononce, and not nest it inside another type new Vector2.direction.normalizedis bogus syntaxnew Vector2(direction)wouldn't work because C# has no clue how to construct aVector2from your enum.direction.normalizedwouldn't work becauseDirectionis just an enum type, and it has no property namednormalized
dont worry i've already gotten rid of the .normalized bit
this is my first time using enums
Hi everyone, do you think it would be better to use an invoke here to run the startTheGame function after the onPlayButtonClick function has executed? I think it would be better because it would eliminate a public variable and make the code more concise and easier to read. ```cs
public bool hasPlayButtonBeenClicked = false;
public void OnPlayButtonClick()
{
// Prepare canvas
mainMenuCanvas.SetActive(false);
getReadyCanvas.SetActive(true);
// Click sound
AudioManager.Instance.PlaySound(transitionSwooshSound);
// Has play button been clicked = true
hasPlayButtonBeenClicked = true;
}
void startTheGame()
{
if (Input.GetMouseButtonDown(0) && hasPlayButtonBeenClicked == true)
{
getReadyCanvas.SetActive(false);
PipesController.Instance.canSpawnPipes = true;
PipesController.Instance.hasCollisioned = false;
playerRb.bodyType = RigidbodyType2D.Dynamic;
player.canPlayDieSound = true;
player.canPlayJumpSound = true;
AudioManager.Instance.PlaySound(jumpSound);
playerRb.velocity = Vector2.zero;
Vector2 fuerza = new Vector2(0f, player.impulse);
playerRb.AddForce(fuerza, ForceMode2D.Impulse);
hasPlayButtonBeenClicked = false;
}
}```
is it important that startTheGame does not run instantly?
Its the time it takes to change the ready screen to the play screen in a flappy bird, what do you think?
Its for a mobile game...
use a coroutine
I'd keep the "has been clicked" variable, though, so that you can't start the game 15 times
note that it doesn't need to be public here
Oh, thats true
also, an important distinction: "public" and "serialized" are two separate ideas
the former means that other components can see the variable. the latter means it shows up in the inspector and gets saved in the scene
public variables are serialized and private variables aren't, by default
So if you were thinking that it's annoying to have that in the inspector, then that's not strictly because it's public -- it's because public variables are serialized by default.
Oh, thank you for explain me that
i didnt have much clear the difference between both of them
A non-public field can be serialized if you add [SerializeField] to it, and a public field can be non-serialized if you add [System.NonSerialized] to it
and in a few words, serialize, is to make it visible and editable on unity inspector, right?
Something is "serialized" if it's saved, basically
that means it will show up in the inspector
thaankksss
And, one other thing, if for example I create a public var cs public int points = 5; on c# and later i change its value on unity inspector to 6, when i make the final build of the project, wich value will it take? what will happen with the other one?
That's called a "field initializer". It provides an initial value for the field.
The value in code is just the default value when creating a new instance of this script
This happens the instant that the object is created. Unity will then apply the serialized values.
So, for objects in the scene (or for prefabs), the value in the inspector is the value you will get.
points will be be 5 or 6 or whatever the initializer says until Unity applies the saved values
(and it does so immediately)
New instances will use the initializer's value, since there is no saved value at all
And if you hit "reset" on a component, you'll also get the initializer value
since the whole point of that Reset option is to clear the saved values
I know I can build one but.
Does anyone have any good free assets that allow for easy debug menu creation? EG: Press F1, give yourself/spawn in items, all that jazz. I know I'd have to build the hooks into it, but yeah. Just curious if theres anything already out there.
Really much clearr. thank you so much
That might work, thanks.
np (:
So if you make that field private, or add [System.NonSerialized], then it won't show up in the inspector, and no value will be saved
so you'll always get whatever value the initializer sets
If you make it private, and then add [SerializeField], it will go back to having its value saved
Hello all. I've had a problem that I hope somebody could help me with - I guess it's probably a beginner query since I'm trying to do something quite basic that, as I understand, should work, but just... Doesn't.
I'm trying to serialize a list as part of a MonoBehaviour:
private List<WeaponInfo> weapons;```
This list is read, but never modified or assigned, by the containing class; and no other class has access to it.
The `WeaponInfo` class is defined in a separate file as follows:
```[Serializable]
public class WeaponInfo
{
[SerializeField] private int weaponID = 0;
[SerializeField] private int groupID = 0;
[SerializeField] private bool isAvailable = false;
[SerializeField] private GameObject weapon = null;
}```
This omits some accessors for the sake of brevity.
However, what I'm observing is that, although I'm able to populate the list and WeaponInfo data as expected within the inspector, upon entering play mode, the list in memory is empty - although it still appears populated in the inspector. I've confirmed the list isn't being cleared anywhere in the code I've written, and nor is it being reassigned. The inspector continues to show what I expect (ie. the data I populated the list with), but debugging reveals the list to have no elements. I'm not using any custom editor or serialization code for this class.
Furthermore, if I add an additional list, and an array, purely for the sake of testing:
```public List<GameObject> gameObjects;
public GameObject[] gameObjects2;```
And then populate them via the inspector with data, these behave in the same way as the original list - that is, the inspector will appear populated, including on entering play mode, but the list and array will in fact be empty if I place a breakpoint and inspect them with my debugger. This will happen even if I try to populate an array of primitives, eg. `public int[] ints;`.
I imagine that there's some very simple mistake that I've made here - but I can't for the life of me think what it might be. Could anybody offer any insight?
(And apologies for such a long initial query, but I wanted to include as much relevant information as I could)
This data is being set in the inspector?
Make sure you're not reinstantiating the list
Yes - the list and the contents of WeaponInfo appear in the inspector, and I can edit them as expected. In the inspector, they remain populated when I enter play mode - but as soon as code that attempts to read them runs, the code will start logging errors because the list is unexpectedly empty. It's not being reinitialised or modified anywhere in the containing class, and there's no other class that has access to it (and it's not passed to another class's method either; it's strictly internal to the containing MonoBehaviour)
the list and array will in fact be empty if I place a breakpoint and inspect them with my debugger
Are you sure you're looking at the correct instance of this thing?
can you show more of the code (especially the part that reads the list?) and where you set your breakpoints?
Is a horizontal line a function?
sure:
f(x) = lineHeight;```
or whatever the height of the line is
lineHeight
The line is on y=2
then sure the function is f(x) = 2
Show your code.
I am having hard time understanding because I thought a function had to be consistent because multiple y values equal different x values
you are thinking of the mathematical definition of a function.
Yes that's correct
the mathematical definition of a function only dictates that each input has a single output. It says nothing about the uniqueness of outputs
but yes, that's still not a problem
a vertical line is impossible to define as a function of x
in this case it happens that all outputs are 2, no matter the input
but a horizontal line is fine.
If the weapons list is still visible in the inspector, then that instance's weapons list is not empty. It does not mean every instance's weapons list contains data. You need to check if the one you're looking at is the same one that you're setting in the inspector
I suspect you are looking at the wrong instance, yes.
Thanks a lot @wintry quarry and @swift crag
Good to see the same guys are here a year later.
I'm on math now. Had to put game dev on pause because I need sharper math skills for it
i've never really thought about the formal definition of a function when working on a game
It looks like you're right - there were, somehow, two instances of the class on the same GameObject, one at the bottom of the components list and one somewhere in the middle where I hadn't noticed it (and I hadn't been looking for a second instance since the behaviour had DisallowMultipleComponent); I hadn't spotted this while debugging since my breakpoint was on an accessor, and thus only being triggered for the instance returned by GetComponent when the caller was initialised - which was the erroneous instance rather than the one I'd populated.
I'm not sure quite how the second got there - above several other components when it should have been the most recently added, and especially with DisallowMultipleComponent - but that was indeed the problem. Thanks.
Clicking on an error in the console will take you to the offending component, if possible
That can help you find duplicates
why is this under lined
Ambiguity
?
It doesn't know whether to use System.Random or UnityEngine.Random
Fully qualify it or write
using Random = UnityEngine.Random;
oh
Well wait. You don't have using System....
What does the error actually SAY?
What does your IDE tell you to do to fix it?
does that matter
Oh I see it. Unity.Mathematics
the error is right there, its ambiguity between Unity.Mathematics.Random and UnityEngine.Random
i fixed it ty
Hey, dumb beginner question. Simple player movement code with rigidbody2d.velocity I'm getting a lot of sliding around when I release the direction button. I can get rid of it by increasing the drag, but then I get some weird issues with jumping. Suggestions?
How can I have my button working. I do not know what I am doing wrong
Why do you even have Unity.Mathematics there? I would just remove that as the simplest fix, since you aren't using it there
But yeah, I guess you fixed it already
idek why its there
What do you want to happen when a directional button on the controller isn't pressed?
As is, you're not doing anything to velocity when the buttons aren't pressed.
Maybe have v.x = 0f on line 4
Ok, that was my next question, just a default to 0 velocity somewhere? I'll give that a shot. Thanks
If not directly setting it to zero, maybe smooth damp it to zero or decelerate it to zero.
Ok that gives me the smooth stop I was looking for, thank you. I just need to work out carrying that velocity over into the jump, as now it loses all momentum on a jump
Maybe only apply the stop/deceleration if grounded
Can someone please help me?
this wont crash my pc will it
Yea that seems like a good start, thank you again. I can tweak things from here
Why would it? (I do not see any infinite loops)
yea just found out it doesnt do anything
Your random position won't be so random though
whys that
Get a random value
Get another random value
Create a vector with all three values being equal to the first random value```
Is that SetActive call affecting the object that script is attached to? Because when you deactivate it, the rest of the code won't run
I'm assuming you wanted to use rand like a short cut variable for randomly generating values.
yea im trying to make world generation
looks like you're missing an event system in your scene
how can I add one?
nvm got it
thank you very much
you should definitely learn the basics of c# before doing unity, world gen is not an easy topic and you'll be learning both c# and unity at once.
have any idea how i can make a inf world so it only loads things within my view
Follow a tutorial
you really dont even need to do that yourself, unity already does frustum culling. You just need to not load things that arent nearby (like minecraft)
you will want to scale this down by a lot though, infinitely scaling worlds will have problems very quickly.
is there a Material.SetTextureOffset for rotating a material? I cant find anything on the material methods page for rotating a material around a point
(does this even belong in beginner? I still feel like a noob but Im not sure when I should start posting in #archived-code-general...)
what are you trying to do? you could possibly use a shader or rotate the actual object
Im trying to make this conveyorbelt turn
I have a straight conveyor with arrows that move straight using the Material.SetTextureOffset, but if I wanted my arrows to rotate for a curved conveyorbelt I would need to rotate a texture around a pivot
I mean if its really hard to do I dont mind just using a mesh but I would rather do this with materials
that Debug Updater object is normal
how are you moving the objects? i think easiest would be actually rotating the belt then
oh
thx
anyone know why the pos is not working
You probably want the random as the index in the instantiate call, not rand
You only make one rand variable. Start is only called once
inside the[]?
So they all go to the same position
Yes. Because random is the one limited to the length of the array
oh yea thats right doesnt go from 1
no, Im rotating the material
like a scrolling material
I want to do the same thing for rotation
i meant objects on the conveyer belt, as those will be moving right?
yeah
Im not talking about that
thats already done
Im talking about aesthetic animation
Hey guys sorry, I have one final error! : Assets\Plugins\Assembly-CSharp-firstpass\DG\Tweening\Plugins\Options\NoOptions.cs(11,2): error CS1513: } expected
But I have the closed Bracket so i can't work out what it wants me to do š¤
using System.Runtime.InteropServices;
namespace DG.Tweening.Plugins.Options
{
[StructLayout(LayoutKind.Sequential, Size = 1)]
public struct NoOptions : IPlugOptions
{
public void Reset()
{
}
}
any ideas?
@deft yacht You are missing the ending brace } for the namespace (the one to match the red one)
Always count the braces. You have 3 opening ones and only 2 closing ones
!vscode
how is this?
you mind as well code on notepad if you're not configuring your ide lol
Definitely follow that link. It will make things MUCH easier
#š»ācode-beginner message
Okay I'll check it out, i just installed c# ddev kit exstention also
ah and now the unity one, did not know that exists ahaha
Follow the instructions closely.
this?
Yep š
it still goes to one position
That wasn't the issue for that part
This was
Start only runs ONE time, and you use that ONE rand value for the whole for loop
So of course they all spawn in the same place
You have to set rand and pos INSIDE the for loop
but i made more
oh
That doesn't help at all
That is just making two separate values you make only once and use for every object
how do i put them into for loop
that whole code should go in the loop if don't want the same thing
first don't write loops inline like that
its ugly as hel
Instead of putting them outside the loop, put it in the loop
for (...)
{
line of code;
Other line of code;
Even more lines of code;
}
so for every plus 1 it does whatever is below it in the {}?
Yep, exactly. It loops as many times as it takes to satisfy the middle condition
So that means it would make a NEW position for each new object
do i leave the var outside
How would I be able to make it when a player spawns in they spawn in with a character already for multiplayer for vr?
You want to SET the variables inside the loop.
randX, randZ, and pos need to be in there
You can DECLARE them wherever though. If you want to use them elsewhere, put them as a class variable (where randX are in your last screenshot). Or as a local variable in start
public class worldGen...
// class variable
public int randX;
public void Start()
{
//local variables
int random;
for (...)
{
// all equals signs that you want to be unique go here
randX = Random.Range(0,10);
random = (whatever);
//use the values
}
}
i dont understand why i have to define randX and randz inside the loop is it bc at the start it will choose a random value and stay like that?
You don't define them in the loop. You assign them. I added the type (int) where I declare a variable.
And the = where I assign. If I put int at both places, it would create a new local variable, disconnected from the class variable one.
So game starts (simplifying it):
It reads the "definitions", one time
Then it gets the message to Start()
It reads the variables inside one time. (If rand was 2, it would have been (2,0,2)).
Then you looped over objects and spawned all of them at that position.
If it's INSIDE the foor loop, it would assign a new value to the variable each iteration.
oh so inside the for loop every 1 that gets added to i till 100 is individually assigned the random var
the for loop will run the statement below it num times
since a block statement is below it, everything in it will run num times
anything that isn't inside that for loop will run once
I know this isn't a coding problem but a unity issue, I apologise wasnt sure which channel to go to, but this is my final error š„²
hello! I am currently making a breakout game and had a question, I have everything completed except for one thing. I want to make it to where if the ball hits a certain block, it goes a certain speed, such as if it hits a red block, it would be fast.
Put it OnCollisionEnter of the ball
if(hit.comparetag("RedBrick")
movespeed = moveSpeedRed
^ example, don't copy
anyone know a good method to make sure that the assets are on the ground
Need help
public void SelectCharacter(CharacterData data)
{
// Close the character selection panel
mainMenu.characterSelectionPanel.SetActive(false);
// ...then set the "character using" in the DataCarrier
for (int i = 0; i < characters.Length; i++)
{
if (data == characters[i])
{
DataCarrier.chosenCharacter = i;
PlayerPrefs.SetInt("SelectedCharacterIndex", i);
}
}
PlayerPrefs.Save();
mainMenu.characterIconPresenter.sprite = data.icon;
}
When I save the selected char it saves it but it does not the icon so when I select one then go into game and come back to menu its still selected but it shows the icon of the default one and not the one thats saved
public void LoadValues()
{
int selectedCharacterIndex = PlayerPrefs.GetInt("SelectedCharacterIndex", 0);
DataCarrier.chosenCharacter = selectedCharacterIndex;
CharacterData selectedCharacter = DataCarrier.characters[selectedCharacterIndex];
mainMenu.characterIconPresenter.sprite = selectedCharacter.icon;
}
Im loading the prefs in another script
Is someone able to help me out? Can't find out why my legs and feet wont move left and right, forward and back. On a test model it worked fine but I don't understand what's wrong.
Log or place breakpoints and step with debugger to figure out if the correct values are being loaded/assigned and in what order.
Seems like you're using the animation rigging package, so it might complicate things, but it seems like the ik targets for the feet are not parented to the object you're moving, so the feet are trying to match the target which stays at the same place.
Not really a coding question btw
Oh ok wasnāt sure kinda new to this
Where would I go for questions like these?
Ok
I have the following code, that is working perfectly, but is there a way I can do this mathematically without hard coding the coodinates?
float[] yPositions = { 0, -7.5f, 7.5f, -15, 0, 15, 7.5f, -7.5f, 0 };
for (int i = 0; i < xPositions.Length; i++)
{
float x = xPositions[i];
float y = yPositions[i];
print($"X: {x}, Y: {y}");
}```
The result should be:
X: -30, Y: 0
X: -15, Y: -7.5
X: -15, Y: 7.5
X: 0, Y: -15
X: 0, Y: 0
X: 0, Y: 15
X: 15, Y: 7.5
X: 15, Y: -7.5
X: 30, Y: 0
Are these number sequences follow some kind of linear pattern? If not, then you're probably better of with keyframes like you have now.
No im not looking for the pattern, i just want the results to match, im trying to spawn a gameobject at grid coordinates
I would love to do something like minX = -30, maxX = 30, minY = -15, maxY = 15
Well, then there's no way to do it mathematically(unless you want to train an ML ai to find some pattern in your coordinates).š
just cant figure out the math to do this correctly, i came close few times ;P
It would work if your sequences were changing linearly. But they have repeating numbers and going from positive to negative, back to positive.
Basically, it's hard to derive a mathematical function from your data.
I did this earlier and it almost worked perfectly, it was just missing 2 gameobjects:
X: 0, Y: - 15
X: 30, Y: - 15
minX = -30,
maxY = 15f,
minY = -15f,
thresholdX = 15,
thresholdY = 15; // Adjusted thresholdY to match the expected output
for (float x = minX; x <= maxX; x += thresholdX)
{
for (float y = minY; y <= maxY; y += thresholdY)
{
print($"X: {x}, Y: {y}");
Vector2 spawnPosition = new Vector2(x, y);
Instantiate(gridManagerPrefab, spawnPosition, Quaternion.identity, gridArea.transform);
}
// After each row, adjust the Y coordinate for the next row
minY = minY == -7.5f ? 0 : -7.5f;
}```
Will calling an Invoke inside my method to start the method again every x seconds lead to any issues down the line?
better using coroutine
Just using startcoroutine inside the coroutine?
just a while loop would suffice
But I need it to only run once every minute or so
Won't using a while loop and making a manual timer impede on runtime as it's checking that every frame?
its a Coroutine which kinda works async
IEnumerator Repeat(float timeBetween = 60)
{
while (true)
{
yield return new WaitForSecondsRealtime(timeBetween);
//do the thing
}
}```
First of all, that'd already not a "mathematical" way. It's a programmatic way. And it's making it more complex than just to have a list of points. Not to mention that it skips some, because you have some points share the same x or y position as others.
while(true) feels cursed to use in a practical sense though lmao
Appreciate the help
I usually do use a bool to break it, but most of the time I just store this in a Coroutine incase i need to stop it as well (another benfit for coroutine)
MyCoroutine = null;
MyCoroutine = StartCoroutine(Repeat())
StopCoroutine(MyRoutine)
I usually just do StartCoroutine("nameOfCoroutine")
Is that bad code or just down to prefrence?
using strings is not type safe
Meaning?
if you mispell it the editor has no idea
But if I just copy paste the name there's no mispellings to be had
Though editing later on it's possible to accidentally edit it
So I do see where you're coming from now
yus
Thank you again!
anyone got any ideas what this could mean? getting desperado for solutions
I was thinking, but u can use span here. 
It's an issue with the services package. Either it's current installed version is incompatible with unity or some other package, or your library folder cache is corrupted.
Try updating the package and if that doesn't work, delete the library folder.
Thank you, very much i just foud this out but i really appreaciate the response
It kind of is a bad code. 
Even if u just copy paste it or smth, just changing the name of the method will still break it. You have the nameof() to get changed along with it (using with ctrl + r + r in visual studio not code to rename something and update all references to that thing).
But i'd rather avoid relying on string inputs for stuff like this anyways.
Here's an extra reason why not to use string input ig.
/*Declaration*/
public Coroutine StartCoroutine(string methodName, object value = null);
/*Description*/
//Starts a coroutine named methodName.
In most cases you want to use the "StartCoroutine" variation above. However "StartCoroutine" using a string method name lets you use "StopCoroutine" with a specific method name. The downside is that the string version has a higher runtime overhead to start the coroutine and you can pass only one parameter.
IEnumerator Mark(int i)
{
HighlightColumn(i, Color.blue, 0, array[i]);
yield return new WaitForSeconds(delay);
}
``` when i call this there is no delay, the variable is define and it works elsewhere in the script, idk what to do
you're not delaying anything there. you're calling the HighlightColumn method, then it waits. but since nothing comes after the wait nothing is being delayed
if i put the delay before it still doesnt delay
then either delay is zero, or by "doesn't delay" you actually mean that it only delays for the first time you call it, then every time after that you don't see any delay happening. and if the latter is the case then you're probably just starting the coroutine in update without doing any sort of checks for whether it is currently running or not
also keep in mind that coroutines do not delay the calling code in any way (with the exception being starting a coroutine inside of another coroutine and yielding that)
oh, i need to delay the calling code, but i dont want the calling code to be a coroutine
is that code inside of update?
no
then it needs to be a coroutine
or you need to be calling the method over and over and use if statement(s) to control what part of that code executes
ok if the calling code is a coroutine then can i keep the delay in Mark? how do i make the delay in Mark work
yield return StartCoroutine()