- Home /
Simply calling a method from another script :(
I'm new to Unity (via AS3), and have scoured the forum trying different things, but I am proper stuck. Must be a n00bie hurdle :(
All I want to do is control a camera rotation with a GUI button and, at present, my error is "Unexpected token: cam". I would really love some help :)
My ButtonScript.js is...
var customSkin:GUISkin;
var cam: CameraScript;
function Start () {
}
function Update () {
}
function OnGUI(){ if(GUI.Button( Rect(10, 10, 320, 80), "Cha...")) { cam: GameObject.FindWithTag("MainCamera").GetComponent(CameraScript); cam.moveCameraPlus(); } }
and my CameraScript.js
var target:Transform;
function Start () { transform.LookAt(target); }
function Update () { moveHorz = Input.GetAxis("Horizontal"); if (moveHorz > 0){ moveCameraPlus(); } else if (moveHorz < 0){ moveCameraNeg(); } }
public function moveCameraPlus () { transform.LookAt(target); transform.Translate(Vector3(0,100,0).right * (Time.deltaTime)); }
public function moveCameraNeg () { transform.LookAt(target); transform.Translate(Vector3(0,100,0).left * (Time.deltaTime)); }
Answer by aldonaletto · Apr 11, 2012 at 11:20 PM
There's an error: you're not assigning correctly the CameraScript to cam:
function OnGUI(){ if(GUI.Button( Rect(10, 10, 320, 80), "Cha...")) { cam = GameObject.FindWithTag("MainCamera").GetComponent(CameraScript); cam.moveCameraPlus(); } }But there's a property available to access the main camera directly:
function OnGUI(){ if(GUI.Button( Rect(10, 10, 320, 80), "Cha...")) { cam = Camera.main.GetComponent(CameraScript); cam.moveCameraPlus(); } }Or - better yet - you could cache the camera script in Start:
function Start(){ cam = Camera.main.GetComponent(CameraScript); }
function OnGUI(){ if(GUI.Button( Rect(10, 10, 320, 80), "Cha...")) { cam.moveCameraPlus(); // just use the cached camera } }
Oops! I made a mistake in Start - answer is fixed now.
Works a treat, Aldo. Thanks a lot! $$anonymous$$y first hurdle is now behind me ;-)
Your answer
Follow this Question
Related Questions
Moving and Attacking 0 Answers
Can't Override Virtual Method In Inherited Class 1 Answer
Change calling object with extension method 1 Answer
Does Unity support extension methods? 3 Answers
Calling Method within a Method from a different Class 0 Answers