- Home /
Can't instantiate bullets when calling shoot function in one script from another script.
Hello,
I have a problem that I have been struggeling with for too long, so I hope that you can come to my aid.
I am making a game with some friends and we are using Unity in 2D mode. We have a Weapon class that can shoot, and then we have an Enemy class that should use the weapon to shoot, so it calls the shoot() in Weapon, but for some reason it will not instantiate the bullets when doing it this way.
Class Shooter: The point of this class is to call pew() in the PewPew class.
public class Shooter : MonoBehaviour {
PewPew pewpew;
// Use this for initialization
void Start () {
pewpew = gameObject.AddComponent<PewPew> ();
}
// Update is called once per frame
void Update () {
pewpew.pew ();
}
}
Class PewPew: This class is the one that will instantiate the bullets and send them on their way, and it does do so, if I call pew() inside this class but when I call pew() from Shooter all I get is a bounch of errors.
public class PewPew : MonoBehaviour {
public GameObject bullet;
float speed = 20.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(!true) // If set to true, it will start spawning bullets
{
pew ();
}
}
public void pew()
{
Debug.Log ("PEWPEW");
Rigidbody2D bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
bulletInstance.velocity = new Vector2(speed, 0);
}
}
I get the Debug.Log message whenever I call the function, so I know that I can get to it, but for some reason I just can't get it to instantiate the bullets when I call from Shooter.
Thank you in advance for any help you can provide.
Answer by KMKxJOEY1 · Apr 14, 2014 at 01:08 AM
Ok first of all, in your Shooter class, this code is redundant if you already have PewPew attached to the GameObject:
// Use this for initialization
void Start () {
pewpew = gameObject.AddComponent<PewPew> ();
}
If not, then you are just adding a second PewPew instance onto your shooter object. I would recommend deleting that line, and just assigning the PewPew class to the variable in the inspector.
Also, this code could be simplified from
Quaternion.Euler(new Vector3(0,0,0))
to simply:
Quaternion.identity