✅ putting an object from an array into a variable changes the array
I'm trying to make a game using Raylib and I have a readonly array with a some levels in it
I also have a variable called currentLevel which has levels[0] in it
if I do it doesn't only remove the first block from currentLevel it also removes it from levels[0]
26 Replies
that's just a feature of reference types (classes), a variable just holds a reference to the actual data, not the data itself, so a copied variable still uses the original data
if you want it to not do that, when setting currentLevel, you have to make copies of all the original data yourself
How do I make an exact copy of a class without having to enter all the info manually
Using some deep clone library would probably be the easiest
so you can't just make a direct copy with pure .net?
Not for reference types, no
Well, I guess you could do the classic
how should I reset a level when the player dies then?
Could maybe try using records
They're immutable, so you will always have to create a copy when changing it's values
And making a copy should be as simple as
with {}
shadow copies though
Angius
REPL Result: Success
Result: <>f__AnonymousType0#1<Foo, Foo, Foo>
Compile: 565.842ms | Execution: 107.002ms | React with ❌ to remove this embed.
in the example they were using RemoveAt on a list
Huh, true
would need to swap the list out for like, ImmutableList, then it can work
so like this?
More like the list of blocks would have to me immutable
And then you could do
Although... I think that already clones the list
oh wait I have an idea
I'm confused
Just throwing some possibilities for cloning
All in all, I'd say your best bet would be to just find some deep clone library, preferably one based on source generators, and just clone your current level or whatever it is
but when I do this I get 5 not 2, so why isn't this a reference
Because integer isn't a reference type
It's a value type
so what is the reference type when I do
Whatever is based on a
class
is a reference type
Whatever is based on a struct
is a value typeahhh ok
so is there really no easy way to load levels then?
Deep clone the level from the list into
currentLevel
GitHub
GitHub - mostmand/Cloneable: Auto generate Clone method using C# So...
Auto generate Clone method using C# Source Generator - GitHub - mostmand/Cloneable: Auto generate Clone method using C# Source Generator
Here, this looks promising
thanks a lot for your help
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.