#💻┃code-beginner
1 messages · Page 138 of 1
hi can someone help me with this script? in this script i basically have an input field which i can type phone numbers in it (and i can configure the numbers in the inspector) the problem is, no matter what number i type it gives me the invalid number audioclip. i also setted up a debug log to tell me which number i typed and it always appear to be blank. sorry for my bad english. can someone explain me this? thanks in advance
how do i do that
by reading the page you were linked to
Why do you have a component named ScriptableObject? You shouldn't name scripts the same as unity built in types that's just going to cause problems
please just read it
yeah i know
like how on most gameconsoles, the console will prompt you with a whole keyboard UI for the console, and then put the string into the game once tou close
honestly man idk
ah, so like what you can do on a Steam Deck
switch, xbox, ps4, ps5 have it
Before you start typing, the box is blank. Blank is not a valid number.
You'll want to first check and make sure there's something in it before you check if it's valid
I'm not aware of a plugin. I know how I'd do it, though.
a standard UI for the console to bring up a way to input strings
you'd give a callback to the keyboard and have it appear, then wait for the callback to be run with the string the user provided
Is it a must to do it with tag
no
no. please read the page you were linked to.
hi, im new to unity and im using visual studio but for some reason my errors arent underlined
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Why is that?
you'll want to follow these instructions
yeah im trying to understand it
thank you i'il try to figure that out
You should be able to know immediately at a glance what any line of code does completely removed from any surrounding code.
Var makes it harder to read your code because it requires context to know what type it's supposed to be. Small bits of extra effort to read a line add up over the hundreds or even thousands of hours you spend in a project
the UI component InputField does this
serialize reference is how you set a direct reference to something in the inspector. Singleton is to get access to a specific class of which there is exactly one. GetComponent is to get a specific component on a gameobject once you have a reference to the gameobejct
If you require to know the type, your other code should be written in a way that's self documenting. Types are not what makes the world goes round, it's the context to those types.
i’ll look into it. ty
that's a fair point!
I do find it a little "unsatisfying" to read a var line
Again, you shouldn't need other code to know what a line does
var doohickey = GetContraption();
Yes, that's right. It's the line that matters, not the type.
because code should be self explanatory and using var obscures that
obviously I can hover over var to find out that GetContraption returns a Widget
but that's a layer of indirection
No, it doesn't, if it obscures it, the method or member name is badly written.
And when the line has var that's slightly less information than without
It doesn't, you still have the same information.
after going through the layer of indirection, yes
it’s just not obvious exactly what type you are working with by just looking at your code. period
rubbish unless you are going to implement one of the old unsave typess or C conventions
I'm not sure why badly written or indirected code has anything to do with var? That's just... bad code
Except the type, which you can infer, but why spend the time inferring when you could just know
you are not convincing me of my own stance on var
But you know that through intellisense?
which is the indirecetion, yes
but not by looking at your code
C# is type safe, no need to implement that.
i have to stick my cursor on the var to find out what it actually means
Intellisense is not indirection
Or just use the variable in code?
yes, at compile time but not when you read it
foreach (var entry in myList) {
What type is entry? You can’t know based on what I wrote
What?
Bad code will happen with or without var. Why not pick the one that makes the bad code less bad and doesn't affect good code at all?
Why does it matter what type it is to me? I know I have a list. If you call your variable myList, that's a red flag.
How can I use Quaternion.Lerp() to rotate towards an object's position?
I would suggest using Quaternion.RotateTowards
Because var doesn't make it bad?
that will let you rotate at a constant rate
var makes it worse to read
Right but it does make bad code worse and if you can avoid that by just using the real type why wouldn't you?
transform.rotation = Quaternion.RotateTowards(transform.rotation, goalRotation, Time.deltaTime * 90);
this is a 90 degree per second rotation
In what sense?
thx mate
How does it make it worse?
and then I can just lerp the '90' towards a lower value i guess
Bad code is bad code with or without an explicit type.
var makes all code less obvious because you just don’t show the name of the type you are working with IN THE CODE
do you want the rotation to slow down as you get closer to the target?
yeah
I don't need to know the name of the type, I'm working with logic, not types
so tell me, in that example, what type is entry?
I'd do something like this, then
i'm trying to rotate a player camera towards a target
In what code?
The many examples you've been given where your only response was "well that's just bad code"
Yeah, it is. And sometimes that happens to the best of programmers, so why make it harder to read bad code
In the majority of places the specific sizes of types dont matter. It's the "shape" of a type that determines the logic of the code.
I would agree with using explicit type names in networking or any form of binary serialize adjacent code... but general code, nope
float closeness = Mathf.InverseLerp(0, 180, Quaternion.Angle(transform.rotation, goalRotation));
float rate = Mathf.Lerp(30, 180, closeness);
transform.rotation = Quaternion.RotateTowards(transform.rotation, goalRotation, rate * Time.deltaTime);
myList is poorly named:
foreach(var entry in timeEntries)
Yes but bad code with an explicit type still gives you more info as to what the code is than bad code with var
This will rotate at 180 degrees per second at the maximum angle and 30 degrees per second at the minimum angle
I'm not sure what playing bingo or gotcha with type names is in relation to using var. It obscures nothing, there is no type safety lost here.
You deal with logic, not with the names of types. If using var hinders you from programming, you've generally got other issues in code.
Let's imagine if you have some code like:
var z = x.FirstOrDefault(y => y.Name == z);
How are you supposed to read this code?
Simply you can't, you have to go back up your previous code and look at what x/y/z are:
IEnumerable<User> x = ...;
string z = ...;
But that's the thing: if your code is so unreadable that you have to commit to memory "x is an IEnumerable<User> and z is a string" just to be able to understand what it does, at that point it's not even about your type anymore.
If you just properly name your variables, it literally does not matter what the types are:
var foundUser = users.FirstOrDefault(user => user.Name == targetName);
Does it matter if users is IEnumerable<User> or User[] or List<User>? Nope, you absolutely can still understand what that piece of code does.
so what is a timeEntry? a TimeSpan? A float? A string?
much appreciated 🙂
^ This. The solution to most of the complaints about var are writing better code in the first place. Writing the explicitl type here would not stop me failing your code review
Yes but with explicit typing it doesn't matter if it's poorly named you can just know the type
cool. so… is entry a float? an int? a TimeSpan?
TimeEntry.
var and implicit generic types can make this stuff really hard to read
Only if your variables are not properly named.
If you have to commit to memory "x variable is of type Y" just to read the code, you are already on the wrong path.
ummh i still dont know how to do it bud
It does matter, code clarity matters. I feel if you're relying on explicit typing to cover up bad code, I'm still going to call that out in a code review
If anything, var forces people to write better.
I don't support accommodating to lazy naming. Write better code.
Check the length of the string
ok, so you're saying the Type should be in the variable name, what do you think this is? C?
They're not, that's the other extreme.
we're bringing back Hungarian notation!
That's all well and good if you're the only person writing the code.
What about when it's the intern that left the company six months ago and you have to refactor their code
This is not "use the type or specify the type in the variable name", it's a bit silly to assume that.
Look at the example I gave above, does it matter if users is IEnumerable<User>/User[]/List<User> or something else? Absolutely does not, you can perfectly read and understand what it does.
It should've been caught at the PR level.
That's the rest of the team's fault for letting it through.
it is exactly what they are saying, the type should be inferable from the variable name
users gives enough information with context, you don't need to name your variable aListOfUsers.
"just don't write bad code" is a meaningless take
of course you shouldn't write bad code
ok so i should instead write
foreach (var timeEntryAsTimeSpan in myListOfTimeSpanEntriesForMySpring) {
and this is better than
foreach (TimeSpan entry in springTimeEntries) {
that’s what you are saying?
No, because putting the variable name isn't clear there either
std::string m_szFoo is less descriptive than var fooName
this way, I just know my variable’s type, because every variable has the type in its name….
real
we follow rules to make things better.
even when the imperfect human beings creating those things make mistakes
Yes, the Magical Christmas Land scenario where everything is named perfectly and all code is reviewed var is fine but in an actual pragmatic case where you deal with brain farts, undercaffeination and just plain bad decisions it makes things harder to read and using an explicit type doesn't make good code any worse so why not just use it from the get-go?
List<string> list = /* .. */
var orderedList = list.Select(element =>
{
if (!int.TryParse(Regex.Match(element, "\\d+").Value, out int index))
{
index = 0;
}
return (element, index);
})
.OrderBy(pair => pair.index)
.Select(pair => pair.element)
.ToList();
what type is orderedList?
A) that is C++ and B) if it was C it would be s_Foo
why would you use var if you could just use the datatype of what it's actually gonna be
just seems more complicated imo
@languid spire replace std::string with const char* there and it's c
Exact same thing
I will use var for short-lived variables.
It's not meaningless; you stated that bad code made it in the system. That means someone didn't do their job. If you need the type explicitly on the line as you're fixing their mistakes then you don't know how to use the tools at your disposal and should use that as a learning experience for yourself.
You would just write:
foreach (var time in springTimes)
{
Debug.Log(time.Subtract(startingTime).TotalMilliseconds);
}
Does it matter if springTimes is IEnumerable<TimeSpan> or TimeSpan[] or List<TimeSpan>? No, that piece of code is very clear what it does without you needing to know anything about the type of any of those variables.
var target = Quaternion.LookRotation(direction);
transform.rotation = target;
(contrived example, yes)
Putting more context into a variable name does not mean putting the type in 🙂
what's the advantage?
the type of springTimes would not appear anywhere with explicit types, so...
my point is to just not use var, and just write TimeSpan, then it is more obvious what you have
it does if you rely on var to tell you anything meaningful
I think you’re being very stubbornly unrealistic about how to use var
A script could be a class, a struct, an enum. A script is just a file
Unity puts in boilerplate for it being a MonoBehaviour class though
That's the thing, because springTimes already gives you enough information (it's some collection of spring times), that's why the type is irrelevant.
It's not like creating a class it literally is creating a class
in that code, if you use var, it is not immediately obvious that the timeEntry is a TimeSpan vs a float vs int
no, I'm working on a great deal of experience
If you gave springTimes a terrible name like xs and you have to scroll back up to read that IEnumerable<TimeSpan> xs = ...;, you've already did it wrong.
but you do not know if the entry is a timespan or a float without writing it out. Which gives access to different methods
an argument of authority is never good to present 🙂
that's not even the right fallacy
As are plenty of us 
you can only really justify var once your type names are very long
the point that's being missed here is that more information helps.
you can infer the meaning of something with incomplete information, yes, but why not have more information?
In a pragmatic case, I expect developers to be giving their members meaningful names, that's not magical Christmas land where everything's perfect; that's a standard where I work now, and everywhere else I've worked. To be clear, I'm not against using explicit types, but I'm not hard against using var, and I don't think anyone should have an arbitrary rule against something that's useful when used properly.
Sure, I can harm myself or others if I play with a nail gun, but used properly it saves time.
especially when you are working with something you're unfamiliar with
What about when the type is already evident on that line?
Code Lens and similar in VS helps with the unfamiliar code
Fine, then feel free to repeat the mistakes I made and learned from many, many years ago, come back in 50 years and we'll have this conversation again
It lets you optionally display the typenames inline
If you really want to devovle to this level, you ought to head over to the C# server, check my roles, or google my name or go to my GitHub page 🙂
That does not matter, you have an idea, when your press . all the code you can use show up.
var vs explicit type only matters when you read code, and when you read time.Subtract(...).TotalMilliseconds it doesn't matter what time is and if Subtract is a valid method, because you wouldn't even be allowed to submit this code for review if it doesn't even work.
if I have HashSet<FixedSpawnpointHandler<TilePlacementSingle, CircleCollider2D>>, then yes write var so you can see what you are doing
also, this holy war has probably outstayed its welcome in #💻┃code-beginner ...
heretics must be purged
Does it matter if time is a TimeSpan or some random time class you invented yourself that has Subtract method on it? Absolutely does not.
When you see time.Subtract(startingTime).TotalMilliseconds, you don't need to know anything about those types and you can still understand what that piece of code does: it gets the elapsed milliseconds since starting time.
This is, again, a poorly named example.
foreach (var expansionTime in spring.ExpansionTimes)
Why do I care in the context of this single line if expansionTime is a float or TimeSpan?
sometimes I like to have it as var, then I can swap out the type really fast without caring, as long as it happens to have the same property name 😄
Microsoft MVP, don't make me laugh, the very fact that you put that on your profile tells me everything I need to know
because that changes the methods i get access to on the following lines when reading quickly
still not obvious in your “correct” example
It's ok, you'll get there some day!
I didn't ask about the following lines. I asked about that line.
declaring a variable type doesn’t normally affect the line you declare it. it affects the following lines where you USE it
just make a pr with for (var i=0; i < 10; i++) if you want a lazy friday
i'm more of a ++i sort of fellow
don't make me tap the sign
i'm not a huge fan of how several people joined exclusively to argue in a holy war about a keyword
You... may want to look up SteveSmith haha
i'm swiss, when in doubt, we always vote: https://strawpoll.com/PbZqR25eNyN
this is taking up a huge amount of space in a chat for Unity beginners
You're right, but the context of the lines you use it on will help you understand what you're dealing with. In the context of a single line, the type doesn't matter.
Hmmm, int and var are the same lengths. How is one the lazy approach? 🤔
can you change your name please, I have to keep hovering over it with my mouse to see who is really talking
Use it means you are writing it in an IDE, and pressing . shows you all the things you can use.
var vs explicit type is a matter of readability it does not affect how you write code.
If you want to continue discussing this create a thread
One's definitely more explicit though.
some people get triggered when using var with primitive types
I have no need to, because I like to discuss programming with anyone at the same level of respect
how do i do sth to all object containing a tag
What are you trying to make your game do?
for example
This might be the best option, but there also might be a smarter way.
make all maps dissapear
"You'll get there some day"
I reckon seeing bikeshedding over var is quite insightful for the juniors in a way
unactive
in a sense, yes
You get the respect you give 🙂
this has been amazing. i've written 0 lines of code so far today
"maps"?
well thats just a name
Set the object inactive, disable the renderer or whatever
all of them have a tag called 'maps'
the point is there are a lot of them
learn what is loop
so you can absolutely do this with https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
do i need to loop through them or what
Do it to each of them
It will give you an array of GameObject you can iterate over
What's the actual issue?
I'm still unsure if this is the best way to do what you want, though.
i think it is
what is your game doing here?
How to manage a group of types? How to find a group of types? How to iterate a group of types? What?
tell me what's happening from the player's point of view.
basically
i want the map to change
my way is like hide all the map and show a new one
Hi. I have a question about optimization: if scrolling with the mouse wheel and the fact that the camera field is less than 40, how should I set it correctly so that it is better? Or will nothing change from their arrangement?
okay, so this isn't going to work very well with tags
the second map's objects would all have to be tagged "Map 2" or something
It sounds like you want to just load a different scene.
When might be important so that we know what you've got access to. If at any time, you may need a manager else someone needs to pass reference to the collection of "maps" or you'll have to search the hierarchy etc
I don't understand what you're asking here. This looks pretty reasonable -- except that it ignores the magnitude of the delta
It'll zoom super-fast on a macbook trackpad, which sends a lot of tiny scrolls
Yes, I wanted to check how it would work first. I'll add Time later.deltaTime
deltaTime is not appropriate here.
Input.mouseScrollDelta.y is a distance -- how far you've scrolled
If you scroll by a certain amount, the camera should zoom by that amount
Yes, I just gave an example of time
this is not optimization (at least to me)
you ++ and -- no matter what the magnitude is
"an example of time"?
I use a translator
In short, should I write if mouse scrolling first, and if camera restrictions second, or vice versa? Or will nothing change from their location (about what would be better for optimization)?
Ah, I see what you are asking.
It should not matter at all. However, I think the way you wrote it makes more sense.
eh why are the brackets in red
You have a syntax error.
Something is wrong with the public void changeMap(... line, most likewly.
theres a semi colon at the b ack tho
That's incorrect!
i mean the line
you don't just use semicolons everywhere
A semicolon ends the current statement. It's like the period at the end of a sentence.
yes i know
The syntax for a method declaration looks like this
i mean the inside code
Ah, okay
Also, you have an access modifier inside a method
just show all of the code please
th is that
Private inside changemap
we can't see your screen, so we can't tell you what's wrong
public class flowManagerScript : MonoBehaviour
{
public GameObject mapListFolder;
// Start is called before the first frame update
public void changeMap(string map)
{
private Array mapList = GameObject.FindGameObjectsWithTag("Maps");
}
}
Ah, interesting, the compile error winds up there
You can't write private/public/etc inside methods
private here?
private Array mapList = GameObject.FindGameObjectsWithTag("Maps");
so, yes, as Aeth said, access modifiers -- private, public, etc. -- are only used when declaring the members of a class
Members are things you declare directly inside of the class
A refactoring could be: If delta y isn't zero fov = clamp (fov - delta y, 5, 40)
I'm a little surprised the error was on the {. I guess the compiler saw the private and then decided the prior { was bogus?
Yes, this is a good idea
fov = Mathf.Clamp(fov + Input.mouseScrollDelta.y, 5, 40);
^ it'd look like this
You may need to divide the delta by something
to slow it down
i think everything would be more obvious if we all changed our names to var
you can already open the profile to see what my base username is anyway
How do i use a power function with the short datatype?
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
@deep robin ^
I think this conversation has run its course here but the developers over in the C# discord are easily entertained and are still going strong if you'd like to join them 👍
are they arguing right now about var lmao
we don't argue in C#, we type cast
Thanks @hexed terrace. I got that sorted out. Anyway, I still have this problem.
I'm tempted to ask what's the generally take about #region in C# then if I see this
but I fear to wake up another dinosaur
🙃
The Unity and C# math power functions are explicitly for float/double. You could probably make a utility class that accepts and return your desired type using some logarithmic operation or whatnot.
What's the issue say?
Sounds like work. Do you know how to do that? I want the macroUnit to be the microUnit to the power of two.
@clever mica What do you mean?
@swift crag I don't plan on having the values be any bigger, I should really make them constants.
short microUnit = 1 << 3;
short macroUnit = 1 << 6;
alternatively, multiply microUnit by itself. C# doesn't offer those math functions for integral types
should be byte anyway (just being picky)
This... I'm a little dumb on the mouse wheel. How to do the opposite: Now, if I turn the mouse wheel backwards, the zoom increases, and if I turn forward, it decreases. I want to do it the other way around.
there was a pre-hiostorical take on var few hours ago and I land on a screen with another fossile vestige of C# which is #region so it's like drama are calling out
I did not except to see that
Negative instead of positive
I'd say like 90% of the usage of #region I've seen has been actively obnoxious and unnecessary
"-" to the place of "+"?
yeah, bit more than 90% but yeah
it does look pretty overkill in that screenshot
@twilit pilot How's it obnoxious and unneccasary? I like to #region EVERYTHING.
in the days when we worked with 15" monospaced monitors or even 800x640 resolution #region was usefull, today? Nah
I'm very happy with being able to jump to definitions (either locally in the file, or across the whole project)
private methods take up too much space so i usually make a new class and then copy the private method and make it public instead
🤔
partial class
no not partial class
Should be fine for collapsing with thousands of lines of code. Where reading quality can improve with less static but other than that, it's probably not necessary unless for habitual practices/patterns/whatever.
carefull when critizing choice of year 1995
i don't think i could handle a CSS holy war in here
what do you have against monospaced fonts, mr TeBeCo?
that C# discord is on fire discussing var
monospace for code is the dogs bollocks, everyone should use it
nothing
||y||||o||||u|| ||d||||o||||n||||t|| ||s||||e||||e|| ||a|| ||l||||i||||t||||t||||l||||e|| ||b||||i||||t|| ||o||||f|| ||a|| ||p||||r||||o||||b||||l||||e||||m|| ||w||||i||||t||||h|| ||s||||t||||r||||u||||c||||t||||u||||r||||i||||n||||g|| ||y||||o||||u||||r|| ||c||||o||||d||||e|| ||i||||n|| ||t||||h||||i||||s|| ||k||||i||||n||||d|| ||o||||f|| ||w||||a||||y||?
@ivory bobcat "less static"? I see them as like folders. The more you have more organized everything is.
yeah that's why i cliecked on the text that is not code
👍
thx
it’s like a scratching off ticket lmao
dynamic is where it's at
what's the type? i dunno man, i'm just a dog
Don't incite the individual 
aeugh
Hey that's kind of cool actually

I still have written zero lines of code today
ok time to work
@twilit pilot No, I actually see zero problem. If you nest the regions seperately from how you nest everything else you can make things quite deep and it only makes everything more manageable.
cheat code => copy text 😄
I would agree if you did not create a single region for each one to 3 line of code in the same code block, there's "new line" for that
@buoyant knot So keep it there, we don't need to bring it back here. Thanks.
we already had and concluded our war on var here an hour ago.
Apparently not if you keep trying to bring it up
sorry. I’m done here with it
I disagree, and I feel like my message above was a pretty good example of why. You're basically just using functions here except instead of actually using functions you're hiding things in russian dolls and getting none of the IDE definition or naming benefits
Russian dolls is actually a great example lmao
You can collapse functions anyway in Visual studio so I never really saw the point of # region
"i will fix that issue later, not now"
put every for of issue inside
code design / code split / god object / bad code / hidden code
@clever mica I've actually found a scenario to make regions in input braces. Unfortunately that functionality doesn't exist, at least in G.M.L. Hovering your mouse over the region also seems to help. I'm actually only thinking about using Unity just cause Game Maker Studio's regions don't work concsistently when you use them too much. Some regions just don't close as some sort of bug.
it's like creating a folder named Utils
This isn't Unity related anymore. Make a thread if you want to debate regions.
I'm just talking about my use of regions, it's not about game maker.
Yeah but this channel is intended for helping ppl not really long code debates
Sure, then:
The file structure is robust and can make things easier to read but maybe a bit less structuring can make things more legible. Not saying you can't or shouldn't do something in a particular way that you feel is good but why you might see others have suggestions related to being pragmatic
https://youtu.be/-AQfQFcXac8?si=UpV90qvq5Q_uNphK
Put down the keyboard!
There is nothing worse that using code that has been written to some arbitrary set of standards in the guise of professionalism. Often due to inexperience, or the urge to just keep on trucking, some coders make a complete mess of otherwise perfectly acceptable code.
Source Code: https://github.com/OneLoneCoder/videos/blo...
Hi, could someone help me explaining to me what a tick (in terms of Unity) means exactly?
tbf, I just finished adding a combination of 7 different classes and interfaces to my project, to support moving the starting position of a level.
Programmers put down the keyboard
lmao. That guy has an amazing C++ tutorial on game engines
"tick"?
a tick is one cycle of a CPU. it is one actual operation
Depends where you've heard this from (may differ relative to the source) but likely a single frame or some variable period.
I think he means fps but I could be wrong
Ok, where would I go to continue this? Not to mention, if someone could tell me how to use a power function with a short that's what I originally came here for. @ivory bobcat, easier to read means more legible. What do you mean? I could continue talking about the benefits of regions but I don't think this's the place for it.
Frames per second
I know there are physics ticks, graphic ticks and logic ticks
I think he means tick as in one frame
Pretty sure it's already been stated that pow does not accept the integral type. Bit shift operation or logarithmic operation can yield you the correct results (preferably the first).
better ask in different channel as this is code related channel
@ivory bobcat, do you know the code to turn my eight into 64 with those cause I didn't even use those in G.M.L.
Left shift three #💻┃code-beginner message
Those aren't really Unity terms. The closest would be the Time Step and Physics Step, which are when Update and FixedUpdate run. A "tick" is just a general term for any cyclical check in any sort of virtual clock
okay, thanks a lot
@ivory bobcat, sounds interesting. You said there was a third way? The first was to multiply microUnit by itself.
Cast to float, use Mathf.Pow, cast back to short
does this save the values or a reference to the transform?
@polar acorn, how do I cast it back to short?
The same way you cast anything else
I guess I don't know how to cast cause the example I looked up looked like a way I've already tried.
Structs are value types
(TypeIWantToCastTo)
Put the type in parenthesis before the value
so does it save the value then?
That is what value type means
cus i remember trying to save a transform in a variable and people said it was a bad idea
Can I juse get code?
Transform is not a struct, which means it is a reference type
so classes save references and value types store values
interesting thank you
Logarithmic operation but the Unity and C# math libraries use floating point values so you'll not be able to use your integral type without casting - same result as pow. Here's the relationship between pow and log though https://www.mathsisfun.com/algebra/exponents-logarithms.html
Isn't log supposed to be the inverse of pow? Anyway I think I figured out how to cast it.
not a bad idea at all
depends on what do you want to do with it
yeah i mean like it was a bad idea for what i wanted to do
How can I get a postion of a object and convert it to a vector 3? This object does move constantly
isnt sqrt the inverse of pow?
no
sqrt is the same as the pow function
just with an exponent less than 1
sqrt is x ^ (1/2)
log is the inverse of exponentiation
sqrt is inverse of square
log is inverse of pow
a^b=x, log(x)/log(a)=b
1/2 is kinda inverse of 2, thats what i meant
sure. x^2 * x^(1/2) = x
So if you have a script that instantiates items from prefabs, how do you change which prefab is 'loaded' in that serialized field at runtime? Like I can drag and drop different prefabs into that field in the inspector, but how would I do so from within a script when I want to instantiate a different item?
Resources.Load
Set the variable to something else
However you want to get that "something else". From Resources, from a different class, from a list
just change which prefab that variable holds
How do I have my Line Render connect to a object? Cause right now it just goes up instead of at the object I click at
Set the position of one of the points at the position of the object you want it to connect to
You would probably just have several variables.
It a grapple so it changes
or have a list of prefabs
So then change the point again
The point of the field is to give you a reference to a specific prefab. That's all it does.
Well I thought I did that with the lastRaycasthit
is there a way to have serialized private attributes be non editable in the inspector?
Kinda like how you can't change the script attribute in a component
Not baked-in. I've definitely seen [ReadOnly] attributes before.
You'd have to write a custom property drawer.
it's actually 2 lines of code in a custom attribute if you wanna make one
Use NaughtyAttributes: https://dbrizov.github.io/na-docs/attributes/meta_attributes/read_only.html
or write your own
but yeah naughtyattributes will do it for you
why does it say that rb isns announced even though it is https://paste.mod.gg/tvibenoebneh/0
A tool for sharing your source code with the world!
it says it hasn't been assigned, not announced
presumably, a different copy of the script is causing the error
If the error says it's not assigned, then it's not assigned. Your screenshot shows that at least one PointCounter has an rb assigned, but that does not mean all of them do.
yeah it seems i accidentaly put the script on the Ui too and didnt asign anything
Hey everyone. Need some help. I'm trying to make it so that when the player shoots, the gun will push the player backwards a bit. I've got it kinda working, it's just that the force ends abruptly, rather than naturally tapering off. Can anyone help me figure out how to achieve this please?
https://wtools.io/code/print/bSQL
I've also code my script here if anyone wants to take a look
It ends abruptly because you have this in FixedUpdate:
rb.velocity = new Vector2(Horizontal * speed, rb.velocity.y);```
you are completely overwriting the existing velocity to your desired velocity here
SHould I put that in Update()?
so the force will only get to affect the velocity for a single FixedUpdate frame
no
Update won't help
you are missing the point
Is there like a contest to find the worst paste sites or what
It was the first one I found on Google 😦
I think I get it. The force is only being applied for a single FixedUpdate Frame. Then it gets overwritten
You should add to it rather than assign velocity a fixed value if you're not wanting the previous value to be loss
but how could I stop it from getting overwritten until the force is at 0?
Agreed. I was too terrified to click the link 😅
It literally tried to print the code. I had to cancel my printer before it finished spooling up
Sorry 😬
lmfao
Proper syntax would be something like.. (I'm on mobile - coding can be error prone)cs rb.velocity += rb.transform.right * Horizontal * speed; @west sonnet
here you go buddy! [prints]
Why can't I use forceDir in my FixedUpdate()? It was created in Update. Both Update and FixedUpdate just have void, no public or private
forceDir is my direction, right?
It doesn't exist in the other function
forceDir is a local varaible to the Update method
how can I get it to be used outside of Update?
don't make it local
It's declared here
Or declare/evaluate it again in Fixed Update since it isn't anything specific to Update
why do you not know this?
I'm not sure what you mean?
Because I'm new. I'm learning
well time to learn some c# basics then
I wrote rb.velocity += forceDir * Horizontal * speed; in FixedUpdate() but now I can't move my player and if I shoot, the player won't stop moving backwards
Why put it in fixed update? And why use force direction? The code I provided suggested using transform direction right.
AI Generated code or pure copy/paste?
Pretty sure the code was related to your horizontal movement from input
Why ain't my LineRender going where it should. When I aim at a object and click to grapple to it. The grapple seems to go above where it should be.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Context would be necessary (code and image of incorrect offset)
Because the direction of the gun is to be facing the cursor position
Also, Transform.Right is Vector3 but I'm using Vector2
Try using the transform direction right for movement relative to your character.
Cast to vector 2 if necessary
(Vector2)rb.transform.right
I'm guessing player is in world space and the line renderer is in screen space
A screen space?
Show the inspector of your line renderer
I found it and you were right. I didn't know it wasn't using world space
Didn't know it was a option that need to be put on
This is what I have atm. Is this correct? Because my player still won't stop after shooting and I can't control the player movement
Just have what you had before at #💻┃code-beginner message with the correct direction though (for the velocity assignment in Fixed Update)
That if statement is your shooting mechanic and shouldn't be relative to your character direction
hey guys, did someone used Netcode for multiplayer ?
how do I make a reorderable vertical scroll view in unity so that user can reoder the items easily and which works with android to
It's relative to the direction that the players gun is facing, so that it pushes the player back, like recoil would
Probably at some point yeah
Just undo what you've done. The issue is that your velocity assignment in Fixed Update is overwriting the velocity completely. Don't change the other stuff.
This doesn't seem code related
oh mb
Direction was incorrect in fixed update for movement. I did not click the link but according to blue, your original velocity assignment was #💻┃code-beginner message @west sonnet
But should have instead been something like #💻┃code-beginner message
I've added to Update(), but it's the same. I can move but the recoil force abruptly ends
Wait, I've commented out that line in FixedUpdate() rb.velocity = new Vector2(Horizontal * speed, rb.velocity.y);
Stop touching line 59. Undo it.
The velocity assignment = was the issue
Not your shooting kicking back.
Hi, have a question about some unexpected transform positioning behavior that's really confusing me.
I'm making a meter/timeline:
- I have a StartMarker at localPos (0, 0, 0) and EndMarker localPos (1, 0, 0)
- Also have a CursorParent object at localPos (0, 0. 0) that is a **sibling **of StartMarker and EndMarker.
- If I move the CursorParent to (1, 0, 0), all the cursors line up exactly with EndMarker
- The unexpected bit: When I move an individual cursor (child of CursorParent), **its local x pos is 1.6 before it lines up with EndMarker. **
- All the cursors are at localPos (0, 0, 0), lining up exactly with CursorParent, and the pivot point is the same, so
what would cause this discrepency? The rotations on all mentioned objects are (0, 0, 0), so I don't think it's that?
Linda 71 will not do what you are wanting it to do. Comment out that line. Line 59 only occurs when you're shooting (but it's supposed to be your movement mechanic that replaces line 71)
You're getting everything mixed up. The issue isn't your shooting mechanic, it's your movement mechanic that's faulty - overwrites the velocity with the assignment operator (the equal operator = ).
Hey Ho! I have 2 types of Projectiles, one that shoots at a direction and one that shoots towards a position and acts once it gets there, from there on out many more types come out (For example a sniper as normal projectile and a rocket as targeted projectile) I have thought about using abstract classes, but the only thing the projectiles have in common are that they come from an owner and do an action once interacted with. Maybe interfaces work better with this but I am just unsure, would appreciate it if any of you could help me on this!
Do any of these objects have a scale other than 1,1,1
Yes
That will affect the coordinate system of any of the children which means their local positions are not going to perfectly align to the position grid of world space
Do you mean the movement that creates the recoil force movement or the player control movement?
Line 71 is the problem
Thank you, that fixed it. Had no idea scale would affect that!
How can I fix it?
Comment that line out
You cannot use that line of code with what you're wanting to do.
I have but my player still can't move and the recoil force never disappears
Move line 59 to line 72
Scaling the object also scales the "inner" space of that object. So for a parent at 0,0,0 with scale of 2,2,2 a child object placed locally on 1,1,1 will be at world pos 2,2,2
Okay but if I shoot now, my player never stops moving back
This implies that Horizontal is your input value
That's what you've wanted to a certain degree right?
To not overwrite velocity
I want the force to slowly go down to 0, so the player stops moving backwards naturally
Yeah
How do I move the LineRender to where I want to be? It keeps spawning at the render instead of the object I set for it to spawn
One "unit" is the size of the parent object. This means an object at local position 1,0,0 is always one "parent distance" to the right
Like, if you shot a big gun, you wouldn't keep moving back forever
You can assume "world" is an object with an identity transform (0,0,0 position, 0,0,0 euler angles, and 1,1,1 scale)
Well, there's no friction in the air. You'll not stop or slow down unless something slows you down. You can slowly damp your speed if you want the object to eventually stop without additional forces.
And the movement isn't enough to stop the shot force.
So how do I have it move within this World?
A ball in outer space or in the air somewhat would.
By changing the position of something
All movement results in changes to world position
Ooh, I see
even if you do the move through local position, the end result is the world position is different
Increasing the Linear Drag on my players Rigidbody would work, right?
Are you able to move with your current script?
Yeah
So how do i move the world position so the Line Render can move with my character and spawn and stretch to a object he clicks on?
Change the position of something rather than the localPosition
position is world space
How would I do that? How do I change the World instead of the local?
By changing position instead of localPosition as I said
Thank you!
On the LineRender?
A line renderer only has one kind of position, it is either always local or always world depending on the checkbox in the inspector
Ok and I have only used Postion in my code so unless we are talking about in Unity. I'm confused
If your code only ever modifies position of a transform, that is world space
Modifying the positions of a Line Renderer depends on whether that line renderer is set to use local or world space
It is using world space yet it doesn't move
Are you actually giving it a position that is different from what it currently is at
Yes, I made it so when it spawns. through Instantiate it should spawn on a object.
By making it equal it's postion
Maybe you should actually post !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
So what position are you changing
The Rope but making it equal (On 57) Playerrope position. (Btw, I just moved it down to GrappleRope as I just figured it was on the wrong place. It didn't fix the issue sadly
Line 57 stores the current position of whatever object PlayerRope is in the Spawnrope variable
Mhm and I use it on Instantate on line 77 or 78 to make it move to said spot
Which looks like it's used to determine the position to spawn a copy of the Rope object at
So Rope will always be at the position of PlayerRope when it spawns
Correct
But it doesn't do that
Yes, it does.
The clone of Rope is at the whatever position PlayerRope currently is whenever it is spawned
Yes, but it also spawns in the same spot. It doesn't move to the play
Hold on
Take a look at the positions of those objects in the inspector. Spawn one, move PlayerRope, and then spawn another. Are they at different positions
How do i upload code again?
They don't move
Well the arrow does
But not the render
Show the inspectors of those Rope clones
The transforms of two of them
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Why did you use the bot and then copy-paste the text from the bot into another message
Yes, but look at the render
They are the same
Well, obviously. You never change that
Nothing in your code even touches these clones beyond creating them
ok so here is my code and RB. My character starts spinning as if his rotation had velocity after colliding with something. What do I need to change?
How do iI change that?
Well, the rotations are frozen so maybe something else is spinning (parent, different body part, procedurally, etc)
You can verify by looking at the inspector values for rotation
I got a better understanding but how do I set it's Index to where my player will be at?
I don't know what you mean by setting its index
The index is which point you want to change
anyone here familiar with Unity's rule tile pretty well?
The Index is the postion it's set to but I can't set a vector3 only a int
Because index is not a vector3
It's an int
The index is the point
I know.... How do I set iyt so it will follow my player
A line has multiple points. The index would refer to which point - first, second, third etc.
Set one of the positions to the player's position
How do I do that. Cause I can only put numbers. How do I set it to my player?
Set one of the positions of the line renderer to the position of the player
Which part of the function are you having issues with?
What have you tried?
If you're getting the signature wrong, you'll need to look at the docs.
@ivory bobcat man I am trying to test what you said but I can't for the life of me recreate it now... I am not sure if maybe it just loaded improperly or what lol. thanks for the help anyway
How do I do that if all I can do is put in a number?
You can do more than just put a single number
Did you look at the link at all
Did you read the docs?
I know I can put in multiple number but how do those number make it spawn on my character?
You change one of the positions to the position of the character
You'd set one of those points to your character's position.
The function I linked you is how you change one of the points in your line renderer
set that point to the position of your player
public static T TryDequeue<T>(this Queue<T> from, System.Func<T> desperateReturn) where T : Component{
while(from.Count > 0)
{
T ret = from.Dequeue();
if(ret != null)
{
ret.gameObject.open();
return ret;
}
}
return desperateReturn();
}
```lol, apparently, I cant use this generic because GameObject's gameObject is not the same thing as Component's gameObject
This implies you're able to get your characters position
is there a gameObject interface between the 2 class?... yea nah
What's the error?
I got it now, sorry but I just wasn't understanding what you guys meant. But I get it now
I cant use it to trydequeue a Queue<GameObject>
(hope you still rememeber how this method try to work)
I'm still not sure why you cannot use it. Is there a compilation error, unwanted behavior or undefined behavior?
Do rigidbodies update through framerate or deltatime?
Im running a game where i need specific timestamps through deltatime and not all of it is adding up
solution is to make a duplicate TryDequeue
https://docs.unity3d.com/Manual/ExecutionOrder.html
It interpolates for loss frames (play catch-up) and can possibly not occur in some frames.
So it looks like something you're doing is trying to use something of type Component, but you're giving it a GameObject
that gets a gameobject queue and returns gameobject, but having these two because of not having interface just kinda suck
What's the squiggly line say?
Pretty sure that's what's hovered
Ah, small screen moment.
you all can see my chat, yes?
TryDequeue expects T to be a Component. GameObjects are not Components
yea, GO is a new class under Object.. appraently, there's no way that component's gamObject property is related to GO's gameobject
even though they are meant to get the same thing
I have no idea what you mean by this
The issue is with TryDequeue
Reference components and not Game Objects
this is the solution to make it accept go's as well
which si nasty haviong to need a separate method for it special
Transform or almost anything other than GameObject should work.
Or just change the restriction on T to not require Component
UnityEngine.Object maybe?
Hey, guys! I have a question. I want on my game to play my particle effect when my player jumps with a space button. Can I somehow make that to happen?
yes
Object doesnt have gameObject property (which is needed in the method)
I was thinking of getting the transform of my player and instantiate the particle but I am not sure if that's correct.
actually this is quite doable, havent imagined using trasnform lol
oh yeah, I've had a similar problem before
Sure why not
i was trying to use MonoBehaviour lol
(and the solution was, indeed, duplication)
Neither does GameObject it looks like
https://docs.unity3d.com/ScriptReference/GameObject.html
At least I don't see it on the docs
How can I make time display in a game? I was trying time.datetime and even divided by 1000 just shot it up really quickly
What kind of time? Elapsed time since launched?
that's weird (docs not having it), prettysure you should be able to do cs gameObject.gameObject.gameObject.gameObject.gameObject.gameObject.gameObject.gameObject
Yes
Time.time
Was originally trying for a scoreboard that goes up each second
Does that not just give the current time?
read the documentation
You could click on the link I sent that tells you exactly what that value is
This value is undefined during Awake messages and starts after all of these messages are finished.
Huh, that's a new one
If you're needing time between two instances and not the entire life of the current process, cache the time (current at that moment) and subtract from the current time when you're needing the score to acquire the elapsed time between the two points.cs score = Time.time - startTime;
i presume that's during the initial Awake messages on the first scene load
i have a Interface for attacks and an scriptible object for characters and i want to save there an script for the attack to later then add the script to the player
I tried cs public IAttack attack; but i cant set it
And what's an IAttack? (Obviously an interface but there's no concrete type)
Use a concrete class for the inspector referencing or you could try the Serialized Reference attribute
Don't recall if it'll work or not
[SerializeReference] won't provide an inspector UI for you automatically
SerializeReference I think you need custom inspector stuff to set it
Ah bummer
https://openupm.com/packages/net.tnrd.serializableinterface/ is a pretty nice option
Although I've only used it a little -- I haven't made a decent-sized game that depends on it yet
So, you know, salt, grains, etc.
i kinda ditched serializableInterfaces
Yeah time.time keeps freezing my unity 😂
I feel like I need to limit it in some way
Show your implementation
it would be nice if they were supported but trying to go against Unity for serialization purposes always comes back to bite me
Like /10?
could you send the code i dont know what you mean
public interface IAttack
{
void RightClick();
void LeftClick();
}``` and this is IAttack
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I barely use interfaces because I cant be bothered with the inspector part, and half the time I dont even write another script that actually uses the interface
Like if your while loop has dependency on it but because it's used improperly, the evaluated value doesn't ever change.
yeah, sometimes I feel like I'm working more on making the editor happy than actually working on my projects
interfaces would make a lot of my code cleaner though
Some code has to actually implement this
It won't work. Unity inspector doesn't work with interfaces without custom inspectors
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this runs a loop until scorevalue is greater than 10
nothing else can happen until this loop terminates
scorevalue never changes inside of the loop
Had to slash it out bc it was freezing unity
unity freezes.
It goes to 10 immediately
That would be an infinite loop
Well 10.004
No, it gets set to Time.time in the loop
Time doesn't pass while your code is running.
Your code must finish before Unity can complete the current frame and start the next frame.
When I load into the game, it's always on 10
When it works
Or freezes when it doesn't
I am trying to make some walkable buttons and number 1 and 2 work perfectly (data.cost[0 - 1])
And i don't know why it isnn't working since it should work fine
so i get this error:```
IndexOutOfRangeException: Index was outside the bounds of the array.
Button.OnTriggerEnter (UnityEngine.Collider other) (at Assets/scripts/button.cs:61)
and this is my code
```C#
if (other.name == "m3")
{
if (data.money >= data.cost[2]) //error is on this line
{
data.multi += data.earn[2];
data.money -= data.cost[2];
}
}```
This is my data script
public class Data
{
public BigDouble money;
public BigDouble[] cost;
public BigDouble[] earn;
public BigDouble multi;
public Data(){
money = 0;
cost = new BigDouble[] {10, 25, 75, 250, 750, 2500, 50000, 250000, 1000000, 15000000};
earn = new BigDouble[] {1, 2, 5, 12, 40, 125, 1500, 6500, 35000, 400000};
multi = 0;
}
}```
I don't know what you're talking about. Do you mean it starts at 10?
as in, scorevalue is set to have a value of 10 in the inspector from the start?
because then, yes, the loop will not run at all, and your game won't freeze
(as long as the score value is over 10, that is)
btw bigdouble isn't the problem, same error with any other var
No, in the update, it changes the scorevalue to 10 before I finish loading into the game
It does it way too quickly
Even /1000 didn't slow it
That is not what your code is doing at all.
As long as that while loop's condition is true, the body of the loop will run over and over
Start:
start = Time.time
Update:
if (Time.time - start > 10)
start = Time.time//setup for the next interval
//other stuff
...```
Nothing else can happen until the loop exits.
But the loop will never exit if Time.time is <= 10
This is almost certainly what you want.
Each frame, you use the current time to compute a value
Ah, so that explains why it jumps in less than a 10000th of a second lol
And that explains the freezing
btw, do you still remember if you could maybe have solved your problem by using Transform instead of GameObject?
Is there a way to not show the decimals or round to the hundredth slot?
string formatting can do that for you
$"Score: {scoreValue:N2}"
this would round to two decimal places
$ makes a string into an interpolated string
And thank, this seems to work, was the while loop causing the issue?
Is there a reason why circle prefab is a Game Object and not a Component like Transform?
you can insert expressions with { braces } and then add format info after a colon
not really
$"{123.456f:N0}" would render as "123"
it could be anything (I was even desperate enuff to use MB)
What's the N0 mean?
N means it's a general number
number format 0 decimal
0 means 0 decimal places
someone else will have to grab the page with all the format options
i'm on my tableeet
Hmn, imma have to play around with that to get used to it
N0 specificall format numbers to 1,000,000
Pretty cool feature though
I love N0 lol, fav format haha
Is there a way to show the time in xx:xx:xx format?
Update already occurs every frame so there's not much point to repeat that process in Update that single frame. Other than that, the process was kept busy there indefinitely and never returned control to the handler for the Unity Window and whatnot causing the OS behavior of the application to not respond - extra details.
Oh, so I was trying to call the seconds every frame
Hey
i have a code
and It is meant to load 1000 files
and i want that during the code loads all those files
it also make a loading bar
rather than the whole game freezing because the code is not finished
https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=net-8.0
Bring out your googlefoo
Regions can't be overused, change my mind.
You were only ever on that single frame running that while loop endlessly
Never truly completing the update function
#regions are good, but you definitely don’t want to overuse them lmao
could smb help me out?
Oh, I remember something like this from regular c#, it allowed for dates and times and other stuff, can't believe I forgot about that 🤦♂️
@buoyant knot, you can't overuse them.
I suppose you could use them incorrectly but I don't think there's overusing them if you do. I'd love both sides to elaborate.
Should probably take that to the !csd as this server is more about Unity where the channel focuses on beginner coding in Unity
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Ok, I mean it could've still been relevant to Unity. The thread's closed.
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
Double check that you have the right components on the player and the ammo item
hm- how can I only make a unit render for a player only if a certain condition is met?
Question, is interpolate or extrapolate more accurate?
enable the GO
GO?
gameobject
right, can do it by component too only if you just care about the render component
otherwise just flip the gameobject on and off
oh right yeah I only want to disable the sprite render
how to check if a certain key has been pressed, for example escape key (Esc)
are there an event that catches if any gameObjectis destroyed?
OnDestroy()
there's no listener only?
Thank you, i also checked google but got diff results each time
public class ExampleClass : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("space key was pressed");
}
}
}```no problem
You can call whatever you want in there
Escape is also the hot key for unfocusing in the Unity Editor so you may get some unwanted behavior in the Editor.
you could hack together a system for listening for OnDestroy() i guess if that fits ur needs
facts, even if i need an Esc keypress i use an alternative until I build
just to avoid any irritations this is bound to cause lol
@deep robin #region MyFunction #region Docstring for my function ///<summary>Docstring</summary> #endregion #region Declare function private void MyFunction(int x) { #region Declare variables List<int> allValues = new(); #endregion #region Loop for (int i = 0; #region Loop break logic i < 10; #endregion #region Increment index ++i){ #endregion #region inner loop myList.Add(i); #endregion } #endregion #region Assign list this.myList = myList; #endregion } #endregion #endregion
There's an option to disable usage of Editor shortcuts while focused in the game window, so that shouldn't be a problem if that toggle is ticked
yea, could be like fun if there's just a single object that catches events too, rather than just a sender version
i’m really proud of enclosing the for loop declaration with 4 separate #region statements
wouldnt figure that'd be very optimized
actually that might be right
particle systems go BRrtrtrtatata
can you collapse nested regions?
yes… as long as you are willing to manually collapse/expand when you reopen one
IDE remembers which #regions are collapsed, even if nested in a collapsed one
lol, no Ctrl+ shortcut eh
CTRL+A, then DLT collapses all
into oblivion
nested regions are nasty to begin with
removed the Joystick.. all touch controls now 🙂
👍
now just needs to be more responsive, i think
you think? i added some lerps and slerps for smoothing
it was super responsive
it would get into a rotational whirlwind lol
it just looked like the first one didn’t respond to mouse
oh no it was just a raycast ripple effect spawning thing
the 2nd one is the movement
oh then that is fine
main controls I expect:
- Double tap to translate,
- Drag to pan around a point
- Pinch to zoom/unzoom
might feel totally different on the phone
you might also want two finger drag to translate
and for rotations i expect
not sure how that would feel tbh, but it might be worth testing
two fingers can pan, zoom and rotate
all at the same time..
thats what i commonly see
Yesterday I was looking for Inspiration for the type of game i want to make.. and i found Door Kickers (2)
looks easy, probably super complicated tho
AI movement is always my stall point
plus in this game the spline follows the navmeshagents path... as u draw
cant even imagine where to begin with a mechanic like that
i would make a game idea before you implement anything
ya, absolutely..
the only way i can imagine the camera being a core gameplay mechanic is with a 3D scavenger hunt thing
which might be a unique idea
eg a 3D collectathon platformer without the platforming
Trying to make a light appear on my gun for a second when the player shoots, but my light is not being enabled when left clicking? Anyone know why? Is it an issue with 2D lights?
Can you show the inspectors for this object and also GunLight
Your Light2D is already enabled
This script it attached to the particle system which I'm using for bullets
and the object it's on is not
Camera is a side character... (i hope)
mechanic might be toggling targetted enemies.
like an auto-shooter.. but you have to swap targets according to ur setup/surroundings
but its a organic developing situation
is this bad to run 20 times per frame? I know I shouldn't worry about optimisation very much at the beginning. But I was worried this might be egregious.
i condensed lines 24 and 25
yes, that is bad
2 GetComponent calls per object per frame is definitely not ideal. Your list should be List<CommandButton> rather than List<GameObject> and you won't need to do a GetComponent call at all
ok yeah, I wasnt gonna optimise it unless it was bad. but definitely did that. Is it bad now?
Or at least use TryGetComponent<T>(out T) to reduce it to one call
a GameObject is not a command. that part is confusing already. the list should be of CommandButton type . . .
Significantly better but I wonder what's the point of the loop if totalFill is only going to contain the last fillAmount in the list
oh oops i misplaced totalfill
Also why you're incrementing i each time instead of just using myCommandsList.Count at the end
oh didnt know about that
im being dumb
i did know about that just didnt connect the dots
why var i instead of int i?
here we go again
no reason was just the first draft of it. is one better?
no
If totalFill is only used inside of Update why is it a field?
good point
What would cause the initialization of a C# class to result in 'null' when it inherits from MonoBehaviour, but not when it's a plain C# object?
are you doing something silly like calling the constructor for a MonoBehaviour?
It's just MyClass class = new MyClass()
Show your implementation
Yeah, that would be calling the constructor
yeah that's the problem. you don't manually call the constructor for a MonoBehaviour and you should be getting a warning in your console that tells you that
You would use Instantiate instead
or AddComponent if you just want to add the component to an existing gameobject
Ahh right. I recently moved from Monobehaviours to C# objects for these custom classes, and then changed it back to Monobehaviour so I could test something on a gameobject
I wish you could somehow configure C# classes in editor without them having to be monobehaviours. Although I'm sure there's some valid reason that's not possible, lol
If you make them serializable, you can. Have a mono behavior script reference the class type and you'll be able to modify it's fields in the inspector for that mono behavior.
you can provided the classes are serializable and a serialized field of some monobehaviour
Oh wow, look at that! Thanks both
hi
im adding a feature where if an enemy is in range, it stops moving and attacks
how would i go about doing this
(making it stop)
void Update () {
step = speed * Time.deltaTime;
if (Vector3.Distance(transform.position, player.position) < 5 ){
transform.position = Vector3.MoveTowards(transform.position , player.position ,step);
}
``` this is how i currently handle movement towards player
Distance formula, collider with circle/sphere check, physics callback etc
State machines are useful, you could have a "chasing" state where the enemy just moves to the player
Then change to a "ranged attack" state when you are close enough
but if i keep this in update it would keep moving even when in range for the attack, wouldnt it
I do not see what this error could be referring too in this line-
explosionHits was null
Did you initialize that variable to a new List<Collider2D>() somewhere?
I just have-
The list is null.
oh its supposed to colliders isnt it
It works because Collider2D derives from Component, so you can add stuff to it
But it's best to use the most concrete type available, if you're going to only store colliders, then yes it should be a list of Collider2D
How can I make my Vector 3 accesible for all scripts but mantaining its privacy?
that
looks like a lot of errors I do not understand
I'd make a property that exposes the field, read-only:
// Keep the field private.
private Vector3 _vec;
// Short for 'public Vector3 Vec { get { return _vec; } }'
public Vector3 Vec => _vec;
Thanks a lot bro
Then all your other scripts can access Vec and will receive a copy
thanks a lot again
but if that vector changes its value through time, does it have the same alterations in the scripts I use it on?
Yes, the property evaluates the value of the field and returns it each time it's accessed
thanks bro
this is very useful because you don't want random scripts to just alter your variables whenever the hell they want
whenever you declare a public variable, imagine a public toilet. very good analogy
and if you want to expose a List or Dictionary as readonly, you can always do:
public IReadOnlyList<int> MyList => myList;```
what could this mean?
=> is just short for making a lambda expression, which is just like a 1 line function
The first one happens when you modify a list while foreaching over it (very illegal).
The second one happens when you destroyed an object, but still try to do things with it in a variable (very illegal too).
The last two are editor errors, and may have caused the first two, or vice-versa.
Select (don't double-click) the first error and it'll show more details.
in this example it is not a lambda expression, it's just expression body syntax
I'm always confused about the emphasis on setting things to private. If variables are being accessed by other classes in unwanted ways, isn't that your own fault for writing bugs?
defensive programming, prevent bugs by just not allowing them in the first place
true, but it feels similar to how you do syntax for lambda
bool MyFunc(int x) => x > 0;
is the same as
bool MyFunc(int x) { return x > 0; }
it's the same operator, yeah. but it's explicity not a lambda expression which is an anonymous method
fair
Yep look at the stack trace
The first two lines are internal code of C#, but the third points to your own code (CodingRaycastTest, line 97)
if I need to modify list as I enumerate through it, I iterate backwards
for (int i = myList.Count - 1; i > -1; i++) {
myList.RemoveAt(i);
}
ah so its here
Two lines above the one you highlighted
You remove one element from explosionHits, while iterating over it with foreach
SPR is right. won't work
doesn't let you use what
the vector Im trying to make public
@desert elm like this
be more specific about what you are trying to do and what is actually happening (and show relevant code)
If you want to remove elements, what you can do is use a reverse for loop. In your editor type forr and [TAB]. It'll auto-complete a whole reverse for loop automagically
yeah- a bit weird, as I copied the code from another script which worked fine
this is from other script
don't do this lmao
you're just copying the list with the ToList method
in explosionHits.ToList() creates a new list, which avoids the error
yep . . and I for some reason removed it when I copied it
you cannot use a non static value in a field intializer. you could make that a readonly property that just returns _characterMovement.PlayerVelocity instead
we're literally telling you how to do it right, and you are refusing to do it
.ToList() is wrong to use here
I also hope you know that GetComponentInParent<Transform>() is the same as doing .transform
what?
Also you forgot to name your field!
private Vector3 = _characterMovement...
^ NAME expected here!
oh yeah that too
found out later from a friend after writing the code, I know now
you can't just say "what". i'm not about to explain that entire message, if you don't understand some part of it then you need to actually ask clarifying questions.
But i'm also not about to explain properties to you again so 🤷♂️
wait why?
Just in case, insisting on the fact that this does not get the parent's Transform. GetComponentInParent will search yourself (the object this script is attached to) before going up.
So you get your own Transform
yeah, I am aware
thats why I didn't change it
I'm trying to figure out how to use the internal keyword more.
So let's say I have 420 scripts/classes in main assembly, and a group of 69 scripts/classes in that need special access to each other, and the 420-69 scripts need access to these 69 scripts, and visa versa. Is there any way to break up the 69 scripts into a different assembly? Because that would be cyclic dependency, right?
can't have cyclical dependencies, yeah. so if you have two classes that need to reference each other they'd have to be in the same assembly
but that may also be an indication that your code is too tightly coupled
so internal keyword is useless, and C# has no way to allow me to set access modifiers like this?
internal is basically the same as public but only within the same assembly. other assemblies would not be able to access that
well, I have a singleton LevelBuilder where other scripts need to send requests to in order to change the level. But I want my LevelBuilder to have a whole set of classes where they just talk to each other mostly to actually do the building
i'm not sure what you mean here
internal does exactly what it says it does: restricts visibility to the same assembly
internal keyword requires you to actually have an assembly that is totally decoupled (in one way or another) from the rest to function