Hello! This is going to be my first question so leave responses telling me how I can improve it.
I am trying to make a clone of the game RotMG (Realm of the Mad God) and I am starting to work on multiplayer. However, I encountered a weird bug that I came here to solve. I have implemented shooting and equipment, however, there seems to be a problem with either unity or my code. I have a basic projectile class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
public bool ShotByPlayer;
public int Damage;
public float LifeSpan;
public bool IsBase;
public bool KilledItself = false;
public int ShooterID;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
}
public void SetSprite(Sprite newSprite) {
gameObject.GetComponent<SpriteRenderer>().sprite = newSprite;
}
void OnTriggerEnter2D(Collider2D OtherCollider) {
if(OtherCollider.gameObject.GetInstanceID() == ShooterID) {
return;
}
GameObject EventManagerHost = GameObject.FindGameObjectsWithTag("EventManagerHost")[0];
EventManagerHost.GetComponent<EventManager>().ProjectileHit(gameObject, OtherCollider.gameObject);
if(IsBase == false)
Destroy(gameObject);
}
}
And it seems to work. Everytime a player clicks the following method is called
public void CreateBullet(Vector2 Position, Vector2 Velocity, int Damage, Sprite sprite, bool ShotByPlayer, Vector2 Size, float Range, int Id, Quaternion Rotation) {
GameObject Bullet = Instantiate(GameObject.FindGameObjectsWithTag("BaseProjectile")[0]);
Bullet.tag = "Projectile";
Bullet.transform.position = Position;
Bullet.GetComponent<Rigidbody2D>().velocity = Velocity;
Bullet.GetComponent<Projectile>().ShotByPlayer = ShotByPlayer;
Bullet.GetComponent<Projectile>().SetSprite(sprite);
Bullet.GetComponent<SpriteRenderer>().size = Size;
Bullet.GetComponent<Projectile>().Damage = Damage;
Bullet.GetComponent<Projectile>().ShooterID = Id;
Bullet.GetComponent<Projectile>().IsBase = false;
Bullet.transform.rotation = Rotation;
Bullet.transform.SetParent(GameObject.FindGameObjectsWithTag("ProjectileContainer")[0].transform);
Destroy(Bullet, Range / 23);
}
So it sets the basic characteristics of a bullet: position, velocity, rotation, damage, sprite, size, and lifetime (Range)
And it seems to work fine in my editor, when I shoot it works fine and destroys itself after its lifetime is over. However, when I go to build my game and run it, it stops working (Kind of).
it still shoots and a bullet is created that looks fine and SOMETIMES destroys itself on time, however, oddly enough, only when I shoot forward, the bullet prematurely destroys itself and only when I shoot forward.
Can someone please explain why this is and how I can fix it?