instantiate objects between two mouseclicks
I am a newby to c# and unity!! I would appreciate a little help with my problem which is that I want to instantiate objects as I drag my mouse across the screen.
This is my script so far;
if (Input.GetMouseButton (0))
{
ghoststartspot = Input.mousePosition;
Debug.Log (ghoststartspot);
Vector3 difference = blockmousescript.currentmousepoint - ghoststartspot;
for (int change = 0; change < difference.magnitude; change++)
{
Vector3 spawnblock = ghoststartspot + difference.normalized * change;
Vector3 blockspawn = new Vector3 (Mathf.RoundToInt (spawnblock.x), Mathf.RoundToInt (blockmousescript.currentmousepoint.y + height), Mathf.RoundToInt (spawnblock.z));
GameObject blockspawnerx = Instantiate (ghostplenty, blockspawn, Quaternion.identity);
As you can see I use a for loop and try to use a normalized vector to represent the direction I want to instantiate in. Then the i++ in the for loop would allow me to instantiate "i" further along the vector each time the loop iterates through.
However while this mostly works it spawns hundreds of different objects at each point along the loop.
I have no idea why this is happening and would appreciate help to improve my understanding here. Ty
That is happening because each frame if you have your mousebutton pressed then It instantiates a gameobject. The real question is, what do you want to do? How many objects do you want to instantiate?
Answer by hexagonius · Mar 01, 2017 at 05:31 PM
Instead of GetMouseButton, you should be using GetMouseButtonDown. On the first click, save the mouse position to a variable. On the second click, subtract that position from the new current position and add half of it to the old position. That will give you the position in between last and current mouse position. Also instantiate your object and place it on second click. If it's the first or second click you could just use a boolean and toggle it true and false on each click.
Your answer
![](https://koobas.hobune.stream/wayback/20220612112224im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Comparing distance of vector 3's on a dynamic growing list 0 Answers
Right Click and Drag Formation Line RTS 0 Answers
Finding the vertices of each edge of a mesh face found by a raycast hit 0 Answers
[SOLVED] Remove Vector3 Array step by step when GameObject spawned 1 Answer
how can I "play" the whole MoveTowards sequence after one click? 1 Answer