Hi,
I have a Enemy game object, to which I have attached a playerpref score manager script, which looks like this:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class scoreManager : MonoBehaviour {
public int score;
public Text scoreText;
void Start () {
PlayerPrefs.GetInt ("scorePref");
score = PlayerPrefs.GetInt ("scorePref");
}
void Update () {
PlayerPrefs.SetInt ("scorePref", score);
if (scoreText.name == "Score") {
scoreText.text = "Score: " + score;
}
}
}
This works just fine, my only problem is this. The Enemies are prefabs and have this script and the ‘Enemy move’ (below) scripts attached to them. However, when these enemies are instantiated, the score does not always go up, and when it does it jumps randomly.
I want to destroy the Enemy, when it collides with the bullet, but this then seems to mess up the score on the player prefs. Any ideas what’s happening? As you can see from the enemy script, the collision with the bullet should make the enemy disappear and the score go up by 5, but this doesn’t happen. The only way it works is when I comment out all the Destroy lines of code.
Thanks,
EnemyMove script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class EnemyMove : MonoBehaviour {
public Transform track;
private float moveSpeed = 3;
public Color damageColor = Color.red;
Renderer rend;
void Start() {
rend = GetComponent<Renderer> ();
rend.material.color = Color.white;
}
void Update () {
float move = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, track.position, move);
}
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "Bullet") {
rend.material.color = damageColor;
GetComponent<scoreManager> ().score += 5;
Destroy (GetComponent<MeshRenderer> ());
Destroy (GetComponent<BoxCollider> ());
Destroy (gameObject);
}
if (col.gameObject.tag == "Player") {
Destroy (gameObject);
}
}
}