I am fairly new to unity and am trying to make a game based on mapbox location based game. Right now I have an welcome scene where they choose a name and a character (male or female), which works perfectly fine and they chosen character shows on the map.
Now, I have three scripts: GameManager, Player & BonusXP. In the GameManager I am instantiating the chosen player and place them on the map.
In the player script I have certain variables such as xp and level and methods like AddXP().
In the bonusXP script which I attached to a random object, when that one is clicked there needs to be added a certain amount of XP to the player. In this example I used 10. Now I had it working fine until I added the choose a character functionality. Before I would drag the player into the GameManager serialised field and stuff worked. Now that that one is gone. It stopped working. How do I add XP to a instantiated Player chosen by the user?
The Gamemanager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : Singleton<GameManager> {
public GameObject[] players;
public Transform spawnPoint;
private void Awake() {
int selectedC = PlayerPrefs.GetInt("selectedcharacter");
GameObject prefab = players[selectedC];
GameObject clone = Instantiate(prefab, spawnPoint.position, Quaternion.identity);
clone.AddComponent<Player>(); //attaches player script to the clone
}
// public Player CurrentPlayer {
// get
// {
// if (currentPlayer == null) {
// }
// return currentPlayer;
// }
// }
}
`
The BonusXP Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class XPBonus : MonoBehaviour {
[SerializeField] private int bonus = 10;
private void OnMouseDown() {
GameManager.Instance.CurrentPlayer.AddXp(bonus);
Destroy(gameObject);
}
}
The necessary parts of player script:
public class Player : MonoBehaviour {
[SerializeField] private int xp = 0;
[SerializeField] private int requiredXp = 100;
[SerializeField] private int levelBase = 100;
public void AddXp(int xp) {
this.xp += Mathf.Max(0, xp);
}
}