Create an object based on a Prefab from a script

Page update date :
Page creation date :

Verification environment

Windows
  • Windows 11
Unity Editor
  • 2021.3.3f1
Input System Package
  • 1.3.0

Prerequisites for this tip

The following settings have been made in advance as a premise for the description of this tip.

Create an object based on a Prefab in a script

In the previous Tips, we placed objects from the Prefab to the view, but in this case, we place a predetermined number of objects and launch the game. However, some games may want to add objects dynamically while the game is running. In that case, you will have to add it from the prefab in the script.

Sample creation

After deploying the new project, place the button. Let's try to generate an object from the prefab every time we click the button.

Create a prefab. This is the same procedure as the previous tips.

Create a script to add the object the next time you click the button. ButtonEvent Leave the name as .

using UnityEngine;

public class ButtonEvent : MonoBehaviour
{
  [SerializeField] private GameObject SpritePrefab;

  public void OnClick()
  {
    // Instantiate にプレハブを渡すとそれをもとに新しいオブジェクトを生成する
    var obj = Instantiate(SpritePrefab);

    // 配置位置はランダムに
    obj.transform.localPosition = new Vector3(Random.value * 6 - 3, Random.value * 6 - 3);
  }
}

GameObject Define the field so that you can set which prefab to be generated based on in advance.

Instantiate You can pass a method to create a GameObject new object based on that object.

The position of the created object becomes the origin, and no matter how many objects are created, the objects overlap and it is difficult to understand, so the position is set randomly after creation. The position adjustment value is appropriate because it is a sample.

Attach the script to EventSystem.

GameObject is set so drop the prefab here.

When the button is clicked, the method is OnClick called.

Sample Execution

Once created, run the game and click the button. Each click should generate an object.

Of course, since it is generated based on the prefab, if the value of the prefab changes, the generated object will be generated according to that value.