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 BenKurdziel · Aug 30, 2013 at 06:08 PM · c#gameobjectlistadding

Add Object to List of GameObjects C#

So I've seen a ton of similar questions, and none of the fixes have worked for me.

Essentially, I'm creating an RTS, and I'm dragging to select my units. I can determine what objects are in that area, but when I go to add them to a list so that I can perform actions with the selected unit, I get a null reference exception.

Before someone brings up that I need to reference the List before I can use it, I've already done that.

I'll just go ahead and paste the whole script.

The part that matter to me here is that when the player lets up on the Left Mouse Key, it should Update Units to determine what we have, then check the area we ragged over. Empty out the old selected unit list. Then check each of our Units (which will eventually be cleaned up for performance) and determine if it is in the area to check.

This all works fine and I have some Debugging and GUI Rect's that even confirm that all my positioning is correct for each object.

However, when I get to this section:

 if (areaCheck.Contains(positionCheck))
                 {
                     Debug.Log("Adding unit.");
                     Debug.Log("This unit is: " + myUnit.name);
                     selectedUnits.Add(myUnit);
                 }

It recognizes the object and sends it to the Debugger correctly (it prints the unit's name, so clearly myUnit DOES have a space in memory as a gameObject. When I go to add it however with the next line "selectedUnits.Add(myUnit);" it throws me a Null Reference Exception.

And yes, "public List selectedUnits= new List();" I have already referenced the list, so that shouldn't be the problem.


 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class script_Player : MonoBehaviour {
 
     // Use this for initialization
     
     public float camSpeed;
     public Camera mainCam;
     
     private Ray leftClickRay;
     private RaycastHit leftClickHit;
     private Vector2 mousePosDown;
     private float mouseXDown;
     private float mouseYDown;
     private Vector3 mouse3DHitDown;
     
     private Ray leftUpRay;
     private RaycastHit leftUpHit;
     private Vector2 mousePosUp;
     private float mouseXUp;
     private float mouseYUp;
     private Vector3 mouse3DHitUp;
     
     private float xDif;
     private float yDif;
     
     public LineRenderer lineRenderer;
     private Vector2 screenPointClick;
     private Vector2 screenPointUp;
     
     private float screenXDif;
     private float screenYDif;
     
     public GUISkin dragSelectSkin;
     
     public GameObject[] units;
     private Vector2 positionCheck;
     public List<GameObject> selectedUnits= new List<GameObject>();
     
     void Start () {
         mainCam = Camera.mainCamera;
         //selectedUnits = new List<GameObject>();
     }
     
     // Update is called once per frame
     void Update () {
         
         #region Movement
         if (Input.GetKey(KeyCode.W))
         {
             this.gameObject.transform.Translate(0,0,camSpeed);    
         }
         if (Input.GetKey(KeyCode.A))
         {
             this.gameObject.transform.Translate(-camSpeed,0,0);    
         }
         if (Input.GetKey(KeyCode.S))
         {
             this.gameObject.transform.Translate(0,0,-camSpeed);    
         }
         if (Input.GetKey(KeyCode.D))
         {
             this.gameObject.transform.Translate(camSpeed,0,0);    
         }
         #endregion
         
         #region Player Left Click Store
         //When Player left Clicks Get the Position of Click and store it
         if (Input.GetKey(KeyCode.Mouse0))
         {
             if (mouse3DHitDown == new Vector3(0,0,0))
             {
                 mousePosDown = Input.mousePosition;
                 mouseXDown = mousePosDown.x;
                 mouseYDown = mousePosDown.y;
                 leftClickRay = mainCam.ScreenPointToRay(new Vector3(mouseXDown, mouseYDown, 0));
                 Debug.DrawRay (leftClickRay.origin, leftClickRay.direction * 100, Color.yellow);
                 
                 if (Physics.Raycast(leftClickRay, out leftClickHit, 300))
                 {
                     mouse3DHitDown = leftClickHit.point;
                     Debug.Log(mouse3DHitDown);
                 }    
             }
             
             mousePosUp = Input.mousePosition;
             mouseXUp = mousePosUp.x;
             mouseYUp = mousePosUp.y;
             leftUpRay = mainCam.ScreenPointToRay(new Vector3(mouseXUp, mouseYUp, 0));
             Debug.DrawRay (leftUpRay.origin, leftUpRay.direction * 100, Color.yellow);
             
             if (Physics.Raycast(leftUpRay, out leftUpHit, 300))
             {
                 mouse3DHitUp = leftUpHit.point;
                 Debug.Log(mouse3DHitUp);
             }    
             
             #region Create Debug Drag Selection Line
             xDif = mouse3DHitDown.x - mouse3DHitUp.x;
             yDif = mouse3DHitDown.z - mouse3DHitUp.z;
             
             Debug.DrawLine(mouse3DHitDown, (new Vector3(mouse3DHitDown.x - xDif, mouse3DHitDown.y, mouse3DHitDown.z)), Color.green);
             Debug.DrawLine(mouse3DHitDown, (new Vector3(mouse3DHitDown.x, mouse3DHitDown.y, mouse3DHitDown.z - yDif)), Color.green);
             Debug.DrawLine((new Vector3(mouse3DHitDown.x - xDif, mouse3DHitDown.y, mouse3DHitDown.z)), (new Vector3(mouse3DHitDown.x - xDif, mouse3DHitDown.y, mouse3DHitDown.z - yDif)), Color.green);
             Debug.DrawLine((new Vector3(mouse3DHitDown.x, mouse3DHitDown.y, mouse3DHitDown.z - yDif)), (new Vector3(mouse3DHitDown.x - xDif, mouse3DHitDown.y, mouse3DHitDown.z - yDif)), Color.green);
             #endregion
         }
         
         #endregion
         
         if (Input.GetKeyUp(KeyCode.Mouse0))
         {
             mouse3DHitUp = new Vector3(0,0,0);
             mouse3DHitDown = new Vector3(0,0,0);
             //screenYDif = 0;
             //screenXDif = 0;
             
             Debug.Log("Updating Units");
             UpdateUnits();
             
             Rect areaCheck = new Rect(screenPointClick.x, screenPointClick.y - screenYDif, -screenXDif, screenYDif);
             
             selectedUnits = null;
             
             foreach (GameObject myUnit in units)
             {
                 positionCheck = mainCam.WorldToScreenPoint(myUnit.gameObject.transform.position);
                 positionCheck.y = Screen.height - positionCheck.y;
                 
                 Debug.DrawRay(mainCam.WorldToScreenPoint(myUnit.gameObject.transform.position), Vector3.forward, Color.blue);
                 
                 Debug.Log("Screen Pos for Unit = " + positionCheck + " / Area to Check = " + areaCheck);
                 
                 if (areaCheck.Contains(positionCheck))
                 {
                     Debug.Log("Adding unit.");
                     Debug.Log("This unit is: " + myUnit.name);
                     selectedUnits.Add(myUnit);
                     
                 }
             }                    
         }
 
 //        if (Input.GetKeyUp(KeyCode.Mouse0))
 //        {
 //            mousePosUp = Input.mousePosition;
 //            mouseXUp = mousePosUp.x;
 //            mouseYUp = mousePosUp.y;
 //            leftUpRay = mainCam.ScreenPointToRay(new Vector3(mouseXUp, mouseYUp, 0));
 //            Debug.DrawRay (leftUpRay.origin, leftUpRay.direction * 100, Color.yellow);
 //            
 //            if (Physics.Raycast(leftUpRay, out leftUpHit, 300))
 //            {
 //                mouse3DHitUp = leftUpHit.point;
 //                Debug.Log(mouse3DHitUp);
 //            }    
 //            
 //            xDif = mouse3DHitDown.x - mouse3DHitUp.x;
 //            yDif = mouse3DHitDown.z - mouse3DHitUp.z;
 //            
 //            Debug.DrawLine(mouse3DHitDown, (new Vector3(mouse3DHitDown.x + xDif, mouse3DHitDown.y, mouse3DHitDown.z)), Color.green);
 //            Debug.DrawLine(mouse3DHitDown, (new Vector3(mouse3DHitDown.x, mouse3DHitDown.y, mouse3DHitDown.z + yDif)), Color.green);
 //            Debug.DrawLine((new Vector3(mouse3DHitDown.x + xDif, mouse3DHitDown.y, mouse3DHitDown.z)), (new Vector3(mouse3DHitDown.x + xDif, mouse3DHitDown.y + yDif, mouse3DHitDown.z)), Color.green);
 //            Debug.DrawLine((new Vector3(mouse3DHitDown.x, mouse3DHitDown.y, mouse3DHitDown.z + yDif)), (new Vector3(mouse3DHitDown.x + xDif, mouse3DHitDown.y + yDif, mouse3DHitDown.z)), Color.green);
 //            Debug.DrawLine(mouse3DHitDown, mouse3DHitUp, Color.green);        
 //        }
         
         #region Create Line Renderer
         xDif = mouse3DHitDown.x - mouse3DHitUp.x;
         yDif = mouse3DHitDown.z - mouse3DHitUp.z;
         
         Debug.Log("xDif = " + xDif);
         lineRenderer.transform.position = mouse3DHitDown;
         lineRenderer.SetPosition(0,mouse3DHitDown);
         lineRenderer.SetPosition(1, new Vector3(mouse3DHitDown.x - xDif, mouse3DHitDown.y, mouse3DHitDown.z));
         lineRenderer.SetPosition(2, new Vector3(mouse3DHitDown.x - xDif, mouse3DHitDown.y, mouse3DHitDown.z - yDif));
         lineRenderer.SetPosition(3, new Vector3(mouse3DHitDown.x, mouse3DHitDown.y, mouse3DHitDown.z - yDif));
         lineRenderer.SetPosition(4,mouse3DHitDown);
         #endregion
     }
     
     void OnGUI () {
         GUI.skin = dragSelectSkin;
         
         GUI.Box(new Rect(positionCheck.x, positionCheck.y,10,10), "");
         
         screenPointClick = mainCam.WorldToScreenPoint(mouse3DHitDown);
         screenPointUp = mainCam.WorldToScreenPoint(mouse3DHitUp);
         
         screenXDif = screenPointClick.x - screenPointUp.x;
         screenYDif = screenPointClick.y - screenPointUp.y;
         
         screenPointClick.y = Screen.height - Input.mousePosition.y;
         
         if (screenXDif != 0)
         {
             GUI.Box(new Rect(screenPointClick.x, screenPointClick.y - screenYDif, -screenXDif, screenYDif), "");
         }
     }
     
     void UpdateUnits () {
         units = GameObject.FindGameObjectsWithTag("Child");    
     }
 
 }


Any advice for me? This has been driving me crazy for a couple days now.

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
2
Best Answer

Answer by Jamora · Aug 30, 2013 at 06:13 PM

You set selectedUnits to null in line 125. This causes the null reference exception later on in the same function. I think what you want instead is selectedUnits = new List(); instead

Comment
Add comment · Show 2 · 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 BenKurdziel · Aug 30, 2013 at 06:32 PM 0
Share

Wow, I feel silly.

I thought that setting it to null would just Empty the list. Should have realized that one.

Worked perfectly, thanks. Probably never would have even occurred to me. :P

avatar image CyberDemonas · Nov 12, 2013 at 12:33 PM 0
Share

You can just clear list with clear method. For example: selectedUnits.clear()

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

19 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

Related Questions

Subtracting the position of transform from the position of Game Objects in a list. 1 Answer

How to select an Game Object from an Item List 0 Answers

C# List foreach problem 1 Answer

How to select the Nth gameObject in a list and put it into a gameObject variable 1 Answer

Cant instantiate from one list to another? 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