I want to build a quick and simple prototype where I have a weapon sprite on the ground, the square walks to it, and it picks up the gun, making it usable. I have a shooting script that works on the gun prefab, but needs variables to be dragged and dropped.
My gun prefab that is spawned already attached to the player needs the camera, gun gameobject transform, as well as the bullet prefab and the UI element which references the ammo HUD.
I want to make a system where I can pick up a gun prefab and have it equipped to shoot, but instantiating the gun prefab requires the drag and dropping of the aforementioned gameobjects in order for the script to function. Is there a solution that does not require the prefab variable drag and dropping?
Shooting script:`[SerializeField] private int ammo;
[SerializeField] private Text ammoDisplay;
[SerializeField] private Transform fireP;
[SerializeField] private float fireRate = 0.3f;
[SerializeField] private float nextFire = 0f;
public bool isFiring;
[SerializeField] private GameObject bulletPF;
[SerializeField] private float bulletForce = 20f;
private void Start(){
fireP = GameObject.Find("Fire Point").transform;
}
// Update is called once per frame
void Update(){
ammoDisplay.text = ammo.ToString();
if (Input.GetMouseButton(0) && !isFiring && Time.time > nextFire && ammo > 0){
nextFire = Time.time + fireRate;
Shoot();
ammo--;
}
if (Input.GetKeyDown(KeyCode.R)){
ammo = 6;
nextFire = 0f;
}
}
void Shoot(){
isFiring = true;
GameObject bullet = Instantiate(bulletPF, fireP.position, fireP.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(fireP.up * bulletForce, ForceMode2D.Impulse);
isFiring = false;
}
`
Arm Cam script:
Vector2 mousePos;
public Camera cam;
public float slerpSpeed = 20f;
public Transform tr;
// Update is called once per frame
void Update(){
cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
tr = GetComponent<Transform>();
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
private void FixedUpdate(){
Vector2 lookDir = mousePos - (Vector2)tr.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
tr.rotation = Quaternion.Slerp(transform.rotation,rotation, slerpSpeed*Time.deltaTime);
}