Hi, I want my player object to shoot projectile and take damage to enemy when the projectile collides with the enemy.
To do this, I wrote 3 scripts ; Player, Enemy, Projectile.
However, when projectile hits the enemy, the unity editor has an error like this
“NullReferenceException: Object reference not set to an instance of an object
Projectile.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/ScriptTest/Skill.cs:25)”
Please explain why it is and how to fix it.
(the codes worked out when projectile was not prefabs but just an object.)
Here is my 3 scripts
public class Player : MonoBehaviour
{
public GameObject projectilePrefabs;
private Rigidbody playerRb;
void Start()
{
playerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
SpawnPrefab();
}
private void SpawnPrefab()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
Instantiate(projectilePrefabs, transform.position, projectilePrefabs.transform.rotation);
}
}
}
public class Enemy : MonoBehaviour
{
public int maxHealth = 10;
private int currentHealth;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
}
// Update is called once per frame
void Update()
{
}
public void TakeDamage(int amount)
{
currentHealth -= amount;
Debug.Log(currentHealth);
}
}
public class Projectile : MonoBehaviour
{
private Rigidbody projectileRb;
private int speed = 5;
private Enemy enemyScript;
void Start()
{
projectileRb = GetComponent<Rigidbody>();
enemyScript = GetComponent<Enemy>();
}
// Update is called once per frame
void Update()
{
projectileRb.transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
private void OnCollisionEnter(Collision collision)
{
enemyScript.TakeDamage(1);
}
}