- Home /
How to drag and drop in 2D game
Hello everyone!
I'm really new to Unity programming and I'm trying to make a game where the player can drag and drop items showed in the upper right part of the screen and to be placed in the scene in the position where the mouse is clicked, right now I have two problems 1) The item is instantiating on a totally different part of the screen. 2) I can only instantiate the 1st item on my GameObject array:
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public GameObject[] items;
public GUIText gameOverText;
private bool gameOver;
void Start()
{
gameOver = false;
gameOverText.text = "";
}
void Update()
{
if (Input.GetButton("item1") || Input.GetButton("item2") || Input.GetButton("item3") || Input.GetButton("item4"))
Invoke("Spawn", 0.5f);
}
void Spawn()
{
Vector2 mousePos = Input.mousePosition;
//Inspects the array and returns the selected item.
if (Input.GetButton("item1") && Input.GetMouseButtonDown(0))
Instantiate(items[0], mousePos, transform.rotation);
else if (Input.GetButton("item2") && Input.GetMouseButtonDown(0))
Instantiate(items[1], mousePos, transform.rotation);
else if (Input.GetButton("item3") && Input.GetMouseButtonDown(0))
Instantiate(items[2], mousePos, transform.rotation);
else if (Input.GetButton("item4") && Input.GetMouseButtonDown(0))
Instantiate(items[3], mousePos, transform.rotation);
}
}
Hope you guys can help me out.
Comment