Spawn and drag on spawn multiple objects with android multiouch
This one has been bugging me for days so I decided I might as well ask you guys for some advice. So I've been trying to make a scene where I could spawn multiple object by touch and as soon as one spawns, drag it with the finger it was spawned with. I almost got it to work, when I spawn objects (1,2,3...), I can move them around just like described and when i remove fingers in reversed orded (...3,2,1), but the problem starts when i got 3 fingers on the screen and remove my finger off the screen with some different order (1,3,2...forinstance). If I remove 1st finger first, my 2nd object becomes 1st and 3rd objects buggs out and stays on the scene forever. I am beginner in unity and in c# so I hope you can be gentle with me. I got 3 scripts placed in 3 objects, scripts (code) are practically identical so I will paste only one of them.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour
{
public GameObject itemToSpawn;
private GameObject itemToSpawnInstance;
Ray GenerateTouchRay()
{
var touchPos = Input.GetTouch(0).position;
Vector3 touchPosFar = new Vector3(touchPos.x, touchPos.y, Camera.main.nearClipPlane);
Vector3 touchPosNear = new Vector3(touchPos.x, touchPos.y, Camera.main.nearClipPlane);
Ray mr = new Ray(touchPosNear, touchPosFar - touchPosNear);
return mr;
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.touches[0];
switch (touch.phase)
{
case TouchPhase.Began:
var touchPos = Input.GetTouch(0).position;
var createPos = Camera.main.ScreenToWorldPoint(new Vector3(touchPos.x, touchPos.y, 1));
itemToSpawnInstance = (GameObject)Instantiate(itemToSpawn, createPos, Quaternion.identity);
break;
case TouchPhase.Moved:
Vector3 newPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
itemToSpawnInstance.transform.position = new Vector3(newPos.x, newPos.y, itemToSpawnInstance.transform.position.z);
break;
case TouchPhase.Ended:
Destroy(itemToSpawnInstance);
break;
default:
break;
}
}
}
}
Your answer
Follow this Question
Related Questions
Unity Gradle Build Error 2019.3.10f 0 Answers
How to Disconnect a client from the server properly using unity Netcode for GameObjects ? 0 Answers
clicks pass through UI elements on android 1 Answer
How to change Sprite Image when it reaches 90 degrees? 0 Answers
Tools for Unity Visual Studio 2019 1 Answer