I'm wanting to know how I can call a method from another class without having to make a new instance of that class. I've looked up this and 90% of the examples I see require me to make a new copy of my referenced class.
Something like this:
Fooclass test = new Fooclass();
test.CallMethod();
However, I'm wondering if there is a way I can call the method without making a new class instance. Right now I've tried the following in unity.
public ImageLoader image;
void Start ()
{
image = gameObject.GetComponent<ImageLoader>() as ImageLoader;
}
void OnClick()
{
image.MoveForward();
}
however, when I run this I get the following error:
NullReferenceException: Object reference not set to an instance of an object
i know this would be settled with making a new instance of my image loader class but I can't do that as it is holding a lot of data I don't want duplicated multiple times.
Yes you can. The first way is to make your class to be static.
This way, whenever to your code you can call the
CallMethod()
like the following:Another apporach it would be to define a static method in your current class, without the class needed to be static, like the following:
Now since all the instances of the
Fooclass
would share the same method calledCallMethod
, you can call it like below:without again needed to instantiate an object of type Fooclass, despite the fact that now Fooclass isn't a static class now !
For further documentation please take a look to the link Static classes and Static Members.