Trying to change Source Image of UI Image via Script
Hello,
I have been working on trying to access this particular component and have not had any luck, this script works (no errors) but its not changing the Source Image component of the object the script is attached to.
Note: I am using a button to SendMessage(string) to run the Roll () method in this script.
The field I want access to change is:
Both highlighted fields should be the same.
Code is Below. Thanks in advance for the help!
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class diceImage : MonoBehaviour {
public int rng;
public Sprite diceImg;
public Sprite blank;
public Sprite clear;
public Sprite crit;
public Sprite focus;
public Sprite hit;
void Awake () {
diceImg = GetComponent<Image> ().sprite;
}
// Use this for initialization
void Start () {
diceImg = blank;
rng = 0;
}
// Update is called once per frame
void Update () {
}
void Roll () {
rng = Random.Range (1, 9);
Debug.Log (rng);
if (rng == 1) {
diceImg = clear;
} else if (rng == 2) {
diceImg = crit;
} else if (rng == 3) {
diceImg = focus;
} else if (rng == 4) {
diceImg = hit;
} else if (rng == 5) {
diceImg = focus;
} else if (rng == 6) {
diceImg = hit;
} else if (rng == 7) {
diceImg = clear;
} else if (rng == 8) {
diceImg = hit;
} else {
diceImg = blank;
}
}
}
Does this answer still hold for Unity 5.x.x? There is no component named .
Answer by Veldars · Jul 24, 2015 at 09:25 AM
Hi, you must assign your sprite directly on the image.
GetComponent<Image>().sprite = newSprtie;
or
Image img = GetComponent<Image>();
img.sprite = newSprite;
I hope this help...
Thanks Veldars! This is the help I was looking for.
I changed every if and else if from this
if (rng == 1) { diceImg = clear;
To this
if (rng == 1) {
GetComponent<Image> ().sprite = clear;
}
I removed the diceImg variable completely.