charlieyin
charlieyin

Reputation: 411

How to change the transform position of an instantiated GameObject?

Very basic beginner question: I'm making a brick breaker Unity game and I want my instantiated ball to spawn on the paddle and follow the paddle until I click my mouse. I'm expecting my code to work, but it just spawns a ball and does not follow the paddle around when instantiated. I've tried putting this code on my ball prefab script, but I am unable to reference the GameObject paddle from the prefab.

public bool isActive;
public GameObject ball;
public GameObject paddle;

// Start is called before the first frame update
void Start()
{
    isActive = false;
    SpawnBall();
}

// Update is called once per frame
void Update()
{
    if (isActive == false)
    {
        ball.transform.position = new Vector2(paddle.transform.position.x, paddle.transform.position.y);
    }
}
private void SpawnBall()
{
    // spawn a ball on top of the paddle
    Instantiate(ball, new Vector2(paddle.transform.position.x, paddle.transform.position.y + 0.4f), Quaternion.identity);
}

Upvotes: 0

Views: 782

Answers (1)

asker
asker

Reputation: 346

Try using the Insatiate overload which takes in the transform of the parent:

Instantiate(Object original, Vector2 position, Quaternion rotation, Transform parent);

So you could do this:

Instantiate(ball, new Vector2(paddle.transform.position.x, paddle.transform.position.y + 0.4f), Quaternion.identity, paddle.Transform)

Upvotes: 1

Related Questions