- Home /
Adding to score after passing an instantiated object
I'm working on a project for school where I need to make a Flappy Bird clone. In my project, I spawn enemies at a certain interval with a random Y-value by instantiating an enemy prefab. I need to make it so that the player gets awarded 10 points when their character passes one of these prefab instances. I have no idea how to figure out how to check if the player's x-position is greater than n number of the instances' x-positions. So far I managed to get this:
int score = 0;
public Text scoreText;
public GameObject player;
GameObject[] enemy;
bool[] passed;
void Update () {
enemy = GameObject.FindGameObjectsWithTag("Enemy");
//Debug.Log("There are " + enemy.Length + " enemies.");
for (int i = 0; i < enemy.Length; i++)
{
if (!passed[i])
{
if (player.transform.position.x > enemy[i].transform.position.x)
{
score = score + 10;
passed[i] = true;
}
}
}
scoreText.text = "SCORE : " + score;
}
but this way doesn't properly assign the instances into the enemy array. I get a null reference exception every frame. So, how can I check if the player is ahead of a certain number of enemies and add 10 points for each that they've passed?
Answer by KittenSnipes · Jan 29, 2018 at 02:38 AM
@zackarhino
I mean you could use a list to get the enemies and you could calculate the distance an enemy is away so you can get it not just from the x direction but from all directions. When did flappy bird have enemies? lol
Well here is an example script so hopefully you can learn from it. Cheers Mate:
This will be our script that does all the calculations:
//A null list to contain enemies
List<Transform> enemies;
//Reference to our players score
ScoreManager playerScore;
//Tag to find all our enemies
public string EnemyTagToFind = "Enemy";
//Max distance enemy is allowed from player
public float maxDistanceFromPlayer = 10;
//Score to add after enemy exceeeds our max distance from player.
public int ScoreToAdd = 10;
void Start()
{
//Make a new list for use later on
enemies = new List<Transform>();
//This will be the manager of the players score
//We modify this score later
playerScore = GetComponent<ScoreManager>();
}
void Update()
{
//When an enemy is removed from the list because it is dead
//This will say an error because it was modified
//You can ignore that error
//FindObjects(EnemyTagToFind);: Find Enemies based on the tag entered.
FindObjects(EnemyTagToFind);
//GetClosestEnemyDistance(enemies, maxDistanceFromPlayer);: Gets enemies
// Distance and
// Checks to see
// if it is too far
// from maxDistanceFromPlayer
GetClosestEnemyDistance(enemies, maxDistanceFromPlayer);
}
void FindObjects(string TagToFind)
{
if (enemies.Count < (GameObject.FindGameObjectsWithTag(TagToFind)).Length)
{
//Loops through all the enemies with this tag
for (int i = 0; i < GameObject.FindGameObjectsWithTag(TagToFind).Length; i++)
{
//Gets all of the enemy transform with the tag
if (enemies.Count < 0 || enemies == null)
{
//Adds them to our list
enemies.Add((GameObject.FindGameObjectsWithTag(TagToFind))[i].transform);
}
else
{
if (!(enemies.Contains((GameObject.FindGameObjectsWithTag(TagToFind))[i].transform)))
{
//Adds them to our list
enemies.Add((GameObject.FindGameObjectsWithTag(TagToFind))[i].transform);
}
}
}
}
else
{
//Loops through all the enemies with this tag
for (int i = ((GameObject.FindGameObjectsWithTag(TagToFind)).Length - 1); i >= 1; i--)
{
//Gets all of the enemy transform with the tag
if (!enemies.Contains((GameObject.FindGameObjectsWithTag(TagToFind))[i].transform))
{
//Adds them to our list
enemies.Add((GameObject.FindGameObjectsWithTag(TagToFind))[i].transform);
}
}
}
}
void GetClosestEnemyDistance(List<Transform> enemies, float distanceAllowedFromPlayer)
{
//This is our players position
Vector3 currentPosition = transform.position;
//This checks each enemy transform in enemies
for (int i = 0; i < enemies.Count; i++)
{
//This is the direction from our player to the enemy
Vector3 directionToTarget = enemies[i].position - currentPosition;
//This is the distance between them
float distanceSquaredToTarget = directionToTarget.sqrMagnitude;
//If our distance from the enemy is above or equal to our max Distance.
if (distanceSquaredToTarget >= distanceAllowedFromPlayer)
{
//Add our points to our score
DestroyEnemy(playerScore, ScoreToAdd);
//Change the tag of our enemy because it is no longer an enemy
enemies[i].tag = "Untagged";
//Remove it from our list because it is no longer an enemy
enemies.Remove(enemies[i]);
}
}
}
void DestroyEnemy(ScoreManager ScoreOfPlayer, int AddedScoreValue)
{
//Adds to our score managers score and shows it
ScoreOfPlayer.AddScore(AddedScoreValue);
}
This will be our script that manages our score:
//This is our text that shows our score
public UnityEngine.UI.Text scoreText;
//Our score reference
int score;
void Start()
{
//Set this to 0 at start
score = 0;
}
public void AddScore(int AmountToAddToScore)
{
//Add AmountToAddToScore to our score
score += AmountToAddToScore;
}
void Update()
{
//Change our score text to show our current score
scoreText.text = "Score: " + score;
}
Add both of these scripts to your player.
Your script untags the enemies before I pass them. I need the tags to be enemy for collision to work properly. There were also some typos that I had to fix. I think I'm just going to try to figure out a different solution, but thanks for the help.
Your answer
Follow this Question
Related Questions
Mouse position not returning actual position 0 Answers
Position + Vector3 doesn't return correct values 1 Answer
Object instantiates on top of the previous object 2 Answers
Infinity runner - best way to spawn board in runtime. 0 Answers
When flipping player, instantiated objects spawn on different spot. 2D shooting 0 Answers