I have an empty game object with children(enemies). When the player attacks the layer f the enemies is supposed to change so the blade can go through the enemy. I thought this was supposed to work (the script is attacked to the weapon).
var theEnemy : GameObject;
function Attack ()
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*.5, Screen.height*.5, 0));
if (Physics.Raycast (ray, hit, maxDistance) && hit.collider.tag == "Enemy")
{
theEnemy.child.gameObject.layer = LayerMask.NameToLayer("DrawAlways");
}
}
To answer the first post, I’ll first suggest an easier way to do what you’re wanting. You’re currently checking hit.collider.tag to see if you’ve hit the enemy. However, if you’ve got several enemies, a better way to check physics-related stuff is by using layers. You can create a new layer (select a GameObject, then under the Inspector tab, click the Layer dropdown, then click Add Layer…, then type in a new layer name for one of the User Layers), then select your enemy(s) in the Editor and change their layer to the one you just created.
//var theEnemy : GameObject;
//the above line isn't needed, Physics.Raycast will give
//"hit" a reference to any GameObject it hits, using
//hit.collider.gameObject. Just be careful to put your
//enemies on the same layer as layerMask, and they'll
//be able to be hit with the Raycast.
var layerMask : LayerMask; //in the Editor's Inspector tab, you can set this to a custom layer that you put your enemy(s) on
function Attack ()
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*.5, Screen.height*.5, 0));
//might not need to check hit.collider.tag, unless you've got
//multiple kinds of enemies on the same layer, in which case
//tags (and other attributes) can sometimes be handy to differentiate
if (Physics.Raycast (ray, hit, maxDistance, 1<<layerMask) && hit.collider.tag == "Enemy")
{
hit.collider.gameObject.layer = LayerMask.NameToLayer("DrawAlways");
}
}