Question by
$$anonymous$$ · Mar 22, 2020 at 06:28 PM ·
if-statementstagsifelseelse if
IF Else Statement being ignored ,the else if condtion is being ignored and playing first IF condition for all game objects.
In my game i have a tag for Enemy and Points so and my code is designed so when the player object collides with these objects which have these tags a corresponding effect will play depending on the tag attached to it.
The problem i have is that the else part of my code is ignored so the same effect is playing for all of the objects which i collide with even if the tag doesnt match? am i missing something?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerCollision : MonoBehaviour
{
public GameObject explosion;
public GameObject pointseffect;
public int Score;
public Text ScoreText;
private void OnTriggerEnter2D(Collider2D other)
{
// Find the Game Object with Tag of Points, run this.
if (GameObject.FindGameObjectWithTag("Enemy"))
{
Debug.Log("Damage Taken");
Destroy(other.gameObject);
GameObject e = Instantiate(explosion) as GameObject;
e.transform.position = transform.position;
}
// If it doesnt have points tag, run this.
else if (GameObject.FindGameObjectWithTag("Points"))
{
Debug.Log("Points Collected");
Destroy(other.gameObject);
GameObject p = Instantiate(pointseffect) as GameObject;
p.transform.position = transform.position;
AddScore();
}
//Score is added if Points are collected
void AddScore()
{
Score++;
ScoreText.text = Score.ToString();
}
}
}
Comment
Ignore the comments above the If statement i swapped them around to see if it is any different so the comments above dont match the code under it.