I have a projectile prefab that is instanced when the player presses the left mouse button. I also have a “target dummy” prefab that has two states, idle and take damage. The projectile has a damage value that needs to be communicated to the target dummy so it knows how much damage it must take. I’m just not quite sure how to do this, despite toying with GameObject.Find and GameObject.FindObjectsWithTag I am always getting a NullReferenceException: Object reference not set to an instance of an object. Can I get any help with this?
This is my code for the projectile:
[SerializeField]
private float projSpeed = 7.0f;
[SerializeField]
private int damage = 1;
// Use this for initialization
void Start ()
{
Destroy(gameObject, 3.0f);
}
// Update is called once per frame
void Update ()
{
transform.position += transform.right * Time.deltaTime * projSpeed;
}
public float ProjSpeed()
{
return projSpeed;
}
public int Damage()
{
return damage;
}
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == "Ground")
{
Destroy(gameObject);
}
else if(col.gameObject.tag == "Dummy")
{
Destroy(gameObject);
}
else if(col.gameObject.tag == "Crusher")
{
Destroy(gameObject);
}
}
This is my code for the target dummy state machine where referencing the projectile is important. (I have “public Projectile bullet;” at the top of my code) My error is at the line “theDummy.TakeDamage(-bullet.Damage());”:
void StateTakeDamage()
{
bullet = GameObject.Find("Projectile").GetComponent<Projectile>();
renderer.material.color = Color.red;
theDummy.TakeDamage(-bullet.Damage());
SetState(DummyStates.IDLE);
}
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == "Projectile")
{
SetState(DummyStates.TAKEDAMAGE);
}
}