- Home /
[C#] Can't get variable from other script. Yields NullReferenceException
I have a script -- Player.cs -- on one game object and another script -- Land.cs -- on a different game object. Land.cs has a public string array named items. I Player.cs to access that array. Here's how I'm trying to do that:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
private string[] items;
private Transform brain;
void Start () {
brain = transform.Find("Brain");
items = brain.GetComponent<Land>().items;
}
}
It throws a null reference exception on the "items = brain.GetComponent().items;" line. Here's Land.cs:
using UnityEngine;
using System.Collections;
public class Land : MonoBehaviour {
public string[] items = new string[8];
void Start () {}
}
I've added a couple test values to the script in the inspector. Both scripts are on active game objects. Any ideas?
I'd start by using variations on Debug.Log("Brain is" + brain == null ? "NULL" : brain.ToString()); to narrow down the problem.
The same thing can be accomplished with this: Debug.Log(brain); It's null. So the problem is that it's not finding a transform that is sitting right there in the root of the heirarchy.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Got a Error about reffering a object i can not fix 0 Answers
NullReferenceException and m_InstanceID == 0 on LoadLevel (C#) 1 Answer