Any way to fix an tag change problem?
I have wasted 2+ days trying to get ground leaves collider trigger to detect object with "Herbivore" tag and then change the ground leaves tag to "GroundLeavesRegen" but for some reason either the tag detection doesn't work or the tag change. Any way to solve this? I really don't know what to do.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundLeavesScript : MonoBehaviour
{
public void OnTriggerEnter(Collider other)
{
if (other.tag == "Herbivore")
{
transform.gameObject.tag = "GroundLeavesRegen";
}
}
}
Answer by andycodes · Jan 12, 2021 at 01:15 AM
When using Triggers and tags, there's a few things you'll want to check first:
Do both objects (the leaves and herbivore) have Colliders attached with one being set as a trigger?
Does at least one of the two objects have a rigidbody component?
Without a ridigbody, the interaction won't be triggered in the first place
Have you registered the tags in the editor?
Is everything being spelt correctly? (Happens more than I'd like to admit)
Also, some critiques on your provided code:
using UnityEngine;
public class GroundLeavesScript: MonoBehaviour
{
// (1)
private void OnTriggerEnter(Collider other)
{
// (2)
if(other.CompareTag("Herbivore"))
{
// (3)
Debug.Log("Herbivore is making contact!");
gameObject.tag = "GroundLeavesRegen";
Debug.Log($"new tag set to: {gameObject.tag}");
}
else {
Debug.Log($"Object with tag: {other.tag} has entered");
}
}
}
OnTriggerEnter
should be marked private, since you shouldn't be calling it from other classes. See docsPrefer to use
other.CompareTag("..")
when checking tag equality. docsWhen debugging,
Debug.Log()
is your friend!
I've created a quick demo scene after checking all of this and was able to get the desired results:
Your answer
Follow this Question
Related Questions
How to use 2 tags in FindGameObjectsWithTag. 2 Answers
Using particle trigger with tags 0 Answers
Destroying Object OnTriggerEnter2D not working 1 Answer
C# GetKeyDown not working 3 Answers