C# Call function from another script on the same gameobject.

Hello, sorry to bother, but I’m a bit stuck and despite looking everywhere around I can’t find anything to help. I’m an utter beginner at Unity, so technical words are confusing me more than helping me…

I have in my scene a GameObject with on it scriptA, which have a void Function1 and in it a bool var Bool
I want to call and execute this Function one, from scriptB, if Bool is true.

I tried use this Unity - Scripting API: GameObject.GetComponent as well as different forums answers, but I can’t get it to work.

I have two versions of that script, each getting a different error.

GetComponent<scriptA>();

if (scriptA.Bool)
{
scriptA.Function1
}

return this error:
Only assignment, call, increment, decrement, and new object expressions can be used as a statement

And if I try ask it to change the variable the function is supposed to change, directly

GetComponent<scriptA>();

if (scriptA.Bool)
{
scriptA.Variabletext.text = "text";
}

I get this
An object reference is required to access non-static member scriptA.Bool

Anyone to help me?

You need to store the ScriptA instance that you got form GetComponent and call the function on that instance.

scriptA scriptAInstance = GetComponent<scriptA>();
 
if (scriptAInstance.Bool)
{
    scriptAInstance.Function1();
}

scriptA scriptAInstance = GetComponent<scriptA>();

if (scriptAInstance.Bool)
{
    scriptAInstance.Variabletext.text = "text";
}

Write “static” in the declaration of the scriptA-method if you want a static method. This means that you can call on the method without having to instantiate an object. It would look like this:

public static void Function1(){
   ...
}

Also you have forgot a “();”. This line:

 scriptA.Function1

Should look like this:

 scriptA.Function1();

ok, thanks a lot to both! I had not stored the instance, so doing that got rid of one error and then indeed, Unity did not recognize the function because of the lacking ()
Now it work fine ^^