Hi All having a really stupid issue I am trying to create a really simple script which takes a list of sprites as a property in the inspector, The script adds a Sprite renderer and assigns it to a property in the Start method and randomly assigns one of the sprite in the list in onEnable()
but I keep getting the error “NullReferenceException: Object reference not set to an instance of an object” in onEnable
Ive previously done some quite complex scripts but I’m a bit rusty and I cant for the life of me figure out whats wrong with the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class RandomSprite : MonoBehaviour
{
public List<Sprite> images = new List<Sprite> { };
Vector2 size;
Vector2 largestObject;
protected SpriteRenderer spriteRenderer;
void Start()
{
spriteRenderer = this.gameObject.AddComponent<SpriteRenderer>();
spriteRenderer.sprite = images[0];
foreach (Sprite sprite in images)
{
if (largestObject.x < sprite.bounds.size.x) largestObject.x = sprite.bounds.size.x;
if (largestObject.y < sprite.bounds.size.y) largestObject.y = sprite.bounds.size.y;
}
Debug.Log("start fired");
}
private void OnEnable()
{
spriteRenderer.sprite = images[Random.Range(0, images.Count - 1)];
size = spriteRenderer.sprite.bounds.size;
Debug.Log("sprite width " + size.x);
}
}
Any Help greatly appreciated