- Home /
selecting, deselecting from a mousemanager script
so this script is made that when you select an gameobject that it turns blue to indicate that it is selected and then turn white when another object gets selected.
this mostly works, in that yes, it does change the color but only when you select another object, you mouse over the previously selected object.
now my question is, how can i get it to update the color immediatly when i select another object?
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class mouseManager : MonoBehaviour {
movement selectedUnit;
// trSelect stores the currently selected unit when one gets selected
static private Transform trSelect = null;
private bool selected = false;
// Update is called once per frame
void Update () {
// is the mouse over a unity UI element?
/*if (EventSystem.current.IsPointerOverGameObject ()) {
// it is, so don't do any custom mouse stuff
return;
}*/
// casts a ray from the mouse in unity world units so it know where the mouse is
Ray ray = Camera.main.ScreenPointToRay ( Input.mousePosition );
// contains the data of whatever gets hit by the ray
RaycastHit hitInfo;
if(Physics.Raycast(ray, out hitInfo) ){
GameObject hitObject = hitInfo.collider.gameObject;
if (hitObject.transform != trSelect && selected) {
selected = false;
}
// if the gameobject has the "movement" script on it execute the function
if (hitObject.GetComponent<movement>() != null) {
MouseOver_Unit (hitObject);
}
// if the gameobjects name is plane execute the function
if (hitObject.name == "Plane" != false) {
MoveUnit (hitInfo);
}
}
}
void MouseOver_Unit(GameObject hitObject){
// gets the meshrenderer so you can change the color
MeshRenderer mr = hitObject.GetComponent<MeshRenderer> ();
if (Input.GetMouseButtonDown (0)) {
// get the movement script so you can move the currently selected gameobject
selectedUnit = hitObject.GetComponent<movement> ();
// store the gameobject's transform in trSelect
trSelect = hitObject.transform;
Debug.Log (trSelect.transform);
// toggle the selected bool to true
selected = true;
//change the color to indicate the gameobject is selected.
mr.material.color = Color.blue;
// if you click another gameobject than the currently selected one
// and selected is true, set selected to false.
// and set the color back to white
} else if (hitObject.transform != trSelect && !selected) {
mr.material.color = Color.white;
}
}
void MoveUnit(RaycastHit hitInfo){
// checks if a gameobject is selected
if (selectedUnit != null) {
if (Input.GetMouseButtonDown (0)) {
// uses the "destination" function from the movement script
// and uses hitinfo to know where to move the gameobject on the plane
selectedUnit.destination = hitInfo.point;
}
}
}
}
Comment