Hello, I’m a total begginer to Unity3D and C# and I’m trying to make a simple shooting game and while I have the bullet and it’s movement done, it’s doing it at position x=0,y=0,Z=0 instead of shooting from the character.
I guess I should use a getComponent() of the character but I tried to do so and failed.
I have my “Player Control” class attached to the character (Where I create the bullets) and the “Ammo” class attached to the AmmoPrefab (the bullet itself).
I’m pasting the code here so you can see if there is something wrong.
Player Control:
public class PlayerControl : MonoBehaviour
{
//Prefab to instantiate
public GameObject AmmoPrefab;
public int Ammo = 10;
string FireWeapon(int NumberofBullets)
{
if (Ammo <= 0)
{
return "Fired Nothing";
}
else
{
for(int i=0; i<NumberofBullets; i++)
{
//Instantiate prefab
Instantiate (AmmoPrefab);
}
Ammo = Ammo - NumberofBullets;
return "Fired Weapon";
}
}
// Update is called once per frame
void Update()
{
//If fire pressed
if(Input.GetKeyDown(KeyCode.Mouse0))
{
FireWeapon(1);
}
}
}
And the “Ammo” one (the collistion is not that important yet, I just want to have it on the same vector so it would eventually collide):
using UnityEngine;
using System.Collections;
public class Ammo : MonoBehaviour
{
//Lifetime for ammo
public float AmmoLife = 20.0f;
//Speed of ammo
public float AmmoSpeed = 10.0f;
// Use this for initialization
IEnumerator Start()
{
//Wait for ammo life time
yield return new WaitForSeconds(AmmoLife);
//Destroy ammo
Destroy(gameObject);
}
//Destroy on collision
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag != "Player")
Destroy(gameObject);
}
//Ammo travels in direction at speed
void Update()
{
transform.Translate(-Vector3.forward * AmmoSpeed * Time.deltaTime, Space.Self);
}
}
Thank you very much in advance and I’m sorry if I made english mistakes or anything of the sort (English not my main language).