How do I scale the Xmax value of a RectTransform

Im trying to create a status bar that scales to the amount of points you put in it. Everything is good so far except for the actual scaling part. This is what I have so far

float t = armorSlider.GetComponent<RectTransform> ().rect.xMax;
t = (t / 8) * MainControl.instance.ArmorSliderState;
armorSlider.GetComponent<RectTransform> ().rect.xMax = t;

However it gives me this error:

Cannot modify a value type return value of `UnityEngine.RectTransform.rect’. Consider storing the value in a temporary variable

I understand the problem, im just not entirely sure how to make a temporary variable for something like this. I just need to figure out how to edit the Xmax value. Any help is greatly appreciated.

The “rect” property of the RectTransform is of type Rect which is a struct. You need a temporary copy of the Rect value in order to change it and then assign it back:

RectTransform rt = armorSlider.GetComponent<RectTransform>();

Rect tmp = rt.rect;
tmp.xMax *= MainControl.instance.ArmorSliderState / 8;
rt.rect = tmp;

This should do what you want.

RectTransform.rect returns a struct copy of rectTransform’s, and you are trying to setting the value on that copy only. So it wont work.

See this: https://forum.unity3d.com/threads/setting-top-and-bottom-on-a-recttransform.265415/

Edit:

Alternative approach is to do:

RectTransform rt = GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(t, 20.0f);

If anyone’s wondering, I got it to work. I actually just decided I wasn’t going to mess around with the RectTransform. I set the pivot to the far left center and then I just did this.

float x = armorSlider.transform.localScale.x;
float y = armorSlider.transform.localScale.y;
x = (x / 8) * MainControl.instance.ArmorSliderState;
armorSlider.transform.localScale = new Vector3 (x, y, 1);