Search Unity

Using Scriptable objects withouth IF

Discussion in 'Scripting' started by MrZeker, May 27, 2019.

  1. MrZeker

    MrZeker

    Joined:
    Nov 23, 2018
    Posts:
    227
    Hello.
    im trying to make a character selction, and im using Scriptable objects to store all the data of the character, such as stats, mesh, materials, skills, etc.

    so my question is, how can i make a way to set all the player settings into the CharacterX, ,withouth using just an IF statement for each character. (theres gonna be a lot of characters).
    `
    Code (csharp):
    1.  
    2.  
    3. public KCharacter Char1;
    4. private int characterID;
    5.  
    6.     [Header("Player Skin Slots")] //M1
    7.     public SkinnedMeshRenderer PlayerSkin;
    8.  
    9.     void Start()
    10.     {
    11.  
    12.         characterID = CharacterSelection.CharacterID;
    13. PlayerSelect()
    14.  
    15.     }
    16.     void PlayerSelect()
    17.     {
    18.  
    19.         PlayerSkin.sharedMesh = Char1.CharacterSkin;
    20.         PlayerSkin.materials = Char1.CharacterSkinMat;
    21.       }
    22.  
    This is just an eaxmple of the code im using. What i plan to do is just add char2,3,4, and so. Is there any way that i can tell unity to just use all the settings from CharX scriptable gameobject to replace the Player game objects?
    i cant use prefabs to replace the whole player.
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Don't hard code your player to use data from Char1, but from whatever character they've selected from the list of options.

    psuedocode:
    Code (csharp):
    1.  
    2. CharacterDataScriptableObject chosenCharacter;
    3.  
    4. void OnCharacterPortraitClickedViaUserInterface(Portrait portrait)
    5. {
    6.    chosenCharacter = portrait.characterDataScriptableObject; // portrait stores a reference to the character SO that this portrait represents
    7. }
    8.  
    9. void OnStartGame()
    10. {
    11.     Character prefabInstance = Instantiate<Character>(); // "blank" character
    12.     prefabInstance.hat = chosenCharacter.hat; // fill in the data from our chosen character SO
    13.     prefabInstance.dance = chosenCharacter.dance;
    14. }
    15.  
     
    MrZeker likes this.
  3. MrZeker

    MrZeker

    Joined:
    Nov 23, 2018
    Posts:
    227
    Thanks, that was really usefull!