- Home /
The question is answered, right answer was accepted
Spawning objects help
Hello there, this script spawns a prefab in front of the player when E is pressed however the player does not know exactly where he/she is placing the object.
How could this script be altered so that the first time E is pressed it shows where the object will be placed but is still moveable (it is just following the player around) at this point the player can either press E again to place the object in that desired position or press Esc and delete the object all together? Thanks.
public var prefabObject : GameObject;
private var offset : Vector3;
private var fwd : Vector3;
private var clone : GameObject;
var unit : float = 3.0f;
function Update()
{
fwd = transform.TransformDirection(Vector3.forward) * unit;
offset = transform.position + fwd;
if(Input.GetKeyDown(KeyCode.E))
{
clone = Instantiate(prefabObject, offset, transform.rotation);
}
}
Answer by CupOfThings · Jul 06, 2014 at 12:26 PM
I solved it by writing this script which hides and shows the object that is going to be placed but is not actually part of the placing function.
renderer.enabled = false;
function Update () {
if(Input.GetKeyDown(KeyCode.Z)){
renderer.enabled = true;
}
if(Input.GetKeyDown(KeyCode.X)){
renderer.enabled = false;
}
}
Answer by crazynerk · Jul 06, 2014 at 12:25 PM
If knowing where it will spawn is your problem try putting a gameobject or small cube attach to your player in front of them, var spawntarget : Transform; public var prefabObject : GameObject; private var offset : Vector3; private var fwd : Vector3; private var clone : GameObject; var unit : float = 3.0f; function Update() { fwd = transform.TransformDirection(Vector3.forward) * unit; offset = transform.position + fwd; if(Input.GetKeyDown(KeyCode.E)) { clone = Instantiate(prefabObject, spawntarget.position, transform.rotation); }else if(Input.GetKey("r")){ clone.position = spawntarget.position; } }
This allows the player to know where the object will spawn, and how to move it