How to call FUNCTIONS defined in another Script. Examples in C# Unity

Introduction

In this article we will see how to execute functions defined in one script from a second script. First we look at the generic procedure.

In the following video I explain how to call functions from another script.
All the information is presented to you as a generic example, two scripts, “ScriptA” and “ScriptB“, the function we want to call is defined inside ScriptA, so from ScriptB we are going to access to ScriptA.




Procedure

1. We start with 2 Scripts, “ScriptA” and “ScriptB”. In Script A is the function we want to call. In Script B we are going to call the function that is in ScriptA.

2. In ScriptA we make sure that the function is declared as public, otherwise we will not be able to access it from a context outside of ScriptA.

3. In ScriptB we declare a ScriptA type variable and we must find the reference of that object. This will depend on where we are programming, in the case of Unity we will do it in the Start method and with the instruction FindObjectOfType.

4. To call the function of ScriptA from ScriptB, we use the rererence we defined from A and with the dot operator we can access it and execute it inside ScriptB.

Scroll to Top
Secured By miniOrange