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

Question Goal for player 1 is scoring, Goal for player 2 is not..where am I going wrong?

Discussion in '2D' started by Jacobnichols80, Aug 29, 2023.

  1. Jacobnichols80

    Jacobnichols80

    Joined:
    Aug 13, 2023
    Posts:
    6
    I've scoured over this for 2 hours at this point, this is something I'm doing in my spare time as a hobby, so I'm learning pretty slowly. But, the goal for player 2 is not scoring, I will attach all of my scripts as well as the code. If someone could point out where I went wrong, I'd greatly appreciate it.
    The code for the goal system:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Goal : MonoBehaviour
    6. {
    7.     public bool isPlayer1Goal;
    8.  
    9.     private void OnTriggerEnter2D(Collider2D collision)
    10.     {
    11.         if (collision.gameObject.CompareTag("Ball"))
    12.         {
    13.             if (!isPlayer1Goal)
    14.             {
    15.                 Debug.Log("Player 1 Scored...");
    16.                 GameObject.Find("GameManager").GetComponent<GameManager>().Player1Scored();
    17.             }
    18.         }
    19.         else
    20.         {
    21.             Debug.Log("Player 2 Scored...");
    22.             GameObject.Find("GameManager").GetComponent<GameManager>().Player2Scored();
    23.         }
    24.     }
    25. }
    26.  
    The code for the Game Manager:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using TMPro;
    4. using UnityEngine;
    5.  
    6. public class GameManager : MonoBehaviour
    7. {
    8.     [Header("Ball")]
    9.     public GameObject ball;
    10.  
    11.     [Header("Player 1")]
    12.     public GameObject player1Paddle;
    13.     public GameObject player1Goal;
    14.  
    15.     [Header("Player 2")]
    16.     public GameObject player2Paddle;
    17.     public GameObject player2Goal;
    18.  
    19.     [Header("Score UI")]
    20.     public GameObject Player1Text;
    21.     public GameObject Player2Text;
    22.  
    23.     private int Player1Score;
    24.     private int Player2Score;
    25.  
    26.     public void Player1Scored()
    27.     {
    28.         Player1Score++;
    29.         Player1Text.GetComponent<TextMeshProUGUI>().text = Player1Score.ToString();
    30.         ResetPosition();
    31.     }
    32.     public void Player2Scored()
    33.     {
    34.         Player2Score++;
    35.         Player2Text.GetComponent<TextMeshProUGUI>().text = Player2Score.ToString();
    36.         ResetPosition();
    37.     }
    38.     private void ResetPosition()
    39.     {
    40.         ball.GetComponent<Ball>().Reset();
    41.         player1Paddle.GetComponent<Paddle>().Reset();
    42.         player2Paddle.GetComponent<Paddle>().Reset();
    43.     }
    44. }
    45.  
    The code for the ball:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Ball : MonoBehaviour
    6. {
    7.     public float speed;
    8.     public Rigidbody2D rb;
    9.     public Vector3 startPosition;
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         startPosition = transform.position;
    15.         Launch();
    16.     }
    17.     public void Reset()
    18.     {
    19.         rb.velocity = Vector2.zero;
    20.         transform.position = startPosition;
    21.         Launch();
    22.     }
    23.     // Update is called once per frame
    24.     void Update()
    25.     {
    26.  
    27.     }
    28.     private void Launch()
    29.     {
    30.         float x = Random.Range(0, 2) == 0 ? -1 : 1;
    31.         float y = Random.Range(0, 2) == 0 ? -1 : 1;
    32.         rb.velocity = new Vector2(speed * x, speed * y);
    33.     }
    34. }
    35.  
     
  2. Jacobnichols80

    Jacobnichols80

    Joined:
    Aug 13, 2023
    Posts:
    6
    And just to attach some more information, I have these selected in Unity under the scripts. To the bottom right.
    upload_2023-8-29_15-14-34.png
    This is for the player 1 goal
    This is the player 2 goal Also in the bottom right.
    upload_2023-8-29_15-15-17.png
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,752
    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
    Jacobnichols80 likes this.
  4. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,343
    It appears on your Goal script that you are never going to reach the Player2Scored. You Else logic is "Elsing" the wrong If block. It is Elsing the CompareTag, so you can only reach the Player2Scored if something other than a gameobject with the tag "Ball" hits the goal. Move it up inside of that If block so it is the Else to the !isPlayer1Goal If block.

    As a minor thing, your if block says !isPlayer1Goal, which means if it is false, add score to Player1, but you want that to be true. Just remove the !
     
    Jacobnichols80 likes this.
  5. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,343
    One more thing i just noticed, you are calling GameObject.Find("GameManager") which isn't very performant as it has to loop through all GameObjects in the scene to find one called GameManager. This is probably a larger list than just using FindObjectOfType<GameManager>() which loops through all gameobjects with the GameManager class attached, probably just one.
     
    Jacobnichols80 likes this.
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,752
    Oh my goodness, yes OP, for sure fix that noise!!! And while you're at it, fix those other horrible long GetComponent<T>() lines... those are just disasters waiting to happen.

    Remember the first rule of GameObject.Find():

    Do not use GameObject.Find();

    More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

    More information: https://forum.unity.com/threads/why-cant-i-find-the-other-objects.1360192/#post-8581066

    In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.

    If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way(tm) success of accessing things in your game.
     
    Jacobnichols80 likes this.
  7. Jacobnichols80

    Jacobnichols80

    Joined:
    Aug 13, 2023
    Posts:
    6
    You all helped me fix it, thank you so much! I'll look into all of those links as well. Here's to hoping I get better at debugging and figuring out myself lol