- Home /
FPS instantiate objects
I'm trying to make a game where you create objects when you press the mouse button.
I've followed the tutorial on 3Dbuzz and they helped me fix that prefabs spawn in the game everytime I press the mousebutton.
but the tutorial dealt with a simple 2D shooter, so the spawn position of the prefabs are pretty dull: they spawn in a fixed X position and the player is using the FPS script.
I want the objects to spawn where the player looks, both X and Y positions.
here's the code:
using UnityEngine;
using System.Collections;
public class playerscript : MonoBehaviour {
public GameObject cubeprefab;
//Vector3 originalposition;
//Quaternion originalrotation;
// Use this for initialization
void Start () {
//if(transform.position != null)
//{
//transform.position = originalposition;
//transform.rotation = originalrotation;
//}
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown("e"))
{
//originalposition = transform.position;
//originalrotation = transform.rotation;
Application.LoadLevel("the cave");
}
if(Input.GetKeyDown("mouse 1"))
{
Vector3 position = new Vector3(transform.position.x, transform.position.y + transform.localScale.y / 2);
Instantiate(cubeprefab, position, transform.rotation);
}
}
void Reset () {
}
}
Answer by Proportion · Oct 13, 2011 at 11:09 AM
add a public variable gameobject named camera; then on your fps character thing add the childed camera gameobject to this public variable. then replace your mouse 1 code with this
if(Input.GetKeyDown("mouse 1")) {
Instantiate(cubeprefab, camera.transform.position, camera.transform.rotation);
}
this will make your cube prefab pop straight out of where the camera is, unless your camera is in the player collider, in that case you have to use physics.ignorecollision for the cubeprefab and the fps thingy
let me see if I got this right: I add the variable gameobject camera in the playerscript then I go to the unity interface and add the first person controller object to the gameobject variable in the playerscript directory?
where do I write the ignorecollision? in the playerscript(which is in the first person controller) or do I fix a script for the cubeprefab?
or is there a way to spawn the objects in front of the camera ins$$anonymous$$d? cuase if I make this right....the object will be created exactly where the player is(I'm making non moving cubes)
you can spawn them infront of it but you have to make another empty gameobject for it to spawn from. just put physics.ignorecollision(cubeprefab.collider, collider) under your instantiated cube
Your answer
![](https://koobas.hobune.stream/wayback/20220613005717im_/https://answers.unity.com/themes/thub/images/avi.jpg)