- Home /
Scoring System
Hi, I am currently in the process of making a space shooter game and have hit a bit of a wall when it comes to scoring. We currently have collisions working for the enemies and the bullets but we just need it to register the score every time an enemy is destroyed.
using UnityEngine;
using System.Collections;
public class EnemyMove : MonoBehaviour {
float speed = 3.0f; // move speed
float score = 0.0f;
void Update(){
GameObject target = GameObject.FindGameObjectWithTag("Player");
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed*Time.deltaTime);
}
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "bullet 2(Clone)")
{
Destroy(col.gameObject);
score += 1.0f;
Debug.Log(score);
}
}
void OnCollisionPlayer (Collision col)
{
if(col.gameObject.tag == "Player")
{
Destroy(gameObject);
}
}
}
We have declared the score a float and need it to register a + 1 when the enemy collides with the bullet, as it stands now the score just = 1 no matter how many enemies are destroyed rather than increasing the number further, any help would be greatly appreciated. Thanks
Answer by SkaredCreations · Mar 22, 2014 at 07:14 PM
You shouldn't store the score in a script that is attached to enemy if you're destroying the enemy object, because the variable belongs to the script attached to the object that you later destroy. You should store the score in your player script or alternatively you could declare "score" as static (and public if you want to access it outside of EnemyMove script).
public static float score = 0.0f;
That's actually a really good point haha. So if we were to add this to the player object, how would the statement look? because the collision happens between 2 different objects, those objects being bullet and enemy?
I usually declare a public static variable in my player script to easily access the current instance:
public class Player : $$anonymous$$onoBehaviour {
public static Player instance;
public int score = 0;
void Start() {
instance = this;
}
}
public class Enemy$$anonymous$$ove : $$anonymous$$onoBehaviour {
void OnCollisionEnter (Collision col) {
if(col.gameObject.name == "bullet 2(Clone)") {
Destroy(col.gameObject);
Player.instance.score++;
}
}
}
Don't forget to accept/vote the answer if it's what you looked for and/or adopt it, for the others understand that's it :)
Your answer
Follow this Question
Related Questions
How to add the right amount of points when my player destroys a gameobject? 0 Answers
How do I make my score go up upon a collision? 2 Answers
Multiple scores from collisions how do I stop after one collsion 3 Answers
I need help making my score not reset on Awake, but on a scene i have 0 Answers
Questions about Is Triggers and player collision. HELP! 2 Answers