'Unity2D Collision issues, gameObject.tag if statement not working with own gameObject and tag
I apologize in advance if this question has a really easy solution, but I am working on a school project and can't find anything to help me with this issue. The (gameObject.tag=="Large Asteroid") always returns with a false, which doesn't make sense to me, because I belelive I am doing that piece of code right. This code I found online, and it's from an earlier version of unity, so that might be the issue. I just need some help with the if statement.
` void OnTriggerEnter2D(Collider2D c) {
print("hitting");
if (c.gameObject.tag.Equals("Bullet"))
{
//// Destroy the bullet
Destroy(c.gameObject);
print("girlworld");
// If large asteroid spawn new ones
if (gameObject.tag == "Large Asteroid")
{
print("startgirl");
// Spawn small asteroids
Instantiate(medAsteroid,
new Vector3(transform.position.x - .5f,
transform.position.y - .5f, 0),
Quaternion.Euler(0, 0, 90));
// Spawn small asteroids
Instantiate(medAsteroid,
new Vector3(transform.position.x + .5f,
transform.position.y + .0f, 0),
Quaternion.Euler(0, 0, 0));
// Spawn small asteroids
Instantiate(medAsteroid,
new Vector3(transform.position.x + .5f,
transform.position.y - .5f, 0),
Quaternion.Euler(0, 0, 270));
}
if (tag.Equals("Medium Asteroid"))
{
// Spawn small asteroids
Instantiate(smallAsteroid,
new Vector3(transform.position.x - .5f,
transform.position.y - .5f, 0),
Quaternion.Euler(0, 0, 90));
// Spawn small asteroids
Instantiate(smallAsteroid,
new Vector3(transform.position.x + .5f,
transform.position.y + .0f, 0),
Quaternion.Euler(0, 0, 0));
// Spawn small asteroids
Instantiate(smallAsteroid,
new Vector3(transform.position.x + .5f,
transform.position.y - .5f, 0),
Quaternion.Euler(0, 0, 270));
}
else
{
// Just a small asteroid destroyed
}
// Destroy the current asteroid
Destroy(gameObject);
}
}`
Solution 1:[1]
First use compareTag if(c.CompareTag("Bullet"))
check : https://docs.unity3d.com/ScriptReference/Component.CompareTag.html
The (gameObject.tag=="Large Asteroid") always returns with a false : -The script you attached to this object must have this tag "Large Asteroid"- As far as I understand from the code, the problem is that the object that this code calls does not have this tag.
"gameObject" means the object that attached your code in to. Maybe It'll help you more : https://www.youtube.com/watch?v=0XgOJ7ioSuA
Solution 2:[2]
First, make sure your gameObject have the tag "Large Asteroid" on the top of the inspector tab.
Try using if(this.gameObject.tag == "Large Asteroid")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ArIaNFury |
| Solution 2 | Felipe Graff Ampolini |
