- Home /
Question by
AndyW19 · Oct 30, 2020 at 12:35 AM ·
c#errorobjectgameobjects
Referencing a variable to a prefab from another script that is applied to multiple game objects
I'm fairly new to Unity and C# and I've spent the past few hours trying to figure this out. Basically I want to send a damage variable from my PlayerShootBullet script that is applied to multiple gun game objects to my bullet prefab to control how much damage the bullet will do depending on what gun is being used. I can't seem to get this to work though as I always get the same error. NullReferenceException: Object reference not set to an instance of an object
.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShootBullet : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
Animator anim;
public float bulletForce = 20f;
public float fireRate = 1f;
public float range = 100f;
public float damage = 10f;
public int maxAmmo = 9;
private int currentAmmo;
public float reloadTime = 3f;
private bool isReloading = false;
public bool isFullAuto = false;
public bool isAnimated = false;
private float nextTimeToFire = 0f;
void Start()
{
anim = gameObject.GetComponent<Animator>();
currentAmmo = maxAmmo;
}
void OnEnable()
{
isReloading = false;
}
void Update()
{
if (isReloading)
{
return;
}
if (Input.GetKeyDown(KeyCode.R))
{
StartCoroutine(Reload());
return;
}
if (isFullAuto == false)
{
if (Input.GetMouseButtonDown(0) && Time.time > nextTimeToFire && currentAmmo >= 1)
{
Shoot();
}
} else
{
if (Input.GetMouseButton(0) && Time.time > nextTimeToFire && currentAmmo >= 1)
{
Shoot();
}
}
}
IEnumerator Reload()
{
isReloading = true;
yield return new WaitForSeconds(reloadTime);
currentAmmo = maxAmmo;
isReloading = false;
}
// Update is called once per frame
public void Shoot()
{
currentAmmo--;
nextTimeToFire = Time.time + fireRate;
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.right * bulletForce, ForceMode2D.Impulse);
if (isAnimated == true) {
anim.SetTrigger("Shoot");
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public PlayerShootBullet playerShootBullet;
void Awake()
{
playerShootBullet = FindObjectOfType<PlayerShootBullet>();
}
void OnCollisionEnter2D(Collision2D collision)
{
var enemy = collision.collider.GetComponent<EnemyHealth>();
if(enemy)
{
enemy.TakeHit(playerShootBullet.damage);
}
Destroy(gameObject);
}
}
If anyone could help point me in the right direction for how I would go about doing that would be great.
Comment
As per the error, it is due to a unity script itself and nothing to do with playerShootBullet.damage
, try restarting unity