- Home /
You are not allowed to call this function when declaring a variable
Hello Unity Community, i have an Error that messes my builded game up with a report message, so heres the error i'v got:
UnityException: You are not allowed to call this function when declaring a variable. Move it to the line after without a variable declaration. If you are using C# don't use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function. Pause Controller..ctor () (at Assets/Scripts/Pause Controller.js:2)
and heres the script the error comes from:
var menuHeight:float=500;
var menuWidth:float=500;
var buttonSpacing:float=25;
var mainMenu: String = "MainMenu";
var titleTexture:Texture2D;
var customSkin:GUISkin;
var customStyle:GUIStyle;
var Player: MouseLook = GetComponent(MouseLook);
var MainCamera: MouseLook = GetComponent(MouseLook);
function OnGUI(){
GUI.skin = customSkin;
GUILayout.BeginArea(Rect(Screen.width/2-menuWidth/2,Screen.height/2-menuHeight/2,menuHeight,menuWidth),customStyle);
GUILayout.Space(50);
GUILayout.Label(titleTexture);
GUILayout.Space(buttonSpacing);
Time.timeScale=0;
Screen.showCursor = true;
Player.GetComponent(MouseLook).enabled = false;
MainCamera.GetComponent(MouseLook).enabled = false;
if(GUILayout.Button("Resume Game")){
gameObject.GetComponent(PauseMenu).enabled = false;
Time.timeScale=1;
Screen.showCursor = false;
Player.GetComponent(MouseLook).enabled = true;
MainCamera.GetComponent(MouseLook).enabled = true;
}
GUILayout.Space(buttonSpacing);
if(GUILayout.Button("Exit to Desktop")){
Application.Quit();
}
GUILayout.Space(buttonSpacing);
GUILayout.EndArea();
}
i really hope to get this thing solved. thanks in advance ^^
Answer by Bunny83 · May 14, 2013 at 08:03 AM
Replace those two lines:
var Player: MouseLook = GetComponent(MouseLook);
var MainCamera: MouseLook = GetComponent(MouseLook);
with those:
var Player: MouseLook;
var MainCamera: MouseLook;
function Start()
{
Player = GetComponent(MouseLook);
MainCamera = Player;
}
Also you don't need to get the component again and again. In OnGUI just do
Player.enabled = false;
btw what's the point of having two variables holding the same component? It seems you set them both at the same time which makes zero sense.
I guess you simply should remove all GetComponent calls and assign your references in the inspector.
actually i just solved it myself by changing the 2 variables to something like this: var Player : GameObject; and the same for the camera and now it works fine, but thanksfor your effort ^^
Your answer
![](https://koobas.hobune.stream/wayback/20220613102201im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How do I report a bug in Unity? 2 Answers
Unity Webplayer Issues 0 Answers
Updating bug, script crash, cant compile script 0 Answers
Crash reports translate ?? 1 Answer