Here I have been trying to create a selection management so that at any given time there will be only one gameobject selected or highlighted. I have done my utmost and here I have put the script. The thing is, i cant seem to alternate selections and I often get a “NullReferene”. The script is partly working and partly not. Can you help me out? I need to know how to get thing done.
using UnityEngine;
using System.Collections;
public class MouseControl1 : MonoBehaviour {
//This scripts handles the actions performed by the mouse
public GameObject currentlyselected;
public bool selected = false;
public RaycastHit hit;
public void Start ()
{
}
public void Update()
{
MouseController();
}
//This funcition controls the actions performed by the mouse
public void MouseController()
{
//if the left mouse button is down
if(Input.GetMouseButtonDown(0))
{
//Player pressed the mousebutton
Debug.Log ("Player pressed the mousebutton.");
//cast a ray into the scene to detect objects
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit, Mathf.Infinity))
{
//print the name of the object the ray collided
Debug.Log(hit.transform.gameObject.name);
}
//if the ray hits a player
if(hit.transform.gameObject.tag == "Player")
{
currentlyselected = hit.transform.gameObject;
Select();
Debug.Log(1);
} else {
if(selected == true)
{
Deselect();
currentlyselected = hit.transform.gameObject;
Select();
Debug.Log(2);
}
}
//if the ray doesn't hit the player and the object is selected
if(hit.transform.gameObject.tag != "Player" && selected == true)
{
Deselect();
Debug.Log(3);
} else {
if(selected != true)
{
Debug.Log("There was nothing there.");
Debug.Log(4);
}
}
}
}
public void Select()
{
currentlyselected.transform.FindChild("Blob Light Projector").gameObject.SetActive(true);
selected = true;
}
public void Deselect()
{
currentlyselected.transform.FindChild("Blob Light Projector").gameObject.SetActive(false);
currentlyselected = null;
selected = false;
}
}