- Home /
Error in accessing variables from another script
I have two prefabs each having its own individual script. I am then loading both prefabs through a third script and need to work between their variables. Here is what I have done :
public class GameManager : MonoBehaviour {
public Transform buttonPrefab;
public Transform playerPrefab;
private GameObject b;
private GameObject p;
private ButtonScript button;
private PlayerController player;
// Use this for initialization
void Start ()
{
p = Instantiate (playerPrefab, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject;
b = Instantiate (buttonPrefab) as GameObject;
button = b.gameObject.GetComponent<ButtonScript> ();
player = p.gameObject.GetComponent<PlayerController> ();
}
// Update is called once per frame
void Update ()
{
if (button.IsClicked)
player.Move ();
}
}
But I keep getting the Error: NullReferenceException: Object reference not set to an instance of an object.
What am I doing wrong ?
EDIT: After restarting Unity the problem was gone. Thanks anyway!
Yeah it would help to know about the script it's accessing. Have you tried adding if(button != null)?
Answer by JoaoOliveira · Jan 16, 2014 at 12:01 PM
I think instantiating GameObjects from a Transform reference won't work.
Try changing these lines:
public Transform buttonPrefab;
public Transform playerPrefab;
to:
public GameObject buttonPrefab;
public GameObject playerPrefab;
nope, that doesn't fix the problem. Any other suggestions?
In which line do you get the NullReferenceException?
Also, there is no need to write "b.gameObject.GetComponent...". 'b' is already a reference to the GameObject. (This not the problem, just pointing it out)
@JoaoOliveira : I am getting the error in the Update function and I tried doing "button.gameObject.GetComponent ();" and it was still throwing an error hence the unnecessary modification.
@mohanrao164: yup both prefabs have been assigned their respective scripts
Yes it changes nothing, there is just no need to use 'gameObject' in this situation.
If you are getting NullReferenceException in update, then it must be because one of the prefabs doesn't contain the correct script. Did you hit "Apply" after attaching the script to the game objects?
Your answer
![](https://koobas.hobune.stream/wayback/20220613130606im_/https://answers.unity.com/themes/thub/images/avi.jpg)