Referencing a temporary, instanced object?

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);
		}
	}

The likely problem is that you are destroying the bullet on line 36 of the first script which may happen before you execute line 3 in the second script. The typical solution to this problem is to have the projectile communicate to the object, either by directly calling a method or through SendMessage.

I’m not completely sure how you have things structured, but typically you do something like this in the projectile script:

    else if(col.gameObject.tag == "Dummy")
    {
        col.gameObject.SendMessage("TakeDamage", -damage);
        Destroy(gameObject);
    }

or:

    else if(col.gameObject.tag == "Dummy")
    {
        col.gameObject.GetComponent<SomeComponent>().TakeDamage(-damage);
        Destroy(gameObject);
    }

Where ‘SomeComponent’ is the component has the ‘TakeDamage()’ method.