c# – How to Call a function from another script?

Well you are doing var cube1 = new Cube1(); which is how you would make an object in C#, but since it is Unity, and this is a MonoBehaviour, you are not supposed to make it like that.

Instead, make a new GameObject and attach the Cube1 script to it.


void Start()
{
    // make a new gameobject.
    GameObject gameObject = new GameObject();

    // attach a Cube1 script to it. note: by doing Cube1 cube = ... as Cube1;
    // cube now holds a reference to the script you added.
    Cube1 cube = gameObject.AddComponent<Cube1>() as Cube1;

    // call the function on that cube.
    cube.Rectangle();
}

Sidenote, if you don’t make an object in the scene that holds the ClockController, it won’t execute the Start() method.


When you already have an existing GameObject (instead of making a new one) that has a script you want to access, you can use gameObject.GetComponent<Cube1>() , store it in a variable (if necessary) and access it that way. You just need to get that specific GameObject to begin with.