❔ Is there any way to create a pointer to a C# generic class

I have a script that uses a class "fogGrid<bool>". At the start of the script I want it to be able to specify which instance of the class is manipulated. Essentially I want fogGrid to be a pointer to instances of the same class in another script (SqrFog, TriFog or CirFog) I've allowed unsafe code to run, but whenever I try to run it, it states that "It cannot take the address of, get the size of, or declare a pointer to a managed type ("FogSystem<bool>") For tests sake i was just trying to get it to point to sqrFog. After some googling it says I cannot make pointers to generic types, is there any workaround?
18 Replies
Thinker
Thinker2y ago
What is sqrFog? Oh it's a FogSystem What is FogSystem? A class or a struct?
docklandslightrailway
For some clarification yeah I generate it from FogSystem in the game controller script
Thinker
Thinker2y ago
Is it a class or a struct?
docklandslightrailway
I think it'd be a structure?
docklandslightrailway
It just generates a grid to width by size and cellsize with each location storing a value of type TGridObject
Thinker
Thinker2y ago
You can't get a pointer to managed types, only to unmanaged structs
docklandslightrailway
Then it has a few methods around that to get and set
Thinker
Thinker2y ago
If FogSystem is a class then you don't need to use pointers and unsafe here in the first place If it's a struct then you can't force it to be the same instance because of how structs are stored
docklandslightrailway
What do you mean by this? the pointer isn't to the class but a specific instance of it stored in a different script. So I assumed it'd need the pointer to choose between instances
Thinker
Thinker2y ago
A class is a reference type, which means that doing a = b; sets a to the same instance as b.
docklandslightrailway
Oohhhh ok that makes so much sense
Thinker
Thinker2y ago
And you also can't get a pointer to a reference type. $refvsvalue
docklandslightrailway
Thank you so much! Will have a play with that concept
MODiX
MODiX2y ago
thinker227#5176
REPL Result: Success
class C
{
public int x;
}

C a = new();
a.x = 1;
C b = a;
b.x = 2;

Console.WriteLine(a.x);
Console.WriteLine(b.x);
class C
{
public int x;
}

C a = new();
a.x = 1;
C b = a;
b.x = 2;

Console.WriteLine(a.x);
Console.WriteLine(b.x);
Console Output
2
2
2
2
Compile: 649.964ms | Execution: 32.327ms | React with ❌ to remove this embed.
docklandslightrailway
My code now works as intended and I can change the class that the script is referencing Learn something new everyday, thank you!
Thinker
Thinker2y ago
np catsip
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server