This solution let’s you create something similar to what you want, while not using real pointers.
First, create a new C# script file called Pointer.cs and put this inside:
using System;
public static class Pointer
{
public static Pointer<T> Create<T>(Func<T> read, Action<T> assign)
{
return new Pointer<T>(read, assign);
}
}
public class Pointer<T>
{
public T Value
{
get { return getter(); }
set { setter(value); }
}
protected Func<T> getter;
protected Action<T> setter;
public Pointer(Func<T> getter, Action<T> setter)
{
this.getter = getter;
this.setter = setter;
}
public static implicit operator T(Pointer<T> pointer)
{
return pointer.Value;
}
}
Now you can use it anywhere in a simple way. I will rewrite your sample code:
public class MyClass
{
public bool bBool;
private Pointer<float> pData;
void Start()
{
if (bBool)
pData = Pointer.Create(()=> otherObject.fData, (value) => otherObject.fData = value);
else
pData = Pointer.Create(()=> differentObject.fData, (value) => differentObject.fData = value);
}
public void OtherFunction(float _fNewData)
{
pData.Value = _fNewData;
}
public float AnotherFunction()
{
return pData; // No need to specify pData.Value when returning it or assigning it to a float.
}
}
The important part is how you create the Pointer< T >.
You call to Pointer.Create(readingLambda, assigningLambda)
for that, where readingLamda
is a lambda expression without parameters that returns the member from the object, and assigningLamda
is a lambdaExpression with a parameter that assigns the parameter to the member of the object.
For example, let’s say I have a
class Person
{
string name;
int age;
}
and then in another part…
var john = new Person{name="John", age=21};
var mary = new Person{name="Mary", age=33};
var agePointer = Pointer.Create( ()=>john.age, (val) => john.age = val );
int theAge = agePointer; // theAge is now 21
agePointer.Value = 66; // john.age is now 66
agePointer = Pointer.Create( ()=>mary.age, (val)=>mary.age = val);
agePointer.Value = 15; // mary.age is now 15
This approach has the benefit (over real pointers) that the object owner of the field or property will never leave scope or be collected as long as your Pointer object itself exists. So no problems in that respect.