How to display a sprite as image?
Hey, How could I show the players current equipped weapon on the canvas? I need to find the name of the sprite from in the Item script that is attached to the players weapon slot and display the sprite as an image on the UI. Something like this
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DisplayWeapon : MonoBehaviour
{
public Image CurrentWeapon;
void Start()
{
ChangeImage(newWeaponName);
}
public void ChangeImage(string newWeaponName)
{
newWeaponName = Player.Instance.transform.FindChild("WeaponSlot").GetComponent<ItemScript>().spriteNeutral.name;
CurrentWeapon.sprite = Resources.Load<Sprite>(newWeaponName);
}
}
Comment
Best Answer
Answer by kkiniaes · Dec 16, 2016 at 10:19 PM
Instead of accessing the name of weapon and then loading it from Resources, have you tried using a public Sprite field in your ItemScript class?
I'm assuming that the ItemScript class is attached to a prefab, so you could assign a sprite to each weapon that you have in the game.
What I mean is your code could say something like:
CurrentWeapon.sprite = Player.Instance.transform.FindChild("WeaponSlot").GetComponent<ItemScript>().sprite;
Thank you. This helped. I was able to figure out a way to do it with this.