Run function in other C# Script

Hi all,

ok so I’m making the dreaded leap from JS to C#!! I know right!!?.. Scary stuff!

So I’ve run into another problem…

Ive got function on my main character called myFunction();

How can i run that function from another C# script located on another object? Whats the syntax?

Cheers guys! :slight_smile:

The procedure is same as JS.

  1. Get reference to the object and script required.
  2. Call the function from that script using this reference.

Consider you have Player game object on which your PlayerScript resides which has a function called PlayerFunction. Now you want to call that function from your MyScript. Do something like:

GameObject player = GameObject.Find("Player");
PlayerScript playerScript = player.GetComponent<PlayerScript>();
playerScript.PlayerFunction(); // Here you call the PlayerFunction()

This all can be done in one line as:

GameObject.Find("Player").player.GetComponent<PlayerScript>().PlayerFunction();

But getting reference allows you go cache the results so you don’t have to perform these tasks again and again as it is not efficient.