How to make OnTriggerEnter Only work for certain Gameobjects?
How do I only make a cooking collider cook the chicken patties? I have already made a custom tag for the cook able items. Also need help to only have animation play when inside the trigger. using System.Collections; using System.Collections.Generic; using UnityEngine; public class CookFood : MonoBehaviour { %|1603254598_1|% %|1671281540_2|% %|736461570_3|% %|548796267_4|% %|284888560_5|% %|1596870978_6|% %|819998687_7|% %|-1699521485_8|% %|-1207445934_9|% void Update () { %|-1057342426_11|% %|-1731482512_12|% %|-420389490_13|% %|221049047_14|% %|-522694938_15|% %|-198492382_16|% %|-527023563_17|% }
Answer by T_Lavell · Feb 12, 2017 at 10:15 PM
FindWithTag is not to be confused with CompareTag.
OnTriggerEnter will be called whenever the gameObject your script is attached to comes into contact with any trigger - not necessarily just your stove object (unless it is the only trigger that exists). The reference you call 'Stove' is actually a reference to whichever other collider(trigger) came into contact with this one. So, if you want to trigger a 'Cook' animation when the player (or whatever the script is attached to) comes into contact with a Stove, or other object with the 'cook' tag, you need to perform a little discernment.
Try
void OnTriggerEnter(Collider otherObject)
{
if (otherObject.gameObject.CompareTag("Cook") )
{
Animator _anim = otherObject.GetComponent<Animator>();
_anim.SetTrigger("Cook");
// Or you can use legacy Animation and Anim.Play code here instead.
}
}
What I've done is to first check if the trigger object has the tag "Cook", and then if it does, told its animator component to play the cook animation (the trigger "Cook" would have to be set up already in the AnimatorController as a parameter, and a transition set up). If you are using legacy animation, you could do so here - but you will want to be careful that you are playing the animation on the correct gameobject, etc. I wrote code that assumed the triggering object should play the animation - but you could instead piggyback a reference if you need.
'FindObjectWithTag' could reference any object in the scene with that tag, and returns true if it finds any such object.
Answer by SirOrange · Feb 11, 2017 at 10:23 PM
oops here'`using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CookFood : MonoBehaviour {
public Collider Stove;
public GameObject Chicken;
public Animation Cook;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter (Collider Stove){
if(GameObject.FindWithTag("Cook")){
Cook.Play ();
}
}
} `s the code