0
votes

When spawning a Prefab, I'm trying to have each individual GameObject that makes up the Prefab run its own respective scripts. Basically, I want the Prefab to break after spawning; leaving individual game Objects.

I have the GameObjects in the Prefab as children of an Empty. Any suggestions.

enter image description here

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

public class CreateFab : MonoBehaviour
{
    public Transform Spawnpoint;
    public Rigidbody Prefab;

    public void OnClick()
    {
        Rigidbody RigidPrefab;
        RigidPrefab = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation) as Rigidbody;
    }

    public void DetachFromParent()
    {
        // Detaches the transform from its parent.
        transform.parent = null;
    }
}

Cube Script

using UnityEngine;
using UnityEditor;
using System.IO;

public class WallClick : MonoBehaviour
{
    string path;
    public MeshRenderer mRenderer;


    public void OpenExplorer()
    {
        path = EditorUtility.OpenFilePanel("Overwrite with png", "", "png");
        GetImage();
    }

    void GetImage()
    {
        if (path != null)
        {
            UpdateImage();
        }
    }

    void UpdateImage()
    {
        byte[] imgByte = File.ReadAllBytes(path);
        Texture2D texture = new Texture2D(2, 2);
        texture.LoadImage(imgByte);

        mRenderer.material.mainTexture = texture;
    }
}
2
Prefabs are already broken when the game is running. Changes to one spawned prefab do not affect others. If you mean unparenting them in hierarchy, set their transform.parent to null.Swift
I added 'transform.parent to null' to the spawn script but it didn't allow me to click on each individual cube in the prefab. I'll add the code I tried...user6411634

2 Answers

0
votes

If you spawn a prefab, give the spawned item a reference.

var obj = Instantiate(prefabGameobject);

You can then do whatever you like with the spawned object

var script = obj.AddComponent<YourScript>();

And you can then modify the variables of your script and so on. Your prefab will not be touched.

0
votes

The transform.parent you're using here refers to the transform of the gameobject your CreateFab.cs script is attached to, not the prefab's childrens (smaller cubes).

The correct way would be:

// Instantiate the prefab
RigidBody rigidPrefab = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation) as Rigidbody;

// Detach all children from the parent. Each child refers to the transform of a single cube.
foreach (Transform child in rigidPrefab.transform)
{
    child.parent = null;
}