I have some code that creates objects with an Image
component, in which I want to replace the Source Image
with one of the default built-in sprites, through the code.
Example:
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class PotionManager : MonoBehaviour {
Image sourceImage;
private float timer=25;
static int COUNT_OF_ORDERS = 0;
public Transform parent;
public List<PotionAsset> potionList = new List<PotionAsset>();
private float posX,posY,posZ;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if (timer >= 30)
{
CreateOrderHolder();
}
}
void CreateOrderHolder()
{
posX = 160 * COUNT_OF_ORDERS + 80;
posY = -70;
posZ = 0;
COUNT_OF_ORDERS++;
GameObject temp = new GameObject("Potion Order " + COUNT_OF_ORDERS, typeof(RectTransform));
temp.transform.SetParent(parent);
temp.transform.localPosition = new Vector3(posX, posY, posZ);
temp.transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);
temp.GetComponent<RectTransform>().anchorMax = new Vector2(0, 1);
temp.GetComponent<RectTransform>().anchorMin = new Vector2(0, 1);
CreatePotionHolder(temp.transform);
timer = 0;
}
void CreatePotionHolder(Transform parent)
{
posX = 0;
posY = 13.5f;
posZ = 0;
GameObject temp = new GameObject("PotionHolder", typeof(RectTransform), typeof(Image));
temp.transform.SetParent(parent);
temp.transform.localPosition = new Vector3(posX, posY, posZ);
temp.transform.localScale = new Vector3(1, 1, 1);
temp.GetComponent<RectTransform>().sizeDelta = new Vector2(100,50);
sourceImage = temp.GetComponent<Image>();
sourceImage.sprite = Resources.Load<Sprite>("Resources/unity_builtin_extra/UISprite");
Debug.Log(sourceImage.sprite);
}
}
In the end, sourceImage.sprite
returns null
. I tried to add at the end of the file path the file extension like png, psd, but this did not help.
Resources.Load
returns null if it can not find the asset under the provided filename. Where exactly is the file located? Also, what kind of file is it?Resources.Load<Sprite>
will require an Unity sprite asset at that position. Not an image asset or a .psd file. \$\endgroup\$ – Philipp Jul 24 '19 at 10:43Resources
folder is deprecated. The new recommended way of loading assets at runtime is Addressable Assets. \$\endgroup\$ – Philipp Jul 24 '19 at 10:47