I have a class called Foo
and a public static Foo handle
variable declared inside of it for global access.
I can access the public members in Foo
by doing: Foo.handle.mypublicmembers
.
In an effort to increase readibility, I’m trying to reduce that to simply: foo.mypublicmembers.
I thought I could get this to work by doing:
Foo foo;
void Awake() {
foo = Foo.handle;
}
But I get object reference instance errors whenever I try to use foo somewhere. I guess hoping to operate like I would in C++ and simply use a pointer to the handle instance but I guess the only thing this is doing is creating a copy? Is what I want possible in C#?
You’ll need to define each and every public member of your handle in Foo if you wish to have that:
public class Foo {
public static SomeHandle handle;
public static int mypublicmembers { get { return handle.mypublicmembers; } }
public static string anotherpublicmember { get { return handle.anotherpublicmember; } }
}
“but I guess the only thing this is doing is creating a copy”
You always copy one value to another, always.
Foo foo;
void Start(){
foo = Foo.handle;
}
this means in the Foo class you should have:
public static Foo handle = null;
void Awake(){
if(handle == null)
handle = this;
}
Just to explain the copy thingy, your Foo object is at 0x00AA, so this is the value contained in handle. In the other script, the Foo reference gets copied the value contained in handle, so foo contains 0x00AA. It is indeed copied.
One reason I see for this to be wrong, is that you are doing in Awake, and you may have the Foo handle init in Awake as well. As a result, handle may not be ready yet.
Solution:
public class Foo:MonoBehaviour{
private static Foo handle = null;
public static Foo Handle {
get{
if(handle == null){
handle = this:
}
return handle;
}
}
}
And you use elsewhere:
Foo foo = null;
void Awake(){
foo = Foo.Handle;
}