I have created a boss game object with a script BossBulletSpawner attached to it.
public class BossBulletSpawner : MonoBehaviour
{
[SerializeField]
private GameObject BossBullet;
private string[] bulletColors = { "Blue", "Red", "DarkBlue", "Green", "Pink", "Purple", "Red" };
List<Sprite> bulletImages = new List<Sprite>(); //should turn this into a dictionary later on
System.Random rnd = new System.Random();
Vector3 bossPos;
void Start()
{
foreach (string bulletColor in bulletColors)
{
Sprite img = Resources.Load<Sprite>("Sprites/Bullets/Bullet" + bulletColor);
bulletImages.Add(img);
}
int maxIndex = bulletColors.Length;
Vector3 bossPos = transform.position;
bossPos.z -= 1;
Instantiate(BossBullet, bossPos, transform.rotation);
BossBullet.GetComponent<BulletBehavior>().setSprite(bulletImages[rnd.Next(0, maxIndex)]);
BossBullet.GetComponent<BulletBehavior>().setDirSpeed(new Vector2(3, -3), 3); BossBullet.GetComponent<BulletBehavior>().setSprite(bulletImages[rnd.Next(0, maxIndex)]);
}
}
I pass my bullet prefab to it. It works relatively well, bullet gets spawned on the screen with a random sprite. But I’ve got an issue with giving it speed and direction.
Here is my script attached to the bullet prefab:
public class BulletBehavior : MonoBehaviour
{
Rigidbody2D bulletBody;
void Start()
{
bulletBody = GetComponent<Rigidbody2D>();
}
public void setSprite(Sprite sprite)
{
gameObject.GetComponent<SpriteRenderer>().sprite = sprite;
}
public void setDirSpeed(Vector2 newDirection, float newSpeed)
{
bulletBody.velocity = newSpeed * newDirection;
Debug.Log(newSpeed * newDirection);
Debug.Log(bulletBody.velocity);
}
}
Even though I have clearly assigned a value to bulletBody in the Start() method I get the error “UnassignedReferenceException: The variable bulletBody of BulletBehavior has not been assigned.”
I’ve also tried to initialize bulletBody inside of the setDirSpeed method like so:
public void setDirSpeed(Vector2 newDirection, float newSpeed)
{
Rigidbody2D bulletBody = GetComponent<Rigidbody2D>();
bulletBody.velocity = newSpeed * newDirection;
Debug.Log(newSpeed * newDirection);
Debug.Log(bulletBody.velocity);
}
I’m not getting any errors using this method, but the velocity of my bullet doesn’t change. What have I done wrong?