Cannot figure GetComponent out.

public class Test : MonoBehaviour {

	GameObject Main_Script;
	public int Owned = Main_Script.Ammount_ROL; //Set the int Owned to the same as Ammount_ROL
	public int Price = Main_Script.Cost_ROL; //Set the int Price to the same as Cost_ROL
	public float ROL_Time = 10.0f; //Timer for ROL

	// Use this for initialization
	void Start () {

		Main_Script = GameObject.Find ("Text").GetComponent <Text_Var>(); //Find the GameObject
	}

I get the error : Assets/Test.cs(7,28): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `Test.Main_Script’

Same for line 8.

The error is not in the GetComponent line, it is in line 4 of your code.

You are defining a private member variable “Main_Script” in your class (“no modifier” implies the keyword “private”), and then try to initialize the public fields “Owned” and “Price” by accessing “Main_Script”. There are several problems with this:

  • “Main_Script” is of type GameObject, which does not HAVE Ammount_ROL or Cost_ROL
  • “Main_Script” will still be unassigned/uninitialized when trying to access it

You can fix this by:

  • declaring Main_Script not as type GameObject, but instead as the class/Component which has the fields Ammount_ROL and Cost_ROL (I’m assuming that class is called “Text_Var”, according to your GetComponent-line?)
  • to be able to access the fields Ammount_ROL or Cost_ROL of a class, even if it is unassigned yet, the fields Ammount_ROL and Cost_ROL must be declared using the keyword “static”, i.e. they are the same for all instances of that Component.
  • if for some reason you do not want this, you will have to move the initializations into Start() or Awake(), probably after assigning “Main_Script” (especially if the fields are non-static). Note they will then be executed only at runtime, not in the Editor.

Note that in all cases, once a Component is initialized in the Editor (=attached to a GameObject), its values shown in the Inspector will ALWAYS override any default declarations (or in other words, even when changing Ammount_ROL or Cost_ROL afterwards, all current instances of “Test” will still show the old values. To prevent this, assign/override these in Start(), or use Editor scripts.

Text_Var Main_Script;

void Start () {
 
         Main_Script = GameObject.Find ("Text").GetComponent <Text_Var>(); //Find the GameObject
     }

Hope This will solve your problem