Hi everyone!
Im currently starting a card game project and the way I give my cards information of what they are is through Scriptable Objects.
I have a card Prefab with a variable to put an Scriptable Object on it and when the card is created it shows the info just fine.
My problem is: How do I instantiate the card prefab and attach a scriptable object of my choosing through a script? For now im trying to do it but I cant access the script variable to change it when the card is instantiated
You can either create a MonoBehaviour foreach card or have a Script that is handling all the cards. The first one is easier so I will show just that.
I suppose you have a scriptable object similar to this one:
using UnityEngine;
[CreateAssetMenu(fileName = "Card", menuName = "ScriptableObjects/Card")]
public class CardScriptableObject: ScriptableObject
{
public int health;
public int attack;
public int defense;
public int manaCost;
}
You need to create a MonoBehaviour class that stores the reference of this ScriptableObject:
using UnityEngine;
public class CardHandler: MonoBehaviour
{
public CardScriptableObject cardScriptableObject;
}
And now you can Instantiate the card and keep track of the associated ScriptableObject:
private void CreateCard(CardScriptableObject cardScriptableObject){
Transform cardTransform = Instantiate(cardPrefab).transform;
CardHandler cardHandler = cardTransform.gameObject.AddComponent<CardHandler>();
//This isn't very good programming, you should use getters and setters but it works
cardHandler.cardScriptableObject = cardScriptableObject;
}