MrRockis
MrRockis

Reputation: 17

Unity Call a class function from other script

I have 2 scripts: Console and Test. I want to call "appendLogLine" function from Test script but cannot get it working.

Console.cs:

public class ConsoleController
{

    public void appendLogLine(string line)
    {
        if (line == "Unable to process command ''")
            return;

        Debug.Log(line);

        if (scrollback.Count >= ConsoleController.scrollbackSize)
        {
            scrollback.Dequeue();
        }
        scrollback.Enqueue(line);

        log = scrollback.ToArray();
        if (logChanged != null)
        {
            logChanged(log);
        }
    }
}

Test.cs:

public GameObject ConsoleObject;

public void CallLog()
{

    ConsoleObject.GetComponent<ConsoleController>.appendLogLine ("Test123");
}

I get error with that: "error CS0119: Expression denotes a method group', where avariable', value' ortype' was expected"

Upvotes: 0

Views: 2093

Answers (1)

Programmer
Programmer

Reputation: 125455

In order to use GetComponent, the script you are performing GetComponent on must inherit from MonoBehaviour. This is not the case here.

public class ConsoleController {} should be public class ConsoleController : MonoBehaviour {}

Now, you use GetComponent on the ConsoleController script. Note that you forgot "()" too. You must include that since GetComponent is a function.

It should be this:

ConsoleObject.GetComponent<ConsoleController>().appendLogLine("Test123");

Upvotes: 4

Related Questions