send a message with RaycastHit2d

Hello there, my First Question , and i hope it would not be that last haha!.

i have this piece if code here :

	// Update is called once per frame
	void Update () {
		transform.position += transform.right * Input.GetAxis (AxisName) * speed * Time.deltaTime;

		if (Input.GetKey(KeyCode.D))
		   {
			anim.SetTrigger ("Walk");
		}
		if(Input.GetKey(KeyCode.J))
		   {
			RaycastHit2D hit = Physics2D.Raycast(transform.position , Vector2.right);
		}
	}
}

from what i understand , in order to send a message taken from the raycasthit2d , i need a variable made from the position of the the hit itself, or just to send the collision it self? if so , witch method should i use , i just want to send a message of a character being hit , that is all

thank you for your kind answers

1 Answer

1

I’m assuming that this object is casting a ray against the character and wanting to send a message to the character. You want something like this (untested):

if(Input.GetKey(KeyCode.J)) {
	RaycastHit2D hit = Physics2D.Raycast(transform.position , Vector2.right);
	if (hit != null && hit.collider.name == "Character") {
		hit.collider.SendMessage("ApplySomeDamage", 1.0);
	}
}

Substitute whatever name you’ve given your character instead of “Character”.