In my game when you kill an enemy it spawn “xp ball” that you can take and get xp. But allways when i take the “xpball” it sets xp to 0.3 when it should add 0.3 when player is lvl 0. Im pretty noob at coding and i think is should be right when i wrote xp += 0.3. Here is the code:
public class Exp : MonoBehaviour
{
public GameObject XpBar;
float xp = 0;
int level = 0;
public Text Lvl;
void Start()
{
xp = 0;
}
// Update is called once per frame
void Update()
{
Lvl.text = (level.ToString());
print(xp);
if (xp > 1)
{
xp = 0;
level += 1;
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
if (level == 0)
{
xp += 0.3f;
XpBar.transform.localScale = new Vector3(xp, 1, 1);
print(xp);
Destroy(gameObject);
}
if (level == 1)
{
xp += 0.2f;
XpBar.transform.localScale = new Vector3(xp, 1, 1);
print(xp);
Destroy(gameObject);
}
if (level == 2)
{
xp += 0.05f;
XpBar.transform.localScale = new Vector3(xp, 1, 1);
Destroy(gameObject);
}
if (level == 3)
{
xp += 0.01f;
XpBar.transform.localScale = new Vector3(xp, 1, 1);
Destroy(gameObject);
}
if (level == 4)
{
xp += 0.005f;
XpBar.transform.localScale = new Vector3(xp, 1, 1);
Destroy(gameObject);
}
}
}
}
According to your code, the component is attached on the balls, and that’s clearly the problem. It should be attached to the Player.
I’ve reworked a little bit the script to handle this new setup and made it clearer (and more performant)
public class PlayerExperience : MonoBehaviour
{
public GameObject ExperienceBar;
public Text LevelText;
public float[] ExperiencePerLevel = new float[]
{
0.300f,
0.200f,
0.050f,
0.010f,
0.005f
}
private float experience = 0;
private int level = 0;
public float Experience
{
get
{
return experience;
}
private set
{
experience = value ;
ExperienceBar.transform.localScale = new Vector3(experience, 1, 1);
if(experience > 1)
{
Level += (int) experience;
experience = 0;
}
}
}
public int Level
{
get
{
return level;
}
private set
{
level = value ;
LevelText.text = level.ToString();
}
}
void Start()
{
Experience = 0;
}
void OnTriggerEnter2D(Collider2D other)
{
// Tag the XP balls as follow `XPBall`
if (other.CompareTag("XPBall"))
{
Experience += ExperiencePerLevel[Level] ;
Destroy(other.gameObject);
}
}
}