maxel
maxel

Reputation: 29

how to instantiate a prefab in unity3d at position (2D Game)

enter image description hereenter image description hereI am trying to instantiate a prefab and I want it's location to be the exact same as the position of game object with name "spawnedPos" . Somehow the prefab is not instantiated on the exact same position.

code :

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

public class ShurikenSpawn : MonoBehaviour
{
    public GameObject[] gameReference;
    public GameObject spawnedShar;
    public Vector2 pos;
    public Transform playerPos;
    public float posX, posY;
    public Transform spawnedPos;
    
    void Start()
    {

     

    }
    private void Update()
    {
        spawnedPos = GameObject.FindWithTag("spawnedPos").transform;
        playerPos = GameObject.FindWithTag("Player").transform;
        //posX = playerPos.position.x;
        //posY = playerPos.position.y;
      //  pos = new Vector2(posX, posY);
        spawnedPos.position = playerPos.transform.position;
       
      
       // spawnedPos.transform.position = pos;
       
        if (Input.GetKeyDown(KeyCode.F))
        {
            spawnedShar = Instantiate(gameReference[0],spawnedPos);
           
         }
    }
    
}

enter image description here

Upvotes: 0

Views: 1145

Answers (1)

Soroush Hosseinpour
Soroush Hosseinpour

Reputation: 571

The code you are using for instantiation sets the parent of the object and not the position.

Use this:

Instantiate(gameReference[0],spawnedPos.position, Quaternion.identity ,spawnedPos);

Upvotes: 1

Related Questions