- Home /
NullReferenceException after adding a script at runtime
Hi there! I'm working on a unity project for university with other students together. Each of us has to build a spaceship and a level with the intention that all spaceships are able to race in all levels. In my level I want the ships to be able to shoot stuff and I wrote a very simple script to allow this. As I can't add anything to the ships of my teammates manualy, I want to add the script to the ships at runtime if my level is selected. I have a bullet prefab that I use to clone the bullets and if I add my script manually to a ship it works, I can shoot. But if I add it at runtime, I get the following error each time I try to shoot:
NullReferenceException: Object reference not set to an instance of an object T4PlayerShoot.Update () (at Assets/T4/T4PlayerShoot.cs:35)
I guess after adding the script at runtime it loses the reference to the bullet.prefab. How can I fix this? Here is my relevant code: in my levellogic:
void OnGUI() {
//...
var ship_objects = GameObject.FindGameObjectsWithTag("Ship");
foreach(var ship_object in ship_objects){
ship_object.AddComponent<T4PlayerShoot>();
}
//...
}
the shooting script:
public class T4PlayerShoot : MonoBehaviour {
public Rigidbody bullet;
public float velocity = 10.0f;
protected string fire;
private bool firePressed = false;
//Get the Firekey of the Controller
protected virtual string FetchFire(Controller controller)
{
return controller.ctrlAxisFire;
}
private string FetchFire0()
{
Controller ctrl = GetComponentInParent<Controller>();
if (ctrl != null)
return FetchFire(ctrl);
return null;
}
void Update () {
if (fire == null) {
fire = FetchFire0 ();
}
if (fire != null) {
firePressed=0!=Input.GetAxis(fire);
}
if (firePressed) {
Rigidbody newBullet=Instantiate(bullet,transform.position,bullet.rotation)as Rigidbody;//ERROR
newBullet.AddForce (transform.forward*velocity,ForceMode.VelocityChange);
}
}
}
Thanks for your help!
Your answer
![](https://koobas.hobune.stream/wayback/20220613200816im_/https://answers.unity.com/themes/thub/images/avi.jpg)