#archived-code-general

1 messages · Page 403 of 1

quick token
#

oh, that makes a lot more sense

hardy pasture
#

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

cold parrot
#

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.

vestal arch
#

it's an upcast to Object to ensure the right bool conversion is called

#

isn't it necessary though

quartz folio
vestal arch
#

ah there's no cast at all there

knotty sun
#

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

thin aurora
#

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

thin aurora
#

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

vestal arch
quartz folio
#

To be clear that isn't boxing, that's UnityEngine.Object

hardy pasture
#

Magic numbers, too.

thin aurora
#

BTW the part you reference here talks about passing boolean parameters

#

Idk how this is relevant

hardy pasture
#

How is this not relevant

thin aurora
hardy pasture
#

It's used as a boolean in the function

quartz folio
#

It's just checking that the object exists

thin aurora
#

Also, TranslateY(10); still uses magic numbers so I don't see your point

vestal arch
chilly surge
#

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.

vestal arch
hardy pasture
thin aurora
#

My life has been a lie

hardy pasture
#

And 2 more arguments

#

That you have to repeat all the time

vestal arch
#

0 is not really a magic number

hardy pasture
#

When you translate by 1 axis

quartz folio
#

0 as a magic number is hilarious

vestal arch
#

you could use like, uint32.MIN_VALUE, i guess? lol

thin aurora
#

10 is

#

You still use 10 with TranslateY

hardy pasture
vestal arch
#

i feel like you're just spewing buzzwords without really understanding how to properly apply them now

thin aurora
#

I feel like this whole discussion is based on somebody being overly confident in the wrong approach and not accepting valid criticism

chilly surge
#

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).

thin aurora
quartz folio
#

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

vestal arch
cold parrot
#

conventionally -1, 1, * 0.5, / 2, 0 and the like are not magic numbers

hardy pasture
knotty sun
cold parrot
knotty sun
hardy pasture
thin aurora
hardy pasture
vestal arch
#

because your arguments aren't accepted
this is exactly what qyou is saying

quick token
#

came for the code, stayed for the entertainment popcorncat

still jungle
vestal arch
hardy pasture
thin aurora
#

Because 0 is a magic number?

vestal arch
#

...well, i think that proves quite a few of our points

knotty sun
vestal arch
#

smh Count is already basically calling a method in disguise

thin aurora
#

I wonder how Count/Length == 0 is not already clear enough

still jungle
chilly surge
# hardy pasture No, the way you refactor it is: `if (list.IsEmpty())` and `if(list.HasItems())`....

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.

quartz folio
#

I've had so many physical double takes when reading code like that lol

#

Recoiling in confusion

vestal arch
#

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

thin aurora
#

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

hardy pasture
# knotty sun calling a method is better than checking a constant?

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.

vestal arch
vestal arch
#

and forces the reader to reverse-engineer the code to understand what's being done here
what even???

quartz folio
vestal arch
#

it's literally asking, "is the size 0"

quartz folio
#

It's so simple it's self apparent

vestal arch
knotty sun
vestal arch
#

it's a thing that works in every language, every context

#

well maybe not cstrings

hardy pasture
# quartz folio But the implementation is the explanation

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.

quick token
#

who is uncle bob and why do we keep citing him

vestal arch
hardy pasture
quartz folio
vestal arch
#

they absolutely do not

chilly surge
#

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.

vestal arch
#

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

hardy pasture
# vestal arch they absolutely do not

They absolutely do. Here's a few examples:

  1. Strategy pattern. Used everywhere: Java library, C# .NET, C++ library, Unity, Unreal, Sprint boot framework. I can continue forever.
  2. Single responsibility principle. Same list as before.
  3. DRY. Same as before.
    Are you going to tell me those 3 don't apply to Unity?
vestal arch
#

for example, SOLID doesn't apply universally, they only apply to OOP patterns

hardy pasture
#

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 ...

▶ Play video
cold parrot
# quick token who is uncle bob and why do we keep citing him

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.

vestal arch
vestal arch
hardy pasture
cold parrot
hardy pasture
vestal arch
#

lmao what?

hardy pasture
#

But saying that X pattern/princple can't be appliied in the whole industry is just wrong

