In my game, pressing a button will change the player’s (prefab) sprite to a new skin. This works, but the Sprite Renderer will only change when the prefab is selected in my prefabs folder.
Here is the code I’m using for the skin changer:
using UnityEngine;
using System.Collections;
public class SkinChanger : MonoBehaviour {
public SpriteRenderer spriteRenderer; //will store sprite renderer
void Start()
{
spriteRenderer = gameObject.GetComponent<SpriteRenderer> (); //get sprite renderer & store it
}
public void change(Sprite differentSprite)
{
spriteRenderer.sprite = differentSprite; //sets sprite renderers sprite
}
}
How are you storing the differentSprite variable?
If there is no reference in the scene then the differentSprite is null if the prefab is not selected.
Try setting the different sprite as a variable that is already present/stored in the scene and check if the error persists.
Man that sucks. Good lukf
Well, there are many things wrong with your approach. First of all you manipulate the actual prefab (asset) in your project, not an instance of a prefab. You shouldn’t do that because:
- Changing assets when testing in the editor could have those changes persist. So it’s possible that you mess up your prefab and have to reimport or recreate / reassign stuff in the editor.
- In a built game those changes would persist for the duration of the session but when your game is closed, everything would be reverted to the point how the prefab looked like when you built the game.
You usually want to either just remember which sprite you want to use when your game starts and apply that sprite to your actual player instance (once it has been instantiated or loaded), or if your player object / instance does already exist in your scene, you want to change that object and not the prefab.
Of course the preview of your asset does not magically change when you (wrongly) silently alter an asset in your project. Only when the Project view repaints you would see the changed asset. Though as I said, runtime code should never alter assets on disk.