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 /
avatar image
0
Question by Gawee08 · Aug 10, 2017 at 07:15 AM · c#unity 5scripting probleminstanceobject reference

Object reference not set to an instance of an object

I am making an RTS and whenever I try to click on a unit, it returns with an error saying

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

This is my script, please help.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class MousePoint : MonoBehaviour {
 
     #region Class Variables
 
     RaycastHit hit;
 
     public GameObject Target;
     public static GameObject CurrentlySelectedUnit;
     public static ArrayList CurrentlySelectedUnits = new ArrayList();
     public static ArrayList UnitsOnScreen = new ArrayList ();
     public static ArrayList UnitsInDrag = new ArrayList();
 
     private static Vector3 mouseDownPoint;
     private static bool UserIsDragging;
     private static float TimeLimitBeforeDeclareDrag = 1f;
     private static float TimeLeftBeforeDeclareDrag;
     private static Vector2 MouseDragStart;
     private static float clickDragZone = 1.3f;
     private bool FinishedDragOnThisFrame;
 
     //GUI
     public LayerMask SelectMeshLayerMask;
 
     #endregion
     
     // Update is called once per frame
     void Update ()
     {
 
         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
 
         if (Physics.Raycast (ray, out hit, Mathf.Infinity)) {
             //Store point at mouse button down
             if (Input.GetMouseButtonDown (0)) {
                 mouseDownPoint = hit.point;
             
             //Mouse drag
                 if (Input.GetMouseButtonDown (0)) 
                 {
                     TimeLeftBeforeDeclareDrag = TimeLimitBeforeDeclareDrag;
                     MouseDragStart = Input.mousePosition;
                 } 
                 else if (Input.GetMouseButton (0)) 
                 {
                     //If user is not dragging, do tests
                     if (!UserIsDragging) 
                     {
                         TimeLeftBeforeDeclareDrag -= Time.deltaTime;
                         if (TimeLeftBeforeDeclareDrag <= 0f) 
                         {
                             //If tests pass true, user is dragging
                             UserIsDragging = true;
                         }
                     }
 
                     //User is dragging, lets compete (GUI)
                     //if(UserIsDragging)
                     //Debug.Log("User is dragging!");
                 } 
                 else if (Input.GetMouseButtonUp (0)) 
                 {
                     TimeLimitBeforeDeclareDrag = 0f;
                     UserIsDragging = false;
                 }
             
             }
 
             if (hit.collider.name == "TerrainMain") {
 
                 //When we click the right mouse button, instantiate target
                 if (Input.GetMouseButtonDown (1)) {
                     GameObject TargetObj = Instantiate (Target, hit.point, Quaternion.identity) as GameObject;
                     TargetObj.name = "Target Instantiated";
 
                 } else if (Input.GetMouseButtonUp (0) && DidUserClickLeftMouse (mouseDownPoint))
                 {
                     if(!CTRLKeysDown())
                         DeselectGameObjectsIfSelected ();
                 }
 
 
 
             } //End of the terrain
 
             else { 
 
                 //Hitting other objects
                 if (Input.GetMouseButtonUp (0) && DidUserClickLeftMouse (mouseDownPoint)) 
                 {
 
                     //Is the user hitting a unit?
                     if (hit.collider.gameObject.GetComponent<Unit>() || hit.collider.gameObject.layer == LayerMask.NameToLayer("SelectMesh"))
                     {
                         Transform UnitGameObject;
                         if (hit.collider.gameObject.layer == LayerMask.NameToLayer ("SelectMesh"))
                             UnitGameObject = hit.collider.transform.parent.transform;
                         else
                             UnitGameObject = hit.collider.transform;
 
                         //Are we selecting a different object?
                         if (!UnitAlreadyInCurrentlySelectedUnits (UnitGameObject.gameObject)) 
                     {
                             
                             //If the CTRL key is not down, remove the rest of the units
                             if (!CTRLKeysDown ())
                                 DeselectGameObjectsIfSelected ();
 
                             GameObject SelectedObj = UnitGameObject.Find("Selected").gameObject;
                             SelectedObj.active = true;
 
                             //Add unit to currently selected units
                             CurrentlySelectedUnits.Add (UnitGameObject.gameObject);
 
                             //Change unit Selected value to true
                             UnitGameObject.gameObject.GetComponent<Unit> ().Selected = true;
 
 
                         } else {
                             //Unit is already in the currently selected units arraylist
                             //Remove the unit
                             if (CTRLKeysDown())
                                 RemoveUnitFromCurrentlySelectedUnits (UnitGameObject.gameObject);
                             else 
                             {
                                 DeselectGameObjectsIfSelected ();
                                 GameObject SelectedObj = UnitGameObject.transform.Find ("Selected").gameObject;
                                 SelectedObj.active = true;
                                 CurrentlySelectedUnits.Add (UnitGameObject.gameObject);
                                 UnitGameObject.gameObject.GetComponent<Unit> ().Selected = true; //Need to show this
                             }
                         }
 
                     } else {
                         //If this object is not a unit
                         if(!CTRLKeysDown())
                             DeselectGameObjectsIfSelected ();
                     }
                 }
             
 
             }
      
         } else {
             
             if (Input.GetMouseButtonDown (0) && DidUserClickLeftMouse(mouseDownPoint))
                 if(!CTRLKeysDown())
                     DeselectGameObjectsIfSelected ();
         }
     }
 
     void LateUpdate()
     {
         
     }
 
     #region Helper function
 
     //Is user dragging, relative to mouse drag start point
     public bool UserDraggingByPosition(Vector2 DragStartPoint, Vector2 NewPoint)
     {
         if(
             (NewPoint.x > DragStartPoint.x + clickDragZone || NewPoint.x < DragStartPoint.x - clickDragZone) ||
             (NewPoint.y > DragStartPoint.y + clickDragZone || NewPoint.y < DragStartPoint.y - clickDragZone) 
             )
             return true;
         else
             return false;
     }
 
     //Check if a user clicked mouse
     public bool DidUserClickLeftMouse(Vector3 hitPoint)
     {
 
          if(
             (mouseDownPoint.x < hitPoint.x + clickDragZone && mouseDownPoint.x > hitPoint.x - clickDragZone) &&
             (mouseDownPoint.y < hitPoint.y + clickDragZone && mouseDownPoint.y > hitPoint.y - clickDragZone) &&
             (mouseDownPoint.z < hitPoint.z + clickDragZone && mouseDownPoint.z > hitPoint.z - clickDragZone)
             )
             return true; else return false;
     }
 
     //Deselects gameobject if selected
     public static void DeselectGameObjectsIfSelected()
     {
         if (CurrentlySelectedUnits.Count > 0) 
         {
             for (int i = 0; i < CurrentlySelectedUnits.Count; i++) 
             {
                 GameObject ArrayListUnit = CurrentlySelectedUnits [i] as GameObject;
                 ArrayListUnit.transform.Find ("Selected").gameObject.active = false;
                 ArrayListUnit.GetComponent<Unit> ().Selected = false;
             }
 
             CurrentlySelectedUnits.Clear();
         }
     }
 
     //Check if a unit is already in the currently selected units arraylist
     public static bool UnitAlreadyInCurrentlySelectedUnits(GameObject Unit)
     {
         if (CurrentlySelectedUnits.Count > 0) {
             for (int i = 0; i < CurrentlySelectedUnits.Count; i++) {
                 GameObject ArrayListUnit = CurrentlySelectedUnits [i] as GameObject;
                 if (ArrayListUnit == Unit)
                     return true;
             }
 
             return false;
         } else 
             return false;
         }
 
     //Remove a unit from the currently selected units arraylist
     public void RemoveUnitFromCurrentlySelectedUnits(GameObject Unit)
     {
         if (CurrentlySelectedUnits.Count > 0) {
             for (int i = 0; i < CurrentlySelectedUnits.Count; i++) {
                 GameObject ArrayListUnit = CurrentlySelectedUnits [i] as GameObject;
                 if (ArrayListUnit == Unit) 
                 {
                     CurrentlySelectedUnits.RemoveAt (i);
                     ArrayListUnit.transform.Find ("Selected").gameObject.active = false;
                 }
             }
 
             return;
         } else 
             return;
     }
 
     //Are the control keys being held dowN?
     public static bool CTRLKeysDown()
     {
         if (Input.GetKey(KeyCode.LeftControl))
             return true;
         else
             return false;
     }
 
     //Check if a unit is within screen space to deal with mouse drag selection
     public static bool UnitWithinScreenSpace(Vector2 UnitScreenPos)
     {
         if(
             (UnitScreenPos.x < Screen.width && UnitScreenPos.y < Screen.height) &&
             (UnitScreenPos.x > 0f && UnitScreenPos.y > 0f)
             )
                 return true;
             else
                 return false;
     }
 
     //Remove unit from screen units UnitsOnScreen arraylist
     public static void RemoveFromOnScreenUnits(GameObject Unit)
     {
         for (int i = 0; i < UnitsOnScreen.Count; i++) {
             GameObject UnitObj = UnitsOnScreen [i] as GameObject;
             if (Unit == UnitObj) {
                 UnitsOnScreen.RemoveAt (i);
                 UnitObj.GetComponent<Unit> ().OnScreen = false;
                 return;
             }
 
             return;
         }
     }
     #endregion    
 }
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

Answer by ShadyProductions · Aug 10, 2017 at 07:19 AM

Simple, GameObject SelectedObj = UnitGameObject.Find("Selected"); is null so doing .gameObject on it returns your null reference exception.

It seems like Selected doesn't exist.

Comment
Add comment · Show 3 · 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 Gawee08 · Aug 10, 2017 at 07:21 AM 0
Share

So how would I go about fixing this? (I'm following a tutorial and am fairly new to C#)

avatar image ShadyProductions Gawee08 · Aug 10, 2017 at 10:28 AM 0
Share

Well I don't know specific what is happening but you are trying to get an item called Selected, but it does not exist??

avatar image Gawee08 ShadyProductions · Aug 11, 2017 at 08:57 AM 0
Share

I have a unit named "House". It has a child object named "Selected". It has the same layout with another unit which is named "Character" and it works fine with those ones. Whenever I try to click on the house, it returns this error.

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

402 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to obtain this prefab name in this circunstances 1 Answer

NullReferenceException Issues 3 Answers

NullReferenceException: Object reference not set to an instance of an object Plane.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/Plane.cs:37) 0 Answers

Polymorphism for decisions in a dialogue editor 1 Answer

How to check if animator is in crossfade 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