- Home /
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;
}
Wouldn't it just be easyer to make a prefab of the bullet with the script already atached and just instantiate the bullet?
Answer by HappyGuyDK · Aug 28, 2014 at 02:34 PM
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!
Correction! It's called a prefab and not an object. (Just to avoid confusion)
Answer by Sisso · Aug 28, 2014 at 01:11 PM
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.
Answer by AyAMrau · Aug 28, 2014 at 01:12 PM
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?