I've already got a script working that allows me to select and deselect objects. Now I have the problem that when I have to objects of the same kind that are moveable in the scene, that both objects move to the clicked point on the floor - but just the first one was selected.
I'm aware that I have to store the selections somehow in a list, an array or something. But I'm looking for some advice how to do this properly in unity. One of my problems is that it looks like that an object has no unique id or something like this. So how can I identify my object again after I've put it in the list (which would be in another script file)?
As a use case of what I try to approach take any RTS game as an example where you can select 1 - N units and order them to move.
Update: I updated the code, it handles now multiple selections but I'm not sure if its properly done? Any suggestions how to improve it?
var selections = new Array ();
function Update() {
if (Input.GetMouseButtonDown(0)) {
//Debug.Log("Clicked");
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 1000.0)) {
Debug.Log(hit.collider.gameObject.name);
if (hit.collider.gameObject && hit.collider.gameObject.name == "Space Marine") {
//Debug.Log("Hit Pawn");
//selections.Add(hit.collider.gameObject);
//test<GameObject> =
//Debug.Log(selections);
inSelection = false;
for (go in selections) {
if (go == hit.collider.gameObject) {
//Debug.Log(selections);
inSelection = true;
}
}
if (inSelection == false) {
selections.Add(hit.collider.gameObject);
Debug.Log("selections: " + selections);
}
}
if (hit.collider.gameObject && hit.collider.gameObject.tag == "floor") {
for (go in selections) {
go.transform.position = hit.point;
go.transform.position.x = Mathf.Round(hit.point.x);
go.transform.position.y = Mathf.Round(hit.point.y);
go.transform.position.z = Mathf.Round(hit.point.z);
}
}
}
Debug.Log(selections);
}
// deselect (right mouse)
if (Input.GetMouseButtonDown(1)) {
Debug.Log("Reset selections");
selections = new Array ();
}
}