Check if Clone passed a certain position - Score Count

Hello! I’m a total Unity beginner and tried myself on a simple pong game. Here I simply instatiated a clone of a prefab ball when hitting space who moves. If it passes a certain x position (which is behind the pong bat) the score should increase. I asume I did simething wrong with the clones? Thanks for answers! (Before implementing hitting space feature and the ball just was there, not as a clone, everything worked)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class count_score : MonoBehaviour
{

public Text Scoreboard;
public GameObject Ball;
private int Bat_1Score;
private int Bat_2Score;


void Start()
{
  

}

void Update()
{
  
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Instantiate(Ball, new Vector2(0, 0), Quaternion.identity);

    }

    if (Ball.transform.position.x >= 11f)
        {
            Bat_1Score++;
            
        }

        if (Ball.transform.position.x <= -11f)
        {
            Bat_2Score++;
        }

        Scoreboard.text = Bat_1Score.ToString() + " - " + Bat_2Score.ToString();
        print(Bat_1Score + " , " + Bat_2Score);

    if (Bat_1Score == 10 || Bat_2Score ==10)
    {   Bat_1Score = 0;
        Bat_2Score = 0;

        Destroy(Ball.gameObject);

       

    }

}
}

Good day.

Yes you have “reference problems”.

Let me xplain this, In yur script, there is a variable called Ball. This Ball is a prefab stored in Unity memeory. But when you instantiate it, you aare creating a new object, and this object is not stored as a varaible in the script, so when you say Ball.transform.position… you are talking about the PREFAB, not the Instantiated ball in the scene, so you are not cheking the position of the ball in the scene, you are cheking the position of a stored prefab (not a real object.,…)

What you need, is to have 2 different variables. One fore the prefab and another for the object created in the scene (that will be a clone of the prefab)

So… you can do this.

First, have 2 variables, “Ball” and “SceneBall”. Ball needs to be public, because we will use it to store the prefab to instantiate, and SceneBall, will be a GameObject variable for this script, to know what is the object created. You have to instantiate it like this:

pubic GameObject Ball;
GameObject SceneBall;

void Start()
{
}

void Update()
{
     if (Input.GetKeyDown(KeyCode.Space))
     {
        SceneBall = Instantiate(Ball, new Vector2(0, 0), Quaternion.identity); 
     }
[......bla bla bla]

So now, you have a copy of Ball instantiated in the scene, and stored in the variable called SceneBall.

So now, all you want to do with the ball in the scene, must be done with the variable SceneBall, (not Ball)

Understand? :smiley:

Now change all “Ball” for “ScneBall” that is needed in your script.

Bye!!