hi, i have a script that is supposed to spawn a cube along a line once per mouseclick but it works like this:
- first object is spawned once
- second object is spawned twice
- third 4 times
- fourth 8 times and so on
can someone help me fix that?
here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class istantiate : MonoBehaviour
{
[SerializeField] GameObject myCube;
[SerializeField] float width = 1f;
[SerializeField] float height = 1f;
[SerializeField] Vector3 inputPosA = Vector3.zero;
[SerializeField] Vector3 inputPosB = Vector3.zero;
[SerializeField] Vector3 result;
[SerializeField] Vector3 avoidBehindCamera;
private GameObject thisCube;
// Use this for initialization
void Start()
{
avoidBehindCamera.z = 10f;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
inputPosA = Camera.main.ScreenToWorldPoint(Input.mousePosition+avoidBehindCamera);
}
if (Input.GetMouseButtonUp(0))
{
inputPosB = Camera.main.ScreenToWorldPoint(Input.mousePosition+avoidBehindCamera);
SpawnAlongLine();
}
}
void SpawnAlongLine()
{
Vector3 posC = ((inputPosB - inputPosA) * 0.5F) + inputPosA;
float lengthC = (inputPosB - inputPosA).magnitude;
float sineC = (inputPosB.y - inputPosA.y) / lengthC;
float angleC = Mathf.Asin(sineC) * Mathf.Rad2Deg;
if (inputPosB.x < inputPosA.x) { angleC = 0 - angleC; }
Debug.Log("inputPosA" + inputPosA + " : inputPosB" + inputPosB + " : posC" + posC + " : lengthC " + lengthC + " : sineC " + sineC + " : angleC " + angleC);
thisCube = Object.Instantiate(myCube, posC, Quaternion.identity);
thisCube.transform.localScale = new Vector3(lengthC, width, height);
thisCube.transform.rotation = Quaternion.Euler(0, 0, angleC);
thisCube.transform.parent = null;
}
}