- Home /
"tag" & "if condition with OnTriggerEnter
Hello
I have a collider who's many objects are going into it. For each object going to the collider, the score is +1.
Now, i want to have the score -1 for a special object.
I've tried to separate them with tag, but i have difficult. All object give me yet +1 .
Am I on the good direction? Do you have idea for doing that? Thank you (and sorry for my bad english)
Here my script:
void OnTriggerEnter(Collider theCollision)
{
if (theCollision.tag == "piece")
print("piece +1score");
myPlayerScript.theScore++;
if (theCollision.tag == "piecebonus")
print("piece -1score");
myPlayerScript.theScore--;
}
Answer by You! · May 25, 2012 at 09:12 PM
Firstly, there are a few fixes to your code...they may help.
void OnTriggerEnter( Collider theCollision ) // C#, type first, name in second
{
if (theCollision.gameObject.tag == "piece")
// By using {}, the condition apply to that entire scope, instead of the next line.
{
print("piece +1score");
myPlayerScript.theScore++;
}
else if (theCollision.gameObject.tag == "piecebonus")
{
print("piece -1score");
myPlayerScript.theScore--;
}
}
If these fixes aren't enough, you might have to change "theCollision.gameObject.tag" to "theCollision.gameObject.name" and use the object's name instead. Also check to see if you have the object tags correct in your script (this last problem is one I've had before).
[Edit by Berenger : Collider theCollision instead of theCollision : Collider (C#), explained the why {}]
I tried your fixes but it don't work. All the conditions are executed and tag or name is not check
$$anonymous$$aybe must i search an other way to do that
If you use "theCollision.gameObject.name" you must use the name of the object...if that is your problem...
I just saw that there aren't nearly enough curly braces. I will update my answer to show where you need them!
Edit: You should probably also use "else if" on your second "if" statement, just because both statements are calling for similar stuff... This won't really change how it operates, though.
Thank you for your help
$$anonymous$$y tag was on the instantiate prefab but not in the mesh. Now all work perfect
Thanks to you, my script is cleaner
Answer by Berenger · May 26, 2012 at 02:46 AM
Using the name for that purpose is ill advised, as you might need it for something else. Several object with different names can share the same tag however.
If the score does go up no matter what object collide with that one, it means none of them has the tag piecebonus. Make sure it's correctly set in the editor and that it's not modified by a script somewhere.
Your answer
Follow this Question
Related Questions
GameObject tag to if condition 1 Answer
Check if there is a child with a tag? (multiple children but each diff tag) 1 Answer
random range/if conditions? 2 Answers
if for array 1 Answer
OnTriggerEnter doesn't read a tag of a moving object 1 Answer