Change Canvas Image from Another Script
So I am trying to change a canvas's image to red if there has been a collision with the player. I have a canvas with an image component, with "Source Image" set to a transparent square that I made in photoshop. I want to change it to another red square that I made in photoshop vi my PlayerBehavior script if there has been a collision. This is what I tried:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerBehavior : MonoBehaviour {
Image image;
void start() { }
void update() {}
void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "bullet") {
Canvas canvas = GetComponent<Canvas>();
image = canvas.GetComponent<Image>();
image.sprite = Resources.Load ("flashred.png");
}
}
}
I am getting this error:
Error CS0266: Cannot implicitly convert type `UnityEngine.Object' to `UnityEngine.Sprite'. An explicit conversion exists (are you missing a cast?) (CS0266) (Assembly-CSharp)
I just wanted to note/update: as of Unity 5.6.1f1, and $$anonymous$$onoDevelop 5.9.6, the latter example ( by aditya007) works, the former (as Sprite by Namey5) does NOT, I just tested them both; so everyone who needs this: use the second example and you should be fine.
Answer by Namey5 · Nov 14, 2016 at 06:00 AM
Try;
image.sprite = Resources.Load ("flashred.png") as Sprite;
or image.sprite = Resources.Load<Sprite> ("flashred.png");
both are same though.