- Home /
Changing the sprite of a prefab with in a script?
I'm attempting to change the sprite of an uninstantiated prefab with script, but it's giving me a null reference exception when I try to get the Sprite Renderer.
using UnityEngine; using UnityEditor; public class CarSelector : MonoBehaviour { GameObject playerPrefab; SpriteRenderer playerSprite; private void Start() { playerPrefab = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Player", typeof(GameObject)) as GameObject; playerSprite = playerPrefab.GetComponent<SpriteRenderer>(); } }
Your script will automatically load the prefab into the scene with the new sprite. Is that what you want?
Answer by UltraGearGames · Jan 23, 2019 at 09:02 PM
You should make a script which references the prefab, and its sprite renderer, and changing it. Something like: public Sprite car01; public Sprite car02; public GameObject carObject; void Start() { ChangeSkin(car01); } void ChangeSkin(Sprite carSprite) { carObject.GetComponent<SpriteRenderer>().sprite = carSprite; }
Something along these lines. Hope this helps!
Your answer
Follow this Question
Related Questions
Change a prefab sprite using Random.range instantiate in a script 3 Answers
Change sprite at runtime 1 Answer
Problem with Image and Sprite 1 Answer
Manual sprite split 0 Answers