Signup/Sign In

Call a method from other Behaviour Scripts in Unity 3D

In this tutorial we will learn how we can call a public method defined in one script from any other script attached to different gameObject.

One way to do so is by using the static method which we saw and used in our last tutorial, but that is not the right way.


Unity 3D: Call a method from other Script

Lets define a new behaviour class with name FirstScript

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FirstScript : MonoBehaviour
{
    
    void Start()
    {
        // some code
    }
    
    void Update() 
    {
        // some code
    }
    
    public void SayHello()
    {
        Debug.Log("Hey there!");
    }

}

Now lets define our second class with name SecondScript and call the method doSomething() defined in the first script in the second.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SecondScript : MonoBehaviour
{
    public FirstScript first;
    
    void Start()
    {
        // some code
    }
    
    void Update() 
    {
        // calling SayHello() method every frame
        first.SayHello();
    }

}

Hey there! Hey there! Hey there! ...

It will keep on printing Hey there! in the console until the game is in play mode.