I have a scene in which there are 2 players tagged players and each of them has a script RayCasterAttacks. Now in a script I want to store all the players (2 players) in an array and in another variable I want to store their respective RayCasterAttacks script. There are going to be more players later that’s why I want to do thru array and for loop for assigning.
PROBLEM: I am getting all the players in scene in an array but when I write a for loop to assign the RayCasterAttacks which is a component to each it says racasterattacks[ ] are never assigned a value an it will always be null.
This is my code:
using UnityEngine;
using System.Collections;
public class ElementFusion : MonoBehaviour {
GameObject[] players;
GameObject[] attacks;
RayCasterAttacks[] rayCasterAttacks;
int tempLayer;
void Awake()
{
players = GameObject.FindGameObjectsWithTag(Tags.elements);
//Debug.Log("a" +players[0].layer);
for (int i = 0; i <players.Length; i++)
{
rayCasterAttacks[i] = players[i].GetComponent <RayCasterAttacks>(); // Problem here. Please help!
}
attacks = GameObject.FindGameObjectsWithTag(Tags.attack);
tempLayer = 0;
}
Because the variable ‘rayCasterAttacks’ has never had an actual array assigned to it. It’s an empty variable.
Variables are just pointers to objects, if you don’t have an object for it to point at, it’s null (except for value types like float/bool/etc which always have a value).
players = GameObject.FindGameObejctsWithTag(Tags.elements);
rayCastAttacks = new RayCasterAttacks[players.Length]; //creates an array of RayCasterAttacks with same length as players
for(int i = 0; i < players.Length; i++)
{
rayCasterAttacks[i] = players[i].GetComponent<RayCasterAttacks>();
}
//... so on, so forth
It is showing me this error:
NullReferenceException: Object reference not set to an instance of an object
Steam.Awake () (at Assets/Scripts/Steam.cs:24)
FindGameObjectWithTag isn’t guaranteed to return a result if no gameobject with that tag is found.
try:
var go = GameObject.FindGameObjectWithTag(Tags.steam);
if(go != null) steam = go.GetComponent<Transform>();
else Debug.Log("NO STEAM FOUND"); //this line not needed, but surves for debug purposes so you know there was no steam in the scene