Home > other >  How to change the transform position of an instantiated GameObject?
How to change the transform position of an instantiated GameObject?

Time:07-10

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);
}

CodePudding user response:

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)

  • Related