- Home /
UnityException: You are not allowed to call this function when declaring a variable. Move it to the line after without a variable declaration
Hi everybody! I'm new to game development and programming and I've got a little problem.
#pragma strict
var otherObj = gameObject; // The sword
var Damage : int = 50;
function OnCollisionEnter (hit : Collision)
{
if (otherObj.animation["Attack"].enabled)
{
if(hit.gameObject.tag == "enemy")
{
hit.gameObject.SendMessage("ApplyDamage", Damage);
}
}
}
The code seems to be working but I always get an error (UnityException: You are not allowed to call this function when declaring a variable. Move it to the line after without a variable declaration.).
What is wrong and what should I do?
I tried reading answers on similar questions but I could barely understand them. Please, explain it in simple words so that a newbie like me will understand. :)
Answer by meat5000 · Jul 11, 2014 at 03:48 PM
var otherObj = gameObject; // ?
try
var otherObj : GameObject; // :)
You are trying to dynamically create a variable of type GameObject and make it equal to the gameObject the script is attached to.
#pragma strict
won't let you do that. Cuz its strict mode.
Also, When you use a capital letter for something like GameObject or Transform, it refers to the Type. So, 'of this Type'.
edit : See Bunny83's corrections below. All thumbs up go there ;)
The error's gone and a new lesson is learnt, thank you very much!)
That variable isn't dynamic. It's statically typed and is allowed even in strict mode. The problem is the "gameObject" property which you can't use in a field initializer since those are executed from the loading thread.
Your solution is correct but to initialize the variable you usually would do this:
var otherObj : GameObject
function Awake()
{
otherObj = gameObject;
}
However in most cases you would initialize public variables in the inspector by dragging the desired object onto the variable. I guess that the OP actually doesn't want to reference the own GameObject.
ps: a dynamic variable declaration would look like this:
var someVar;
When you use a field initializer (so when you assign something to the variable when you declare it) the variable is statically typed. The type is inferred from the expression you assigned.
example:
var someVar = 4; // statically typed as int
var someVar2 = 2.0; // statically typed as float
var someVar3; // dynamic variable, doesn't work when using pragma strict.
function Start()
{
someVar = 5.0; // error, can't assign float to int
someVar2 = "Hello world"; // error, can't assign string to float
someVar3 = 5.0; // should work
someVar3 = "Hello World"; // should work
}
Your answer
Follow this Question
Related Questions
Declaring List variable for subclasses with baseclass or without type? 1 Answer
Scripting error! 1 Answer
Range of Unitys Variables 2 Answers
Camera issue (storing temp variable C# problem) 3 Answers
Random time interval 1 Answer