- Home /
Unexpected Public variable inside a void
Hey guys, I'm with a strange bug, I'm converting a Java 2dMove script to C#, I only put the variables on the project, but I'm not able to use public variables inside a void on C#.
It show a bug "Unexpected public" I dont know why, here my script, only put it on the MonoBehavior or Visual C# and you will understand:
using UnityEngine;
using System.Collections;
public class move2d : MonoBehaviour {
public bool canControl = true;
public Transform spawnPoint;
public void move2D()
{
public float runSpeed = 7;
public float slideFactor = 0.05F;
[System.NonSerialized]
public float slideX = 0.0F;
public float gravity = 60.0F;
public float maxFallSpeed = 20.0F;
public float speedSmoothing = 20.0F;
[System.NonSerialized]
public Vector3 direction = Vector3.zero;
[System.NonSerialized]
public float verticalSpeed = 0.0F;
[System.NonSerialized]
public float speed = 0.0F;
[System.NonSerialized]
public bool isMoving = false;
[System.NonSerialized]
public CollisionFlags collisionFlags;
[System.NonSerialized]
public Vector3 velocity;
[System.NonSerialized]
public float hangTime = 0.0F;
}
}
Answer by $$anonymous$$ · Dec 07, 2012 at 01:58 PM
This is because you can't use access modifiers inside methods in C# since it doesn't really make sense (because variables declared inside a method will only ever exist on that specific stack frame.
Instead of doing this:
public float runSpeed = 7;
public float slideFactor = 0.05F;
You simply leave out the "public" part and just write:
float runSpeed = 7;
float slideFactor = 0.05F;
Don't use keywords such as private and public inside methods, these keywords are meant to be used at class scope :)
So inside your Move2D method, you just have to remove all keywords such as private and public from the variables. Don't use these keywords inside methods at all.
Hope this helps you.
Answer by loopyllama · Dec 07, 2012 at 02:02 PM
You cannot declare variables to be public inside of a method (in your case inside of method move2D. To fix your error you can make all the variables inside of the method move2D private by removing the keyword "public".
However, it looks like the method move2D doesn't do any real work besides setting some variables to some values. It looks like you might want to remove the method move2D and leave all of those variables as public.
As a general note, you might want to consider naming your methods a little better. move2D method inside of class move2d is a little confusing (not to mention I see no code that moves anything in 2d!). A better name for the method move2D might be Init...but in that case you might want to init your variables in an Awake() or Start()
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Return Type Error? 1 Answer