why is new Rect Static

public class ItemC {
private float XPos = 0 ;
private Rect InventoryButtonrec = new Rect(XPos,0,0,0);
}

Assets/Class/ItemC.cs(24,52): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `ItemC.IPos

I don’t want it to be static I cannot afford that

IF I make that XPos Static the error goes away witch means InventoryButtonrec is readed as Static

public int InventoryButton (int ItemCount, Rect IPos, Rect EPos){
		if (pressed){ // we move button
			MX = Event.current.mousePosition.x ;
			MY = Event.current.mousePosition.y ;
			XPos = -40-IPos.x+MX;
			YPos = -30-IPos.y-(ItemCount*20)+ MY;
		}
		
		// if button is pressed
		if (GUI.RepeatButton(new Rect(XPos + IPos.x ,  YPos + IPos.y + ItemCount*20 + 20  ,  80  ,  20),Name)){
			pressed = true;
			if (Input.GetKeyUp(KeyCode.Mouse0)){
				pressed = false;															// box 0 = y280 y320 x0  x40
				for (int box = 0; box < 9*40; box += 40 ) {									// box 1 = y280 y320 x40 x80
					if ((MY>EPos.y && MY<EPos.y+40) && (MX>EPos.x+box && MX<EPos.x+box+40)){	// box x = >U   <D   >L  <R
						XY0() ;	// return to original position								// EPos.x 0 EPos.y 280
						return (box/40); // returns number of box that needs to Equip
					}
					else {XY0() ;} // return to original position
				}
			}
		}
		return -1;// default as null
	}

and in this 2. part it does understand new rect is not static WHY

I’ve posted full code of the function in class maybe I missed something

and stuff that goes in function isn’t static as for infinitive items I need for every items different value and not same

2 Answers

2

Your problem is that class field initializer are executed even before the constructor and they are executed in arbitrary order. Your problem is that you use XPos in the field initializer of InventoryButtonrec. Since XPos is a non static member of the class you can’t use it in an field initializer. Only static values are allowed. If you want to initialize the Rect with XPos, do it in the constructor.

But initializing a privat rect with a private int doesn’t makes much sense to me. Where is XPos intitialized? Why do you even has a seperate variable XPos?

The rect on line 3 of the first code has the same name as the function line 1 of the second code, InventoryButton. No can do !