vestal arch
#

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

knotty sun
cold parrot
#

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".

hardy pasture
knotty sun
hardy pasture
#

You guys just saying false things

vestal arch
#

who is "he"?

#

uncle bob?

hardy pasture
#

And misrepresenting my position.

vestal arch
#

you really gotta come up with better references than your idol

hardy pasture
vestal arch
#

yikes

cold parrot
#

"he says" is never a good argument

hardy pasture
#

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

vestal arch
#

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

vestal arch
hardy pasture
#

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?

vestal arch
#

i'm asking for better references

#

1 guy on a youtube video is not a very good reference

vestal arch
quick token
#

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 pepeshrug)

knotty sun
thin aurora
cold parrot
thin aurora
#

Making code pretty has the effect that code might not end up scalable enough and/or working in general

vestal arch
hardy pasture
# vestal arch im not sure where you're seeing personal attacks

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

thin aurora
#

For example, making aliases for Translate hides the extra parameters that might be included, so you just make it worse for youself

quartz folio
#

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

vestal arch
# hardy pasture > i feel like you're just spewing buzzwords without really understanding how to ...

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?

hardy pasture
# knotty sun basically yes, backed up by 50 years of professional experience. The solution sh...

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.

quartz folio
#

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

hardy pasture
vestal arch
#

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

wheat spruce
#

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
hardy pasture
# quartz folio but globally applying these "clean code" ideas is absolute nonsense made by peop...

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.

vestal arch
#

ok so

wheat spruce
#

my Shapes arent actually unity objects, so its not like I could give them a Unity Component

vestal arch
#

if you're saying uncle bob is like, the only resource you have

knotty sun
hardy pasture
#

Yeah of course

vestal arch
#

and you're saying uncle bob would agree completely with your stance, that dry and solid are strict rules

hardy pasture
#

Because it all changed so much compared to the 1970s

vestal arch
#

yeah i don't think i trust this uncle bob, or at least your portrayal

vestal arch
knotty sun
vestal arch
#

i think you're conflating what you've heard with your own interpretation

hardy pasture
knotty sun
#

Does Uncle Bob work for the RaboBank?

quick token
vestal arch
hardy pasture
vestal arch
#

😒 what is this now, an old age contest

knotty sun
quick token
knotty sun
hardy pasture
#

Yes

wheat spruce
#

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

wheat spruce
#

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

vestal arch
# hardy pasture No, he wouldn't agree. As I wouldn't. They're not strict rules. You don't apply...

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

wheat spruce
#

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

hardy pasture
wheat spruce
#

"is it slower to use function X or is it slower to do function Y" really shouldnt ever really be a concern

vestal arch
#

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

wheat spruce
#

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

vestal arch
#

and what coordinate system unity is in doesn't matter, since your own utility methods are also using xyz

wheat spruce
#

like people who think every class they write has to derive from MonoBehaviour

vestal arch
#

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

wheat spruce
#

its something like they think they cant use anything that Unity has, unless its a MonoBehaviour class

vestal arch
#

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

hardy pasture
#

You don't have to do any reverse engineering whatsoever

#

The code you guys showed and wrote requires the reader to do reverse-engineering

vestal arch
#

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

hardy pasture
#

My code explains itself well and there is nothing you have to reverse

vestal arch
#

that is not what reverse engineering is

#

and there really is no extra mental load

