- Home /
find tag from raycast
hi everybody ive been trying to make an if statement so when i click the block it get destroy depending on the item equipped and the item your trying to mine i tried different ways i have problems identifying the tag for the times heres the scripts
if(Input.GetMouseButtonDown(0 && WoodShovel.ShovelSelected == true) || Input.GetMouseButtonDown(1)) { var Hit : RaycastHit; var LookingDirection = transform.TransformDirection(Vector3.forward); if (Physics.Raycast(transform.position,LookingDirection, Hit, Range)) { if(Input.GetMouseButtonDown(1)) { if (BlockSelected == 1) { var GrassBlock : Transform = Instantiate(GrassBlock, Hit.collider.transform.position + Hit.normal.normalized, Quaternion.identity); GrassBlock.tag = "GrassBlock"; } if (BlockSelected == 2) { var StoneBlock : Transform = Instantiate(StoneBlock, Hit.collider.transform.position + Hit.normal.normalized, Quaternion.identity); StoneBlock.tag = "StoneBlock"; } } else { if(BlockSelected == 0) { if ( Hit.transform.tag == "GrassBlock"){ Destroy(Hit.transform.gameObject,WoodShovelDestroyTime); } else { Destroy(Hit.transform.gameObject,12); } } if(BlockSelected == 1) { Destroy(Hit.transform.gameObject,GrassBlockDestroyTime); } if(BlockSelected == 2) { Destroy(Hit.transform.gameObject,StoneBlockDestroyTime); } } } }
Please reformat your code, it's quite hard to read this way.
On lines 25, 30, 36 and 40 you are accessing either a stale or an undefined Hit. You only know that Hit is value inside the if statement starting at line 1.
srry for the formating i tried to use the code sample but in the end it all fucked the formating ill try to make it nicer next time thanks for comment
Answer by pumpkinszwan · Jun 11, 2014 at 11:15 AM
Try the 3D equivalent of this:
// store the position of the mouse click
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//Cast a ray to detect object clicked
Raycast2D hitObject = Physics2D.Raycast(mousePosition, new Vector2(0, 0), 0.1f, mask);
//can now access the tag and/name from the hitObject's transform
string objectTag = hitObject.transform.tag;
thanks much thats exactly what i was looking for i will give it a try thank you :)