- Home /
Trying to call Image varible with GetComponent, doesn't want to work
Basically this is the way my script is set up atm
Storage str;
Dig dig;
Image img;
public GameObject storage1, storage2;
void Start (){
str = FindObjectOfType<Storage> (); //Another Script
dig = FindObjectOfType<Dig> (); //Another Script
img = GetComponent<Image> ();
}
void Update () {
}
public void UpdateInventory(){
if (dig.temp == "Object") {
if (storage1.GetComponent<Image> ().sprite == str.spr1) {
storage1.GetComponent<Image> ().sprite = str.spr2;
return;
} else if (storage2.GetComponent<Image> ().sprite == str.spr1) {
storage2.GetComponent<Image> ().sprite = str.spr2;
return;
}
}
}
}
I need to be able to find a way to use the variable img
instead of always having to write out GetComponent<Image> ().sprite
all the time because it will get tedious and repetitive.
I've checked out the documentation and other questions and stuff but still can't figure this one out. I've tried out something like storage1.img.sprite =
but the error that comes up is something like img isn't defined or something.
Any help would be appreciated.
Answer by Chik3r · May 26, 2018 at 01:14 PM
Because storage1 & storage2 are a GameObject, the only way to get an Image component would be to use GetComponent<Image>()
, GameObject has no variable called img-image-etc. that has a reference to an Image component.
What you could do is add a script to your storages and have a reference to that script, and inside that script have a variable called "img" of type Image that gets defined at the start.
Storage str
is a link to a script within storage1 and 2. So I just define the GetComponent
within an Image variable in Storage then I just call str.img
within the if statements?
Okay, I think I've got this figured out. When I use the direct script (Storage) I need to hold the variable inside of a sprite for it to not throw out any errors. So even though it is technically an Image ins$$anonymous$$d of SpriteRenderer, I still need to use a Sprite variable to transfer the data across.
Your answer
Follow this Question
Related Questions
How can I put the single pieces of a sliced Sprite into an array? 0 Answers
Changing a UI image sprite in scripts results in a black texture 0 Answers
Unable to drag image from Assets folder to Sprite: None under Sprite Renderer. 0 Answers
How do I change the import settings when using sprite.create with a WWW.texture from a png image. 1 Answer
How do i generate random types of sprites in game ?,Can i set a variable to an image asset ? 0 Answers