Question by
LiamSmith1 · Feb 18, 2018 at 04:02 PM ·
arraynullreferenceexceptionscriptableobject
Calling an array
I have an array that I have placed 20 scriptable objects inside of (in the inspector not in code). Another script randomizes the array so it is different each time (like shuffling a deck of cards). The problem is that when i try to access the array using the value clicks
(from a different script to the one it was made in) it says there is an error Object reference not set to an instance of an object
.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CardStackClick : MonoBehaviour {
private RandomSequence randArr;
public GameObject cardPrefab;
private int clicks = 0;
public void Clicked ()
{
if (clicks < 20)
{
ScriptableObject activeCard = randArr.array[clicks];
clicks += 1;
cardPrefab.GetComponent<CardDisplay>().card = activeCard as CardStats;
}
}
}
Comment
Best Answer
Answer by yummy81 · Feb 18, 2018 at 04:41 PM
It seems that the "randArr" is not assigned and is null. Therefore when you click you get the NullReferenceException. Try to assign the "randArr" in the Awake method, like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CardStackClick : MonoBehaviour
{
private RandomSequence randArr;
public GameObject cardPrefab;
private int clicks = 0;
private void Awake()
{
randArr = FindObjectOfType<RandomSequence>();
}
public void Clicked ()
{
if (clicks < 20)
{
ScriptableObject activeCard = randArr.array[clicks];
clicks += 1;
cardPrefab.GetComponent<CardDisplay>().card = activeCard as CardStats;
}
}
}