Reputation: 21
Hi i am currently working on a turret shooting script. My bullet shoots boet does not go in the enemy's direction. something is wrong or missing and i cant figure out what. I have looked up alot of solutions but cant find recent ones or good ones.
EDIT: my enemy's are instantiated so there is multiple of them. would that be part of the problem? if not do i need to provide more details? im kina new to the site so pls forgive me if i do stuff wrong.
public GameObject Enemy;
public GameObject Bullet;
public float bulletForce = 100f;
private Vector3 direction;
// Use this for initialization
void Start ()
{
ShootFunctionRepeat();
}
// Update is called once per frame
void Update ()
{
direction = Enemy.transform.position - this.transform.position;
}
void ShootFunctionRepeat()
{
InvokeRepeating("ShootFunction", 0.0f, 1.0f);
}
void ShootFunction(GameObject Bullet)
{
GameObject temp = Instantiate(Bullet, this.transform.position + direction.normalized, Quaternion.identity);
temp.GetComponent<Rigidbody>().AddForce(direction.normalized * bulletForce);
}
Upvotes: 2
Views: 735
Reputation: 4889
Your code won't work. You need to remove the GameObject Bullet
paramter from ShootFunction()
because the paramter hides this.Bullet
. And also Unity3D will print warning message Trying to Invoke method: Shoot.ShootFunction couldn't be called.: you cannot use InvokeRepeating
with method parameters.
Now it works:
I used a bullet prefab assigned to public GameObject Bullet
. And public GameObject Enemy
was also assigned a Cube GameObject from the inspector.
But you still need to think about how to recycle and finally destroy the bullets: In your code, you just Instantiate
the bullets, but when will they be destroyed?
Upvotes: 2
Reputation: 4572
It's not easy to know what exactly you are trying to do. But this will at least fix most issues.
I am not sure if your ShootFunction is allowed to have a parameter. I don't think so. Access you member (Bullet) directly.
I also removed an offset in your instantiation location. You might need to add it back in. But I believe it is not necessary.
Sample
public GameObject Enemy;
public GameObject Bullet;
public float bulletForce = 100f;
private Vector3 direction;
// Use this for initialization
void Start ()
{
ShootFunctionRepeat();
}
// Update is called once per frame
void Update ()
{
direction = (Enemy.transform.position - this.transform.position).normalized;
}
void ShootFunctionRepeat()
{
InvokeRepeating("ShootFunction", 0.0f, 1.0f);
}
void ShootFunction()
{
GameObject temp = Instantiate(Bullet, this.transform.position, Quaternion.identity);
temp.GetComponent<Rigidbody>().AddForce(direction.normalized * bulletForce);
}
Upvotes: 1