Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411500 Posts in 69373 Topics- by 58428 Members - Latest Member: shelton786

April 25, 2024, 11:36:43 AM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)Instantiating on wrong position? (HELP)
Pages: [1]
Print
Author Topic: Instantiating on wrong position? (HELP)  (Read 760 times)
Inner
Level 0
**


View Profile
« on: July 11, 2019, 07:22:46 AM »

Hi,
I trying to instantiate an object on a particular position but instantiates on a different position.
What's the problem here?

Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Instantiator : MonoBehaviour
{
    [SerializeField] GameObject cigarette;
    [SerializeField] Canvas parentCanvas;

    GameObject instantiatedCigarette;
    Vector2 firstCigarettePos;
    float startPosxCig = -946.0901f;
    float startPosyCig = -534.46f;

    private void Start()
    {
        firstCigarettePos = new Vector2(startPosxCig, startPosyCig);
        firstCigarettePos = Camera.main.ScreenToWorldPoint(firstCigarettePos);
    }

    public void InstantiateCigarette()
    {
        StartCoroutine(instantiateCoroutine()); 
    }

    IEnumerator instantiateCoroutine()
    {
        yield return new WaitForSeconds(1f);
        instantiatedCigarette = Instantiate(cigarette, firstCigarettePos, Quaternion.identity , parentCanvas.transform) as GameObject;         
        instantiatedCigarette.transform.SetParent(parentCanvas.transform , false);     
        instantiatedCigarette.transform.position = firstCigarettePos;                   
        instantiatedCigarette.transform.localScale = cigarette.transform.localScale;   
    }

}
Logged
Inner
Level 0
**


View Profile
« Reply #1 on: July 11, 2019, 08:54:51 AM »

Okay, I used transform.localPosition instead of transform.position
Logged
barta
Level 0
**


View Profile
« Reply #2 on: July 11, 2019, 08:55:27 AM »

i think the problem may be that you first instantiate the cigarette at firstCigarettePos, then you make it a child of a parent, and then, a line later, you define its position again at firstCigarettePos. i guess this is setting the cigarette's position in the parent's coordinates rather than the global coordinates, therefore it messes with where you want the cigarette to be. try scrapping that line and see if it gives you the result you want.
Logged
Pages: [1]
Print
Jump to:  

Theme orange-lt created by panic