• 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 /
This question was closed Jul 21, 2015 at 08:55 AM by meat5000 for the following reason:

The question is answered, right answer was accepted

avatar image
-3
Question by radsherwin · Jun 25, 2013 at 05:23 AM · errorhighlight

NullReferenceException: Object Reference not set to an instance of an object.

 using UnityEngine;
 using System.Collections;
 
 public class PlayerAttack : MonoBehaviour {
     public GameObject target;
     public float attackTimer;
     public float coolDown;
     
     
     // Use this for initialization
     void Start () {
         attackTimer = 0;
         coolDown = 2.0f;
     }
     
     // Update is called once per frame
     void Update () {
         if(attackTimer > 0)
         {
             attackTimer -= Time.deltaTime;
         }
         if(attackTimer < 0)
         {
             attackTimer = 0;    
         }
         if(Input.GetKeyDown(KeyCode.Mouse0))
         {
             if(attackTimer == 0)
             {
                 Attack();    
                 attackTimer = coolDown;
             }
                 
         }
     }
     
     private void Attack() 
     {
         float distance = Vector3.Distance(target.transform.position, transform.position);
         
         Vector3 dir = (target.transform.position - transform.position).normalized;
         
         float direction = Vector3.Dot(dir, transform.forward);
         
         if(distance < 2.5f)
         {
             if(direction > 0)
             {
                 EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
                 eh.AdjustCurrentHealth(-10);
             }
         }    
     }
 }

By the way this isn't an error that stops me from playing I can still play but I don't want errors at all.

Also I'm watching the hack and slash tutorial, and when I press tab It's suppose to highlight the enemies red but for some reason for 1 of them it highlights two of the mobs!

Sorry for not posting error message but jesus some of you get so mad, anyways It fixed that error but now I get the same one for a different file:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Targetting : MonoBehaviour {
     public List<Transform> targets;
     public Transform selectedTarget;
     
     private Transform myTransform;
     
     // Use this for initialization
     void Start () {
         targets = new List<Transform>();
         selectedTarget = null;
         myTransform = transform;
         AddAllEnemies();
     }
     
     public void AddAllEnemies()
     {
         GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
         
         foreach(GameObject enemy in go)
             AddTarget(enemy.transform);
     }
     
     public void AddTarget(Transform enemy)
     {
         targets.Add (enemy);
     }
     private void SortTargetsByDistance()
     {
         targets.Sort(delegate(Transform t1, Transform t2) 
         { 
             return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position)); 
         
         });
     }
     private void TargetEnemy()
     {
         if(selectedTarget == null)
         {
             SortTargetsByDistance();    
             selectedTarget = targets[0];    
         }
         else
         {
             int index = targets.IndexOf(selectedTarget);    
             
             if(index < targets.Count - 1)
             {
                 index++;
                     
             }
             else
             {
                 index = 0;
             }
             DeselectTarget();
             selectedTarget = targets[index];
         }
         SelectTarget();
     }
     
     private void SelectTarget()
     {
         selectedTarget.renderer.material.color = Color.red;    
         
         PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack");
         
         pa.target = selectedTarget.gameObject;
     }
     
     private void DeselectTarget()
     {
         selectedTarget.renderer.material.color = Color.blue;
         selectedTarget = null;
     }
     
     // Update is called once per frame
     void Update () {
         if(Input.GetKeyDown(KeyCode.Tab))
         {
             TargetEnemy();    
         }
     }
 }
 

NullReferenceException: Object reference not set to an instance of an object Targetting.SelectTarget () (at Assets/My Scripts/Targetting.cs:71) Targetting.TargetEnemy () (at Assets/My Scripts/Targetting.cs:62) Targetting.Update () (at Assets/My Scripts/Targetting.cs:84)

Comment
Add comment · Show 3
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 KiraSensei · Jun 25, 2013 at 06:16 AM 1
Share

And we have to guess at which line there is the error ? You need to be more specific ...

avatar image Benproductions1 · Jun 25, 2013 at 09:20 AM 2
Share

Why do questions like this pass the queue???

avatar image radsherwin · Jun 25, 2013 at 06:09 PM 0
Share

You Guys are right.. sorry I update the post :)

2 Replies

  • Sort: 
avatar image
1
Best Answer

Answer by KiraSensei · Jun 25, 2013 at 06:19 PM

It means that

 PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack");

returns null.

Make sure that you have PlayerAttack script attached to the game objet that contains the second script too. And I would suggest you to use instead :

 PlayerAttack pa = GetComponent(PlayerAttack);
Comment
Add comment · Show 4 · 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 radsherwin · Jun 25, 2013 at 06:38 PM 0
Share

Okay thanks it works but I still get the 2 enemies highlighted red, but I don't care because I don't want that feature any ways.

avatar image KiraSensei · Jun 25, 2013 at 06:41 PM 0
Share

Cool ! Accept my answer as the right answer by ticking it :)

avatar image radsherwin · Jun 25, 2013 at 06:42 PM 0
Share

I did click it. If it didn't work I will do it again later. :)

avatar image KiraSensei · Jun 25, 2013 at 06:43 PM 0
Share

thanks :).

avatar image
1

Answer by Armand · Jun 25, 2013 at 06:38 AM

As KiraSensei said, you should provide the full error message, but from looking at your code I assume the problem is the Attack() method using the target variable without checking if it's set. So basically, Attack() is sometimes called when there is no target, this would give errors but wouldn't stop you from playing. You can fix this in several ways, one being to change your line 30 like so:

 if (target != null) Attack();

You could also check for null inside Attack().

Comment
Add comment · 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

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

17 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

NullReferenceException: Object reference not set to an instance of an object 0 Answers

"NullReferenceException: Object reference not set to an instance of an object" with instantiate C# 1 Answer

what does this error mean ? 2 Answers

[SOLVED] AugmentedImageDatabase doesn't show table 1 Answer

Why can't I import all the files from character controller 1 Answer


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