我有问题。我正在Unity 3D(c#)做一个项目,这是一个3D世界编辑器。我的问题是我想通过选择它们来移动多个对象。我设法用我的鼠标光标移动一个,但是对于多个我失败了:D 这是我移动一个的代码:
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;
}
}
}
感谢您的帮助!
答案 0 :(得分:1)
private GameObject Gobj;
是单 GameObject的变量。将其重新格式化为private List<GameObject> objects;
,而不是Gobj.transform.position = new Vector3 (ObjPosition.x, ObjPosition.y, ObjPosition.z)
执行此操作:
foreach (GameObject item in objects)
{
item.transform.position = new Vector3 (ObjPosition.x, ObjPosition.y, ObjPosition.z)
}
编辑:如果您不确定如何操作列表,List<T>
有一组内置函数可以让它变得非常简单。您现在可以调用objects.Add(newObject);
添加对象,objects.Remove(oldObject);
删除对象。