一、创建垂直滑动列表-物品栏
二、从物品栏拖出物体
- 创建Resources文件夹,在Resources文件夹下创建Prefabs文件夹
- 将要生成的实例物体放入Prefabs文件夹里
- 增加一个Button和Image
- 在Button下添加代码,str写实例名字,image选择合适的Image
- 代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DragSpawn : MonoBehaviour, IPointerDownHandler
{
public string str;
public Image image;
private GameObject objDragSpawning;
private bool isDragSpawning = false;
private void Start()
{
image.enabled = false;
}
void Update()
{
if (isDragSpawning)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
objDragSpawning.transform.position = ray.GetPoint(10);
image.enabled = true;
image.transform.position = Input.mousePosition;
objDragSpawning.SetActive(false);
if (Input.GetMouseButtonUp(0))
{
objDragSpawning.SetActive(true);
isDragSpawning = false;
objDragSpawning = null;
image.enabled = false;
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
str = "Prefabs/" + str;
GameObject prefab = Resources.Load<GameObject>(str);
if (prefab != null)
{
objDragSpawning = Instantiate(prefab);
isDragSpawning = true;
}
}
}
三、左键移动物体+近距离安装
- 在场景中放置目标物体,材质改为高亮颜色
- 当从物品栏拖出物体安装到目标物体处时,拖出物体消失,目标物体材质改为原本材质,销毁拖出物体
- 代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControlMove : MonoBehaviour
{
public string str;
public Material originMeterial;
private Transform target;
private Vector3 cubeScreenPos;
private Vector3 offset;
IEnumerator ie;
void Start()
{
target= GameObject.Find(str).transform;
ie = OnMouseDown();
StartCoroutine(ie);
}
IEnumerator OnMouseDown()
{
cubeScreenPos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cubeScreenPos.z);
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
offset = transform.position - mousePos;
while (Input.GetMouseButton(0))
{
Vector3 curMousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cubeScreenPos.z);
curMousePos = Camera.main.ScreenToWorldPoint(curMousePos);
if (Vector3.Distance(transform.position, target.position) < 2)
{
transform.position = Vector3.MoveTowards(transform.position, target.position, 5 * Time.deltaTime);
StopCoroutine(ie);
if(transform.position==target.position)
{
target.GetComponent<MeshRenderer>().material =originMeterial;
Destroy(gameObject);
}
}
else
{
transform.position = curMousePos + offset;
}
yield return new WaitForFixedUpdate();
}
}
}
|