- Home /
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
}
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.
So how would I go about fixing this? (I'm following a tutorial and am fairly new to C#)
Well I don't know specific what is happening but you are trying to get an item called Selected, but it does not exist??
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.