simple way to send a message threw a raycast

So what im trying to do is send a message to a other script and have it send how much damage to cause it and to call a function.

heres the sending script

public int speed = 5;
    	public Transform hold;
    	public Transform aim;
    	public bool aiming = false;
    	public float FireRate;
    	public RaycastHit hit;
    	public GameObject Barrel;
    	public int dammage; 

	void Start() {
		InvokeRepeating("fire", 2, FireRate);
	}
	// Update is called once per frame
	void FixedUpdate () 
	{
		
		if(Input.GetKey(KeyCode.Mouse1))
		{
			float step = speed * Time.deltaTime;
			transform.position = Vector3.MoveTowards (transform.position, aim.position, step);
		}
		else
		{
			float step = speed * Time.deltaTime;
			transform.position = Vector3.MoveTowards (transform.position, hold.position, step);
		}

		if(Input.GetKey(KeyCode.Mouse0))
		{
			Vector3 fwd = transform.TransformDirection(Vector3.forward);
			
			print("MouseLook button down");
			if (Physics.Raycast(Barrel.transform.position, fwd, 1000))
			{
				hit.collider.SendMessage("hit", SendMessageOptions.DontRequireReceiver);
				print("fired");
			}
		}
	}
	}

here is the receiving script

public float hp = 2.0f;

public void hit()
{
	hp-=1;
	if(hp<=0)
	{
		Destroy(gameObject);
	}
}

Are you having any specific problem or do you have a question?

–

1 Answer

1

I believe what you’re looking for is RaycastHit information.

Can’t really go into specifics without knowing what you’re trying to hit/scripts you’re trying to look for. Like if you’re looking for an enemy, you need to determine which enemy you hit, then access the script component that holds the health information for that enemy.

This should be a good starting point though.

using UnityEngine;
using System.Collections;

public class RayCastDamage : MonoBehaviour {

	void FixedUpdate()
	{
		//Create a RaycastHit so we can store the information from our Raycasts
		RaycastHit hitInfo; 

		if(Input.GetKey (KeyCode.Mouse0))
		{
			Vector3 fwd = transform.TransformDirection (Vector3.forward);

			if(Physics.Raycast (Barrel.transform.position, fwd, 1000, out hitInfo))
			{
				//Save the raycast information into hitInfo
				if(hitInfo.collider.tag == "Player"){
					//Check if the ray hit the player
					//You can then get the script attached the player (or whatever object)
					//And call the funcation to do damage.
				}
			}
		}
	}
}

, out hitInfo that being on the end of the thing makes the script get a error

–

Get rid of the word out and try it with just hitinfo. You're basically just telling it where to save that hitInfo (which is a type RaycastHit into the RaycastHit we created earlier, called hitInfo). Should work!

–

that did not work

–

i found what you are trying to do this is what it is it is the same thing so i well give you it RaycastHit hit; if (Physics.Raycast(transform.position, -Vector3.up, out hit)) float distanceToGround = hit.distance;

–