1

I am creating a GameObject with script and add components like:

card = new GameObject();
card.AddComponent<SpriteRenderer>();

...which works well.

What does not work is to add the script.s

I have a script, "KD_CardScript", stored in the Unity Editor, tested under Assets/Scripts as well as Assets/Resources and is trying to add that script to card using primarily:

card.AddComponent<KD_CardScript>();

...which does not work as it cannot find KD_CardScript. I have googled and tried a few other things with no success.

Is there anyone nice that can lead a blind and show how to do this?

PeterK
  • 4,243
  • 4
  • 44
  • 74
  • 3
    Post the complete code inside the `KD_CardScript`. Also, it would be good to how a screenshot of where the script is currently at at this moment. Do you get any error? If yes please post the error. Can you attach the script from the Editor manually? – Programmer Aug 22 '18 at 02:54

1 Answers1

0

It takes about a frame for Unity to create the gameObject that is why it can not add any scripts to it like that.
Instead of creating an empty game object just pass the scripts you want to attach to the constructor like that:

card = new GameObject("name", typeof(SpriteRenderer));

  • I am on mobile so double check the syntax
Aviv Biton
  • 100
  • 7