Accessing a Nonstatic method from another script

So, for the first time in several weeks my google-fu has failed me, and here i am.

What i want to do is to access a method i’ve got in script A from script B.

script A example:

void printStuff(string stuff)
{
     print(stuff)
}

I want to give printStuff a value which is made in script b, but i dont want to make it static, my scripting genes tell me to use get/return, but i havnt been able to find anything that explains me how it works.

So can anyone here?, i know the question is not directly related to Unity, probably more C#.

Thanks in Advance

  • Kacer

When something isn't static, you need to access a particular instance of the script in question. This is typically done in one script, by calling GetComponent<> on the GameObject, to which the other script is attached. Here's a small example (C#). A and B are attached to two different GameObjects:

public class A : MonoBehaviour
{
    void Start()
    {
        B instanceOfB = GameObject.Find("Name of GameObject to which B is attached").GetComponent<B>();
        instanceOfB.printStuff("this is b's method");
    }
}

public class B : MonoBehaviour
{
    public void printStuff(string blah)
    {
        print(blah);
    }
}

There are two ways:

  1. make your script singleton - see in wiki community. But this way is not always useful.

  2. every script is attached to gameobject. Use GameObject GetComponentto get it.