wheat spruce
#

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();
}
}```
vestal arch
#

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

hardy pasture
thin aurora
vestal arch
#

you absolutely cannot confuse the axes

#

they are xyz

quartz folio
#

Clean code thread

wheat spruce
hardy pasture
quartz folio
vestal arch
#

by mistake? then you misunderstood xyz to begin with
by typo? that's just not gonna happen

quick token
quartz folio
azure frost
#

Here's a look at that rigidbody-based character controller thing I made a while back... it's not working right.

quick token
#

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

azure frost
# quick token whats wrong with it?

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.

quick token
#

-There are times where the jump button doesn't respond.
that's typically caused from checking inputs in FixedUpdate

azure frost
#

Well, there's a rigidbody system that might cause the body not to detect the ground as it should.

quick token
#

-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

quick token
azure frost
#

I'd show more of how this janky setup works, but I can't screen-stream here.

#

(I am also terrible with code...)

earnest gazelle
#

Collider2d.bounds is not Bound2d !!!
and Contains(point) method checks in 3d space :/

azure frost
#

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 ~

▶ Play video
quick token
#

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 guh

azure frost
#

According to my bro, the groundCheck function checks how far the ground is from the player.

quick token
#

i think the code should look like this

    RaycastHit groundCheck()
    {
             RaycastHit groundDetection;
             onGround = Physics.Raycast(transform.position, -transform.up, _rideHeight, out groundDetection)

             return groundDetection;
    }
quick token
#

you sure its not the inputs?

vestal arch
azure frost
#

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

quick token
#

i didn't import the code into a project so i dont have the autocomplete woe

#

might just be the wrong ordering

quartz folio
azure frost
#

I'm using visualstudiocode.

The errors show up in Unity's console.

quartz folio
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

azure frost
#

With how janky and dysfunctional my setup is, I am seriously considering building off of movement lab.

quick token
frail halo
#

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 notlikethis 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

quick token
#

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

leaden ice
#

pressing the button doesn't make the player close

#

OnTriggerEnter makes the player close.

quick token
#

yeah i was going to say that too, consider changing the variable name

leaden ice
#

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

quick token
#

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.

thin aurora
#

previousMusicQueue is empty, you need to enqueue audio clip instances before you dequeue

#

Alternatively, use TryDequeue

trim schooner
#

Unless I'm missing it, you never add anything to the previousMusicQueue?

thin aurora
#

I don't see Enqueue added anywhere anyway. Source: ctrl + f

quick token
#

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

trim schooner
#

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

quick token
#

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)

frail halo
quick token
#

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

trim schooner
#

never heard of Queue before

vestal arch
#

shouldn't "previous" be a stack

#

or you could just use a single list that you transverse, instead of a queue

trim schooner
#

Just use a List, and get the last element of it

vestal arch
#

that way choosing the previous song would just be going backwards through the list

quick token
#

oh yeah that should work. i kept thinking i'd have to use a queue for that for some reason guh

#

thanks for the help, i'll try fixing it now

vestal arch
#

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)

thin aurora
#

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

quick token
#

that sounds a lot more like what i was trying to do with the messy queue

thin aurora
#

Also, considering Dequeue/Pop expects an entry you either have to check if it's not empty and/or use TryDequeue/TryPop instead

vestal arch
quick token
still jungle
#

if the list of songs its constant, simply manipulating the index of array would be the best approach

thin aurora
#

I suppose it could, but seeing as the code had a shuffle system it would bring unnecessary complexity

vestal arch
#

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

still jungle
thin aurora
#

I wasn't disagreeing, just pointing out the obvious

quick token
thin aurora
#

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

quick token
#

will do with the rest though, thanks for the help :D

vestal arch
thin aurora
#

Then you would no longer have the unshuffled list

#

Like with Spotify, you can shuffle or unshuffle

vestal arch
#

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
still jungle
#

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:

  1. Array of all songs
  2. Array of played songs ids
  3. Temporary array for shuffled ids of songs to play
thin aurora
#

Because pretty sure even in Youtube's case you'd unshuffle and get the original list back

vestal arch
#

youtube doesn't shuffle the list

#

the shuffle option just ignores the list and picks a random entry

thin aurora
#

A list of ids is less convenient than a list of references

vestal arch
#

youtube mobile (a while ago, idk if it still does this) has a shuffle button instead of a shuffle option lol

thin aurora
#

Also, risk of playing the same song twice in quick succession

vestal arch
#

yeah, sometimes that risk isn't too bad

thin aurora
#

pre-choose?

vestal arch
#

uhhhh not sure how to explain what i have in mind

thin aurora
quick token
#

(not sure if im talking about the right part here, but the initial list of songs stays constant)

vestal arch
#

the shuffle option as i described before, but randomized 1 song in advance

thin aurora
#

Yes so you have no idea what comes after that single randomized song

thin aurora
#

Also you'd still have to track the next song

vestal arch
thin aurora
#

Might as well use a second queue for the list of songs

vestal arch
#

i thought you were talking about showing the user what song is next?

thin aurora
#

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

vestal arch
#

less to move around

#

i still don't think queues make sense in the context of being able to shuffle

thin aurora
#

And in return you can only shuffle a single song beforehand with no way to extend it

quick token
still jungle
#

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?

thin aurora
#

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

trim schooner
vestal arch
quick token
vestal arch
#

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

thin aurora
#

By using a List you're unable to get the original order of songs after shuffling

#

Idk how I can be more clear

trim schooner
vestal arch
still jungle
#

just shuffle the cached randomly pulled indexes

thin aurora
#

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

vestal arch
#

if you want to preserve the original order, just randomize next instead of shuffling

thin aurora
#

Imagine wanting a song that has now disappeared because you shuffled

still jungle
#

dont event need to shuffle when its randomly pulled each time

vestal arch
#

youtube doesn't really shuffle the list, it goes to a random entry when the current entry is done

thin aurora
#

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

vestal arch
#

it doesn't have a shuffled list

thin aurora
#

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

vestal arch
vestal arch
thin aurora
#

I thought that was what you meant, it does have shuffling in general just not the UI

vestal arch
#

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 🫠

thin aurora
#

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 😄

vestal arch
#

that's, not really what im talking about

thin aurora
#

I don't really think it matters anyway because we're both talking to a brick wall that thinks they know better

quick token
vestal arch
#

my point is; if you don't need the advanced features, a simpler system is easier to maintain

thin aurora
#

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

vestal arch
#

that's also not what im talking about, but ok 😮‍💨

thin aurora
#

And their initial problem was solved by checking for an empty queue and making sure songs are added, not refactoring to use a list 😄

vestal arch
#

im not talking about the problem, either...

quick token
#

tried making it a single array and now i can only hear coconut mall woe

thin aurora
#

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

ocean mirage
#

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.

thick terrace
quick token
ocean mirage
quick token
vestal arch
#

also next/previous should be wrapped on the 0/array length, or requeue, so you don't index out of bounds

quick token
#

i think the issue is around line 29

thick terrace
# ocean mirage i think so, its for an action rpg like diablo.

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

vestal arch
#

(btw as you have it it'll start on the 2nd song instead of the first)

quick token
#

that is what's happening

#

i have no idea why

#

did i miss something obvious?

vestal arch
#

you increment before assigning the clip

quick token
#

OH

#

it was something obvious woe

vestal arch
#

currentSongIndex starts at 0, you do playnext, it goes to 1, then it starts

vestal arch
#

shuffle/loop/loopsingle, on or off

quick token
#

need to clean up the inspector a bit guh

vestal arch
#

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?)

quick token
quick token
vestal arch
#

like for example in that screenshot setup; if loop is false, and price p5 ends, what should happen

quick token
#

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

vestal arch
#
if musicSource.time >= musicSource.clip?.length && !loopSingle:
  if currentSongIndex < musicQueue.Length || currentSongIndex == musicQueue.Length && loop:
    PlayNext()
```and then have PlayNext handle requeuing & loopSingle?
quick token
#

