Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length

 
Advanced search

1366136 Posts in 64012 Topics- by 55898 Members - Latest Member: obemef

September 17, 2019, 09:10:33 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 157 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