- Home /
Get the name of the collided object
Thanks in advance for reading
I'm using linecast to detect collision. The point is i need to know the name of the object I'm colliding with. So i have four empty game object around my player with linecasts from the player to these points and I can't seem to access the name of the collided object. Here's the code
using UnityEngine; using System.Collections;
public class collisiondetection : MonoBehaviour {
public RaycastHit2D collidedTop;
public RaycastHit2D collidedBot;
public RaycastHit2D collidedRight;
public RaycastHit2D collidedLeft;
public Transform collisionCheckRight;
public Transform collisionCheckLeft;
public Transform collisionCheckTop;
public Transform collisionCheckBot;
public Transform textboxprefab;
bool textbox;
public MovementScript movementscript;
// Use this for initialization
void Start () {
movementscript = GameObject.FindGameObjectWithTag("Player").GetComponent<MovementScript>();
}
// Update is called once per frame
void Update ()
{
collidedTop = Physics2D.Linecast(transform.position, collisionCheckTop.position, 1 << LayerMask.NameToLayer("Obstacles"));
collidedBot = Physics2D.Linecast(transform.position, collisionCheckBot.position, 1 << LayerMask.NameToLayer("Obstacles"));
collidedRight = Physics2D.Linecast(transform.position, collisionCheckRight.position, 1 << LayerMask.NameToLayer("Obstacles"));
collidedLeft = Physics2D.Linecast(transform.position, collisionCheckLeft.position, 1 << LayerMask.NameToLayer("Obstacles"));
}
}
Any idea how i can get the object name?
Answer by robertbu · Jan 31, 2014 at 11:52 PM
Try this:
if (collidedTop != null && collidedTop.collider != null) {
Debug.Log("The top name is: "+collidedTop.collider.name);
}
It doesn't do anything. Nothing is logged. Not even "The top name is: "
The only reason I can see for you not getting output is if the Linecast() fails. You need to debug your Linecast() first to see why it is not return a non-null value. $$anonymous$$are sure all the colliders are 2D. Do a Debug.DrawLine() between transform.position to collisionCheckTop.position to see if the linecast is going where you think. $$anonymous$$ake the obstacle is on the 'Obstacles' layer...
Answer by hossam_shuk · Feb 02, 2014 at 12:08 AM
I did a ridiculous mistake. I miss spelled the layermask name Obstacles when it's actually Obstacle.
Your answer
Follow this Question
Related Questions
Physics2D.Linecast ignoring walls 1 Answer
Linecast ignoring mesh collider 1 Answer
FixedUpdate and LineCast? 0 Answers
Coliders Don't work 1 Answer
I can't get an npc to take damage.,I can't get my NPC to take damage. 0 Answers