Why cant i add to my score when my enemies die
In my game when you shoot the enemies i want the points to increase accordingly. this is my player script the score managerusing System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI;
public class Player : MonoBehaviour { public int health; public int score; public Text text;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (health <= 0)
{
Destroy(gameObject);
SceneManager.LoadScene(thisScene);
}
if (GetComponent<Enemy>().health <= 0)
{
score = score + 10;
}
if (GetComponent<TriangleEnemy>().health <= 0)
{
score = score + 5;
}
if (GetComponent<CircleEnemy>().health <= 0)
{
score = score + 1;
}
text.text = score.ToString();
}
}
Answer by Atenrev · Jul 29, 2019 at 05:16 PM
First of all, if I'm understanding it well, you are getting the enemy component from your player's class.
Secondly, you must think of giving another focus and don't check in the update the life of the enemy to perform the actions, but create a public function to be called by the player that do the stuff and check the life only when the player hits the enemy.
@Atenrev do you mean make a new function and then put the stuff thats in update in the new function and then call that function in update? Also the player never touches the enemy it "shoots" projectiles at the enemies the spawn in and run towards the player.
No, I mean to create a function that is called in the OnCollision. I guess you are using one to tell the enemy that it was touched. So, when the bullet touches the enemy, it should trigger an OnCollision on the enemy and then, call all the stuff you writted in that function. It's more efficient than checking it constantly.
@Atenrev So like this void OnTriggerEnter2D(Collider2D other) { if (health <= 0) { Destroy(gameObject); Scene$$anonymous$$anager.LoadScene(thisScene); } if (GetComponent().health <= 0) { score = score + 10; } if (GetComponent().health <= 0) { score = score + 5; } if (GetComponent().health <= 0) { score = score + 1; } text.text = score.ToString(); }
Your answer
Follow this Question
Related Questions
How to add one score every second to scoremanager c# 1 Answer
Highscore table C# HELP!!! 0 Answers
How do you add +1 to a score counter after a destroy script (C#)? 1 Answer
Increasing score based on speed 1 Answer
Strange (Pun2) RPC Problem. (With Error message that doesn't appear in a google search at all) 1 Answer