Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by $$anonymous$$ · Jan 29, 2018 at 12:16 AM · 2dinstantiateposition

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image $$anonymous$$ · Jan 29, 2018 at 06:48 PM 0
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

171 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges