I am having trouble accessing a script on a game object which is in an array. Can anyone help. I get the ‘Object reference not set to an instance of an object’ error when I run this line of code:
if (woodStacks*.GetComponent<InventoryStack>().value == 50)*
woodStacks is a GameObject[] array
You should try like:
public GameObject[] woodStacks = new GameObject[yourNumberOfElements];
Or at some later stage:
woodStacks = new GameObject[yourNumberOfElements];
In a loop:
GameObject newStack = Instantiate (stackPrefab, transform.position, transform.rotation) as GameObject;
woodStacks *= newStack;*
and whenever needed:
if (woodStacks*.GetComponent().value == 50)*
Using arrays are an older approach, try using System.Collection.Generics.List<T>
. This way you don’t have to specify the number of element at the time of allocation, and there are several other advantages. See [this][1].
Hope it helps!
_*[1]: .net - Array versus List<T>: When to use which? - Stack Overflow
Hi @AlexGan001
public List<GameObject> woodStacks;
(in a loop:)
GameObject newStack = Instantiate (stackPrefab, transform.position, transform.rotation) as GameObject;
woodStacks.Add(newStack)
when you need to change value
if (woodStacks*.GetComponent<InventoryStack>().value == 50)*
Check your field / variable / property named value
is public, if it is not set as public you can;t access even after you get componant, Also check stackPrefab
has script has attahced InventoryStack
, also confrim when you instantiate it it would not be deactivate mode. If it is deactivate mode GetComponant will may not work.