Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity 3D scripts move multiple objects

I have a problem. I'm doing a project in Unity 3D (c#), a 3D worlds editor. My problem is that I want to move multiple objects by selecting them. I managed to move one with my mouse cursor, but for multiple I failed :D This is my code to move one :

public class ClickAndDrag : MonoBehaviour {
    private RaycastHit raycastHit;
    private GameObject Gobj;
    private float distance;
    private Vector3 ObjPosition;
    private bool Bobj;

    // Use this for initialization
    void Start() {
    }

    // Update is called once per frame
    void Update() {
        if (Input.GetMouseButton (0)) {
            var ray = GetComponent<Camera> ().ScreenPointToRay (Input.mousePosition);
            var hit = Physics.Raycast (ray.origin, ray.direction, out raycastHit);

            if (hit && !Bobj) {
                Gobj = raycastHit.collider.gameObject;
                distance = raycastHit.distance;
                Debug.Log (Gobj.name);
            }

            Bobj = true;
            ObjPosition = ray.origin + distance * ray.direction;
            Gobj.transform.position = new Vector3 (ObjPosition.x, ObjPosition.y, ObjPosition.z);
        } else {
            Bobj = false;
            Gobj = null;
        }       
    }
}

Thanks for your help!

like image 651
Sidy Ndaw Avatar asked May 06 '26 16:05

Sidy Ndaw


1 Answers

private GameObject Gobj; is a variable for a single GameObject. Reformat it to private List<GameObject> objects; and instead of Gobj.transform.position = new Vector3 (ObjPosition.x, ObjPosition.y, ObjPosition.z) do this:

foreach (GameObject item in objects)
{
    item.transform.position = new Vector3 (ObjPosition.x, ObjPosition.y, ObjPosition.z)
}

EDIT: In case you aren't sure about how to manipulate a List, List<T> has a set of built in functions to make it really easy. You can now just call objects.Add(newObject); to add an object, and objects.Remove(oldObject); to remove an object.

like image 186
maksymiuk Avatar answered May 09 '26 05:05

maksymiuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!