I’m trying to make a game where you can make custom projectiles with various components that have special properties (like poison, explosions, anti-gravity, mind control).
Then you would be able to put that bullet in a gun.
I’m thinking of using OnCollisionEnter and a box collider to get the GameObject and then use a raycast that would get the gun script on a gun and change the projectile reference to the projectile in the box collider.
Before I actually try that though, I want to make sure I know how to assign a reference in game.
I’ve looked everywhere online and I have not been able to find any information on how to make a script that lets the player change the reference of a gameobject. My gun script currently works by instantiating a projectile prefab through a public gameobject reference.
Here are my current script for guns and projectiles, these are placeholders until I can better understand how to change variables and such in gametime and outside of the scene editor.
public class Projectile : MonoBehaviour
{
public float damage = 10f;
[SerializeField] float speed = 10f;
private Rigidbody projectile;
void Start()
{
projectile = GetComponent<Rigidbody>();
}
void Update()
{
projectile.AddForce(transform.forward * Time.deltaTime * speed, ForceMode.Impulse);
}
private void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
}
}
public class Gun : MonoBehaviour
{
public GameObject bullet;
public Transform muzzle;
public int magazineSize;
public int bulletsInMag;
public float reloadTime = 3;
bool reloading = false;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0) && bulletsInMag > 0)
{
Shoot();
}
else if ((Input.GetKeyDown(KeyCode.Mouse0) && bulletsInMag <= 0 && !reloading))
{
Reload();
}
}
private void Shoot()
{
Instantiate(bullet, muzzle.position, muzzle.rotation);
bulletsInMag--;
}
private void Reload()
{
reloading = true;
StartCoroutine(ReloadTime());
}
IEnumerator ReloadTime()
{
yield return new WaitForSeconds(reloadTime);
bulletsInMag = magazineSize;
reloading = false;
}
}