I have a folder in my unity project under "Resources/ScriptableObjects/Skins". I need to get all the objects in the folder, generate a random number for the index, then assign the sprite to an existing game object that the script is attached to. The current error I'm getting is "NullReferenceException: Object reference not set to an instance of an object" on line 151 but I'm creating an instance of the object on line 149. What gives? Here is my function to assign the sprite from a random scriptableobject in the folder to the game object the script is tied to:
void AssignRandomSkin(){
// Load all skins into memory
Object[] skinObjects = Resources.LoadAll("ScriptableObjects/Skins");
// Get length of list
int amountOfSkins = skinObjects.Length;
// Get random index of skin to assign
int skinToAssignIndex = Random.Range(0, amountOfSkins);
GameObject thisSkin = Instantiate(skinObjects[skinToAssignIndex]) as GameObject;
// Assign it to game object
gameObject.GetComponent<SpriteRenderer>().sprite = thisSkin.GetComponent<Sprite>();
}
Here is the Scriptable Object:
using UnityEngine;
[CreateAssetMenu(fileName = "Skin", menuName = "ScriptableObjects/SkinObject", order = 1)]
public class SkinObject : ScriptableObject
{
public string spriteName; // Name of sprite
public Sprite sprite;
public float xPos;
public float yPos;
public float zPos;
public float xScale;
public float yScale;
public float zScale;
public float fallSpeed; //AKA Weight
public string tier; //Category that skin can be assigned in
}