AddComponent adds too many (C#)

My move script currently adds a bullet and adds the script BulletScript to the bullet when the user presses X.

The problem here is that it adds too many BulletScripts to my bullet game object. Like it’s in an infinite loop or something.


Here’s the shoot part of my move script

void Update () {
	if(Input.GetKeyDown("x") &&  Time.time > NextFire) {
		NextFire = Time.time + FireRate;
		shoot.gameObject.AddComponent<BulletScript>();
		shoot = Instantiate(shoot) as GameObject;
	}
}

And here’s my bullet script

private GameObject player;

void Start () {
    player = GameObject.Find ("Player");
    gameObject.AddComponent<Rigidbody>();
    transform.position = new Vector3(player.transform.position.x,player.transform.position.y,player.transform.position.z);
    collider.isTrigger = true;
    rigidbody.isKinematic = true;
    rigidbody.freezeRotation = true;
}

Double look your code:

shoot.gameObject.AddComponent<BulletScript>();
shoot = Instantiate(shoot) as GameObject;

First you add a new bullet component into a already existent shot, then you clone it. Got it?

So, each fire you add a new BulletScript and then clone it (2 scripts). Next fire, add a new one and clone (3 scripts) and so on.

what’s the shoot variable? you seem to use it both as the prefab and then the bullet object, which probably causes it to accumulate all those components.

Also why not just have the component on the prefab?

Thanks guys but I figured it out!

It was because stupid me had made a script that added a lot to the bullet OBJECT so the object already had a million scripts attached to it.

Also: I know my code is kinda werid right now but don’t worry! I’ll get back to it and fix it!