I can't work out how to access and read changes in a script of a gameObject that has been selected. The script selects enemy objects with right mouse button and player objects with left mouse button. I want to be able to make the enemy null and deselect it when its health reaches zero but I cannot get past the
"NullReferenceException: Object reference not set to an instance of an object"
problem. I have commented out the section of code where it should be accessing the enemy's vitals script to see what its health is.
Here is the script I'm using:
public class CameraDetectClick : MonoBehaviour
{
Ray ray;
RaycastHit hit;
public GameObject currentlySelectedPlayer;
public GameObject currentlySelectedFoe;
public EnemyVitals enemyVitals;
public bool selected;
void Start()
{
enemyVitals = GetComponent<EnemyVitals>();
}
void Update()
{
if(Input.GetMouseButton(0))
{
ray = camera.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit, Mathf.Infinity) && hit.collider.transform.FindChild("SelectedPlayer"))
{
currentlySelectedPlayer = hit.collider.transform.FindChild ("SelectedPlayer").gameObject;
currentlySelectedPlayer.active = true;
selected = true;
}
else if (Physics.Raycast(ray, out hit, Mathf.Infinity) && (hit.collider.name == "Ground"))
{
if(currentlySelectedPlayer != null)
{
currentlySelectedPlayer.active = false;
currentlySelectedPlayer = null;
selected = false;
}
}
}
if(Input.GetMouseButton(1))
{
ray = camera.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit, Mathf.Infinity) && hit.collider.transform.FindChild("SelectedFoe"))
{
currentlySelectedFoe = hit.collider.transform.FindChild ("SelectedFoe").gameObject;
currentlySelectedFoe.active = true;
selected = true;
//here, the beasty foe has been selected, so I need to grab and monitor its vitals script so I
//can see when it drops to zero. This does not work as it says I need to set it to an instance of an object.
enemyVitals = currentlySelectedFoe.GetComponent<EnemyVitals>();
if(enemyVitals.currentBeastHealth == 0)
{
currentlySelectedFoe.active = false;
currentlySelectedFoe = null;
selected = false;
}
}
else if (Physics.Raycast(ray, out hit, Mathf.Infinity) && hit.collider.name == "Ground")
{
if(currentlySelectedFoe != null)
{
currentlySelectedFoe.active = false;
currentlySelectedFoe = null;
selected = false;
}
}
}
}
}