Search Unity

Question How can I store string in prefabs?

Discussion in 'Scripting' started by Metabeta, Jan 18, 2021.

  1. Metabeta

    Metabeta

    Joined:
    Apr 17, 2020
    Posts:
    7
    Hello there! I'm trying to spawn "prefabs" and then rename - write information on these items. (In running)
    Firstly, I tried store in "script". I select item with raycast and try to get its "script". But I don't get "script". I found some similar question in searching. They say, İf you change one items value, it change other items value. Because they connect same "script". I didnt expect that. Can anybody knows how can I set info to "prefabs" separatly?

    I hope I was able to explain myself.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    Sorry, I have no clue what you are asking.
     
  3. Metabeta

    Metabeta

    Joined:
    Apr 17, 2020
    Posts:
    7
    Lol. Okay let me say this way. I want to spawn many items and name them in the playing game. How can I do that. The name of each item will be different.
     
  4. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,996
    It's common to confuse the prefab with a gameObject created from it. Don't change the prefab while running. Common code looks like:
    Code (CSharp):
    1. public GameObject somePrefab;
    2. // don't change this
    3.  
    4. void Start() {
    5.   GameObject g1 = Instantiate(somePrefab);
    6.   // g1 is a normal gameObject, change it any way you like:
    7.   g1.transform.name="horsie";
     
    Last edited: Jan 18, 2021
    Joe-Censored and Brathnann like this.
  5. Metabeta

    Metabeta

    Joined:
    Apr 17, 2020
    Posts:
    7
    Oh, I told my problem wrong again. But thanks this information is useful for my another problem. I searched for some more and I found ScriptableObject, exactly the solution I was looking for. I want to be able to add things such as life, stamina, name, surname to the created prefab. But while the game was running I couldn't understand creating and editing a copy of scriptableObject.
     
  6. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    Note that scriptableObjects do not allow saving in builds. So if you plan to modify the data and try to save it back out in a build, it doesn't work.
     
  7. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,996
    ScriptbleObjects don't do anything prefabs don't. So you can use a prefab to do any ScriptabelObject tricks.. If you like how it works, you could turn it into a ScriptableObject (since making prefabs is easier than making SO's).

    An SO is really just a prefab with a different icon that can't be Instantiated. But that's a nice thing if you have a big project. You don;t need to remember "OK, this prefab holds the data, and should never be used except for that".