I have some experience in unity and flash and I have made a few games and now I´m trying to make a game similar to Plants vs Zombies, just in 3D. I have made inventory before, but ive never made drag and drop inventory.
what I need is basically inventory just like the one in Plants vs Zombies, where you have an inventory and when you press one button the plant follows the mouse (in my case its a 3D object), and on mouse exit the object falls on the terrain exactly where the player dropped it.
so if anyone could please help me or show me a link that shows how to do this I would be very thankful!
thank you paulaceccon, but I actually found the answer yesterday and I figured since I know there are always lot of people asking this question and the answers are so different and a lot of times not at all what you could be looking for, I’m going to put the code that I found here.
here is the source:
but that one doesnt have a inventory… so here is the code that I fixed just a little to make it a DRAG AND DROP INVENTORY:
// mouseplacement & pickup - v1.0 - 08.01.2012 - mgear - http://unitycoder.com/blog/
// instantiate objects with mousebuttondown, while button is held down, move the object at mouse cursor
// also you can pick previously added object and move it around (button held down)
#pragma strict
public var ObjectToPlace:Transform; // prefab to instantiate
private var clone:Transform; // hold instantiated object on this variable
private var inventoryOver : boolean = false; // so that you won't make an object everytime you click the mouse
// mainloop
function Update ()
{
if(Input.GetButtonDown("Fire1") && inventoryOver == true)
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
var layerMask = 1 << 8; // check help page "layerMask", here we only cast ray on layer 8 (prefab layer)
layerMask = ~layerMask; // invert layermask, so we dont hit layer 8 (which is for prefabs)
if (Physics.Raycast (ray, hit, Mathf.Infinity, layerMask))
clone = Instantiate(ObjectToPlace, hit.point, Quaternion.identity);
}
if(Input.GetButtonUp("Fire1") && inventoryOver == true) // button released
{
clone=null; // clear clone variable
inventoryOver = false;
}
if(Input.GetButton("Fire1") && inventoryOver == true) // mousebutton is held down
{
if (clone!=null) // if there is some object in clone variable
{
var ray2 = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit2 : RaycastHit;
var layerMask2 = 1 << 8;
layerMask2 = ~layerMask2; // we are casting rays on other layers, except 8
if (Physics.Raycast (ray2, hit2, Mathf.Infinity, layerMask2)) // we hit something
{
clone.position = hit2.point; // move our object there
}
}
}
}
function OnMouseEnter () {
inventoryOver = true;
}
you put this script on the inventory, witch is just a plane (dont use GuiTexture) and connect a object to the “object to place”.