- Home /
Question by
Prashant_Tomar · Apr 27, 2020 at 07:22 AM ·
error2d gameenemy damage
Whenever I am trying to shoot the enemy my missile is not going towards the enemy and blasting in front of me
NullReferenceException: Object reference not set to an instance of an object rocketHIt.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/rocketHIt.cs:35)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class rocketHIt : MonoBehaviour { public float weaponDamage;
projectileController myPC;
public GameObject explosionEffect;
// Start is called before the first frame update
void Awake()
{
myPC = GetComponentInParent<projectileController>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.layer == LayerMask.NameToLayer("Shootable"))
{
myPC.reomveForce();
Instantiate(explosionEffect, transform.position,transform.rotation);
Destroy(gameObject);
if (other.tag == "Enemy")
{
enemyHealth hurtEnemy = other.gameObject.GetComponent<enemyHealth>();
hurtEnemy.addDamage(weaponDamage);
}
}
}
void onTriggerStay2D(Collider2D other)
{
if (other.gameObject.layer == LayerMask.NameToLayer("Shootable"))
{
myPC.reomveForce();
Instantiate(explosionEffect, transform.position, transform.rotation);
Destroy(gameObject);
if (other.tag == "Enemy")
{
enemyHealth hurtEnemy = other.gameObject.GetComponent<enemyHealth>();
hurtEnemy.addDamage(weaponDamage);
}
}
}
}
Comment
Answer by RaidingShaman · Apr 27, 2020 at 08:27 AM
Check the projectileController script you created. Reply me what's in it.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class projectileController : $$anonymous$$onoBehaviour { public float rocketSpeed;
Rigidbody2D myRB;
// Start is called before the first frame update
void Awake()
{
myRB = GetComponent<Rigidbody2D>();
if (transform.localRotation.z>0)
myRB.AddForce(new Vector2(-1, 0) * rocketSpeed,Force$$anonymous$$ode2D.Impulse);
else myRB.AddForce(new Vector2(1, 0) * rocketSpeed, Force$$anonymous$$ode2D.Impulse);
}
// Update is called once per frame
void Update()
{
}
public void reomveForce()
{
myRB.velocity = new Vector2(0, 0);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612232600im_/https://answers.unity.com/themes/thub/images/avi.jpg)