Home > database >  Child GameObject use world position but must use parent position in Canvas
Child GameObject use world position but must use parent position in Canvas

Time:09-17

I create 2D game and I need Instantiate GameObjects (lines) in child, but when I set position to 0,0,0 in Instantiate my objects Instantiates in the center of scene but their position is 759, -150, -9720.


enter image description here

By arrows I show place where I want to Instantiate lines


My Instantiate code

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

public class SpectrumPartManager : MonoBehaviour
{
    public SpectrumPartObject spectrumPartObject;

    public void Start()
    {
        for (int i = 0; i < spectrumPartObject.linePositions.Length; i  )
        {
            Instantiate(spectrumPartObject.linePrefab, spectrumPartObject.linePositions[i], Quaternion.identity,
                transform);
        }
    }
}

ScriptableObject where I get position

[CreateAssetMenu(fileName = "Spectrum", menuName = "Spectrum")]
public class SpectumSettings : ScriptableObject
{
    public float spectrumLineWidth;
    public Vector3[] linePositions;
    public GameObject linePrefab;
}

CodePudding user response:

You are looking for Transform.TransformPoint. It takes 3 float (or int) as arguments.

Using it for your code:

float lpX = spectrumPartObject.linePositions[i].x;
float lpY = spectrumPartObject.linePositions[i].y;
float lpZ = spectrumPartObject.linePositions[i].z;

Vector3 modifiedPos = transform.TransformPoint(lpX, lpY, lpZ);

Instantiate(spectrumPartObject.linePrefab, modifiedPos, Quaternion.identity, transform);
  • Related