The goal of this script is that the object it's attached to should move with the mouse.
public sealed class FollowMouseComponent : MonoBehaviour
{
private InputHandler _inputHandler;
private InputAction _touch;
private InputAction _mouse;
private static Plane _plane = new(Vector3.up, Vector3.zero);
private Ray _ray;
private RaycastHit _raycastHit;
private bool _isDragging;
public void EndDragging() => _isDragging = false;
public Camera Camera { get; set; }
private IEnumerator Start()
{
_inputHandler = FindObjectOfType<InputHandler>();
Camera = Camera.main;
while (!_inputHandler.Ready)
{
yield return null;
}
_touch = _inputHandler.Control.Touch;
_mouse = _inputHandler.Control.Mouse;
_isDragging = true;
}
private void Update()
{
if(_isDragging)
{
HandleInput();
}
else
{
Release();
}
}
private void HandleInput()
{
var mousePosition = Mouse.current.position.ReadValue();
Debug.LogFormat("{0}: Mouse position: {1}", gameObject.name, mousePosition);
_ray = Camera.ScreenPointToRay(mousePosition);
if (!_plane.Raycast(_ray, out float distance))
{
return;
}
gameObject.transform.position = _ray.GetPoint(distance);
Debug.LogFormat("{0}: {1}", gameObject.name, gameObject.transform.position);
}
private void Release()
{
if (!CanRelease())
{
return;
}
Debug.LogFormat("Releasing");
Destroy(this);
}
private bool CanRelease()
{
Debug.LogFormat("Touch is pressed: {0}, Mouse is pressed: {1}", _touch.IsPressed(), _mouse.IsPressed());
return !_touch.IsPressed() || !_mouse.IsPressed();
}
}
I have a cube in the scene with this script. This cube behaves as expected. However, if I create a cube using another script and assign this script to it as a component, the created cube does not follow the mouse.
Here's the code I use to spawn the cube:
var gameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
gameObject.AddComponent<FollowMouseComponent>();
What could be the reason this script-created cube does not follow the mouse?
EndDraggingis never called and neither is the _isDragging set to false therefore \$\endgroup\$