1 script to trigger another script under same GameObject

Hi guys, I have a simple question that I cannot seem to figure out.

I have a GameObject which is the main camera. Under this main camera I have a NGUI user interface with a couple of buttons. What I want to achieve is that when I click one of these buttons, the script that is attached to the main camera is triggered (moves the camera).

I know I have 2 options to do this:

  • GetComponent
  • SendMessage

All the examples that I found so far involve scripts on 2 different GameObjects. How would I go about this using 2 scripts that are on 1 game object?

The reason for using 2 scripts is that the main camera script works perfectly and is rather complex. This is why I would really like another (short) script attached to 1 of the buttons to trigger this script when the button is pressed.

Hierarchy

  • MainCamera (GameObject) < – [Script 1]script to be triggered, contains camera movement
    • NGUI camera with GUI
      • GUI Panel
        • GUI Button ← -[Script 2]with OnClick function that should trigger script 1.

The camera script works well and moves the GUI along since it is a child of the MainCamera.


Any thoughts on what I would need to put in script 2?

In this particular case, you could use the variable Camera.main to get a reference to the main camera and SendMessage or get Script1 with GetComponent:

Camera.main.SendMessage("FunctionInScript1");

or

var scr1: Script1 = Camera.main.GetComponent(Script1);
scr1.FunctionInScript1();

A more general alternative could be to use SendMessageUpwards:

SendMessageUpwards("FunctionInScript1");

SendMessageUpwards searches for the specified function in all scripts upwards in the hierarchy. It’s a little slower than a direct call, but fast as a lightning for user input.