How do I call a method from one class from within a separate class

Title says it all. Basically I have a C sharp script with

ClassA
{

public void Method1 ()
{
stuff
}

}

ClassB

{
void Method2 ()
{
ClassA.Method1 ();
}

}

This results in a "An object reference is required for the non-static field, method, or property ‘ClassA.Method1 ()’ " error message.

I obviously need to create an instance of ClassA within the ClassB script before running this method, but I cannot seem to figure out how.

Thanks for the help.

Replace the body of Method2 with:
{
ClassA obj = new ClassA();
obj.Method1();
}

Thanks for the help.

Unfortunately, now I am getting a warning within Unity itself:

You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all.

Oddly enough, the code still appears to be working.

One follow up question though. Say I want to create want to insure Method1 is called from the same instance of ClassA using different instances of ClassB, is there a way to do that?

So put each class in a different script and “add component” to your GameObject B. Like this

GameObjB :MonoBehaviour
{
       ClassA _instance = GetComponent<ClassA>();
        _instance.Method1();
}

Or use a public property in class b that you drag from your hierarchy or prefabs ClassA into the inspector for class bs property. Then

public ClassA _objClassA;

Start()
{
      ClassA instance = Instantiate(_objClassA, new Vector3( 0, 0, 0), Quaternion.identity);
      instance.Method1();
}

Sorry for typos I am on iPad. Crappy typing.

I tried your first method but I am getting the error message:

A field initializer cannot reference the non-static field, method, or property ‘Component.GetComponent()’

Alternatively, I can just used the command

ClassA instance;

to declare the variable and then within ClassB.start I can write

instance = GetComponent();

which the compiler accepts. Unfortunately, and attempt to call ClassA.Method1 from ClassB when running the code gives the following error

NullReferenceException: Object reference not set to an instance of an object.

Perhaps I need to create a single instance of MethodA elsewhere before calling this script?

Thanks for the help.

Just because the compiler accepts doesn’t mean it is correct. NullReference means you didn’t instantiate your object. GetComponent works by getting a script or other component that is attached to a game object in the hierarchy by selecting “Add Component” on your game object in the U.I. scene mode inspector, adding ClassA script to the object.

Try just ClassA _clsA = GetComponent(); after you add component.

2407355--164451--Capture.GIF