V
V
Vyacheslav Marvin2020-04-20 08:15:46
Unity
Vyacheslav Marvin, 2020-04-20 08:15:46

How to change the position of a child object on creation (curatin)?

Hello.

When creating a child game object, let's say Cube , I want to change its position relative to the parent, according to the parent's vector, but so far I'm at an impasse.

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

public class Strike : MonoBehaviour
{
    public GameObject Cube;

 public void  SetParent(GameObject Sphere)
    {
        Cube.transform.parent = Sphere.transform;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
            StartCoroutine(instObj());

        Cube.transform.position = transform.position;
    }

    IEnumerator instObj()
    {
        yield return new WaitForSeconds(0f);
        Instantiate(Cube);
    }
}

What was enough for me is
instCube = Instantiate(Cube) as GameObject;
instCube.transform.localPosition = new Vector3(0f, 25f, 0);
instCube.transform.position = transform.position;

But that didn't help at all. It also creates a child object inside the parent object. Even with such a large Y value.

Please tell me. In what direction should I move in order to solve this problem. Because I don't have much experience. What to read, what to study?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Gaydak, 2020-04-20
@MrMureno

so let's try to figure it out

instCube.transform.localPosition = new Vector3(0f, 25f, 0);
instCube.transform.position = transform.position;

in the first line, you have shifted the local position (relative to the parent, if it exists at that moment).
then in the next line you assign GLOBAL coordinates to the same object.
You are overwriting the values ​​previously set (perhaps thinking that the offset will somehow additionally remain).
You either need to add an offset for the child object all the time or stop moving (changing) it and change the coordinates / move the parent.
Plus, after Instantiate - do not forget to assign a parent first, by default there is Null and the object will simply be at the root of the hierarchy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question