#archived-code-general
1 messages · Page 403 of 1
That's how we end up with untested spaghetti code with files 15000 lines long, classes 6000 lines long, and functions 2000 lines long with 10 different arguments. Because programmers think that DRY, SOLID and GRASP is unnecessary
And it's all untested, of course
right and you think a fully DRY & SOLID codebase is something you actually want to have, you try that and report back in a couple of years.
it's an upcast to Object to ensure the right bool conversion is called
isn't it necessary though
ah there's no cast at all there
You should go had have a look at the very popular Easy Save asset, their code is full of it
it's called boxing and unboxing btw and it's horrible
Ah yes, very hard to understand that the first three parameters are always x, y and z
If this is your argument then just use the Vector3 overload
(isn't it this signature though https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime%2FTransform%2FScriptBindings%2FTransform.bindings.cs#L147)
Also, if you have unnecessary arguments then often the answer is "pass an object". This is not applicable here, though. But neither is it necessary anyway because it's very clear what the usage is
Actually, it would be applicable. But guess what, there's the Vector3 overload so it already applies
ah it's already typed as Transform which doesn't override (or inherit an override) to Object's conversion, so no upcast is necessary, right?
@quartz folio
To be clear that isn't boxing, that's UnityEngine.Object
It stacks together in the solution once you take this approach and say "it's fine". But yeah, Translate(0, 10, 0); is harder to write and harder understand than TranslateY(CharacterHeight);.
Magic numbers, too.
BTW the part you reference here talks about passing boolean parameters
Idk how this is relevant
The relativeTo is used as boolean in the if statement.
How is this not relevant
So like I said, if this is an issue use the Vector3 overload
Translate (Vector3.Up * 10)
It's used as a boolean in the function
It's just checking that the object exists
Also, TranslateY(10); still uses magic numbers so I don't see your point
that's not a fair comparison at all lol, think about Translate(0, CharacterHeight, 0) instead, or Translate(Vector3.up * CharacterHeight) if you really don't want magic numbers
Until the day someone copies TranslateY() 3 times and forgot to change it to TranslateX but no one noticed because it's just one letter difference.
it isn't; unity overrides bool conversion to check if an object is valid
That's very verbose, now we're doing math.
Are you telling me Vector3 is not used for math?
My life has been a lie
Well, it's Translate(0, CharacterHeight, 0) vs TranslateY( CharacterHeight)
The Translate still has 2 magic numbers in it.
And 2 more arguments
That you have to repeat all the time
0 is not really a magic number
When you translate by 1 axis
0 as a magic number is hilarious
you could use like, uint32.MIN_VALUE, i guess? lol
Those are not magic numberssssssssssss
10 is
You still use 10 with TranslateY
It is, but you can encapsulate it and not repeat it. Again, DRY.
i feel like you're just spewing buzzwords without really understanding how to properly apply them now
I feel like this whole discussion is based on somebody being overly confident in the wrong approach and not accepting valid criticism
Next thing someone is going to tell me if (list.Count == 0) abuses magic number and I should refactor to if (list.Count == MIN_LIST_COUNT).
Wait until you see my constants file that's just 100 aliases for the number 0
The whole convo is a great way to not get anything done. Either way just write the damn code, extension methods or not it doesn't matter one bit if you're getting shit done
zero, z, zreo, zeor, Z, Zero, ZERO, invS1, nul, nil, nada
conventionally -1, 1, * 0.5, / 2, 0 and the like are not magic numbers
That's what I started with: I don't want to unnecessarily write Vector.right, multiply, create new vectors, etc.
What we really want to write is: transform.position.y += characterHeight; and my solution is the closest to that.
where is if (List.IsNullOrEmpty(list)) ?
!.Any()
Linq, no way
Nah, you guys are just doing personal attacks, because your arguments aren't accepted. So far Anikki did multiple personal attacks on bob and now you did one on me.
Jokes on you, just wait until 0 is no longer truly zero and my constants allow me to refactor my code instantly
this is a hilarious conclusion
Nope, I'm looking for better practices all the time and accept new ways of doing things all the time, once it's demonstrated that they're better.
because your arguments aren't accepted
this is exactly what qyou is saying
came for the code, stayed for the entertainment 
i guess you cant because its Unity Native Object with shallow manager on C# side so it requires syncing and due to that directly manipulating member of reference is not possibble
you can manipulate a member of a reference
you can't manipulate a member of a value
No, the way you refactor it is:
if (list.IsEmpty()) and if(list.HasItems()). That's better way to do it.
Because 0 is a magic number?
...well, i think that proves quite a few of our points
calling a method is better than checking a constant?
smh Count is already basically calling a method in disguise
I wonder how Count/Length == 0 is not already clear enough
this make a sense, and since you know that, you already know what happend under the hood
That's a lot worse. list.Count == 0 is a universially understood way of checking if a list is empty, the fact that .IsEmpty doesn't exist and you have to go out of your way to make a method, makes everyone who reads your code to do a double take "why isn't it simply written as list.Count == 0, why does this project adds its own empty check extension method and calls it? I better look into that method to make sure I'm not missing anything."
It wastes so much time.
I've had so many physical double takes when reading code like that lol
Recoiling in confusion
i think this boils down to using known ways of doing things when working with other people
when you ask here, or when you're talking about that kind of thing here, you're implicitly working with other people
if you're using it in your own project alone, that's fine, but you're trying to justify it to a wider audience here, and that's just not gonna fly
I think this is honestly just a matter of experience and understanding the point of KISS
Adding a ton of aliases and extensions is a good way to bloat your project
Yes, because the code explains itself and tells the reader what is being done here, explicitly.
The IsEmpty explains the reader what is being done on the conceptual level and allows the reader to read and understand the implementation if the reader wants.
The Count == 0 only shows the implementation without explanation and forces the reader to reverse-engineer the code to understand what's being done here on the conceptual level.
Refactoring.
I better look into that method to make sure I'm not missing anything.
this is Game Dev not App Dev
and forces the reader to reverse-engineer the code to understand what's being done here
what even???
But the implementation is the explanation
it's literally asking, "is the size 0"
It's so simple it's self apparent
i don't think this justification would fly in app dev either
it could, depending on the specific implementation and the scope of the App
i think if this isn't synonymous with "empty" in your mind that kinda speaks more to your experience
it's a thing that works in every language, every context
well maybe not cstrings
The implementation is the implementation, it doesn't tell you what's being done, you have to understand and then reverse-engineer it.
Also, we're examining trivial examples. In the real world on real projects you end up with this kind of code with the approach you guys are suggesting:
That's just a small part of the method.
Rabobank Livestream 2019 with Uncle Bob | A session about clean coding
The program:
09.00 Uncle Bob - Part 1
11.00 - Break
11.20 - Uncle Bob - Part 2
12.30 - Lunch
13.30 - Breakout sessions (NO LIVE STREAM)
15.30 - Uncle Bob - Part 3 - Including Livestream.
#werkenbijRabobank #RabobankIT #unclebob
who is uncle bob and why do we keep citing him
yes, Translate is a trivial example, we're all talking about trivial examples here
we're saying you're making something trivial harder to parse
This is programming, the principles and design patterns apply universally.
I'm not talking about what this is, and nor is anyone else. We're all talking about trivial examples
they absolutely do not
wrong
Similar situations exist everywhere not just list.Count == 0, for example in a backend app if you see someone writes a SQL query SELECT user FROM users WHERE primary_key = ? LIMIT 1, everyone reading that code will be confused by LIMIT 1 ("why is it there, how is it ever possible for there to be more than 1? Am I misunderstanding how users table is set up?")
Perhaps you don't have experience working with other people, but it's often not about what you subjectively think good code looks like, often it's way more important to have everyone on the same page and work effectively. A big part of achieving that, is to write code in a way that everyone understands.
embedded systems, competitive programming, shell scripts, etc will have vastly different ways of going about things
those are the outliers
in different situations for more "similar" kinds of programming, there will still be different ways to think about stuff
even more so with different paradigms
They absolutely do. Here's a few examples:
- Strategy pattern. Used everywhere: Java library, C# .NET, C++ library, Unity, Unreal, Sprint boot framework. I can continue forever.
- Single responsibility principle. Same list as before.
- DRY. Same as before.
Are you going to tell me those 3 don't apply to Unity?
for example, SOLID doesn't apply universally, they only apply to OOP patterns
No, wrong. Uncle Bob uses functional languages, it's his favorite, actually.
Recorded live on twitch, GET IN
https://twitch.tv/ThePrimeagen
MY MAIN YT CHANNEL: Has well edited engineering videos
https://youtube.com/ThePrimeagen
Discord
https://discord.gg/ThePrimeagen
Have something for me to read or react to?: https://www.reddit.com/r/ThePrimeagenReact/
Hey I am sponsored by Turso, an edge database. I think they ...
he's an enterprise software architecture consultant who co-wrote the agile manifesto and wrote a bunch of books that argue for specific principles as the solution to all OO software development problems. He has now personally abandoned OO in favour of FP. Generally in game-dev his ideas are seen as somewhat counter-productive and missing the mark. they are generally not helpful in writing performant code or code that is too complex to be developed in a test driven environment.
how does the L in SOLID apply to functions
are you trying to say those are the only 3 patterns that exist? or that all patterns are universal?
observers aren't used much in js.
solid isn't used in c.
neither are really used in shell scripts.
etc
For FP, it can be applied to generic types. Function with arguments of a generic type should ensure that the implementation works correctly, regardless of the concrete types of passed arguments.
the problems that SOLID tries to address dont exist in FP or any non-OO code really
Those are just 3 examples. All of them apply universally, you just can't apply them in all situations all the time, of course.
lmao what?
But saying that X pattern/princple can't be appliied in the whole industry is just wrong
how are you gonna apply solid in shells
or cp
of course those don't really fit "industry", but the original claim was about programming as a whole
no it's not, there are many specific situations where ALL of your principles and patterns have to go out of the window. Driver software to name just one
these principles typically apply most in large team, long term, high turnover, monolithic, java/.net development situations.
what also applies to these projects is "excessive funding and waste".
They're not. Again, he says that these apply in small teams that want to do small things. And the way to do big things is to use a lot of small teams that do small things.
not to mention shit performance
You guys just saying false things
And misrepresenting my position.
you really gotta come up with better references than your idol
Yes.
yikes
"he says" is never a good argument
So far only you and Anikki did personal attacks.
I'm not saying it's right, because he says so. In this case I said he says is because Anikki misrepresented the position
Where "it only applies to big teams"
Which is not what it's for
Even if you disagree with it
You can't just take and misrepresent the original position like that
i have an engineer uncle of my own
his name is uncle dane and generally he solves most of his problems by jumping really high and building guns behind the enemy
it's a technique derived from ninja code called ninjaneering
Yeah, yeah, idk what your problem is. Just because someone doesn't take your arguments, it doesn't mean you have to start personal attacks.
Are you 20 or something?
Anyway, let's hear what engineering practices you guys are following? Or is it just "anything that comes to my mind today" goes?
im not sure where you're seeing personal attacks
i'm asking for better references
1 guy on a youtube video is not a very good reference
we're following similar principles, we just know when they don't apply
not sure if this helps the argument at all. but i tend to find that working code is better than clean code (i work alone though so
)
basically yes, backed up by 50 years of professional experience. The solution should fit the problem not the problem is shoehorned into my desired solution
Generally you should first make it work, then worry about making it pretty
I think the misunderstanding we're having here is that Kula thinks we don't understand SOLID & Patterns and reject it categorically.
Making code pretty has the effect that code might not end up scalable enough and/or working in general
i guess that would fit the reactions, yeah
i feel like you're just spewing buzzwords without really understanding how to properly apply them now
you need to stop drinking uncle bob cool aid
this stuff (ideas of clean, dry, solid etc) is extremely outdated/incomplete and in many cases tangential or irrelevant to gamedev.
Anikki also changed his message
For example, making aliases for Translate hides the extra parameters that might be included, so you just make it worse for youself
I personally think the Translate overloads are totally fine, clear, and not impeding anyone if they're seen by people in your project as useful shortcuts to a common pattern
idk what anikki's on since im not him, but
i feel like you're just spewing buzzwords without really understanding how to properly apply them now
this wasn't meant as an attack
im commenting on how you're using the buzzwords, and how lackluster your references/sources have been, and that you should probably consider if you do know how to properly apply them
was the implied question/reflection prompt not clear enough?
Do you mean you Steve? Are you 70 or something?
if not, then what you're following is just a different approach to other people then Uncle Bob.
Which is cool by me.
You're the ones started talking shit and telling me my solution is bad by your standards, then I presented that I have good reasons to do what I do, to which you continued attacking me and what I do.
If you're following an alternative school, that's cool by me.
but globally applying these "clean code" ideas is absolute nonsense made by people with very narrow experience, applying patterns too broadly—often at odds to those who first espoused the ideas
yes I am 70 or something
So you're saying you persosnally have 50 years of programming?
to be clear; im not against the overloads. they're probably fine if you use them a ton
im against your justification, and how you're presenting dry/solid as strict rules to abide by
they are not. they are guidelines
definitely agree with vertx above, i think he said it clearer
yes, exactly
what would be a smart way to implement a free transform object, like what you get in photoshop/illustrator, that will be used to drive methods from my XForm interface that my shapes contain?
public class BoxShape : IShape, IXForm
{
...
...
public void Translate(Vector2 translation) { }
public void Rotate(float angle) { }
public void Scale(float scale) { }
}```
I need each of my shape to have the tool, but I'm not sure if theres any special class types that unity provides (like a scriptable object) that would be suitable for it
but globally applying these "clean code" ideas is absolute nonsense made by people with very narrow experience
This is again, false.
Uncle bob, again, programmed in assembly back in the 70s, then wrote C and C++ and programmed hardware, then Java and C# for web.
That's like more broad than 99% of people.
If Steve is telling the truth about his experience, then he probably did the same or very similar in the type of languages he used.
ok so
my Shapes arent actually unity objects, so its not like I could give them a Unity Component
if you're saying uncle bob is like, the only resource you have
Actually I did a great deal more than that
Yeah of course
and you're saying uncle bob would agree completely with your stance, that dry and solid are strict rules
Because it all changed so much compared to the 1970s
yeah i don't think i trust this uncle bob, or at least your portrayal
do you have a ref on this part
globally applying these "clean code" ideas
no, nothing has changed, we are still dealing in zeros and ones, the difference is we, who were programming back in the '70's' know how they work
i think you're conflating what you've heard with your own interpretation
No, he wouldn't agree. As I wouldn't. They're not strict rules.
You don't apply them all over the place all the time.
You apply them for reasons. In this case I do it, because I don't want to repeat and write more code that's necessary, because it's more text, harder to understand, more errror-prone.
Does Uncle Bob work for the RaboBank?
this chat seems a little busy rn, (+ i am not smart enough to understand that so) maybe forward it to #archived-code-advanced (unless someone answers, in which case just ignore this i guess)
im not sure how 3 numbers is harder to understand
I know how they work, too. I can read this just fine:
😒 what is this now, an old age contest
ok, so how does that fit into your patterns and principles?
what does this have to do with the translate method again?
yeah, but could you write it from scratch?
Yes
the issue isnt clean code, the issue is when developers get into a mindset that their code has to use patterns, without considering if they need to really use one
absolutely
like somebody might think theyd need a whole finite state machine, to avoid the idea of having
if(x) {}
else {}
else {}
else {}
else {}```
like its not the greatest approach for that
but some people have a mindset that anything like this block, is terrible, so it HAS to be a state machine
it's more text
this is generally not a justification. ask about more complexity or repetition
harder to understand
is it? using a 3d vector, or 3 numbers, literally the common data structure/format for dealing with 3d space in unity
more errror-prone
how so? in my experience, well-tested library code is often more resilient than your own code, especially since you can modify your own code
i'd get the justification if it were about, say, repetitiveness, or personal preference, but you gotta stop pretending these objective/general reasons exist
especially when the justification is "thats very slow to have those else statements" and not really understanding that the speed of that else block, means absolutely nothing for the vast majority of cases, especially in the early days of code or when youre learning
how so?
You can pass the arguments in wrong order and when you're reading, you need to remember which order they're in.
Repetitiveness is also the main factor, that's what I asked my question about: how do I remove having to duplicate my code.
"is it slower to use function X or is it slower to do function Y" really shouldnt ever really be a concern
You can pass the arguments in wrong order and when you're reading, you need to remember which order they're in.
it's literally xyz
how would you mess this up
it's xyz everywhere
not unless youre doing something really technical, but if that was the case, its not a question youd ever need to ask a discord server
and what coordinate system unity is in doesn't matter, since your own utility methods are also using xyz
honestly, a lot of people working with unity, think they have to make all their code exist purely for the sake of unity
like people who think every class they write has to derive from MonoBehaviour
with your utility methods, you could also call the wrong function. x and z are quite close on the keyboard
noticing the difference would be on par with noticing wrong argument order, but wrong argument order would be harder to accidentally happen since that's separated in time, you can't really typo that
its something like they think they cant use anything that Unity has, unless its a MonoBehaviour class
Repetitiveness is also the main factor, that's what I asked my question about: how do I remove having to duplicate my code.
this, this is a good justification
the rest was not
with your utility methods, you could also call the wrong function. x and z are quite close on the keyboard
Sure, but it explicitly shows you right there which method you called: the code explains itself explicitly. That's the point.
You don't have to do any reverse engineering whatsoever
The code you guys showed and wrote requires the reader to do reverse-engineering
xyz also explains itself, i have no idea where you're getting this idea of needing to "reverse engineer" a few numbers
it absolutely does not
My code explains itself well and there is nothing you have to reverse
I'm sure theres at least a dozen people in this server, who would look at this and think "how is this able to use Mesh or Debug.Log, when Zen isnt MB"
using UnityEngine;
public class Zen {
private GroundPoint_deprecated[,] _centroids;
public Zen(GroundPoint_deprecated[,] centroids) {
_centroids = centroids;
}
public Mesh GenerateMesh() {
Debug.Log($"New Mesh Generated");
return new Mesh();
}
}```
if you're using TranslateX/Y/Z, you already have to be familiar with the XYZ coordinate system
and using 3 numbers for XYZ is very straightforward
got any examples?
Ok, the translate method kinda does. I agree. But.
You still have to repeat the zeroes all over the place when you have to translate by just 1 axis and you can confuse the axes by mistake when calling that function.
I think it's a very valid question considering this could be related to heavy math computations where extra operations really matter. In other cases it would be way less important. Having these extra methods make a massive difference unless you inline them.
Clean code thread
the solution is to come up with a constant rule for your code and never break it
While passing the numbers, you can pass them in the wrong order.
by mistake? then you misunderstood xyz to begin with
by typo? that's just not gonna happen

Here's a look at that rigidbody-based character controller thing I made a while back... it's not working right.
whats wrong with it?
if it's the floaty jumps, you can add a gravity multiplier (just an addforce going down) near the end of the jump or something
Well, other than all-around jank:
-There are times where the jump button doesn't respond.
-I want to implement the character model independently looking from the camera.
-The jump pad particle thingy doesn't launch me correctly.```
It'll take a LOT more showing than just the game view as to what's going on here.
-There are times where the jump button doesn't respond.
that's typically caused from checking inputs in FixedUpdate
Well, there's a rigidbody system that might cause the body not to detect the ground as it should.
-I want to implement the character model independently looking from the camera.
i dont mess with models much so i dont know exactly how to fix that. i'd imagine you could just have the animated model be a seperate object
could you be a little more specific? whats the code look like, if you dont mind sharing
I'd show more of how this janky setup works, but I can't screen-stream here.
(I am also terrible with code...)
Collider2d.bounds is not Bound2d !!!
and Contains(point) method checks in 3d space :/
Here's what scripts I currently have in here.
https://www.youtube.com/watch?v=qdskE8PJy6Q
The rigidbodyforce script is kinda derived from this video.
A detailed look at how we built our physics-based character controller in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Animation Deep Dive mentioned in the video - https://toyful.games/blog/character-animations
- Custom Car Physics in Unity...
o hey, that's a pretty underrated channel. they're code is really good
also, i am actively reading the code, gimme a sec
have you tried just making the onGround variable the raycast?
a raycast just returns a bool anyway
grounded = Physics.SphereCast(transform.position, GroundCheckRadius, -transform.up, out RaycastHit groundHit, GroundCheckDistance, whatIsGround);
(from a recent, similar character controller of mine)
guh, i have no idea how to properly use discord formatting 
According to my bro, the groundCheck function checks how far the ground is from the player.
i think the code should look like this
RaycastHit groundCheck()
{
RaycastHit groundDetection;
onGround = Physics.Raycast(transform.position, -transform.up, _rideHeight, out groundDetection)
return groundDetection;
}
yeah it should, looks correct
you sure its not the inputs?
generally they just check whether or not the player is on the ground rather than distance
There's also the whole "Ride Height" and "Coyote Time" to consider...
But, before we get to that...
Compiler Error
Argument 4 may not be passed with the "out" keyword.```
@quick token
i didn't import the code into a project so i dont have the autocomplete 
might just be the wrong ordering
To be clear, you're getting errors and autocomplete in your IDE, right?
I'm using visualstudiocode.
The errors show up in Unity's console.
!vscode
With how janky and dysfunctional my setup is, I am seriously considering building off of movement lab.
I just finished my full MovementLab project file and created this trailer to show you all it contains.
Make sure to read the note pinned in the comments!
Version 1.1 Trailer: https://www.youtube.com/watch?v=W4zPXPo2NQ8
MovementLab project file included in all of my Patreon tiers!
(The cheapest one is 5$, which is more than just a fair price!...
sure, that works. i think there's a bunch of character controller scripts on the asset store too. should be a couple for free
Hello so i got this code here and there seems to be a problem. This is supposed to show a dialogue once a character is near an object and the players presses E. but for some reason it wont work
The PlayerIsClose bool never turns true even when the player is near the box collision of the object. Although when i manually set it to true it does seem to work. Was wondering if anyone knows a fix or advice https://paste.ofcode.org/7ESpgUdrKJJYuGBX78iH49
OnTriggerEnter only checks the first frame of the collider colliding with the trigger
try changing it to OnTriggerStay
you should also consider adding some kind of check before, to make sure that just any object cant trigger it
YOur logic doesn't make any sense:
if (Input.GetKeyDown(KeyCode.E))
{
playerIsClose = true;
}```
pressing the button doesn't make the player close
OnTriggerEnter makes the player close.
yeah i was going to say that too, consider changing the variable name
You should have that bool and then in Update handle the input
void Update() {
if (playerIsClose && Input.GetKeyDown(KeyCode.E)) {
ShowTheDialog();
}
}```
quick dirty example
OnTriggerEnter/Exit should just set the bool true/false
in fact line 25 of youir code is ALREADY doing this
Just get rid of the input check in OnTriggerEnter
https://paste.ofcode.org/gpDFDi7DdVuSCyrp9mrX8i could someone help me clean this script up a bit. it was going fine until i tried adding the ability to play previous songs
the whole script seems to work fine. but when i get to the last song the "previous" function stops working
i get an error saying the queue is empty
Playlist.PlayPrevious () (at Assets/Music/Playlist.cs:78)
InvalidOperationException: Queue empty.
previousMusicQueue is empty, you need to enqueue audio clip instances before you dequeue
Alternatively, use TryDequeue
Unless I'm missing it, you never add anything to the previousMusicQueue?
I don't see Enqueue added anywhere anyway. Source: ctrl + f
public void PlayNext()
{
previousMusicQueue.PlaceAtFirst(musicSource.clip);
musicSource.clip = musicQueue.Dequeue();
musicSource.Play();
}
yeah its a bit messy, im trying to figure out how to do it more cleanly
its in the commented out part at the bottom
When a song finishes (or is skipped) you need to add that song to the previous queue - you are not currently adding anything to it, so you get an empty error
previousMusicQueue.PlaceAtFirst(musicSource.clip); < this line is a function i added manually (im trying to replace it with a list but im having some trouble with it)
oh lol i get it now thanks guys ill tweak the code a bit
i feel like i should be able to replace all this with a list, but using a queue seems
until i try adding the ability to play the previous song
never heard of Queue before
shouldn't "previous" be a stack
or you could just use a single list that you transverse, instead of a queue
Just use a List, and get the last element of it
that way choosing the previous song would just be going backwards through the list
oh yeah that should work. i kept thinking i'd have to use a queue for that for some reason 
thanks for the help, i'll try fixing it now
if you do want a queue, the "previous song" queue would have to be a stack, so you get FILO order
the most recent song is the first taken out (which i guess is more like LIFO)
I mean the whole point of a queue is to return items in a FIFO order. Using a list with a manual index just reinvents the wheel
You just have to properly add items to the list of previous songs as a stack and it works fine
i just googled what a stack is, how have i never seen this 
that sounds a lot more like what i was trying to do with the messy queue
Also, considering Dequeue/Pop expects an entry you either have to check if it's not empty and/or use TryDequeue/TryPop instead
but wanting the extra layer of going back to the previous element kinda defeats the purpose of the queue
you'd have to put the current element at the front of the queue
oh yeah i did get an error from not having that. it was only when the queue was initially empty so i left it out. would be good to remove another error though so, will do 👍
if the list of songs its constant, simply manipulating the index of array would be the best approach
I suppose it could, but seeing as the code had a shuffle system it would bring unnecessary complexity
the constraints you have here are
- playing stuff in insertion order (so, queue, list, array)
- adding new stuff? (not array)
- being able to go back (not queue)
so you will need some kind of list
oh if there's also shuffling then a list makes even more sense
its shuffled on awake, so from this point of view its constant, the array doesnt change its element order/size
I wasn't disagreeing, just pointing out the obvious
you might be interested in #archived-code-general message
oh good point, i never actually thought of that
If I were you I'd stick to having a Bag like a List or array where all your songs are, and a queue for the items in the current playlist. Lastly, have a Stack for previous songs.
Depending on your use case, separating them in three might be better here instead of a single collection, considering possible added complexity when you want more features such as shuffling. YOu might not wan tto shuffle your main collection that you are listening through
Also, for example, shuffling the main list might give you previous songs you don't want. Instead you want to keep those as "listened" and not repeat those until you finish the list
@quick token
The Bag class in this case would be List<> or Collection<>
Also depends on use case but this is just a quick thought whilst considering what should be possible
for a little extra context, the musicInitial array is all of the songs in the initial order.
will do with the rest though, thanks for the help :D
i mean, you could just shuffle the part of the array/list after the playhead
Then you would no longer have the unshuffled list
Like with Spotify, you can shuffle or unshuffle
i haven't seen how spotify does it but im pretty sure youtube handles that by just
if !shuffle
play next
else
play random
```over the entire list
and it's not too bad, tbh
or just track the position of a song in inital array, each song have its id by it. Then simply another list with those ids being pushed in on song play, so you have tracked history of played songs.
Simply:
- Array of all songs
- Array of played songs ids
- Temporary array for shuffled ids of songs to play
Yes but how would you unshuffle a shuffled list
Because pretty sure even in Youtube's case you'd unshuffle and get the original list back
youtube doesn't shuffle the list
the shuffle option just ignores the list and picks a random entry
At this point just use two separate lists lol
A list of ids is less convenient than a list of references
youtube mobile (a while ago, idk if it still does this) has a shuffle button instead of a shuffle option lol
But then you lose the ability to know which song comes next unless you keep track of the list of ids that come after
Also, risk of playing the same song twice in quick succession
yeah, sometimes that risk isn't too bad
not really? just pre-choose
pre-choose?
uhhhh not sure how to explain what i have in mind
Compared to just not thinking too complex and having a second queue instead which does allow it? 🤔
(not sure if im talking about the right part here, but the initial list of songs stays constant)
the shuffle option as i described before, but randomized 1 song in advance
Yes so you have no idea what comes after that single randomized song
but you shuffle it
Also you'd still have to track the next song
yeah that's typically not really an issue
Might as well use a second queue for the list of songs
i mean... you wanted to, right? are we talking about the same thing?
i thought you were talking about showing the user what song is next?
Yes, but if you're going to do that for a single song then I don't see why a second queue is not the better option lol
less to move around
i still don't think queues make sense in the context of being able to shuffle
And in return you can only shuffle a single song beforehand with no way to extend it
i suddenly remember the second part of my problem 
that's.. not an issue, though?
isnt it better to have 3 arrays? one for all songs and 2 others (played songs cache, shuffled songs cache) with just the index where its the song stored?
The whole point was limiting yourself just to be able to use a single queue
I think it's pretty clear it's not a good idea
it helps to share the error...
Idk what PlaceAtFirst is
i think we have very different ideas of what the constraints are
error is just that it doesn't exist anymore. sorry i thought the context was in the script link i sent earlier
i don't see how the problems you mentioned are problems
i just think a single list is a simpler design
not a better design, just a simpler one
By using a List you're unable to get the original order of songs after shuffling
Idk how I can be more clear
it may well have been, but no one is actively going to remember those details as soon as moving on!
yeah my bad lol
if you shuffle the list directly, yes
but do you need to get the original order? that's just not a design requirement in my mind
just shuffle the cached randomly pulled indexes
Taking Spotify and Youtube as an example which allow it, it's a very user friendly approach to be able to unshuffle a play list
if you want to preserve the original order, just randomize next instead of shuffling
Imagine wanting a song that has now disappeared because you shuffled
dont event need to shuffle when its randomly pulled each time
youtube doesn't have unshuffle
youtube doesn't really shuffle the list, it goes to a random entry when the current entry is done
yes it does, it just doesn't show the next song in the shuffled list
Exactly
But you can still turn it off
That's my point
it doesn't have a shuffled list
Okkkkkkkk then just look at Spotify
Point is, there's a very good reason to not make it so compact because you missed on a possibly crucial feature
And that's why I pointed out to not do that
You just can't do these things with just a single List of entries
nvm it does it just doesn't show it in the ui
possibly crucial feature
i don't see how they're crucial yet
I thought that was what you meant, it does have shuffling in general just not the UI
yeah i thought it didn't but just checked and it appears to
anyways; we're talking about different things here
you're talking about a general solution
im talking about a simple solution, which just covers very basic design requirements
i know it doesn't have those extra features, but i don't see how they're necessary at this point
like, we're just talking about a basic system right? were there advanced design requirements discussed earlier that i missed or something 🫠
Their requirements were related to a bug and they didn't need to have more compact code as a solution
At this point this is just a matter of the right approach and I doubt Jordan even cares 😄
that's, not really what im talking about
I don't really think it matters anyway because we're both talking to a brick wall that thinks they know better
im still lurking, i got a little confused a while ago though ._.
my point is; if you don't need the advanced features, a simpler system is easier to maintain
An extra queue if very complex indeed
You know if we talk complexity then the queue fits in better over refactoring to use a list anyway
that's also not what im talking about, but ok 😮💨
And their initial problem was solved by checking for an empty queue and making sure songs are added, not refactoring to use a list 😄
im not talking about the problem, either...
tried making it a single array and now i can only hear coconut mall 
Probably forgetting to update the index
A queue automatically plays the next one, but a collection needs its index updated
Otherwise share code @quick token
Hi, im fairly new here, but using unity for a while.
Does someone know how i can relate an item with an inventory?
I feel like, i cannot use the grid layout, because its only for single slot items.
I already found very useful interfaces like IBeginDragHandler, IDragHandler, IEndDragHandler.
The tutorials on utube arent helpful for me.
is this for a game with an "inventory tetris" style system?
https://paste.ofcode.org/38RC9bMxSFmFRt2uy7kRxun (== on line 29 is meant to be !=, just fixed that but that didn't fix the unending coconut mall
)
i think so, its for an action rpg like diablo.
its not currently shuffling, index seems to change randomly (when i play next or previous)
is the issue with shuffle on or off?
also next/previous should be wrapped on the 0/array length, or requeue, so you don't index out of bounds
o yeah, just fixed that lol
doesnt seem to be the issue
i think the issue is around line 29
i think you could kind of work around it with the builtin grid layout since children (eg the item graphic) can be larger than the layout size of their parent, so for example that hat could be laid out in the top-left square and have an image inside which overlaps the adjacent squares... but it might be less confusing to implement something custom
(btw as you have it it'll start on the 2nd song instead of the first)
h u h 
that is what's happening
i have no idea why
did i miss something obvious?
you increment before assigning the clip
currentSongIndex starts at 0, you do playnext, it goes to 1, then it starts
no im asking what setup you have where you're having the issue
shuffle/loop/loopsingle, on or off
ok so it's just requeuing endlessly
currentSongIndex == musicQueue.Length is false
loop is true
probably gotta clean up the logic there
if loop and loopsingle are false, does it just stop when it gets to the end?
(as in, is that what it should do?)
if both are false it just plays the next song (which will requeue if the next song is the last song)
yeah this definitely needs some clean up
i mean the end of the list
like for example in that screenshot setup; if loop is false, and price p5 ends, what should happen
should just requeue and then stop. requeueing doesn't cause the audiosource to play (i think, maybe i changed something and forgot)
i think i've almost fixed it up now
if musicSource.time >= musicSource.clip?.length && !loopSingle:
if currentSongIndex < musicQueue.Length || currentSongIndex == musicQueue.Length && loop:
PlayNext()
```and then have PlayNext handle requeuing & loopSingle?
yeah sure i can add that. forgot that loopsingle doesn't even need to be in update
I have arrived to a problem which is oddly similar to the circle vs ellipse problem, where B is A but B must not inherit some of the A method. What is the solution to the circle-ellipse problem?
Decompose A into C and D. Give B a C but not a D.
Instead of:
class A {}
class B : A {}```
Make:
```cs
class A {
C c;
D d;
}
class B {
C c;
}```
B have the same method as A, which is X(). However X() is works differently than the one in A due to constraint. How do i decompose the method?
Use interfaces
That was my exact problem
i just got an idea out of that. thank you.
class A : IHasC, IHasD {
C c;
D d;
}
class B : IHasC {
C c;
}```
But then B is not A if i do that
Is it possible to decompose the method while keeping the "B is A"?
Why does B need to be A
Can't B and A just be IHasC?
Because by definition it is
B is not an A if it doesn't have all the parts of A
you're presenting an impossible conflict of statements.
To use A and B in a common place you can use the interface IHasC
This conversation might be easier if we use concrete terms and concepts
what's the actual use case here?
Hmm thanks, that does make sense. Maybe i need to read more about the circle is ellipse problem
wow, you rewrote the whole thing 
i was almost done debugging too lol
i see where i made a lot of errors now ._.
please don't spoonfeed
https://paste.ofcode.org/36enCLJaidgaXb2x29smWAa < here's my version
musicSource.time = 0;
this doesn't make sense to be inside the if
oh yeah, i was just trying to copy spotify there
oh wait no good point
i'll have to add another check for that one or something
or maybe a bool
maybe check if the current time is less than some threshold
yeah, i'll probably add that as a private field to be set in the inspector
also put the whole script (and an example scene) into a package, if you want to give it a try
i've been having (the older version) play in the background of a project im working on. its pretty fun to have some (totally legally acquired) music playing while i play
*may have added a couple too many songs though
*
added it 👍
he already tryed for long time, and keep trying, so thats just a form of inspiration at this point
i do appreciate the script to help too. i dont actually have a formal education in computer science or anything. having a script to look at is definitely more useful than reading the docs for another week lol
- i really need to learn proper naming conventions. my variable names are a mess

hello im trying to do local multiplayer but im kind confused on why the inputs dont work im using new player input and ive placed the right binds but it wont move the character
if im usinging the normal script it does work but then i cant do the local multi binds
the movment code
https://pastebin.com/EteW434x
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
naming is an art not a science, conventions can only help so much... welcome to the hardest part of programming 😛
the worst part come when variables are named correctly but are too long and mess up the readibility
Only the one with truly good intuition will be able to understand such names. Try to shorten everything. Only a worthy person should be able to uphold the development of your code.
lmao wat?
goofy satire though, love it
i skimmed through and didn't even realise it was satire at first lol
probably should've noticed after seeing "underscores for fun"
literally the first block
Irony detected
Many try to follow ninja paths. Few succeed.
idk, sounds professional to me 
One-letter variables I would fire you immediately lol
im not gonna stop using one-letter variables until i get through the whole alphabet (i only t lol)
i got called out by underscores 😆, i use them for private members of a class, so i know instantly its private/protected member of a class, so its easy to know where to look for it when used inside a method
or just use a proper IDE
makes sense to separate serialized from non-serialized private members (if you have conventions about them being handled differently)
code with _ looks disgusting and its very unecessary imo
m_ its better?
just as shit
camel case it, you already know its a private var..
Pascal Case, its a property or public..
_ are cool for private members
if you have conventions associated with a member it makes sense to make it obvious when a that convention should hold if the IDE doesn't help. so the underscore is by no means unneccessary
go for it if it helps you, I just find it noisy
btw i have proper IDE, its nvim 😆
Without _privateMember, its style would conflict with localVariable. Mutating a private member has very different consequences compared to mutating a local variable, distinguishing them is imo helpful.
I use locals less often, i use _ for local if i must
for me properties are noisy, 2 methods with backing field in one, with naming convention same as methods
or just this. for members with same local name
properties are just fancy methods, they can get messy too
I would not put more than a few lines in a prop though
the main use of style guides is to make everyone shut up, and you have truly arrived in your career when you finally get to mandate silence over it and stomp on everyone who objects. Then make people work with what they got or quit.
ya as long as the team agrees to the same style, it doesn't matter. A good dev can use whatever the team wants to use for that project
no one-letter variables? got it
class M : UnityEngine.MonoBehaviour {
void Update() {
this.gameObject.GetComponent<UnityEngine.Rigidbody2D>().velocity = UnityEngine.Physics2D.Raycast(this.gameObject.GetComponent<UnityEngine.BoxCollider2D>().bounds.center, new UnityEngine.Vector2(0, -1), this.gameObject.GetComponent<UnityEngine.BoxCollider2D>().bounds.extents[1] * 1.2, 1) ? new UnityEngine.Vector2(UnityEngine.Input.GetAxisRaw("Horizontal") / 1.8f, this.gameObject.GetComponent<UnityEngine.Rigidbody2D>().velocity[1]) : new UnityEngine.Vector2(UnityEngine.Input.GetAxisRaw("Horizontal"), UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.Space) ? 10f : this.gameObject.GetComponent<UnityEngine.Rigidbody2D>().velocity[1])
}
}
i spent way too long doing that
jesus lol
ive had to use the most inane styles at work, and i would never agree to their sanity, but the silence regarding style questions is really liberating
there is no need for anyone to agree, thats the point
ninja order
he is back
ya its like fighting over how to style your shoe lacing lol
Having a code formatter among the static analysis checks your CI/CD system does is ❤️
Speaking of formatter, I can recommend CSharpier if you find dotnet format to not be strong enough for you.
@vestal arch Are you back home yet? I really wanna see that juicy top tier code that you were talking about
Yeah, they all ran away when were challenged just a little. But I had to go work. And I still do.
Like Anikki and that guy went back to chatting here after being challenged.
getting flashbacks to es lint dumbness such as 80 char line limit 😐
i gave you the response why you cant manipulate members of struct of UnityEngine.Object, so we done with that topic i guess
colab also has that dotted line at 80 chars by default 
guess it's an old standard lol
I understand why I can't do it, it's a property with a backing field. My question on what's the solution to this without duplication, and while the solution with just .Translate(0, 10, 0) works, the reason for that convo was because I presented the closest to the original transform.position.y += CharacterHeight, which is:
public static class TransformExtensionMethods {
public static void TranslateX(this Transform Transform, float X) {
Transform.position += new Vector3(X, 0, 0);
}
public static void TranslateY(this Transform Transform, float Y) {
Transform.position += new Vector3(0, Y, 0);
}
public static void TranslateZ(this Transform Transform, float Z) {
Transform.position += new Vector3(0, 0, Z);
}
}
But then got many personal attacks and talked down upon instead of arguments after I challenged their worse(in my opinion) solutions.
ages ago i was working on a JS/TS project and for some reason it had auto es lint applying configured for when you committed (git hooks). I hated it i removed it.
it would do lots of dumb stuff that just annoyed me such as that stupid default line length.
pretty much no reason to even do this lol
But yeah, that's usually happens when people are actually challenged: they just leave and ignore. Everyone can do personal attacks and talk down to other people, but most just run away when challenged to see what they got.
Because people don't care. I as well, left the thread almost right away, but joined in again only because the thread ended up being borderline people attacking each other, and I felt bad that you had to fend for yourself, so I decided to at least offer something so you wouldn't walk away from this whole drama with nothing.
I see that what you really care about is just one upping other people.
It's shorter, more expressive, less error-prone.
"run away" buddy, i don't care. and neither should you
let it go
I'm not seeing it, but if you do then more power to you..
No, that's not what I care about. See how you feel when you get trash talked for no good reason.
oh this guy is still going, i blocked them a while ago
I literally got talked down and trash talked instead of arguments.
Well, you are certainly still caring about it, so I'll leave the mods to it.
And now I'm getting accused of one upping
And being the one to start this
because the thread ended up being borderline people attacking each other
They started it. Don't give me "I care about one upping people" routine when I presented arguments and got personal attacks in return.
And then they just ran away after I challenged them to show the code they write.
But yeah gtg now, I don't want to get dragged into this again
the backing field is on native side, the value have to change so the shallow manager of c# side notify serialization system to write it to native side. Hanging member of value doesnt change the value itself so serialization system doesnt catch it. I know you know this but other reads and this is some good knowledge to know.
Then don't, when you return. If you want to continue debating these things, use the thread provided earlier.
Hey. Im new to Unity and was just wondering if any of you guys know how to transfer gameObjects between scenes with all the values being there still. Im making a turn based RPG and have a battle controller object in a battle scene that has references to all the player objects in the scene. Im trying to make a rest point in the dungeon scene that regenerates all the players MP and HP (I used playerprefs for this). When I load into a random encounter and use the DoNotDestroy method, it nulls a lot of the values in the battleController object that was transfered from the previous battle scene (not all the values from the battle scene battle controller are intact such as the player references). The screenshot I provided is the battleController that is passed from the doNotDestory method: Battle Controller Class: ``` public static BattleController Instance;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject); // Keep it persistent across scenes
}
else
{
Destroy(gameObject);
}
}```
`
it nulls a lot of the values in the battleController object that was transfered from the previous battle scene
Nothing is changed on a DDOL object or its components when a scene is loaded.
The reason those references appear to be null now is because they are holding references to objects that were destroyed when another scene unloaded.
how to transfer gameObjects between scenes with all the values being there still
In other words, this happens by default. The values do not change.
Is there a way to dictate the order of rendering of UI objects, that does NOT include reordering the hierarchy?
Put them on different canvases with different depths
and/or rendered on different cameras in a camera stacking setup
that sounds like the way to go for me, thanks!
Or consider switching to UI Toolkit which has its own depth system and doesn't use GOs at all.
Unfortunately I'm making a mobile game that is pretty much 100% UI. UI Toolkit, from what I can tell, doesn't have nearly the flexibility I'd need :/
is it still the case that you can't even use custom shaders in ui toolkit?
I'm not exactly an expert in it, but I'm pretty sure you can. #📲┃ui-ux would be the best place for these questions
probably #🧰┃ui-toolkit instead, but yeah
oh sorry yes
sadly I don't think it's an option for me, at least not on this project
I guess I really should learn it though... eventually
Im a little confused. Would I have to transfer the player objects as well? Cause rn it breaks the game cause the values are null. What could I do to tranfer those missing values? When it loads the first encounter, its fine. The values are all there. But when I get into another one, it nulls a lot of the values such as player
Based on your original screenshot roughly 90% of the job of this object is to just hold onto references to other objects in the scene. Therefore it makes little sense to make this thing DDOL in the first place. What's the motivation behind making it DDOL?
The other thing is it looks like this script is doing way too much. Break up the parts that store data that needs to persist and make those DDOL. The part that's largely just holding references to other objects in the scene shouldn't be DDOL, make it a separate component that lives and dies with the scene.
Again it doesn't "null" anything
you are simply holding references to objects that have since been destroyed.
All the things that say "Missing" have been destroyed.
Oh I see
is there a way to blend two material at runtime
im trying to make a day night cycle with two skybox materials
using UnityEngine;
using System.Collections;
public class ChangeSkybox : MonoBehaviour
{
public Material targetSkybox;
public float transitionDuration = 2.0f;
private bool isTransitioning = false;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
if (!isTransitioning && targetSkybox != null)
{
StartCoroutine(SmoothTransitionToSkybox(targetSkybox));
}
}
}
private IEnumerator SmoothTransitionToSkybox(Material newSkybox)
{
isTransitioning = true;
Material initialSkybox = RenderSettings.skybox;
if (initialSkybox == null)
yield return null;
Material blendMaterial = new Material(initialSkybox);
RenderSettings.skybox = blendMaterial;
float elapsedTime = 0f;
while (elapsedTime < transitionDuration)
{
elapsedTime += Time.deltaTime;
float blendFactor = Mathf.Clamp01(elapsedTime / transitionDuration);
blendMaterial.Lerp(initialSkybox, newSkybox, blendFactor);
RenderSettings.skybox = blendMaterial;
DynamicGI.UpdateEnvironment();
yield return null;
}
RenderSettings.skybox = newSkybox;
DynamicGI.UpdateEnvironment();
}
}
They seem to be using that
yeah the problem is that it start from the initial skybox from the scene, than to completely black over time, than straight to the target skybox
indeed - I didn't look at the code 😬
What's the wanted behavior?
to go from the inital skybox to the target skybox in a smooth way
So simply without the completely blacken material?
yes
i have no black material
Log the initial, blend and new material prior to blending.
Assuming the initial and new materials are correct (as you're able to acquire the targeted skybox) the blend material might have some data unexpected. Printing the properties wouldn't hurt.
MonoBehavior still receives OnTriggerEnter2D message even after getting disabled:
public class MyComponent : MonoBehaviour {
void OnTriggerEnter2D(Collider2D Other) {
Debug.Log("OnTriggerEnter");
}
}
```This runs when I disable this component.
I can work around it by checking if it's enabled:
```C#
public class MyComponent : MonoBehaviour {
void OnTriggerEnter2D(Collider2D Other) {
if(enabled)
Debug.Log("OnTriggerEnter");
}
}
```But I thought this is what this property is for: to not get the Unity messages anymore. Is it the default/preferred way to do it for your own components: to check the enabled variable?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Behaviour-enabled.html
it's not all unity messages, it's specifically Update
(maybe other closely-related messages too? idk, the docs only say update.)
seems like only Update's docs mention "only called if enabled" as well, so i guess it is just that
oh and Start
Log cs Debug.Log("OnTriggerEnter"); Debug.Log($"{other.name} hit {name}"); Debug.Log($"Click to see {other.name} highlighted", other); Debug.Log($"Click to see {name} highlighted", other);
Now, I admit that I'm kinda solving a problem before it appears, but is there a way to do a "async-instantiate" if I have a really large single prefab I want to load in?
I know I can just add a whole another scene, but it's really not the most ideal option in my situation
the goal is to hide it underneath an animation
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
Note: Trigger events are only sent if one of the Colliders also has a Rigidbody2D attached. Trigger events are sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.
hide the wait I mean
There literally exists GameObject.InstantiateAsync what am I even asking...
Disable the collider if you're wanting to disable physics interaction with the object.
Thanks, guys.
Also, on the forums people said, I can remove the component from the object.
Yeah, I just disabled the collider atm.
Also, someone mentioned this on the forums:
You could add an ‘isEnabled’ boolean which cancels the execution in TryInteract
public class Chase : StateMachineNode
{
/// <summary>
/// The target to chase.
/// </summary>
[DoNotSerialize]
public ValueInput target;
/// <summary>
/// The <see cref="AIController"/> used as a blackboard for the AI.
/// </summary>
[DoNotSerialize]
public ValueInput aiController;
protected override void Definition()
{
base.Definition();
target = ValueInput<Transform>("target");
aiController = ValueInput<AIController>("aiController");
targetCaught = ControlOutput("targetCaught");
targetLost = ControlOutput("targetLost");
}
}
Alright, bear with me here because this ones a bit dumb but I've been having trouble finding an answer. I've decided I want to use VisualScripting for my AI state machine. I'm working on reimplementing the state machine I made for my AI onto classes that inherit from Unit so that I can use visual scripting to link them up. I can see I need to use a ValueInput class to get parameters into my class, I'm not sure how I'm supposed to actually get the value contained within the value input class though.
uh, i guess #763499475641172029
This kind of sits on the threshhold between the two since I'm writing an actual script rather than linking nodes together. Do you think it fits better there?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i think it would, the folks there would likely also know about the underlying system more than us
wonder if there is any good indie game made with visual scripting
Honestly, after digging through it there's not a lot of support for it.
I would highly reccomend against making an entire game with visual scripting.
same
funny thing is, you asked this in #archived-code-general
Yeah, I fussed over where to plop my question. This seemed like the best place, especially since the VisualScripting section was a link to another discord.
Visual scripting seems most useful if you can hand your non-programmers a pile of custom nodes to perform common game interactions
But it also has to be something you can't just configure in the inspector
I guess it gives you a framework for basic "if this, then that" schemes that can include some complex control flow
visual scripting is for tool programmers to develop for your team
I wouldn't waste your time on it if you're developing it for yourself
yeah
In my case I want to be able to create a handful of state machine nodes, I have them implemented as a series of C# scripts with a monobehaviour driving the state machine and it works but it's a bit of a pain to set up a new state machine using the same nodes.
while we're on the topic
at what point does spamming unityEvents just become visual scripting ._.
i feel like i've been using unityEvents too much recently but i haven't found a good reason to not use them
i just recently discovered them and they've made setting up stuff way quicker, and made my code more flexible
maybe i just need to read up more on events in general
Immediately. Editor assigned events are not actual events in the sense of the observer pattern, they are method calls performed in a visual scripting layer on top of your c# code.
Their problem is primarily that they break easily when you refactor method signatures, they are not reviewable together with code and they cannot be validated by code.
other than that, they are very limiting in what parameters they can pass and you cannot easily see in the inspector what their meaning is, or when lost, what they should be.
they have their place in prototyping but should be removed in production (if you want to stay productive). They remain tolerable when used only inside the same gameobject’s components for simple, non-critical calls (artist usage).
i see, so far i've just been mainly using it within single objects (mainly prefabs). i'll definitely keep all of that in mind though. changing a single variable name would be pretty deadly for the project because of them ._.
that's also a big problem i've seen so far, i wish there were some kind of way to fix that
i look at it this way: the time to originally write a piece of code, is typically much less than the time you spend on fixing its bugs later on. This extra time grows when you use lazy patterns in the original code in the hope of saving you a few minutes. So try to eliminate the possibility for bugs right away, make code as simple as possible but not simpler: In scripting: turn only stuff into data that you actually need to be configurable, in library code: protect your code flow as much as you can from config errors, log warnings and errors liberally, be very pedantic to help yourself and others use the stuff correctly. Validate number ranges and value combinations. This will save your mountains of time. Unfortunately, all this is very difficult (impossible) when doing visual scripting.
A single bug discovered a month later can add days to what originally only took 10 minutes. At the very least it will add 30 minutes, more if you're in a team.
(apparently people have made entire games using visual scripting, i wonder how they did that though, must take a lot of willpower)
oh yeah i see what you mean. UnityEvents have been really useful for a prototype project im working on, but in a full game i can see them getting messy quickly.
as an example, i've "gun" script that uses 2 events for firing and reloading. for now its only doing effects and audio, but that list of things in the event is going to pile up quickly once i start adding animations, maybe more effects and all the other stuff that's going on
unity events are good for quickly doing that, but i should hardcode some of this in later, considering its only on the gun object anyway
i think overall there is little to gain from pushing the scripting responsibility to non-technical people and if you are a technical person you can only loose time (by visual scripting).
i think not even its approachability (because of discoverable API) argument holds much water anymore
yeah that's definitely true. i've always worked alone. but in the few cases i've worked with teams, just having programmer do the programming is a lot quicker than trying to teach the story writer how to lol
these are the ones you may even retain in production because the tech-art APIs in unity are so convoluted, so just as a way to unify how you deal with fx.
oh yeah, if i were working in a team i'd definitely leave those in
but i'm telling you, the things that always cause bugs late in the development are things misconfigured by designers & tech-art.
not their fault, the just dont have the tools to validate the stuff.
(invest in a tools team!!)
In a project i work in we have lots of objects that need special logic and we use unity events a lot to do lots of them due to the amount of them.
I did make some editor scripting to help such as a button that finds references to a mono behaviour instance by unity events in a scene.
I usually prefer to not use them when i can avoid it, i will always sub to an event in code if i am able as its more reliable. But for that game its often best to avoid a lot of unique scripts for many small cases.
maybe if you really cannot see the abstraction in a system that may be a good use case, I would however look very hard into finding one before i'd accept this as a problem.
oh yeah, i've actually been trying to be a lot more mindful of that recently. i've been making a lot more scripts that are general purpose and can be re-used.
games are actually quite simple in their abstractions so i would be surprised if this ever really comes up (absent time constraints)
there is a danger in that too btw, you can easily end up with little components for super useful little things that never quite fit the problem
The issue is we have like 30 environments and like 100+ items in each and often you need to configure say a specific item to unlock a thing in an env when its picked up but another item needs to go in a container and it is soo many combinations we often use unity events to configure the logic for these (e.g. pick up unity event calls the unlock function)
its a bit vague i know, id want to avoid it myself but we decided making a new script for each and every instance was not a good solution due to the amount of such cases.
understood, seems to me you have not discovered the type object pattern yet? https://gameprogrammingpatterns.com/type-object.html
in unity this can be implemented trivially as an empty scriptable object.
and multiple such instances can be aggregated into collections to declare various game design rules like A needs B and C, all with the same symbol that is entirely abstract from your code that runs it.
this way you can abstract most of your design symbols completely from code. you declare only the usual dependencies, like unlock trees, inventories, abilities etc. this frees you to code systems abstractly without requiring a type for everything in your design domain.
With how items are created in this game im not sure this is applicable and most of the initial design was done before i went to work on it anyway.
Perhaps if we knew of such potential features earlier it could have been done better
fair
there is much more that needs fixing in that project but i don't get to work on it as much anymore apart from some bug fixing every now and again.
reminds me i need to look into abstraction a lot more. i've been casually programming for a few years now but i've never actually looked into stuff like abstraction ._.
there's a lot of more complex things i feel like im missing. i've been fine with the basic stuff but i've slowly started to realise that more complex stuff makes programming a lot simpler
it goes in waves, you find ways to improve, overengineer them out of excitement, this leads to you recognizing their true nature, then you truly improve by seeing 'the truth' and apply it, then discover new areas of improvement and repeat the cycle.
the programmer cycle 
i've got a script from a while ago that uses way too many delegates, from back when i first discovered them
🔥 public event Action myCoolEvent; 🔥
also yeah looking at some of the stuff in my project, this should definitely just be it's own script. it's just a respawning target
i dont use events enough, they seem so useful but i never find a good usecase that isn't just the same as a UnityEvent
if you don't need to configure it in the inspector, then you might as well use the event keyword
that's the problem, i always configure it in the inspector 
an event the "normal" version of unity event basically and ofc therefore faster. HOWEVER you have to set it to null on destroy if used in a mono to avoid GC leaks
oh, that's good to know
i've had a few warnings about leaks in the console but i've never had them in a big enough project to have to fix them
The event keyword ensures you cannot = the delegate and it can only be called inside the declaring class instance
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event
i'm not sure how you'd get a leak from that: if you destroy the Unity object it's attached to and then lose all references to it, the object will get cleaned up normally
o, that actually sounds pretty useful. i like to try and keep the autocomplete clean so that could help a lot with that (there's definitely better uses but thats my main use lol)
I may have it a bit wrong but its quite easy in unity to have the managed objects leak and not get GCd for a while (even if the native counterpart was deleted)
well, sure, if you keep any references to the C# objects lying around
also "for a while" is by design
notably, UnityEventBase has no code that would handle object destruction (and there's no way it could even know about object destruction, AFAICT)
unity objects typically only leak easily when you use them in (void) async contexts that dont get cleaned up properly
I thought i read this a while ago but perhaps i miss understood (ofc if you destroy a mono and do not unsub a member from an event then that will cause a leak until the event is also able to gc)
thats not a leak
yes, that's just objects not randomly ceasing to exist :p
a leak is defined as "the GC or program code does not have a reference to the memory"
hello friends I have a little problem that is bothering me I can't find the problem it's not going in the right direction. would anyone help me?
I guess you could label "I forgor to get rid of the object" as something like a leak
but it's not a memory leak in the proper sense
If class A has an event and class B subs a function to class A. Later we Destroy class b. Class b's instance is not gc'd due to the event sub not being removed from Class A.
i would agree that this happens much more easily
well, yeah
I'd hope that would be the case
The more practical concern is that forgetting to unsubscribe can cause bogus behavior
like unity throwing a tantrum when class B's function tries to access transform
Its ofc not the same as a leak in native code but its still something you want to avoid
using an event member v.s a UnityEvent is also completely irrelevant here
you'd have the same problem either way
but its not guaranteed so its a possibility if you forget
well, sure
this stuff is also easily detected in code reviews
you could also call Application.Quit()
if you want guarantees, use rust
ofc why didnt i think of that!
The thing is that this isn't a problem with an event member vs. a UnityEvent member
i think c# strikes a very nice belance between freedom, performance and convenience
Neither of those can save you from subscribing with the wrong things
and im basically the only one working on projects im assigned too now so no more code reviews 😦
You know, that does remind me
I'd like to be able to scan for events that are "suspicious" -- e.g. the number of subscribers is growing without bound
or there are more than zero subscribers after exiting play mode
I have no clue how I'd do that kind of incredibly invasive analysis, though
why do you write code that needs such checks... tsk tsk tsk
foreach (var thing in GiveMeEveryGodDamnDelegateObject()) {
}
from now on i wont make any mistakes thanks to this chat 👍
Something like that
🌠
I like to write validators where I can
I automatically scan for missing references in most of my game's prefabs
can you use reflection in the OnExitPlaymode (or what its called) method?
That's roughly what it'd be; I'm just not sure where I'd start..
I'll have to poke at it at some point
get all types, get all instances, do your foreach over them instances
but how do you get all instances
maybe from the GC?
you could source generate your way into a solution
make your own little runtime for additional checks
alternatively, I just invoke a bunch of events after the game is supposed to be over
and I see if the console blows up
we call this an "integration test", I think
disintegration test
hi , I am making a 2d game and am planning to complete it and publish it on both pc and mobile
however before i start making levels, i wanna consider aspect ratios since pc/mobile have different screen sizes etc... this is important bec the camera doesnt folllow the character, it shows the entire level
can any1 help me regarding this matter? Idk what aspect ratio to choose, how to play around this entire concept
Continuing on the topic of "leaked managed objects": https://docs.unity3d.com/Packages/com.unity.memoryprofiler@1.1/manual/managed-shell-objects.html
I've been thinking about making a Roslyn analyzer for detecting when you forget to unsubscribe and maybe an auto-suggestion for generating it.
so the rule of thumb could be "make sure to null references to large objects when done with them"
Yea i guess, i didnt really think it was needed before reading this and doing a fair amount of memory profiling for a game as we see lots of graphic related crashes (mobile).
It's important to understand how destroying an object means basically nothing in C# land
i've never had an issue with this kind of thing, cause i generally use a lot of manual cleanup/dispose-pattern in my code but its good to be more aware of it
we're just telling Unity that the object no longer exists in the game world
that's a neat article though! i should go peek at that..
it would make sense to have a dispose pattern on all monobehaviours and possibly a Destroyed event
We use addressables a lot so usually textures get unloaded automatically (if we release correctly) but sometimes when profiling ill see stuff still loaded and i have no idea why 🤷♂️
because something still has the reference (in a shell) and it doesn't get unloaded
well duh but the issue is finding why
things can also live for a while before the GC actually eats them
Yea thats true, i just wanted to improve graphic memory usage however in this particular instance
this might be kind of obvious but, i've got a player character who should be able to equip 2 weapons in each hand
would it be better to instantiate the weapon into the hand when its equipped, or just have 2 disabled instances of the weapon in each hand and then enable them when they get used
i've only got 4 weapons so far and the inspector is already looking a bit messy ._.
nvm, i think i got it. i think its easier if i just make a new script for this
Is there a problem with calling Vector3.lerp during update()? I'm moving/scaling/rotating meshes in a grid and the don't end up very aligned at the end.
show relevant code
You can call any function you want in Update.
You are most likely not understanding the math behind Lerp and using it incorrectly though.
tossing this out there just incase
https://unity.huh.how/lerp/wrong-lerp
To use Lerp "properly" you need to call it like:
current = Lerp(start, end, t)``` where `start` and `end` never change throughout the entire course of the motion and `t` changes slowly from 0 to 1 over the desired duration.
Most likely you are doing something like:
```cs
current = Lerp(current, end, Time.deltaTime * something)```
which makes a nice smoothing effect but does not get you ***L***inear Int***ERP***olation.
t being .1f means you are NOT using it the first way
t cannot be a constant value in the first way
it must go from 0 to 1 over time.
well, that's extra wrong :p
Both of these are wrong:
current = Mathf.Lerp(current, end, 0.1f);
current = Mathf.Lerp(current, end, Time.deltaTime * 0.1f);
The first one is more wrong
Basically that t stands for "what percentage through the motion should we be now?
lol
huh, I find it funny that it mostly worked then
so t needs to be some value calculated between 0 and 1 using deltatime?
Again, lots of people use it the "wrong" way and it makes a nice smoothing effect but what it doesn't do is actual linear interpolation or get you all the way to the final value
it needs to be a timer basically, going from 0 to 1
e.g.
float t = 0;
void Update() {
t += Time.deltaTime;
float currentVal = Mathf.Lerp(startVal, endVal, t);
}```
help please!!!, i need to build and run my game but it says "failure" , " u cant build while comiling or editing" even tho am not editting or compiling
(Lerp automatically clamps it at 1)
I need to set a max of t to 1 right if I'm doing it that way?
no ^
oh
What you might find easier than restructuring everything is to switch to MoveTowards
Does that work with scale/rotate?
current = Mathf.MoveTowards(current, target, Time.deltaTime * speed);```
the semantics of what you're doing don't matter
it's just moving numbers towards other numbers
gotcha
it can be done with anything
For rotation though you probably want Quaternion.RotateTowards
Great, thanks, that will save me a lot of time. I spent a while trying to snap the transforms to grid and for some reason that wasn't working either.
@swift falcon unless you need to save your scene, can you just restart Unity?
didnt work
i even restarted laptop
So it's either busy compiling or importing something then? I've never ran into that one
@leaden ice Would Vector3.SmoothDamp also work?
yes but less controllably. If you want a smoothing effect that's what it's for though.
I'm just very quickly rotating/moving/scaling in a runtime editor, maybe it won't be very noticable
Okay, I have returned to an initial problem I was having.
My rigidbody-based character controller works, more or less. But there's a problem my bro and I have been wanting to solve.
Basically:
Player can only apply rigidbody forces to reach speeds up to "7" to the character. But the environment can apply more than that.```
But the issue is that when an outside force applies the rigidbody force, the "speed limit" kicks in, slowing the object down unnaturally.
Here's the script, derived from Dave/GameDev's third person controller.
Please use a paste site for large code blocks
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://hastebin.skyra.pw/xesolanama.csharp
Okay, how's this?
calculate the player's new velocity in Jump and MovePlayer (instead of SpeedControl) before you apply forces and clamp them to prevent player input from exceeding your limit
Lemme write some pseudocode
Vector3 inputVelocity = curVelocity+wantedForce; //Calculate the velocity you'd get after Force
Vector3 envVelocity = Vector3.ClampMagnitude(inputVelocity, maxPlayerSpeed); //Get the clamped speed
wantedForce -= envVelocity-inputVelocity; //Remove the difference from the wanted force
There's probably a much better way to go about this
Seek's use case is pretty specifically tied to Rigidbody physics, which I rarely use in my projects, so idk if this is right
Is my approach what you're looking for?
roughly yes, although his code uses force for player motion. I try to avoid modifying velocity directly personally
Actually, the velocity from the rigidbody is "curVelocity", which is never modified in this context
Also, he and I are literally in the same room, and working on the same thing here.
Though there's another problem. What if you try going in the opposite direction?
Wouldn't the force vectors add up and cancel out?
would what forces cancel out? Don't clamp force if the resulting player speed is smaller than your threshold. If player movement is opposing their current velocity, their new velocity will be lower than the old velocity and you needn't do anything special
Experimenting. We'll see if it turns out right.
not a code issue, delete and ask in the correct channel - #🎥┃cinemachine
How do i open metadata in visual studio? I wanted to see the metadata for a class from dll. The way i do it right now is to type the class in code, hover over class name, click on the class name in the popup, and revert the code change.
It will open the metadata. Is there other way to do this without modifying the code?
honestly i thought it required code
but am figuring out stuff in it now
it feels cheating asf for havingg such thing not to be coded
@vestal arch I managed to come up with a really nice solution to the shapes! It turned out that having a transform tool would overcomplicate things, for the moment, so instead I opted to go with extensions for the shapes. (plus I can always make the tool later on)
public static class XFormExtensions {
public static void SetCentroidPosition(this IXForm xform, Vector2 position) {
if(xform is IShape shape) {
shape.Geometry.X = position.x - shape.GetSize().x / 2f;
shape.Geometry.Y = position.y - shape.GetSize().y / 2f;
}}}
public static class ShapeExtensions {
public static Vector2 GetCentroidPosition(this IShape shape) {
float x = shape.Geometry.X + shape.Geometry.Width / 2f;
float y = shape.Geometry.Y + shape.Geometry.Height / 2f;
return new Vector2(x, y);
}}```
then its so much easier to work with the shapes myBoxShape.SetSize(boxSize);
took a little while to work out that I could write if(xform is IShape shape) to be able to access the shape from IXForm
anyway, the question is. What is that "xform is IShape" thing called?
Pattern matching?
I dunno you tell me 😆
but yes, it seems like thats what it is
It's a convenient way to find relations between types without doing work on the actual implementation
or whatever its called if I wrote if(foo is null)
is null is something people swear on but I don't see the point
when I came across "is" I saw it used in that way, and I made the assumption that it was an alternative way to write ==
made sense that x is y and x == y both sound like theyre doing the same thing
The way it works in Unity kind of sucks because Unity only has a very small part of what pattern matching as a whole is in .NET
Also the whole "the gameobject is null when destroyed" really ruins it
Or well, pattern matching is probably a lot bigger now .NET Standard 2.1 is a thing
But is doesn't use standard equality check, that's something to remember
It might look the same but depending on implementation of equality checks between types it can be an even bigger difference
I just wish Unity used a newer C# version
theres a few quality of life features I got used to when I've worked outside the context of unity
like namespaces have to be enclosed with {} in the version unity uses
namespace G.Shapes; you cant write something like this
not like it's caused problems or anything, it just means anything I write is forced to always have an additional indent
nor can structs be written as
public struct mytest
{
public float foo = 4f;
public mytest() { }
}```
Hopefully in a few years they will replace shitty mono with the CoreCLR which will give us the new features and greatly improve the compiled IL (i've seen people show how bad mono can be with optimisations in unity).
You could just not indent tho
VS is set up to do smart indenting, so I'd be fighting against what its configured to do
file-scoped namespaces would be nice to have
Finally got to use those in my Roslyn code generator 🙌
Not very “smart” indenting, yeah but I get that would be very nice
why when i use string rather than actionAfterDelay()
the StopCouritine instantly works but with () and not string, it is buggy asf?
Because you aren't using StopCoroutine properly
may u pls explain
or send me a doc link
explaining
Improper usage:
StartCoroutine(MyCoroutine());
StopCoroutine(MyCoroutine());
Proper usage:
Coroutine c = StartCoroutine(MyCoroutine());
StopCoroutine(c);```
i see ok
and if i wanna start couritine i just put c; in a line?
I'm not sure what you mean by " i just put c; in a line?"
My example shows how to start the coroutine.
You use StartCoroutine
if you want to start a coroutine, you call StartCoroutine
nothing else will start a coroutine
Praetor's code stores the resulting Coroutine object in a local variable
It then passes that object to StopCoroutine.
Of course to call my example "proper usage" is maybe also silly, beacuse you wouldn't StopCoroutine on the very next line after you start it. You would do it sometime later.
if (couritineON)
{
StopCoroutine("actionAfterDelay");
couritineON = false;
}
StartCoroutine("actionAfterDelay");
couritineON = true;
----```
this is what i have
this is kind of why i was confused with waht u said
bec mine starts with stop
then start
well this works so i wont change but i still wanna understand for future reasons
You would replace this with:
if (couritineON)
{
StopCoroutine(myCoroutine);
couritineON = false;
}
myCoroutine = StartCoroutine(actionAfterDelay());
couritineON = true; ``` if you want to switch to the other form.
i see!!
ok
Where you declare Coroutine myCoroutine; as a member variable outside the function.
and then i do mycouritine = startcouritine(actionafterdelay()))
inside the local
as in my example
tysm much apperciated!!
So in short, you get a reference of the Coroutine and you use that reference to stop it
Because StopCoroutine(MyCoroutine()); just calls a new reference, and immediately stops that one
Also StopCoroutine with a string sucks because I don't think there's any way to know which one it stops, in case you run multiple ones
yeh that is true
i had 1 couritine
i will use the one u guys taught me for long term reasons obviosuly
tysm
Yeah that is the best idea
Even if you never have multiple, there's no reason to use the string variant unless you start Coroutines dynamically
That's the least of your concerns!
more importantly:
- You can't use the same coroutine method more than one reliably (which one gets stopped?)
- You might type the name wrongly...
Fixable by making it a constant
nameof can help with that, at least
But yeah, doesn't really matter anyway
But it's still going to be worse than just calling the method directly
since Unity will have to use reflection to find the method you want to run
😂
Strings can be incredibly performant
oh ffs, was typing out a question then suddenly my PC became weirdly unresponsive, before showing a "your pc is low on memory"
Constants, Stringbuilder, Char Spans, you can remove all allocation to an extend
seems like I accidentally have a memory leak in the code
Plain strings by itself are shitty though
😂 lool
ik stringbuilder a bit
from java
but not much
i def will eventually learn as i continue coding
Yeah so that's one way to build a string without constantly allocating new ones
Because strings are immutable, but do allocate
And Char Spans are nice because they don't allocate at all
However, this isn't a drop in replacement because they are not truly strings
subbed u on utube btw
It's just a way to mutate strings without again allocating extra strings
Which one? 🤔
how strange, im leaving the project running and looking at task manager, no increase
roydefined
Oh, nice, thanks lol
it definitely showed unity was consuming all memory
how old r u?
i am asking cause i am 18 and new to game dev
Mommy told me not to share that with strangers
Also probably not a good idea to use this channel/server for these things anyway
lmao fair
i was just curious bec u have a good game
But by all means feel free to join the Discord in my bio to chat
alrd did
Thank you very much 😎
why isnt this working? it worked fine with raycast but spherecast refuses to work(i have another problem because i used raycasts, this is why im changing to spherecast)
so, this is the code and how its implemented
private Vector3 GroundDir() {
if (Physics.SphereCast(_gCheckPoint.position, .2f, Vector3.down, out _slopeHit, .3f, allowedLayers)) return Vector3.ProjectOnPlane(wishDir.normalized, _slopeHit.normal).normalized;
return wishDir;
}
Spherecasts ignore colliders that they start inside of
Fen is faster than me today!
Yes your options are basically
- Start your spherecast higher up (e.g. inside the the player object, not touching the ground)
- use OverlapSphere instead
but overlapsphere has no raycasthit T-T
then do the other thing
it needs to be touching the ground ._.
no idea what you mean by that. It can check the ground, the cast just needs to START outside the ground
and then it can HIT the ground
what
its ground check but for slopes
and the groundcheck im using is based on triggers
you currentl;y have the spherecast on the left
you ened to switch to the one on the right
the circle cannot START inside the ground
it must start above the ground
that's all
do you understand what spherecast is doing?
no, this is why i used raycast before the spherecast
Imagine a sphere in the scene, and you throw it through the scene in a straight line and see what it hits
that's a spherecast
ist's just like a raycast but instead of a dimensionless point, it's a sphere
the sphere cannot already be touching the object when it starts its motion
it has to start outside the object, and hit it while it moves
Raycast works the same - the start point of the ray must be above the ground to detect the ground
so it just works like
you shoot a paintball and then check where it hit?
yes
it makes much more sense to me now
my tilemap is designed to return the center position of all my tiles. pretty much the same as shown here. The plan is that I will give these points to my marching squares function so it can return the mesh where theres a quad for every tile.
what concerns me with the idea is that every other marching squares algorithm, uses the corner points rather than the centers.
I figure the option would be either
1: stick with my original plan, which might make it hard to try and find resources online to help as nobody does it like this
2: alter the way my tilemap outputs the points so it is more like a typical marching algorithm
so far im not really intending for the mesh that gets produced to resemble what youd typically see in marching cubes like below. for the moment I just want the grid to have basic quads
how to implement mouse look for touch(android) in new input system that resembles getasix("Mouse x/ Y") from old system?
catch the touch and put it into the world with ScreenToWorldPoint
sry, i couldn't get it ...a bit of explanation would be great
Hi everyone I have a rotation problem but I can't fix it however the Axes look good if someone could help me
how do I actually use spherecasts?
Did you check the doc?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.SphereCast.html
yes, i did
Which part is confusing you
the part where it doesnt work
Show what you tried
this one returns Vector3, i have one other that returns bool but its very similiar
private Vector3 GroundDir() {
if (Physics.Raycast(_gCheckPoint.position, Vector3.down, out _slopeHit, .3f)) return Vector3.ProjectOnPlane(wishDir.normalized, _slopeHit.normal).normalized;
return wishDir;
}
We were talking about spherecast though
yes, the check is a spherecast
I can't help you if you don't show an actual issue
Then show that?
crap, wrong version
private Vector3 GroundDir() {
if (Physics.SphereCast(transform.position, .4f, Vector3.down, out _slopeHit, .54f)) return Vector3.ProjectOnPlane(wishDir.normalized, _slopeHit.normal).normalized;
return wishDir;
}
Looks like you are projecting your move direction on to a slope
the spherecast checks for a angled surface and if its on one, it returns a Vector3 with a proper direction and if its not on angled direction it returns wishdir(input direction
and the check was partially inside of the plaer and partially inside of the ground
and the new one is from inside of the player to ground
anybody know what is needed to set the source image of an image component? I have the image I want to set and I have set it's type to sprite but it still won't let me select it
I still don't know what the issue is, but you can use the Physics Debugger to see what your spherecast is doing
i have opened it but i have absolutely no idea what it does
[ExecuteInEditMode]
public class NetworkObject : MonoBehaviour
{
private string persistendID;
public string ObjectID
{
get { return persistendID; }
}
private void Awake()
{
if(string.IsNullOrEmpty(persistendID))
{
persistendID = System.Guid.NewGuid().ToString();
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
}
}
Hello! Why is the persistendID changing value every time the function get's called?
what function?
It lets you visualize physics queries like ray/spherecasts and more.
what is it even meant to do?
Awake()
Show what you tried
you missing [SerializeField]
You aren't going to get far if you don't use the manual/docs/google