- Home /
Detect objects name you just hit
Hi all,
I have a script which when you run your character into a cube, it destroys it...and it works fine. But now i only want to destroy a cube if it has a certain name....
#pragma strict
function Start () {
}
function Update () {
}
function OnTriggerEnter ( collision : Collision )
{
if (this.gameObject.name == "Cube2"){
GameObject.Destroy ( gameObject ) ;
}
}
That is what I have tried...and it does not work, could anyone point me in the correct direction please? Thanks!
Answer by Em3rgency · Jul 02, 2013 at 04:13 PM
Well, first of all, you never need to use this. in unity. Its redundant.
Second, add a debug line to see the name of the object you hit, and you'll be able to see what you did wrong :)
function OnTriggerEnter ( collision : Collision )
{
Debug.Log("You just hit " + gameObject.name);
if (gameObject.name == "Cube2")
{
GameObject.Destroy ( gameObject ) ;
}
}
The debug.log line does not come up in the console?
Now I'm confused :)
You said it was working fine before, so presumably OnTriggerEnter was being called correctly and you were destroying the object given by collision? Yet you're saying that Debug.Log isn't appearing, which means OnTriggerEnter isn't being called. What code did you have before that was working?
Also, I was presu$$anonymous$$g that this script was attached to the character - what is this script attached to? If it's attached to the cube, why would you need to check the name at all?
We really need more information from you on what exactly you're trying to do, what you expect to happen, and what you're seeing ins$$anonymous$$d.
Right sorry I have made one hell of a mistake....I have pasted the wrong code lol...here is the code i am using which works.
function OnTriggerEnter (other : Collider) {
Destroy(other.gameObject);
Score.score += 1;
}
Right ok it is logging the name as 'object', but I have changed the name of the cube to Cube2? What am I doing wrong here?
Ok, so if the cube gets destroyed, now you just need an if statement. if(other.gameObject.name == "TheCubeYouHate") { GameObject.Destroy(other.gameObject) }
Answer by Julien-Lynge · Jul 02, 2013 at 04:14 PM
'this' is the object the script is attached to. Likely you want to use the 'collision' object rather than 'this'. Check the script reference for Collision.
This is true. I sort of assumed the code was attached to the cube. If that's not the case, you should be using collision.gameObject.name
Your answer

Follow this Question
Related Questions
A node in a childnode? 1 Answer
Timer help please 1 Answer
Unexpected Token BCE0043 0 Answers
Swipe in Unity3d 3 Answers
Mid point of a object 1 Answer