【问题标题】:Create a copy of an gameobject创建游戏对象的副本
【发布时间】:2010-08-19 22:57:39
【问题描述】:
如何在 Unity3D 中通过鼠标单击创建对象的副本?
另外,如何在运行时选择要克隆的对象? (最好是鼠标选择)。
【问题讨论】:
标签:
unity3d
runtime
instantiation
mouseclick-event
gameobject
【解决方案1】:
function Update () {
var hit : RaycastHit = new RaycastHit();
var cameraRay : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (cameraRay.origin,cameraRay.direction,hit, 1000)) {
var cursorOn = true;
}
var mouseReleased : boolean = false;
//BOMB DROPPING
if (Input.GetMouseButtonDown(0)) {
drop = Instantiate(bomb, transform.position, Quaternion.identity);
drop.transform.position = hit.point;
Resize();
}
}
function Resize() {
if (!Input.GetMouseButtonUp(0)) {
drop.transform.localScale += Vector3(Time.deltaTime, Time.deltaTime,
Time.deltaTime);
timeD +=Time.deltaTime;
}
}
您会希望在多次调用 Update 的过程中发生这种情况:
function Update () {
if(Input.GetMouseButton(0)) {
// This means the left mouse button is currently down,
// so we'll augment the scale
drop.transform.localScale += Vector3(Time.deltaTime, Time.deltaTime,
Time.deltaTime);
}
}
【解决方案2】:
最简单的方法(在 c# 中)是这样的:
[RequireComponent(typeof(Collider))]
public class Cloneable : MonoBehaviour {
public Vector3 spawnPoint = Vector3.zero;
/* create a copy of this object at the specified spawn point with no rotation */
public void OnMouseDown () {
Object.Instantiate(gameObject, spawnPoint, Quaternion.identity);
}
}
(第一行只是确保物体上有一个碰撞器,需要检测鼠标点击)
该脚本应该可以按原样运行,但我还没有测试过,如果不行,我会修复它。
【解决方案3】:
如果您的脚本附加到游戏对象(例如球体),那么您可以这样做:
public class ObjectMaker : MonoBehaviour
{
public GameObject thing2bInstantiated; // This you assign in the inspector
void OnMouseDown( )
{
Instantiate(thing2bInstantiated, transform.position, transform.rotation);
}
}
你给 Instantiate() 三个参数:什么对象,什么位置,如何旋转。
这个脚本的作用是在这个脚本所附加的游戏对象的确切位置和旋转处实例化一些东西。通常你需要从游戏对象中移除碰撞体,如果有的话,还有刚体。实例化事物的方式有很多种,所以如果这对你不起作用,我可以提供一个不同的例子。 :)