Search Unity

Edit and save prefab with code

Discussion in 'Scripting' started by Maeve_, Sep 22, 2022.

  1. Maeve_

    Maeve_

    Joined:
    Feb 16, 2022
    Posts:
    4
    Hi !
    i'm a beginner so my question is maybe....stupid :oops: : how do i edit and save my prefabs by using script ? I want to create a script that can edit and save my prefab but i dont know how to do ><.
    I pretty sure that i need to use * Using UnityEditor * but i dont know more... i'm lost and i can't find any tutos like i want.
    So if u have any idea to help me it could be very usefull coz' i dont know how to start :,(
    thanks
     
  2. TinyPhxGames

    TinyPhxGames

    Joined:
    Jul 26, 2016
    Posts:
    31
    Hi Maeve!

    It's not too hard to do. What you're looking for is the PrefabUtility class. Specifically check out the PrefabUtility.SaveAsPrefabAsset.

    There's good sample code on that page. Looks something like this:

    Code (CSharp):
    1. PrefabUtility.SaveAsPrefabAsset(gameObject, localPath, out prefabSuccess);
    Good luck!
     
  3. Maeve_

    Maeve_

    Joined:
    Feb 16, 2022
    Posts:
    4
    hi !
    thx for the answer !!
    i still have a problem : visual cant found "prefabUtility"
    upload_2022-9-23_16-0-29.png
     
  4. TinyPhxGames

    TinyPhxGames

    Joined:
    Jul 26, 2016
    Posts:
    31
    Maeve_, that isn't saying it cant find it. Yellow lines like that are some type of suggestion, not errors. What happends when you run this?

    Also, you probably dont want to call the SaveAsPrefabAsset on every update, that will be more than necessary. You should have some kind of trigger. Perhaps only save on keydown like your're doing above.