Hi everyone,
I’m encountering the following problem.
I have a button that instantiates a prefab to the current mouse position and can rotate with the mouse scroll wheel. But when I press the button to instantiate it, the prefab does something weird.
I have recorded a video about this problem and I hope there is someone here that can explain me why that I have this problem and how to solve it?
The link to the video:
https://drive.google.com/open?id=1elWyqspLpzizAx6eDlALUNtKww0UuyPi
The code that I use for placing objects:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuildPrefab : MonoBehaviour
{
//GAMEOBJECTS
public GameObject placeableObjectPrefab;
public GameObject currentPlaceableObject;
//FLOATS
private float mouseWheelRotation;
public float RotationAmount = 45f;
//BOOLEANS
public bool isClicked = false;
public void Select()
{
isClicked = true;
}
private void Update()
{
InstantiatePrefab();
if (currentPlaceableObject != null)
{
MoveCurrentObjectToMouse();
RotateFromMouseWheel();
ReleaseIfClicked();
}
}
private void InstantiatePrefab()
{
if (isClicked)
{
if (Input.GetMouseButtonDown(1))
{
currentPlaceableObject = null;
isClicked = false;
}
else if (!Input.GetMouseButtonDown(1))
{
currentPlaceableObject = Instantiate(placeableObjectPrefab);
}
}
}
private void MoveCurrentObjectToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
currentPlaceableObject.transform.position = hit.point;
currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
}
}
private void RotateFromMouseWheel()
{
Debug.Log(Input.mouseScrollDelta);
mouseWheelRotation += Input.mouseScrollDelta.y;
currentPlaceableObject.transform.Rotate(Vector3.up, mouseWheelRotation * RotationAmount);
}
private void ReleaseIfClicked()
{
if (Input.GetMouseButtonDown(0))
currentPlaceableObject = null;
isClicked = false;
}
}