- Home /
Question by
SophieSautter · Apr 21, 2021 at 02:21 PM ·
prefabdrag-and-drop
Drag and Drop with Prefabs
Hi everyone,
i want to drag and drop prefabs (simple modular humans). I use an empty GameObject to store my script. In my script I compare the tags with my defined SelectableTag. It works fine with a cube, but with the prefabs, the persons, it didn't.
Maybe you can help me, thanks in advance :)
Here is my script: using UnityEngine; using System.Collections;
public class DragAndDrop : MonoBehaviour
{
private bool _mouseState;
private GameObject target;
public Vector3 screenSpace;
public Vector3 offset;
[SerializeField] private string selectableTag = "Person";
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
// Debug.Log(_mouseState);
if (Input.GetMouseButtonDown (0)) {
RaycastHit hitInfo;
target = GetClickedObject (out hitInfo);
if (target != null & target.CompareTag(selectableTag)) {
_mouseState = true;
screenSpace = Camera.main.WorldToScreenPoint(target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
}
}
if (Input.GetMouseButtonUp (0)) {
_mouseState = false;
}
if (_mouseState) {
//keep track of the mouse position
var curScreenSpace = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
//convert the screen mouse position to world point and adjust with offset
var curPosition = Camera.main.ScreenToWorldPoint (curScreenSpace) + offset;
//update the position of the object in the world
target.transform.position = curPosition;
}
}
GameObject GetClickedObject (out RaycastHit hit)
{
GameObject target = null;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray.origin, ray.direction * 10, out hit)) {
target = hit.collider.gameObject;
}
return target;
}
}
Comment
Answer by gigos22 · Apr 21, 2021 at 04:37 PM
Basically if something works with one thing but not with another it means that there is something missing on that another thing.
Because your code looks alright, I suggests you to maybe make sure your other prefabs have:
Person tag.
Collider.
Other than that, it is very weird scenario.