- Home /
raycast from an empty gameobject?
basically i have a gun, infront of the gun there is an empty game object, i have attatched this script to it. basically i want the raycast line to shoot in the z axis(Vector3.forward) from this empty gameobject and when it hits another object with tag as "enemy" then destory it(for now). i know roughly how this is done but for some reason it isnt working. there is no errors just raycast doesnt work. and yes i have called this function in the update so that isnt the problem. and i have a variable for "public RaycastHit hit;"
here is my code so far:
public void Shoot()
{
if (Input.GetKey("f"))
{
if (Physics.Raycast(transform.position, Vector3.forward, out hit))
{
if (hit.collider.gameObject.tag == "Enemy")
{
Debug.Log("It Hurts");
Debug.DrawLine(transform.position, hit.point);
/* GameObject enemy = GameObject.FindWithTag("Enemy");
EnemyHealth enemyHealth = enemy.GetComponent<EnemyHealth>();
enemyHealth.maxHealth = -10;*/
}
}
}
//else
}
}
i have extra code in there but i just commented it out for now i really just want the raycast to shoot forward from the position of which the gameobject that it is attatched to. thanks plz reply is u know how this is done im sure im not missing out that much. :)
Answer by Steffen Franz · Jan 19, 2011 at 09:58 PM
does your object, the Enemy in this example, have a collider attached?
Physics.Raycast casts against Colliders (from the Script Reference "Returns bool - True when the ray intersects any collider, otherwise false."). If the objects you are trying to "hit" does not have a Collider (e.g. BoxCollider) attached it won't detect it.
also: for the commented out code, don't do .FindWithTag("Enemy"). You already have the object you want to manipulate from hit.collider.gameObject. This might cause your problem for your code not working. If you have more than one "Enemy" tagged GameObject in the scene, Unity will grab one of the many "Enemy" tagged objects. This could be the one not being hit by the Raycast.
thanks man, i also, finally found something else, that made it work. this topic can be set to answered :)
i had to change:
if (Physics.Raycast(transform.position, Vector3.forward, out hit))
{}
to ...transform.position, transform.TransfomrDirection(Vector3.forward)..."
this made it work :D
@Steffen 1 $$anonymous$$y player is an empty gameObject. It has a character controller, therefore, it can't have a collider. How can The player detect hits by raycast?
Your answer
Follow this Question
Related Questions
How to detect if a raycast ray stop hitting an object 1 Answer
shooting and hit script JS 1 Answer
Unity Raycast Script, Help! 1 Answer
raycast to determine pivot 1 Answer
How do I make it know what it's hitting? 3 Answers