Object Generation Hierarchy

Asked 1 years ago, Updated 1 years ago, 79 views

I use unity.
I generated an object with instantiate.
If you are not in canvas, you cannot use the ugui button, so you must generate it in canvas.

Therefore, to create a hierarchy within canvas by specifying it as within canvas,
How should I write it?

This is what I'm writing right now

intenemyIndex=Random.Range(0,enemy.Length);
Instantiate(enemy[enemyIndex], new Vector3(0,3,0), transform.rotation);

c# unity3d

2022-09-30 20:59

1 Answers

Although it is difficult to generate objects directly within Canvas,
You can use SetParent() to place transforms of objects created in Instantiate() into a hierarchy within Canvas.
http://docs.unity3d.com/jp/current/ScriptReference/Transform.SetParent.html

However, you need to get the transform for Canvas.
 There are several ways to retrieve it, including:
 Try the easiest way to get it from your current project.

1. Set Canvas on the editor by serializing the Canvas member variables.

public class EnemyManager:MonoBehavior
{
    SerializeField
    private Canvas m_canvas = null;

} // class EnemyManager

Enter a description of the image here

2. Search and retrieve Canvas from the entire Hierarchy
(If you have more than one Canvas, it's hard to get a specific Canvas.)

var canvas=GameObject.FindObjectOfType<Canvas>();

3. Embed a specific tag into Canvas, searched and retrieved from the tag.

Enter a description of the image here

var canvas=GameObject.FindGameObjectWithTag("CanvasTag");

After Canvas is retrieved, SetParent() is used in the following ways to place the generated objects in Canvas:
 The following code uses "2. Search and retrieve Canvas from the whole Hierarchy" to obtain Canvas.

using UnityEngine;
using UnityEngine.UI;

public class EnemyManager:MonoBehavior
{
    SerializeField
    private Button [ ] m_enemyList = null;

    void Start()
    {
        CreateEnemy();
    }

    private void CreateEnemy()
    {
        intenemyIndex=Random.Range(0,m_enemyList.Length);
        varenemyObject=Instantiate(m_enemyList[enemyIndex], new Vector3(0,3,0), transform.rotation) as Button;

        varcanvas=GameObject.FindObjectOfType<Canvas>();
        enemyObject.transform.SetParent(canvas.transform, false);
    }

} // class EnemyManager

Please refer to it.


2022-09-30 20:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.