Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by Synergeon · Oct 23, 2015 at 06:05 PM · c#instancemeleemelee attackarea-damage

Melee Area Attack - Object reference not set to an instance of an object

Hello everyone. I'm trying to set up a combat system, but I've got stuck with a weird error.

 using UnityEngine;
 using System.Collections;

 
 public class PlayerAttack : MonoBehaviour {
 
     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.GetKeyUp(KeyCode.F)){
             if (attackTimer == 0)
             {
                 FrontAttack();
                 attackTimer = cooldown;
                 }        
             }
 
         if (Input.GetKeyUp(KeyCode.G))
         {
             if (attackTimer == 0)
             {
                 AreaAttack();
                 attackTimer = cooldown;
             }
         }
     }
 
     private void FrontAttack()
     {
         Collider[] colliders = Physics.OverlapSphere(transform.position, 2.5f);
         foreach (Collider target in colliders)
         {
 
             Vector3 dir = (target.transform.position - transform.position).normalized;
 
             float direction = Vector3.Dot(dir, transform.forward);
 
             if (direction > 0)
                 {
                     EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
                     eh.AddjustCurrentHealth(-10);
                 }
             }
         }
 }

The function FrontAttack works properly. So I thought "let's copy an paste the function, name it AreaAttack, change the radius of effect and remove the direction part so it can damage at 360°".

 private void AreaAttack()
     {
         Collider[] colliders = Physics.OverlapSphere(transform.position, 8f);
         foreach (Collider target in colliders)
         {
 
                 EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
                 eh.AddjustCurrentHealth(-5);
         }
     }

But if I try it I get "Object reference not set to an instance of an object" referred to the line which define eh in the AreaAttack function. And if I press "G" repeatedly it damages the enemy, without waiting for the cooldown :(

Here I also paste the EnemyHealth script:

using UnityEngine; using System.Collections;

 public class EnemyHealth : MonoBehaviour
 {
     public int maxHealth = 100;
     public int curHealth = 100;
 
     // display healthbar
     public int left = 10;
     public int top = 40;
 
     public float healthBarLenght;
 
     // Use this for initialization
     void Start()
     {
         healthBarLenght = Screen.width / 2;
     }
 
     // Update is called once per frame
     void Update()
     {
         AddjustCurrentHealth(0);
     }
 
     void OnGUI()
     {
         GUI.Box(new Rect(left, top, healthBarLenght, 20), curHealth + "/" + maxHealth);
     }
 
     public void AddjustCurrentHealth(int adj)
     {
         curHealth += adj;
 
         if (curHealth < 0)
             curHealth = 0;
 
         if (curHealth > maxHealth)
             curHealth = maxHealth;
 
         if (maxHealth < 1)
             maxHealth = 1;
 
         healthBarLenght = (Screen.width / 2) * (curHealth / (float)maxHealth);
     }
 }

I seriously can't understand why this happens. I would like to know if someone can tell me the reason and maybe offer me another solution (I would like to avoid using something like a list of targets btw). Thank you a lot for the attention. If you need other parts of my tiny project ask and I'll be pleased to post them :)

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by SniperEvan · Oct 24, 2015 at 06:50 AM

This is an easy fix :)

The problem is that you are trying to reference a script which doesn't exist on at least one of the objects in the foreach loop. You find various colliders and then GetComponent on each of them but at least one of them is giving an error.

Solution: right before eh.Adjust double check that you found something for eh.

if (eh!=null){ eh.adjust... }

Let me know if that gets rid of the error!

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 Synergeon · Oct 24, 2015 at 08:12 AM 0
Share

You saved my day, now it works :)

 private void AreaAttack()
     {      
         Collider[] colliders = Physics.OverlapSphere(transform.position, 8f);
         foreach (Collider target in colliders)
         {
                 EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
             if (eh != null)
             {
                 eh.AddjustCurrentHealth(-5);
             }
         }
     }

Probably what was interfering was the floor of my world, which was detected by overlapsphere, but obviosuly hadn't the EnemyHealth component. (or maybe I could create an evil floor? hm...) With the direction part it worked because the direction relative to the floor wasn't positive and so it was discarded :)

Thank you!

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

how do you keep high frame rate with 200 or more Gameobjects? 1 Answer

(C# - working)(dll - not working) Object reference not set to an instance of an object 1 Answer

Why is object reference not set to an instance? 1 Answer

Unity Melee Attack Problem / Atak problemi var yardım edin :( 0 Answers

Material instance unwanted 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