Hi,
I’m a new Unity user and have searched the forum but can’t find an answer to this specific problem that works for me.
I have a standard Cube gameObject (with a BoxCollider and my CubeController.cs script) in my scene and I want to be able to click and drag on it to instantiate a new cube prefab (with a BoxCollider and my DragController.cs script) which then follows the mouse.
I have it nearly working but when the new cube prefab is instantiated at the same position as the clicked cube (but 10% bigger) you have to then click the new instantiated object again to then drag it. I have a debug line printing ‘Prefab created’ so the prefab must be sensing that the mouse button is still down.
I’m not sure how i can do it so you click the original cube and the new prefab is created and draggable without having to click again? Any help greatly appreciated.
CubeController.cs:
using UnityEngine;
public class CubeController : MonoBehaviour
{
RaycastHit hitInfo;
Ray ray;
public GameObject CubePrefab;
private bool canCreate = true;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
}
if (Physics.Raycast(ray, out hitInfo))
{
GameObject objectHit = hitInfo.transform.gameObject;
if (objectHit.tag == "Cube")
{
createCubePrefab();
}
}
}
void createCubePrefab()
{
if (canCreate)
{
canCreate = false;
GameObject newCube = Instantiate(CubePrefab, hitInfo.transform.position, Quaternion.identity);
newCube.transform.localScale = new Vector3(1.1f, 1.1f, 1.1f);
}
}
}
DragController.cs:
using UnityEngine;
public class DragController : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Prefab created");
}
}
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
transform.position = cursorPosition;
}
}