I am brand new to unity and am just trying to figure out how some of the things in Unity works. I have a code that i would like to write that fires the projectile in a straight line. The code instead spawns the clone and I don’t see anything. I know there is suppose to be a force modifier in there but I don’t know how to work it to shoot the projectile.
using UnityEngine;
using System.Collections;
public class FireProjectile : MonoBehaviour {
public GameObject bullet;
// Use this for initialization
void Start ()
{
if(bullet == null)
{
Debug.Log("bullet object is null. Please set a GameObject into the bullet type");
Debug.Break();
}
}
// Update is called once per frame
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
Instantiate(bullet,transform.position,transform.rotation);
}
}
}
I currently have the Script attached to the Camera. Thanks all for the help.
2 Answers
2
So, because this script is attached to the camera:
transform.position,transform.rotation
means the position and rotate of the camera. Your bullet is spawned exactly where the camera is located, so it not visible from it. If you keep the game running, and then switch back to the Scene view and look around, you should be able to see the bullet at the position of the camera. The bullet should also be visible in the Hierarchy window.
Finally, to make the bullet move it’ll want some acceleration, force or velocity applied to it. You might care to look at the documentation for Instantiate (Unity - Scripting API: Object.Instantiate) which shows how to fire a bullet.
here this should fix it you did not code it to move so i did it for you here is the new code.
using UnityEngine;
using System.Collections;
public class FireProjectile : MonoBehaviour {
public GameObject bullet;
// Use this for initialization
void Start ()
{
if(bullet == null)
{
Debug.Log("bullet object is null. Please set a GameObject into the bullet type");
Debug.Break();
}
}
// Update is called once per frame
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
Instantiate(prefab, transform.position + transform.forward * 0.3, transform.rotation);
}
}
}
Also make sure Fire1 is set up.
– Chris12345