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 SeawardToast · Jan 11, 2015 at 04:40 AM · raycasting

Getting the object reference not set to an instance of an object error when raycasting

Hey guys, I am trying to raycast and attack an enemy causing it to lose health. I ran into this error when I am sending the ApplyDamage message.

 NullReferenceException: Object reference not set to an instance of an object
 MeleeSystem.Update () (at Assets/Scripts/MeleeSystem.cs:22)

This is the line that the error is thrown on

 hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver); 

Here is my attack script code

 public class MeleeSystem : MonoBehaviour {
 
     int Damage = 50;
     float Distance;
     float MaxDistance = 2;
     Transform TheSystem;
 
     void Update() {
         if (Input.GetKeyDown("l")) {
 
             RaycastHit hit;
             if (Physics.Raycast(transform.position, transform.forward, out hit))
                 Debug.DrawLine(transform.position, hit.point, Color.cyan);
             Debug.Log("Attack Initiated");
             {
                 Distance = hit.distance;
                 if (Distance < MaxDistance)
                     hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
                 Debug.Log("Sending attack!");
 
 
             }
         }
     }
 }

Here is the enemy code where the message is recieved

 using UnityEngine;
 using System.Collections;
 
 public class EnemyHealth : MonoBehaviour {
 
     public int health = 100;
 
     void ApplyDamage(int Damage){
         Debug.Log ("Damage being applied... Stand by");
         if (health > 0){ // if enemy still alive (don't kick a dead dog!)
             health -= Damage; // apply the damage...
             // <- enemy can emit some sound here with audio.Play();
             if (health <= 0){ // if health has gone...
                 Debug.Log ("You killed it");
             }
         }
     }
 }


Please help me fi the error and be able to apply damage to my enemy.

Comment
Add comment · Show 13
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 getyour411 · Jan 11, 2015 at 04:41 AM 0
Share

I don't use Send$$anonymous$$essage so not sure what the 'donotrequirereceiver' does, but what if the thing the ray hits is not an enemy? Around line 16 (top code) add

Debug.Log(hit.name);

Verify the ray is hitting what you are expecting it to.

avatar image SeawardToast · Jan 11, 2015 at 04:47 AM 0
Share

It is throwing an error when I try to add that because ray does not contain name, but what is the way you do yours? I do not have to do raycasting, I just need to be able to kill an enemy

avatar image getyour411 · Jan 11, 2015 at 04:57 AM 0
Share

try hit.transform.name

avatar image SeawardToast · Jan 11, 2015 at 05:00 AM 0
Share

Now only the error shows up. Is there a better way to do this than raycasting? If so, do tell

avatar image getyour411 · Jan 11, 2015 at 05:08 AM 0
Share

hit.transform.name does not return anything? That seems unlikely if you added it in the if(Raycast.hit)

There are other ways, but getting a handle on the basic RayCast functions will serve you. If you are desperate for a different approach, check out Physics.OverlapSphere or similar.

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by HarshadK · Jan 13, 2015 at 10:27 AM

The problem lies in the placement of braces in the script. Everything you have that works with the Raycast hit should be inside your if(Physics.Raycast....) code block and your current placement of braces was a little off.

Here's the correct one:

  void  Update ()
  {
     if (Input.GetKeyDown("l")) 
     {
         RaycastHit hit;
         if(Physics.Raycast(transform.position, transform.forward, out hit))
         {
             Debug.DrawLine (transform.position, hit.point, Color.cyan);
             Debug.Log ("Attack Initiated");
             Distance = hit.distance;
             if (Distance < MaxDistance)
             {
                 hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
                 Debug.Log ("Sending 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
avatar image
0

Answer by Baste · Jan 13, 2015 at 10:32 AM

I copied your MeleeSystem script to my editor, hit "auto format", and then edited it back into your post. Take a look at it and see if you can spot the error!

If not: your brackets are all wrong! In this part of the code:

 RaycastHit hit;
 if (Physics.Raycast(transform.position, transform.forward, out hit))
     Debug.DrawLine(transform.position, hit.point, Color.cyan);

 Debug.Log("Attack Initiated");
 {
     Distance = hit.distance;
     if (Distance < MaxDistance)
         hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
     Debug.Log("Sending attack!");
 }

The if-check on the raycast only stops the DrawLine, all of the rest of the code runs no matter if the raycast hits or not. The brackets after the "Attack Initiated" message doesn't do anything here.

Just move the bracket after "attack initiated" up to after the if, and you're good to go.

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

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

How do I get my camera to rotate around the y=0 coordinate it's looking at? 0 Answers

Detecting if mouseclick is within path 1 Answer

Physics.Boxcast not working with mesh collider 1 Answer

Raycast does not work with touch input but works well with mouse input why? 0 Answers

Tangent Space Normal Map to World Space Normal Vector in C# Script 0 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