Search Unity

Question Clone prefab reference during runtime

Discussion in 'Prefabs' started by Goty-Metal, May 2, 2021.

  1. Goty-Metal

    Goty-Metal

    Joined:
    Apr 4, 2020
    Posts:
    168
    So i have a GameObject with references via inspector to some prefabs i instantiate during runtime, ex:
    Code (CSharp):
    1. public GameObject prefab1;
    2. public GameObject prefab2;
    ...

    What i need is to COPY those prefabs during runtime because i need to modify some of their params depending on the scene WITHOUT instantiating it, something like:

    Code (CSharp):
    1. public GameObject prefab1;
    2. public GameObject prefab1Clone;
    3.  
    4. void Start() {
    5.     prefab1Clone = prefab1.Clone();
    6. }
    So i can do something like:

    Code (CSharp):
    1. ...
    2. prefab1Clone.GetComponent<CircleCollider2D>().radius = newValue;
    ...without messing up the original prefab, otherwise changes persist.
    And no i can't instantiate the prefab and then instantiate from that copy because theyr'e pretty complex GameObjects and i'd mess all the scene if i instantiate them to have them just as reference...

    Thanks for the help!
     
    Jilbarkus1900 likes this.
  2. Goty-Metal

    Goty-Metal

    Joined:
    Apr 4, 2020
    Posts:
    168
    After 3+ weeks i'm still interested and trying to find a solution, but i start thinking it's not possible...
     
    Jilbarkus1900 and fauzannr like this.
  3. efimovrusl

    efimovrusl

    Joined:
    Nov 6, 2020
    Posts:
    2
    Too late, but still..
    Just make a builder class for those prefabs and a scriptable object for storing various settings for different states, so that you could feed a builder singleton with prefab reference, scriptable object and receive a reference of a newly spawned GameObject.
    If there's a better approach, I would be glad to discuss that :)