- Home /
How would I connect the width of an image (in rect transform) to an int?
I'm trying to connect an int to the width of an image so that when the int goes down the image gets smaller. Here is the code. I know there are a few errors and I'm trying to work them out. This script might work but I haven't had the chance to test it since I am presented with a console error because Unity cannot convert an int to Rect transform. Any way to solve this also? using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthBar1stLayerScript : MonoBehaviour { public int Health; private connection combine; void Start() { Health = 100; combine = GetComponents <RectTransform>(); } // Update is called once per frame void Update() { RectTransform Width = Health; } }
Answer by Hellium · Apr 18, 2020 at 05:26 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthBar1stLayerScript : MonoBehaviour
{
private RectTransform rectTransform;
private int health;
public int Health
{
get { return health; }
set
{
health = value;
rectTransform.sizeDelta = new Vector2( health, rectTransform.sizeDelta.y );
// or, depending on your anchors
// rectTransform.anchorMax = new Vector2( health * 0.01f, rectTransform.anchorMax.y );
}
}
void Start()
{
rectTransform = GetComponent<RectTransform>();
Health = 100;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612231807im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Transform to RectTransform Conversion 1 Answer
Help moving left side of Rect Transform 0 Answers
Scale Transform vs RectTransform 0 Answers
RectTransform.rect.Set doesn't work! 1 Answer
How to covert a rectTransform scale to world scale? 1 Answer