Search Unity

Changing Prefab values at runtime

Discussion in 'Scripting' started by CDF, Mar 4, 2015.

  1. CDF

    CDF

    Joined:
    Sep 14, 2013
    Posts:
    1,311
    Hi, so I was wondering if I can alter a prefab at runtime? so that when instantiating objects from that prefab they receive the changed values.

    This seems to work in the Editor play mode. But as soon as I run the app on Android or iOS, changing the prefab doesn't seem to save the values. Upon loading a new scene, the prefab reverts to its "build" state, that is, the state it had when the app launched.
     
  2. roger0

    roger0

    Joined:
    Feb 3, 2012
    Posts:
    1,208
    Hello. So how are you trying to change the prefab values while in the Android/iOS app version? I dont think you can change prefab values while in game. You will need to store the values in a script that will change the prefab right upon Instantiation. Then when a new scene is loaded, use dontDestroyOnLoad on the object that has the script, which has the stored values to carry it onto the other scene.

    Or you could do something with PlayerPrefs. There's a couple different ways.
     
    dahiyabunty1 likes this.
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    I've never tried editing a prefab at runtime, but if you can't get it to work, you could try this instead:

    Place a copy of the prefab into your scene.
    Uncheck the "active" box.
    Give your instantiation script a reference to the inactive object in your scene, instead of the prefab.
    Whenever you instantiate a copy, call .setActive(true) on the new copy.

    Since the object is inactive, it shouldn't affect your game, but now you can edit an object instead of a prefab.
     
  4. AlejandroBoss10

    AlejandroBoss10

    Joined:
    Sep 1, 2017
    Posts:
    7
    Ok, @Antistone that was absolute GENIUS! I was wondering on how to do that for a while now and I can't believe how simple it is. I managed to get this to work very simply and I'm genuinely surprised. Thank you so much for this!
     
  5. rocketlaunchers59

    rocketlaunchers59

    Joined:
    Jun 20, 2022
    Posts:
    1
    How do you reference the object in the scene if you can drag that into the script because the script is on a prefab?
     
    unity_x-kw2EjEFbuaaA likes this.