- Home /
How to TAG the Player?
Hi, Using the First Person Controller, I'm trying to create a simple box trigger that will play a sound 1 time when the player enters the box collider. I found several different scripts how to do this. However there are two things I don't understand...
***First, they all refer to "Tagging" the "Player". I have no clue what this involves.
***Second... all the scripts I find for player entering a box trigger and a sound playing are different. None seem to work and I just get errors. I don’t know if its from not "Tagging" the player (which I don’t know how to do ) or if the script is wrong.
Here is a sample of what I have been using.
function OnTriggerEnter(otherObj: Collider){ if (otherObj.tag == "Player"){ audio.Play(); } else { audio.Stop(); } }
Any help would be greatly appreciated. Thanks.
Answer by fafase · Nov 30, 2012 at 09:12 AM
1-To tag an object you have, look in the inspector at the top, you have Tag Untagged (probably).
2-If you click untagged it opens a drop down from which you can choose already existing tags. You can also add one at the end. It opens a new window in the inspector with a list of tags.
3-Open up Tag section with the little triangle and select the first empty element (probably the first one). Give a tag (Player) and press enter or it won't remain. Now get back to your object via the hierarchy and go back to 2 above.
Now add a script to the triggerbox:
function OnTriggerEnter(other:Collider){
if(other.gameObject.tag =="Player") audio.Play();
}
Make sure your sound has Loop ticked off so it stops automatically. Now you want the sound only once if I got it right.
var once:boolean = true;
function OnTriggerEnter(other:Collider){
if(other.gameObject.tag =="Player"){
if(once){
audio.Play();
once = false;
}
}
}
Ahh ... thank you so much for helping both in Unity and in how to properly use these forums. Yes I am a total NOOB to Unity. I am a 3D artist and not very "CODE" $$anonymous$$ded.
Also I wanted to let you know I am getting a compiler error when I use the script
function OnTriggerEnter(other:Collider){ if(other.gameObject.tag =="Player") audio.Play(); }
var once:boolean = true;
function OnTriggerEnter(other:Collider){ if(other.gameObject.tag =="Player"){ if(once){ audio.Play(); once = false; } } }
the error in the status window at the bottom of unity says "TriggerScript" already has a definition for 'OnTriggerEnter(UnityEngine.Collider)'
ahh the light bulb finally cam on. I see you ment those as 2 different scripts...I had them as 1 and that was my error. Thanks again...It works perfectly!
Hold on, nope. This is only one script. Fact is I show two steps. First is the simple one, second is the simple one evolved to play only once the sound. And your error is because you had twice the same function. So only use the second part that you attach to the object (not the player) with a trigger sphere or box collider. $$anonymous$$ake sure IsTrigger is ticked on the collider.