- Home /
It was my bad
Problem when setting variable in an instantiated gameobject
The premise is this: I wanted to find a way to control the behavior of an instantiated bullet without having to make a different prefab every time,so I made a base Bullet class from which new classes can be created to override the Start() and Update() functions in the base class and then attach the new class to a GameObject. Here's the relevant code. Base bullet class:
public class Bullet
{
public Weapon weapon;
public Sprite bulletSprite;
public Transform bulletBody;
public float speed;
public virtual void Start()
{
bulletBody.GetChild(0).GetComponent<SpriteRenderer>().sprite = bulletSprite;
}
public virtual void Update()
{ }
}
The class I'm trying to get to work:
public class NormalBullet : Bullet
{
public override void Start()
{
bulletSprite = Resources.Load<Sprite>("Bullets\bullet01");
base.Start();
}
public override void Update()
{
bulletBody.Translate(bulletBody.forward * weapon.bulletSpeed);
}
}
The script on the actual bullet prefab
public class BulletScript : MonoBehaviour {
public Bullet bullet; //This returns null after it is instantiated
void Start ()
{
bullet.Start();
}
void Update ()
{
bullet.Update();
}
}
and Finally were the bullet is instantiated (I pass a Bullet class previously created which is "bulletScript" to the prefab):
public override void Fire()
{
GameObject firedBullet = GameObject.Instantiate(bulletPrefab,gunTransform.position,gunTransform.rotation) as GameObject;
Bullet firedBscript = firedBullet.GetComponent<BulletScript>().bullet;
firedBscript = bulletScript;
firedBscript.bulletBody = firedBullet.transform;
firedBscript.weapon = this;
//If I check whether firedBullet has a "bullet" class set it says everything is as it should be
}
When I try to fire the bullet it throws a nullReferenceException from the prefab I'm firing saying there's no Bullet class attached. I checked with Debug.Log and apparently the variable IS set the moment I instantiate the bullet but for some reason the Bullet variable on the bullet itself returns null. inb4 I'm actually blind and it was something really simple to fix.
GG friends I'm actually blind,the problem was that I mistakenly attached a BulletScript to a bullet prefab child and that was the source of the error messages.