0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unityでオブジェクトの複製と動的削除

Posted at

 クリックすると、Cubeが生成され、積み上がるサンプルです。Cubeはprefab化し、Asset内に保持してあり、クリックによりInstantiate命令が実行され、シーンに追加されます。下方には、こぼれ落ちたCubeを削除するための平面とスクリプトが設置されています。
スクリーンショット 2021-01-13 2.01.14.png

0、Edit>ProjectSetting>PhysicsのGravityのyを-50にする
1、sceneにCubeを作成する
2、Cubeにrigidbodyを追加する
3、AssetsにResourcesフォルダを作成する
4、CubeをResourcesフォルダにドラッグ&ドロップし、prefab化する
5、sceneのCubeは削除してしまう
6、Planeで地面groundを作成する
7、新規にスクリプトaddBox.csを作成し、groundに追加する
8、groundからこぼれるCubeを消すため、Planeでdelを作成する
9、新規にスクリプトdelObj.csを作成し、delに追加する

addBox.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class addBox : MonoBehaviour
{
    void Update(){
        if (Input.GetMouseButtonDown(0)){
            Shot();
        }
    }
    void Shot () {
        GameObject dup = (GameObject)Resources.Load ("Cube");
        Vector3 pos = new Vector3(
            Random.Range(-1f,1f),
            5,
            Random.Range(-1f,1f));
        Instantiate (dup, pos, Random.rotation);
    }
}
delObj.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class delObj : MonoBehaviour
{
    void OnCollisionEnter(Collision c) {
        Destroy(c.gameObject);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?