Calling a function from another script on Raycast2D

One character hits the other character, and I want to call the “Die()” function on the other character as it contains the animation

Character 1 kill function:

	void MeleeKill (){
		RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, 100);
		if (hit.collider != null) {
			hit.collider.gameObject.GetComponent<badguy>().Die();
		}
	}

Character 2 dying function in script “badguy”:

	public void Die (){
		anim.Play ("die");
		killCount = true;
		deathTime = currentTime + deathTime;
	}

Whenever I run I get the following error:
NullReferenceException: Object reference not set to an instance of an object

It refers always to the

hit.collider.gameObject.GetComponent<badguy>().Die();

Line in the first script.

I have been struggling with this for hours…

I’m not sure if this is the “best” way to access functions in scripts but this is how I do it.

in your bad guy script put this as a public variable at the top

public static badguy access;

then in the start function of that script put

access = this;

Then you can now call any function from that script in another script…so call your Die function like this

badguy.access.Die();

Sorry if this didn’t answer your question :frowning: