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.
If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method: Main m = new Main(); int a = m. getVariableName(); Hope it helps.
We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.
In order to call Method in another Method that is contained in the same Class is pretty simple. Just call it by its name!
Yes you can. The first way is to make your class to be static.
public static class Fooclass
{
// I don't know the return type of your CallMethod, so I used the void one.
public static void CallMethod()
{
}
}
This way, whenever to your code you can call the CallMethod()
like the following:
Fooclass.CallMethod()
Another apporach it would be to define a static method in your current class, without the class needed to be static, like the following:
public class Fooclass
{
// I don't know the return type of your CallMethod, so I used the void one.
public static void CallMethod()
{
}
}
Now since all the instances of the Fooclass
would share the same method called CallMethod
, you can call it like below:
Fooclass.CallMethod()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With