yeah sure i can add that. forgot that loopsingle doesn't even need to be in update

swift falcon
#

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?

leaden ice
#

Instead of:

class A {}
class B : A {}```
Make:
```cs
class A {
  C c;
  D d;
}

class B {
  C c;
}```
swift falcon
#

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?

swift falcon
#

That was my exact problem

ocean mirage
leaden ice
#
class A : IHasC, IHasD {
  C c;
  D d;
}

class B : IHasC {
  C c;
}```
swift falcon
#

Is it possible to decompose the method while keeping the "B is A"?

leaden ice
#

Can't B and A just be IHasC?

swift falcon
#

Because by definition it is

leaden ice
#

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?

swift falcon
#

Hmm thanks, that does make sense. Maybe i need to read more about the circle is ellipse problem

quick token
#

i was almost done debugging too lol

#

i see where i made a lot of errors now ._.

vestal arch
quick token
vestal arch
quick token
#

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

vestal arch
#

maybe check if the current time is less than some threshold

quick token
#

yeah, i'll probably add that as a private field to be set in the inspector

#

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 guh *

still jungle
quick token
#

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 guh
timid comet
#

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

thick terrace
still jungle
#

the worst part come when variables are named correctly but are too long and mess up the readibility

rigid island
#

goofy satire though, love it

