- Home /
Getting referencing error when trying to position a GUI screen.
Hello, I've started making a game and want to put an introduction GUI screen at the beginning of the first level. I need to position the screen directly in the center of whatever screen the user is currently using. With C#, I've created this script:
using UnityEngine;
using System.Collections;
public class OpeningIntroduction : MonoBehaviour {
public bool isGUIOpen = true;
// Use this for initialization
float windowWidth = Screen.width * 0.7f;
float windowHeight = Screen.height * 0.7f;
float displacementWidth = (Screen.width) - (windowHeight/2.0f);
float displacementHeight = (Screen.height) - (windowHeight/2.0f);
void OnGUI () {
if(isGUIOpen = true){
GUI.Box (new Rect(displacementWidth,displacementHeight,windowWidth,windowHeight),"Test");
}
}
void Start () {
}
// Update is called once per frame
void Update () {
}
}
However, when I run it, I get this error: \ A field initializer cannot reference the nonstatic field, method, or property `OpeningIntroduction.windowHeight' \ This error seems to be pointing to the 9 and 10 lines, but I don't see any problems with them. Any help would be very much appreciated. Thanks in advance.
Answer by Moor · Nov 21, 2013 at 06:33 AM
try it like this
GUI.Box (new Rect(Screen.width*0.15f,Screen.height*0.15f,Screen.width*0.7f,Screen.height*0.7f),"Test");
Thank you. Sorry for the late reply. Both answers work perfectly fine, but you made me realize how pointless and complicated I was making this.
Answer by Huacanacha · Nov 21, 2013 at 06:33 AM
Just as the error says you can't use non-static values to initialize instance variables in place. If you need to set an instance variable based on the value of other instance variables this logic belongs in an initialization function. Typically this would be done in the class constructor but Unity MonoBehaviors work a little differently... put it in Awake():
float windowWidth = Screen.width * 0.7f;
float windowHeight = Screen.height * 0.7f;
float displacementWidth;
float displacementHeight;
void Awake() {
displacementWidth = (Screen.width) - (windowHeight/2.0f);
displacementHeight = (Screen.height) - (windowHeight/2.0f);
}