此游戏仅需一个代码(鼠标点哪里在哪里复制)
1.创建场景,制作克隆对象,编写代码。这里的游戏我创建了一个平面地板(plane),克隆模板是一个球体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// 这个脚本实现鼠标点击的位置,生成一个物体
//拿到鼠标点的位置的坐标
//然后克隆一个物体(代码挂谁身上无所谓)
GameObject Muban;
void Start()
{
Muban = GameObject.Find("Muban");
}
void Update()
{
Ray oneRay = Camera.main.ScreenPointToRay(Input.mousePosition);//射线射击克隆,此处摄像机作为起点发射射线(关于起点没有强制限制)
if(Input .GetMouseButtonDown(0))//0是左键,1是右键
{
RaycastHit HITOBJ;
Physics.Raycast(oneRay, out HITOBJ);
Debug.Log("用户按下左键");
GameObject.Instantiate(Muban,HITOBJ.point, Quaternion.identity);
}
}
}
如果在场景中有其他物体,但是只想在某个物体上克隆,那么可以编写一个if语句,示例如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// 这个脚本实现鼠标点击的位置,生成一个物体
//拿到鼠标点的位置的坐标
//然后克隆一个物体(代码挂谁身上无所谓)
GameObject Muban;
void Start()
{
Muban = GameObject.Find("Muban");
}
// Update is called once per frame
void Update()
{
Ray oneRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Input .GetMouseButtonDown(0))//0是左键,1是右键
{
RaycastHit HITOBJ;
Physics.Raycast(oneRay, out HITOBJ);
if(HITOBJ.transform .gameObject .name =="Plane")//括号里边的名字是根据自己场景里物体的名字写的
{
Debug.Log("用户按下左键");
GameObject.Instantiate(Muban, HITOBJ.point, Quaternion.identity);
}
}
}
}
下图就是例子显示(红色圈圈的就是模板)