quick token
#

i skimmed through and didn't even realise it was satire at first lol

#

probably should've noticed after seeing "underscores for fun"

rigid island
#

literally the first block

Irony detected
Many try to follow ninja paths. Few succeed.

quick token
#

idk, sounds professional to me daihakkenshrug

rigid island
#

One-letter variables I would fire you immediately lol

quick token
#

im not gonna stop using one-letter variables until i get through the whole alphabet (i only t lol)

still jungle
#

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

rigid island
#

or just use a proper IDE

cold parrot
rigid island
#

code with _ looks disgusting and its very unecessary imo

still jungle
#

m_ its better?

rigid island
#

just as shit

#

camel case it, you already know its a private var..

#

Pascal Case, its a property or public..

still jungle
#

_ are cool for private members

cold parrot
rigid island
#

go for it if it helps you, I just find it noisy

still jungle
#

btw i have proper IDE, its nvim 😆

chilly surge
#

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.

rigid island
#

I use locals less often, i use _ for local if i must

still jungle
#

for me properties are noisy, 2 methods with backing field in one, with naming convention same as methods

rigid island
#

or just this. for members with same local name

rigid island
#

I would not put more than a few lines in a prop though

cold parrot
#

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.

rigid island
#

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

vestal arch
# rigid island One-letter variables I would fire you immediately lol

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

rigid island
#

jesus lol

cold parrot
#

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

cold parrot
still jungle
#

he is back

rigid island
leaden ice
#

Having a code formatter among the static analysis checks your CI/CD system does is ❤️

chilly surge
#

Speaking of formatter, I can recommend CSharpier if you find dotnet format to not be strong enough for you.

hardy pasture
#

@vestal arch Are you back home yet? I really wanna see that juicy top tier code that you were talking about

hardy pasture
# still jungle he is back

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.

steady bobcat
#

getting flashbacks to es lint dumbness such as 80 char line limit 😐

still jungle
#

i gave you the response why you cant manipulate members of struct of UnityEngine.Object, so we done with that topic i guess

vestal arch
hardy pasture
# still jungle i gave you the response why you cant manipulate members of struct of UnityEngine...

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.

steady bobcat
rigid island
hardy pasture
chilly surge
hardy pasture
vestal arch
rigid island
hardy pasture
quick token
#

oh this guy is still going, i blocked them a while ago

hardy pasture
#

I literally got talked down and trash talked instead of arguments.

chilly surge
#

Well, you are certainly still caring about it, so I'll leave the mods to it.

hardy pasture
#

And being the one to start this

hardy pasture
#

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

still jungle
vagrant blade
reef elk
#

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);
    }
}```

`

leaden ice
# reef elk Hey. Im new to Unity and was just wondering if any of you guys know how to trans...

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.

wintry crescent
#

Is there a way to dictate the order of rendering of UI objects, that does NOT include reordering the hierarchy?

leaden ice
#

and/or rendered on different cameras in a camera stacking setup

wintry crescent
leaden ice
#

Or consider switching to UI Toolkit which has its own depth system and doesn't use GOs at all.

wintry crescent
#

is it still the case that you can't even use custom shaders in ui toolkit?

leaden ice
leaden ice
#

oh sorry yes

wintry crescent
#

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

reef elk
#

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

leaden ice
# reef elk Im a little confused. Would I have to transfer the player objects as well? Cause...

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.

reef elk
#

Oh I see

sacred python
#

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();
    }
}

hexed pecan
#

They seem to be using that

sacred python
#

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

leaden ice
sacred python
#

to go from the inital skybox to the target skybox in a smooth way

dusk apex
#

So simply without the completely blacken material?

sacred python
#

yes
i have no black material

dusk apex
#

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.

hardy pasture
#

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?
vestal arch
#

