- Home /
Accessing Variables from another object Script
I am trying to access a public variable from another script on a different gameobject. I have seen this question appear numerous times and the solution given was to use the find game object with tag method to get access to the game object and the getcomponent method to access the script. When I use this solution, i get access to the variable and can manipulate it to good effect but the "NullReferenceException: Object reference not set to an instance of an object" error still persists. I cannot seem to find out what I have done wrong.
Edit: Here is the entire code. EnemyAI retrieves score from PlayerController which it increments as the enemy "dies".. It retrieves and updates the playercontroller score accurately but encounter the NullReferenceException regardless.
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
protected PlayerController player;
Vector2 enemy_motion;
public float speed;
protected float health;
public float arrow_damage;
public GameObject projectile;
protected BoxCollider2D coll;
protected Vector2 size;
protected float projectile_timer = 2f;
protected Vector2 projectile_position;
protected int enemy_point;
void Start(){
player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
coll = GetComponent<BoxCollider2D>();
size = coll.size;
}
void FixedUpdate () {
float x = -5f;
float y = 0;
enemy_motion = new Vector2 (x * speed, y * speed);
rigidbody2D.velocity = enemy_motion;
FireProjectile ();
}
void OnCollisionEnter2D (Collision2D collision){
if (collision.gameObject.tag == "Arrows"){
health -= arrow_damage;
Destroy(collision.transform.gameObject);
renderer.material.color = Color.red; // changes to color red for 0.1 seconds to indicate hit
}
if (health <= 0){
die();
}
}
protected void die(){
player.score+= enemy_point; // this is the location of the nullreferenceerror
Destroy (transform.gameObject);
}
void FireProjectile(){
projectile_timer -= Time.deltaTime;
projectile_position = new Vector2 (transform.position.x - size.x / 2 + 0.01f, transform.position.y);
if (projectile_timer<=0){
Instantiate(projectile,projectile_position , Quaternion.identity);
projectile_timer=2f;
}
}
}
PlayerController Code
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
private float movementY;
private float movementX;
public GameObject arrow;
public float health;
public GameObject shotarrow;
public float playerspeed = 5f;
float leftBorder;
float dist;
float rightBorder;
float topBorder;
float bottomBorder;
public int score;
[HideInInspector]
float firerate = 1.5f;
string textFieldString= "Score: ";
Animator anim;
void Awake(){
score = 0;
}
void Start () {
// coll = GetComponent<PolygonCollider2D>();
anim = GetComponent<Animator> ();
Physics2D.IgnoreLayerCollision(8,9);
dist = (transform.position - Camera.main.transform.position).z;
// detects edges of screen left, right, bottom, top
leftBorder = Camera.main.ViewportToWorldPoint(new Vector3(0,0,dist)).x;
rightBorder = Camera.main.ViewportToWorldPoint(new Vector3(1,0,dist)).x;
bottomBorder = Camera.main.ViewportToWorldPoint(new Vector3(0,0,dist)).y;
topBorder = Camera.main.ViewportToWorldPoint(new Vector3(0,1,dist)).y;
}
void Update(){
if (Input.GetKeyUp (KeyCode.LeftShift)) {
anim.SetBool("if_Drawn", true);
anim.SetBool("if_fired", true);
if (arrow.renderer.enabled){
Instantiate (shotarrow, new Vector2 (transform.position.x, transform.position.y), Quaternion.identity);
arrow.renderer.enabled = false;
}
}
else {
anim.SetBool("if_Drawn", false);
anim.SetBool("if_fired", false);
}
if (anim.GetBool ("if_fired")) {
}
}
void LateUpdate(){
if (!arrow.renderer.enabled){
firerate -= Time.deltaTime;
if(firerate<=0){
arrow.renderer.enabled = true;
firerate = 1.5f;
}
}
}
void FixedUpdate () {
MoveControls ();
}
void OnGUI () {
GUI.contentColor = Color.black;
GUI.Label (new Rect (100, 10, 80, 80), textFieldString + score.ToString());
}
void OnCollisionEnter2D (Collision2D collision){
// Debug.Log ("collides");
if (collision.gameObject.tag == "Enemy") {
Destroy(collision.transform.gameObject);
Damage(10f);
renderer.material.color = Color.red;
}
if (collision.gameObject.tag == "Enemy_projectile") {
Destroy(collision.transform.gameObject);
Damage(4.5f);
renderer.material.color = Color.red;
}
}
void Damage(float amount){
health -= amount;
if (health <=0){
die();
}
}
void die(){
Destroy (transform.gameObject);
}
void MoveControls(){
movementY = Input.GetAxis ("Vertical");
movementX = Input.GetAxis ("Horizontal");
bool atleftboundary = transform.position.x <= leftBorder;
bool leftmotion = movementX < 0;
bool atrightboundary = transform.position.x >= rightBorder;
bool rightmotion = movementX > 0;
bool atlowerboundary = transform.position.y <= bottomBorder;
bool downmotion = movementY < 0;
bool attopboundary = transform.position.y >= topBorder;
bool upmotion = movementY > 0;
bool atYboundary = false;
bool atXboundary = false;
rigidbody2D.velocity = new Vector2 (movementX, movementY)* playerspeed;
if ((atleftboundary && leftmotion) || (atrightboundary && rightmotion)){
rigidbody2D.velocity = new Vector2 (0*movementX, movementY) * playerspeed;
atXboundary = true;
}
if ((atlowerboundary && downmotion) || (attopboundary && upmotion)){
rigidbody2D.velocity = new Vector2 (movementX , 0 *movementY )*playerspeed;
atYboundary = true;
}
if((atYboundary && atXboundary))
rigidbody2D.velocity = new Vector2 (movementX*0, movementY*0)* playerspeed;
}
}
Child Class of EnemyAI
public class Dragon : EnemyAI {
// Use this for initialization
void Start () {
health = 50;
coll = GetComponent<BoxCollider2D>();
size = coll.size;
enemy_point = Mathf.CeilToInt((health / arrow_damage)*10);
player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
}
// Update is called once per frame
void Update () {
}
It could help if we get some more information. Like more code to look at. Not alot to go on here
Answer by Sisso · Jul 07, 2014 at 07:38 PM
You can try find it by name
http://docs.unity3d.com/ScriptReference/GameObject.Find.html
Still get the same NullReferenceExceptionError ....Just to inform the variable "player.score" increments as it should when the enemyobject "dies" but the NullReferenceExceptionError occurs regardless