Hello, I’m very new to C#. I know the answer to this question may be obvious for most, but I’m stuck at the moment.
I wrote a “PlayerHealth/Damage Script”. So far, it just has one type of damage, and 4 types of health items. (items are tagged)
When I place one of each item in a row, everything works as expected.
(Player picks up health OnTriggerEnter, & item destroys itself etc)
The problem is, when I place multiple “copy’s” of the Prefab throughout the scene, they basically “don’t match up”. (ex. entering a trigger of one item (ex. bread) could Destroy a different copy of the same item (ex. bread(2)) and so on.
Here is my Script:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class PlayerDamageScript : MonoBehaviour {
int playerHealth = 100;
int damage = 10;
public AudioClip bite;
public AudioClip drink;
public AudioClip belch;
public AudioClip ouch;
public AudioClip dead;
void Start ()
{
print (playerHealth);
playerHealth = 100;
}
void Update()
{
if (playerHealth <= 0)
{
Death ();
}
if (playerHealth >= 100)
{
playerHealth = 100;
if (playerHealth > 100)
{
GetComponent<AudioSource> ().clip = belch;
GetComponent<AudioSource> ().Play ();
}
}
}
//PLAYER HEALTH/DAMAGE TRIGGERS//
//*****************************//
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Enemy")
{
playerHealth -= damage;
print ("Enemy Hit You!" + playerHealth) ;
GetComponent<AudioSource> ().clip = ouch;
GetComponent<AudioSource> ().Play ();
}
if (other.gameObject.tag == "apple")
{
playerHealth += 10;
print ("You ate an Apple + 10 Health =" + playerHealth);
Destroy (GameObject.FindWithTag ("apple"));
GetComponent<AudioSource> ().clip = bite;
GetComponent<AudioSource> ().Play ();
}
if (other.gameObject.tag == ("bread"))
{
playerHealth += 25;
print ("You ate Bread + 25 Health =" + playerHealth);
Destroy (GameObject.FindWithTag ("bread"));
GetComponent<AudioSource> ().clip = bite;
GetComponent<AudioSource> ().Play ();
}
if (other.gameObject.tag == "cheese")
{
playerHealth += 50;
print ("You ate Cheese + 50 Health =" + playerHealth);
Destroy (GameObject.FindWithTag ("cheese"));
GetComponent<AudioSource> ().clip = bite;
GetComponent<AudioSource> ().Play ();
}
if (other.gameObject.tag == "potion")
{
playerHealth += 100;
print ("You drank a healing Potion + 100 Health =" + playerHealth);
Destroy (GameObject.FindWithTag ("potion"));
GetComponent<AudioSource> ().clip = drink;
GetComponent<AudioSource> ().Play ();
}
}
public void Death()
{
SceneManager.LoadScene (8);
}
}
So, how do I make multiple copy’s of a prefab and pick up each one (correctly) by tag?
Any help would be greatly appreciated! Thanks!