(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

dusk apex
wintry crescent
#

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

wintry crescent
leaden ice
wintry crescent
#

hide the wait I mean

wintry crescent
dusk apex
hardy pasture
#

Also, someone mentioned this on the forums:

You could add an ‘isEnabled’ boolean which cancels the execution in TryInteract

inner wasp
#
    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.

vestal arch
inner wasp
#

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?

wheat spruce
#

!ide

tawny elkBOT
vestal arch
still jungle
#

wonder if there is any good indie game made with visual scripting

inner wasp
#

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.

still jungle
#

same

robust dome
inner wasp
#

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.

heady iris
#

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

latent latch
#

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

heady iris
#

yeah

inner wasp
#

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.

quick token
#

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

cold parrot
#

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).

quick token
#

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 ._.

quick token
cold parrot
#

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)

quick token
#

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

cold parrot
#

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

quick token
cold parrot
quick token
#

oh yeah, if i were working in a team i'd definitely leave those in

cold parrot
#

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!!)

steady bobcat
#

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.

cold parrot
quick token
cold parrot
#

games are actually quite simple in their abstractions so i would be surprised if this ever really comes up (absent time constraints)

cold parrot
steady bobcat
#

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.

cold parrot
#

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.

steady bobcat
#

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

cold parrot
#

fair

steady bobcat
#

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.

cold parrot
#

well, best not rock the boat then

#

if you break it, you own it

quick token
#

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

cold parrot
quick token
#

the programmer cycle pensive
i've got a script from a while ago that uses way too many delegates, from back when i first discovered them

steady bobcat
#

🔥 public event Action myCoolEvent; 🔥

quick token
quick token
heady iris
#

if you don't need to configure it in the inspector, then you might as well use the event keyword

quick token
#

that's the problem, i always configure it in the inspector woe

steady bobcat
quick token
#

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

steady bobcat
heady iris
quick token
steady bobcat
heady iris
cold parrot
#

also "for a while" is by design

heady iris
#

notably, UnityEventBase has no code that would handle object destruction (and there's no way it could even know about object destruction, AFAICT)

cold parrot
#

unity objects typically only leak easily when you use them in (void) async contexts that dont get cleaned up properly

steady bobcat
#

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)

cold parrot
#

thats not a leak

heady iris
#

yes, that's just objects not randomly ceasing to exist :p

cold parrot
#

a leak is defined as "the GC or program code does not have a reference to the memory"

dusky oar
#

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?

heady iris
#

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

steady bobcat
#

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.

cold parrot
heady iris
#

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

steady bobcat
#

Its ofc not the same as a leak in native code but its still something you want to avoid

heady iris
#

using an event member v.s a UnityEvent is also completely irrelevant here

cold parrot
#

yes but you avoid that by always unsubscribing on destroy

#

its trivial

heady iris
#

you'd have the same problem either way

steady bobcat
#

but its not guaranteed so its a possibility if you forget

heady iris
#

well, sure

cold parrot
#

this stuff is also easily detected in code reviews

heady iris
#

you could also call Application.Quit()

cold parrot
#

if you want guarantees, use rust

steady bobcat
#

ofc why didnt i think of that!

heady iris
#

The thing is that this isn't a problem with an event member vs. a UnityEvent member

cold parrot
#

i think c# strikes a very nice belance between freedom, performance and convenience

heady iris
#

Neither of those can save you from subscribing with the wrong things

steady bobcat
#

and im basically the only one working on projects im assigned too now so no more code reviews 😦

heady iris
#

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

cold parrot
heady iris
#

I mostly don't (:

#

also, that wasn't me -- that was six month ago me

cold parrot
#

i remember that one

#

total idiot

heady iris
steady bobcat
#

from now on i wont make any mistakes thanks to this chat 👍

heady iris
#

Something like that

heady iris
#

I like to write validators where I can

#

I automatically scan for missing references in most of my game's prefabs

cold parrot
heady iris
#

I'll have to poke at it at some point

cold parrot
#

but how do you get all instances

#

maybe from the GC?

heady iris
#

that's what I was wondering

#

you'd need to find every single object

cold parrot
#

you could source generate your way into a solution

#

make your own little runtime for additional checks

heady iris
#

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

cold parrot
#

disintegration test

swift falcon
#

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

