- Home /
Is there a pointer equivalent in Unity's C#?
I come from a C++ background and without pointers I'm slightly lost on how to solve this problem. I need objectA in Unity to hold a reference to another objectB (This is better for memory as multiple objectAs will need the exact same objectB). How would I accomplish this?
Importantly, this is unsafe code in C# and consequently Unity too. But a C++ programmer isn't going to be afraid of a word like Unsafe but check out the ref anyway :)
Answer by kaplica · Apr 23, 2018 at 10:16 AM
Yes, however only to certain extent. Pointers in C# can only hold values to arrays or value types.
To declare: type *nameOf and then with & you get the memory address.
int largeNumber = 100;
int *ptr = &largeNumber;
then (int)ptr displays the memory address and *ptr displays the value at that memory address
While technically your answer is correct, wouldn't C#'s reference types serve better the above purpose? What I mean is (and maybe I'm completely mistaken) wouldn't the below solve the referencing the same object situation, but with a cleaner syntax?
var objectA = // create objectA in some way
var objectB = objectA; // if objectA's actual type is a reference type, then objectB will "point" to objectA
Expressed even shorter, as far as I know most variables (except for value types) are references by default, just like in Java, so you usually don't have pointers, because almost everything is a "pointer".
That is correct, when dealing strictly with reference types, because it will not copy the value but only a reference to Object A. However the OP, never mentioned which type he wants to use. That is very straight forward in C#.
O$$anonymous$$, thanks for clearing up my doubts! (I never used real pointers in C# before, only heard that they exist).
Answer by fafase · Apr 23, 2018 at 10:57 AM
In C#, you need to forget about pointers, they should only be used in really specific situation like hardware and driver access.
In Unity, you are likely to use them in few situations. When dealing with native code communication, IntPtr is more likely used.
If you need an object to hold another object address, then think of C++ references without the &
MyType objA = new MyType();
MyType objRef1;
objRef1 = objA;
Now your objRef1 points to the same address as objA.
objRef1.item = newValue;
print(objA.item); // This prints the newValue content
You can also box/unbox value type-
int myInt = 10;
object obj = (object)myInt;
print((int)obj); // prints 10
The problem with boxing is that you need to know the type you are dealing with.
Your answer
Follow this Question
Related Questions
What is the purpose of ScriptableObject versus normal class? 4 Answers
Are there any retain cycle gotchas in Unity? 1 Answer
How do Unity manage loading with inspector linkage? 0 Answers
FATAL EXCEPTION: UnityMain on some Android devices 2 Answers
How can I track disassembly code back to a script? 0 Answers