I have spent way to much time on this and it's doing my head in- can someone please help me fix this broken code. -_- Many thanks.
using UnityEngine;
using System.Collections;
public class Mouse : MonoBehaviour {
RaycastHit hit;
public static GameObject CurrentlySelectedUnit;
public GameObject Target;
private Vector3 mouseDownPoint;
// Use this for initialization
void Awake ()
{
mouseDownPoint = Vector3.zero;
}
// 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;
//Debug.Log (hit.collider.name);
if(hit.collider.name == "Floor")
{
if(Input.GetButtonDown(1))
{
GameObject TargetObj = Instantiate(Target, hit.point, Quaternion.identity) as GameObject;
TargetObj.name = "Target Instantiaed";
}
}
else if (Input.GetMouseButtonUp(0) && DidUserClickLeftMouse(mouseDownPoint))
DeselectGameObjectIfSelected();
}
}
}//end of the terrain!
else {
//hitting other objects!
if (Input.GetMouseButtonUp(0) && DidUserClickLeftMouse(mouseDownPoint))
{
//is the user hitting unit?
if(hit.collider.transform.FindChild("Selected"))
{
//found unit to select!
Debug.Log ("Found Unit!");
//are we selecting a different object?
if(CurrentlySelectedUnit != hit.collider.gameObject)
{
//activate the selector
GameObject SelectedObj = hit.collider.transform.FindChild("Selected");
SelectedObj.active = true;
//deactivate the currently selected objects selector
if(CurrentlySelectedUnit != null)
CurrentlySelectedUnit.transform.FindChild("Selected").gameObject.active = false;
//replace currently selected unit
CurrentlySelectedUnit = hit.collider.gameObject;
}
} else {
//if this object is not a unit
DeselectGameObjectIfSelected();
}
}
}
} else {
if (Input.GetMouseButtonUp(0) && DidUserClickLeftMouse(mouseDownPoint))
DeselectGameObjectIfSelected();
}
Debug.DrawRay(ray.origin, ray.direction * mathf.Infinity, Color.yellow);
}
//check if user clicked
public bool (DidUserClickLeftMouse(Vector3) hitPoint)
{
float clickZone = 1.3f;
if(
(mouseDownPoint.x < hitPoint.x + clickZone && mouseDownPoint.x > hitPoint.x - clickZone) &&
(mouseDownPoint.y < hitPoint.y + clickZone && mouseDownPoint.y > hitPoint.y - clickZone) &&
(mouseDownPoint.z < hitPoint.z + clickZone && mouseDownPoint.z > hitPoint.z - clickZone)
)
return true; else return false;
}
public static void DeselectGameObjectIfSelected()
{
if(CurrentlySelectedUnit != null)
{
CurrentlySelectedUnit.transform.FindChild("Selected").gameObject.activeSelf = false;
CurrentlySelectedUnit = null;
}
}
}
↧