steady bobcat
late lion
cold parrot
steady bobcat
heady iris
#

It's important to understand how destroying an object means basically nothing in C# land

cold parrot
#

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

heady iris
#

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..

cold parrot
#

it would make sense to have a dispose pattern on all monobehaviours and possibly a Destroyed event

steady bobcat
#

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 🤷‍♂️

cold parrot
steady bobcat
#

well duh but the issue is finding why

heady iris
#

things can also live for a while before the GC actually eats them

steady bobcat
#

Yea thats true, i just wanted to improve graphic memory usage however in this particular instance

quick token
#

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

compact spire
#

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.

somber nacelle
#

show relevant code

leaden ice
rigid island
leaden ice
#

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.
compact spire
#

I'm using it the first way, t is .1f

#

buuut

leaden ice
#

t cannot be a constant value in the first way

#

it must go from 0 to 1 over time.

heady iris
#

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

leaden ice
#

Basically that t stands for "what percentage through the motion should we be now?

compact spire
#

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?

leaden ice
#

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

leaden ice
#

e.g.

float t = 0;
void Update() {
  t += Time.deltaTime;
  float currentVal = Mathf.Lerp(startVal, endVal, t);
}```
swift falcon
#

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

leaden ice
#

(Lerp automatically clamps it at 1)

compact spire
#

I need to set a max of t to 1 right if I'm doing it that way?

leaden ice
compact spire
#

oh

leaden ice
# compact spire oh

What you might find easier than restructuring everything is to switch to MoveTowards

compact spire
#

Does that work with scale/rotate?

leaden ice
#
current = Mathf.MoveTowards(current, target, Time.deltaTime * speed);```
leaden ice
#

it's just moving numbers towards other numbers

compact spire
#

gotcha

leaden ice
#

it can be done with anything

#

For rotation though you probably want Quaternion.RotateTowards

compact spire
#

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?

swift falcon
#

i even restarted laptop

compact spire
#

So it's either busy compiling or importing something then? I've never ran into that one

compact spire
#

@leaden ice Would Vector3.SmoothDamp also work?

leaden ice
compact spire
#

I'm just very quickly rotating/moving/scaling in a runtime editor, maybe it won't be very noticable

azure frost
#

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.

thin aurora
#

Please use a paste site for large code blocks

tawny elkBOT
azure frost
mossy snow
arctic sparrow
#

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

arctic sparrow
mossy snow
#

roughly yes, although his code uses force for player motion. I try to avoid modifying velocity directly personally

arctic sparrow
azure frost
arctic sparrow
#

Though there's another problem. What if you try going in the opposite direction?

azure frost
#

Wouldn't the force vectors add up and cancel out?

mossy snow
#

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

azure frost
#

Experimenting. We'll see if it turns out right.

trim schooner
swift falcon
#

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?

swift falcon
#

but am figuring out stuff in it now

#

it feels cheating asf for havingg such thing not to be coded

wheat spruce
#

@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?

thin aurora
#

Pattern matching?

wheat spruce
#

but yes, it seems like thats what it is

thin aurora
#

I dunno what your question is about

#

xform is IShape is a pattern match

wheat spruce
#

sweet

#

most of my usage of the word is has usually been as an equality check

thin aurora
#

It's a convenient way to find relations between types without doing work on the actual implementation

wheat spruce
#

or whatever its called if I wrote if(foo is null)

thin aurora
#

is null is something people swear on but I don't see the point

wheat spruce
#

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

thin aurora
#

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

wheat spruce
#

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() { }
  }```
steady bobcat
#

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).

wheat spruce
heady iris
#

file-scoped namespaces would be nice to have

leaden ice
#

Finally got to use those in my Roslyn code generator 🙌

simple void
swift falcon
#

why when i use string rather than actionAfterDelay()

the StopCouritine instantly works but with () and not string, it is buggy asf?

leaden ice
swift falcon
#

or send me a doc link

#

explaining

leaden ice
# swift falcon may u pls explain

Improper usage:

StartCoroutine(MyCoroutine());
StopCoroutine(MyCoroutine());

Proper usage:

Coroutine c = StartCoroutine(MyCoroutine());
StopCoroutine(c);```
swift falcon
#

