Making a spawn button in Unity2D with the following script

350 Views Asked by At

So I want to make some kind of button (either with or without UI) in unity 2D which spawns a "tower" and then I drag it to the desired location.

The script dragging script is as follows:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider2D))]

public class DragEnemy : MonoBehaviour
{
    private Vector3 screenPoint;
    private Vector3 offset;

    void OnMouseDown()
    {

        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag()
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }
}

Usually I have predetermined spots to place my towers, but I want to make them as button(s) to give more control to the player. I'm following a tutorial so here it is if it will help to figure out the code.

http://www.raywenderlich.com/107525/create-tower-defense-game-unity-part-1

What I do is make an UI image, set the image to those openspots (or my image) and then add the Place Monster script (see in tutorial no space here) and a circle collider, but it doesn't work. I want it to spawn a monster onclick and then I want to drag the monster where it should shoot enemies. I then set the public gameobject like in the origninal to the monster I want to spawn (in this case the one with the dragging script) and then I hope for magic.

0

There are 0 best solutions below