How do you create a copy of an object upon mouse click in Unity3D?
Also, how could I select the object to be cloned during run-time? (mouse selection preferable).
How do you create a copy of an object upon mouse click in Unity3D?
Also, how could I select the object to be cloned during run-time? (mouse selection preferable).
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);
}
}
最简单的方法(在 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);
}
}
(第一行只是确保物体上有一个碰撞器,它需要检测鼠标点击)
该脚本应该可以按原样工作,但我还没有测试过,如果没有,我会修复它。
如果您的脚本附加到游戏对象(例如球体),那么您可以执行以下操作:
public class ObjectMaker : MonoBehaviour
{
public GameObject thing2bInstantiated; // This you assign in the inspector
void OnMouseDown( )
{
Instantiate(thing2bInstantiated, transform.position, transform.rotation);
}
}
你给 Instantiate() 三个参数:什么对象,什么位置,它是如何旋转的。
这个脚本的作用是在这个脚本附加到的游戏对象的确切位置和旋转处实例化一些东西。通常你需要从游戏对象中移除碰撞器,如果有的话,还有刚体。实例化事物的方式有很多种,所以如果这对你不起作用,我可以提供一个不同的例子。:)