i see ok

swift falcon
leaden ice
#

My example shows how to start the coroutine.

#

You use StartCoroutine

heady iris
#

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.

leaden ice
#

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.

swift falcon
#
if (couritineON)
{
    StopCoroutine("actionAfterDelay");
    couritineON = false;
}

StartCoroutine("actionAfterDelay");
couritineON = true; 

----```

this is what i have
swift falcon
#

bec mine starts with stop

#

then start

#

well this works so i wont change but i still wanna understand for future reasons

leaden ice
leaden ice
#

Where you declare Coroutine myCoroutine; as a member variable outside the function.

swift falcon
#

inside the local

leaden ice
#

as in my example

swift falcon
#

tysm much apperciated!!

thin aurora
#

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

swift falcon
#

i had 1 couritine

#

i will use the one u guys taught me for long term reasons obviosuly

#

tysm

thin aurora
#

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

swift falcon
#

also if am not mistaken

#

string is also less optimized , performance wise

heady iris
#

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...
thin aurora
heady iris
#

nameof can help with that, at least

thin aurora
#

But yeah, doesn't really matter anyway

heady iris
#

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

swift falcon
thin aurora
#

Strings can be incredibly performant

wheat spruce
#

oh ffs, was typing out a question then suddenly my PC became weirdly unresponsive, before showing a "your pc is low on memory"

thin aurora
#

Constants, Stringbuilder, Char Spans, you can remove all allocation to an extend

wheat spruce
#

seems like I accidentally have a memory leak in the code

thin aurora
#

Plain strings by itself are shitty though

swift falcon
#

from java

#

but not much

#

i def will eventually learn as i continue coding

thin aurora
#

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

swift falcon
#

subbed u on utube btw

thin aurora
#

It's just a way to mutate strings without again allocating extra strings

thin aurora
wheat spruce
#

how strange, im leaving the project running and looking at task manager, no increase

swift falcon
#

roydefined

thin aurora
#

Oh, nice, thanks lol

wheat spruce
#

it definitely showed unity was consuming all memory

swift falcon
#

i am asking cause i am 18 and new to game dev

thin aurora
#

Mommy told me not to share that with strangers

#

Also probably not a good idea to use this channel/server for these things anyway

swift falcon
#

i was just curious bec u have a good game

thin aurora
#

But by all means feel free to join the Discord in my bio to chat

thin aurora
soft escarp
#

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;
    }
heady iris
#

Spherecasts ignore colliders that they start inside of

leaden ice
#

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
soft escarp
leaden ice
soft escarp
leaden ice
#

and then it can HIT the ground

soft escarp
leaden ice
#

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?

soft escarp
#

no, this is why i used raycast before the spherecast

leaden ice
#

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

soft escarp
#

so it just works like
you shoot a paintball and then check where it hit?

leaden ice
#

yes

soft escarp
#

it makes much more sense to me now

wheat spruce
#

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

warm badger
#

how to implement mouse look for touch(android) in new input system that resembles getasix("Mouse x/ Y") from old system?

robust dome
warm badger
dusky oar
#

Hi everyone I have a rotation problem but I can't fix it however the Axes look good if someone could help me

soft escarp
#

how do I actually use spherecasts?

soft escarp
#

yes, i did

hexed pecan
#

Which part is confusing you

soft escarp
#

the part where it doesnt work

hexed pecan
#

Show what you tried

soft escarp
# hexed pecan 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;
    }
hexed pecan
#

We were talking about spherecast though

soft escarp
#

yes, the check is a spherecast

hexed pecan
#

I can't help you if you don't show an actual issue

hexed pecan
soft escarp
#
    private Vector3 GroundDir() {
        if (Physics.SphereCast(transform.position, .4f, Vector3.down, out _slopeHit, .54f)) return Vector3.ProjectOnPlane(wishDir.normalized, _slopeHit.normal).normalized;
        return wishDir;
    }
hexed pecan
#

Looks like you are projecting your move direction on to a slope

soft escarp
#

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

jaunty sleet
#

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

hexed pecan
soft escarp
winged tiger
#
[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?

hexed pecan
winged tiger
still jungle
hexed pecan