- Home /
UnityException not being caught
Here is my code. It is supposed to make a menu screen that shows an "add" button on pressing "escape", and that works. However, there is an error:
using UnityEngine;
using System.Collections;
public class toggleMenu : MonoBehaviour {
bool visible=false;
public Rigidbody mover;
void Update () {
if(Input.GetButtonUp("add")) {
if(!visible) {
try {
gameObject.AddComponent("addMenu");
} catch (UnityException e) {
}
}
visible=!visible;
}
}
}
The error is:
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.
addMenu..ctor ()
UnityEngine.GameObject:AddComponent(String)
toggleMenu:Update() (at Assets/MyAssets/toggleMenu.cs:10)
As you can see, I tried to fix the error to no avail. Once more, I tried to catch the exception, and that didn't work either. Can someone help me out over here?
Answer by Bunny83 · May 20, 2012 at 12:20 PM
Your error is not in this piece of code. Your error is in your "addMenu" class. It seems you used a member variable or function in a field-initializer which doesn't work.
Btw. You shouldn't use the string based version of AddComponent. First, it's slower than the Type based version. Second it can produce runtime errors for example when you misspelled the classname.
gameObject.AddComponent<addMenu>();
This is the faster version and it's type-safe.
I can confirm that this was the error. I had a rigidbody variable in the class statement, and it worked after i moved it into update
Your answer
![](https://koobas.hobune.stream/wayback/20220613071715im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to place/add a HD image/picture in background of my game? 0 Answers
How do I make a stylish GUI? 0 Answers
NGUI: Recommended way of hiding/showing multiple menu panels? 1 Answer
How do I destroy a GUI button when I click on it 1 Answer
How to make a menu that looks like a smartphone/tablet? 2 Answers