Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Amindovermatter · Jul 07, 2014 at 07:33 PM · gameobjectscript.accessing

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 () {
     
     }









Comment
Add comment · Show 6
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Sisso · Jul 07, 2014 at 07:37 PM 0
Share

Did your player have tag "Player"?

avatar image Amindovermatter · Jul 07, 2014 at 07:41 PM 0
Share

Yes it has

avatar image Kiwasi · Jul 07, 2014 at 07:48 PM 0
Share

Its entirely possible score or enemy_point is null.

avatar image Brahim113 · Jul 07, 2014 at 07:52 PM 0
Share

I think a primitive cant be null

avatar image Brahim113 · Jul 07, 2014 at 07:54 PM 0
Share

It could help if we get some more information. Like more code to look at. Not alot to go on here

Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Amindovermatter · Jul 07, 2014 at 07:53 PM 0
Share

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

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

GameObject is already being activated or desactivated 2 Answers

disable a script 1 Answer

GameObject references runtime script in scene file. Unsure whats wrong 2 Answers

How do you access a script if you don't know it's name? 5 Answers

get all scripts attached to gameobject 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges