Text 101 : how to add UI images for each state?

Hi all. My Text101 works fine with just the text. But I wanted to try adding a UI image for each state (changing UI image by script).

So I added UI Image to the Canvas, put some sprites into Assets and made a new script. I followed the advice found here : http://answers.unity3d.com/questions/956554/unity-50-trying-to-change-the-image-source-image-v.html#answer-form

Except that, problem found : An object reference is required for the non-static field/method/property “ImageController.image1”, occurring on the line I commented out.

Am just at the part where trying to assign the first sprite to the UI Image box, so not even started trying to change sprites by script. I experimented by adding an empty game object and attaching the sprites to it, then I tried putting the sprites “physically” into the scene, and also checked out different syntaxes, and some other codes from other searches.

Would be nice to know how to do it, hoping someone got experience with this. Thanks for reading :slight_smile:


[IMAGECONTROLLER SCRIPT]

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ImageController : MonoBehaviour {

Image image1;
public Sprite spritepika;
public Sprite spritejig;
public Sprite spritekof;	


void Start () {
	image1 = GetComponent<Image>();
}


public static void SetPikachu() {
	//image1.sprite = spritepika;
}

}


[TEXTCONTROLLER SCRIPT]

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class TextController : MonoBehaviour {

public Text text1;
private enum States {Pikachu, Jigglypuff, Koffing} ; 
private States states1;

private ImageController imageController;

			
void Start () {
	states1 = States.Pikachu;
	imageController = GameObject.FindObjectOfType<ImageController>();
}


void Update() {
	if      (states1 == States.Pikachu)     {Pikachu();     }
	else if (states1 == States.Jigglypuff)  {Jigglypuff();  }
	else if (states1 == States.Koffing)     {Koffing();     }
	
	print(states1);	
}	

	
void Pikachu() {
	ImageController.SetPikachu();

	text1.text = "A wild Pikachu appears!\n\n" +
	"Press J for Jigglypuff.";

	if (Input.GetKeyDown(KeyCode.J)) {
		states1 = States.Jigglypuff;
	} 
}

Privacy & Terms