How do you call another script in Unity?
In Unity, there are several ways to call another script.
- In the script where you need to make a call, create a reference variable and assign the script you need to call to that variable. Then you can use that variable to call methods or access properties in another script.
public class ScriptA : MonoBehaviour
{
public ScriptB scriptB;
private void Start()
{
scriptB.MethodB();
}
}
- Get Component
public class ScriptA : MonoBehaviour
{
private ScriptB scriptB;
private void Start()
{
scriptB = GetComponent<ScriptB>();
scriptB.MethodB();
}
}
- Locate an instance
public class ScriptA : MonoBehaviour
{
private ScriptB scriptB;
private void Start()
{
scriptB = FindObjectOfType<ScriptB>();
scriptB.MethodB();
}
}
These methods allow you to choose the appropriate way to call another script based on the specific situation.