"You are not allowed to call this functiion..." er

Hi, newbie user so forgive the (probably) stupid question…I’ve been trawling through some scripts and everytime I copy an example script into the update function (specifically it’s example code to do with raycasting and it happens in 2 or 3 examples) I get the following error:

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.

And the code:

function Update () {
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, 10)) {
print (“There is something in front of the object!”);
}
}

I’ve attached the code to the main camera. Can anyone tell me what I’m doing wrong? Thanks

Not positive, I only use C#, but according to the error this should work:

function Update () { 
var fwd;
fwd = transform.TransformDirection (Vector3.forward); 
if (Physics.Raycast (transform.position, fwd, 10)) { 
print ("There is something in front of the object!"); 
} 
}

There’s nothing wrong with that code; your problem is probably code running outside functions, which you should avoid.

Just so you know, this isn’t really a good idea, because it makes the fwd variable dynamically typed and much slower, with no particular benefits to doing so in this case.

–Eric

I encountered this message as well…

It comes as a result of trying to use an example in the documentation either in js or c#.

The example I used that has the problems is here:

Modifying it as Eric5h5 mentioned resolves the error. Here is the original example from the above link:

Changing it to be like this fixed it:

I’ll file a bug report about it.

Just to make the answers in this post more complete.
In C# I ran into this problem when combining normal C# classes with MonoBehaviour classes. To make it more performance I used C# classes but whenever you instantiate a MonoBehaviour class indirectly from within a constructor of a normal C# class I got this error.

For me that happened with the singleton pattern:

public static Thing Instance(
if(instance == null){
GameObject go = new GameObject();
instance = go.AddComponent();

if I then need the Instance for the first time in a constructor of a normal C# class. I get the same error which points to the go.AddComponent() line.