Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Add 1 point when GameObject is in scene

Discussion in 'Scripting' started by rudigreig, Dec 4, 2020.

  1. rudigreig

    rudigreig

    Joined:
    Dec 11, 2018
    Posts:
    50
    My game spawns traffic cars into a scene.
    I want to make it so that if a traffic car with the tag "CarPoints" is spawned, it adds a point
    Here is my script:
    Code (CSharp):
    1.     [SerializeField]
    2.     private Text scoreText;
    3.     public GameObject[] cars;
    4.     void Update()
    5.     {
    6.         cars = GameObject.FindGameObjectsWithTag("CarPoints");
    7.  
    8.         foreach (GameObject car in cars)
    9.         {
    10.             Score = Score + 1;
    11.  
    12.         }
    13.     }
    14.     private int score;
    15.  
    16.     public int Score
    17.     {
    18.         get { return score; }
    19.         set
    20.         {
    21.             score = value;
    22.             scoreText.text = "Cars Hit: " + score.ToString();
    23.         }
    24.     }
    25.  
    26.     private void Awake()
    27.     {
    28.         Score = 0;
    29.     }
    right now whenever I start the scene, the Score value just keeps going up
    anyone know how to do this properly?
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    well, what you do is basically search nonStop in the "Update" loop for GameObjects with a certain "Tag",

    and whenever any car is found, your points go up, what you want to do is to have a spawner which handles that,
    not in an update loop but by Events or any calls,

    I mean, how many cars do you want to spawn in total?
    do the cars have spawn points, or is it random?
    when do you want to spawn more cars additionally?
     
  3. rudigreig

    rudigreig

    Joined:
    Dec 11, 2018
    Posts:
    50
    I figured it out!
    I decided to reverse the system and use unity's messaging system
    it now sends a message from an empty gameobject parented to the car prefabs to any scoremanager objects and then sets itself inactive so that it only sends 1 extra point

    It may be a little janky, but it works
    shame you can't delete forum posts afterwards
     
  4. zurisar

    zurisar

    Joined:
    Nov 4, 2019
    Posts:
    24
    I don't sure that I understand right, you need to add point when car with point spawned.
    If so, you can do next:
    Attach to car with point prefab script in start function call UnityEvent onCarWithPointSpawn, in your scores script listen for this event and do what you want(add scores, update UI and so on)
     
    rudigreig likes this.