0
\$\begingroup\$

I want to have a script in my game that adds a card.

I am using a Card class for all my cards, so I don't have to make a prefab for each card. Instead I can do something like: Card fire = new Card("blah blah"); to define a "fire" card type, then call fire.Generate(position) to create a card sprite of that type at the given position.

Somehow I need my Generate() method to add a new object (sprite) to the game when called. How can I do that?

CardGenerator.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CardGenerator : MonoBehaviour
{
    Card makeYellow;

    private void Start()
    {
        makeYellow = new Card("Make Yellow", "This card makes the player yellow.");
        makeYellow.Generate(Vector2.zero);
    }
}

Card.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Card
{
    public string Name;
    public string Description;
    private Sprite sprite;
    private SpriteRenderer sr;

    public Card(string name, string description)
    {
        Name = name;
        Description = description;
    }

    public void Generate(Vector2 pos)
    {
        // ...
    }



}
\$\endgroup\$
0
1
\$\begingroup\$
public SpriteRenderer Generate(Vector2 pos)
{
    // Add a new game object named after this card to the Active Scene.
    var card = new GameObject(Name);

    // Attach a SpriteRenderer component to this object.
    var spriteRenderer = card.AddComponent<SpriteRenderer>();

    // Assign the sprite you want the card to display.
    spriteRenderer.sprite = sprite;

    // Position the card where you want it to appear.
    card.transform.position = pos; 

    // Return a reference to this object in case other code wants to manipulate it.
    return spriteRenderer;
}
\$\endgroup\$
2
  • \$\begingroup\$ ...or you could use prefabs like a normal person :) \$\endgroup\$
    – Philipp
    Nov 29 '21 at 8:45
  • \$\begingroup\$ There are legitimate reasons why someone would prefer to construct certain objects in code rather than create a prefab for each one, so I think this is still a valid way to do things, if somewhat unconventional as a Unity idiom. \$\endgroup\$
    – DMGregory
    Nov 29 '21 at 12:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .