Hello,
I am trying to find the object that is hit by the ray , but I cannot.
my player is doing a RayCast against the ground layer. the raycast is working as seen in the debug below. but i want to to know the name of that object so I can do CompareTag
Thanks
function FixedUpdate()
{
var hit: RaycastHit2D = Physics2D.Raycast(transform.position,-Vector2.up,1 << LayerMask.NameToLayer("Ground"), -2);
if(hit != null)
{
Debug.Log(hit.transform); //results: tree_log(Clone) (UnityEngine.Transform)
Debug.Log(hit.collider); // result: tree_log(Clone) (UnityEngine.BoxCollider2D)
Debug.Log(hit.collider.name); //results: NullReferenceException: Object reference not set to an instance of an object
Debug.Log(hit.transform.name); //results: NullReferenceException: Object reference not set to an instance of an object
}
}
Get the GameObject from the collider, from there you can extract the name:
hit.collider.gameObject.name
The 2D API will apparently return a non-null Raycast2D even when no collider is found in raycasting, so you should also test for that to determine if a collision occurred. Here’s an example you can use in testing:
#pragma strict
var target : GameObject;
var numTargets : int = 8;
var targetDistance : float = 7.0f;
var sweepSpeed = 3.0f;
var lineRender : LineRenderer;
var targetLayer : int;
var lastHit : GameObject;
function Start () {
lineRender = GetComponent(LineRenderer);
DuplicateTarget();
}
function Update () {
var radius : Vector2 = Vector2(Mathf.Cos(sweepSpeed * Time.time), Mathf.Sin(sweepSpeed * Time.time)) * targetDistance;
var hit : RaycastHit2D = Physics2D.Raycast(transform.position, radius, targetDistance, 1 << targetLayer);
if (null != hit && null != hit.collider) {
lastHit = hit.collider.gameObject;
}
if (null != lineRender) {
lineRender.SetPosition(0, transform.position);
lineRender.SetPosition(1, transform.position + radius);
}
}
function OnGUI() {
var r = Rect(10f,10f,200f,100f);
var label : String = "Nothing";
if (null != lastHit) {
label = lastHit.name;
}
GUI.Label(r, label);
}
function DuplicateTarget() {
if (null != target) {
targetLayer = target.layer;
// Place copies of the target around the space of the sweeper.
var origin : Vector3 = transform.position;
var angleStep = Mathf.PI * 2.0f / numTargets;
for (var i=0; i<numTargets; ++i) {
var angle : float = angleStep * i;
var r : Vector2 = Vector2( Mathf.Cos(angle), Mathf.Sin(angle)) * targetDistance;
var newTarget : GameObject = Instantiate(target, origin + r, Quaternion.identity);
newTarget.name = String.Format("object_{0}", i);
}
target.SetActive(false);
}
}
hey can i know what does the line 1 << LayerMask.NameToLayer(“Ground”) does,
i think Physics2D.Raycast( vector2 , vector2 , float , int ,float ) is the function parameter list. and also antho function that is overridden Physics2D.Raycast( vector2 , vector2 , float , int ,float , float)
where the layermask.nametolayer returns an integer .