How to get reference to a script component despite its name C#?

Hey all,

I’m making a card game. Each card has an individual script which holds that card’s value and details. It’s not efficient but its what I’m working with at the moment.

I would like to get a reference to the script component on each card so I can drill down to the cardValue variable in each.

I’ve tried cardScript = GameObject.FindObjectOfType(Script);

But Script doesn’t exist in the current context.
Thanks

how else would you store instance specific data per card? :face_with_spiral_eyes: or do you mean you have a script called “Ace Diamonds” then another called “Two Diamonds”, then another called “Three Diamonds” (if so, this is where your problem is, don’t “work around it” fix this first)? :hushed:

then you’ll be wanting “FindObjectsOfType” to pick up all of them.

“script” in you example is the name of the script file you’ve created (hopefully something like “Card”)

there are several variants for these kinds of functions, I prefer the generics so

Card[] cards = FindObjectsOfType<Card>();

but there is also

Card[] cards = FindObjectsOfType(typeof(Card));

and probably one which works off the string, but ewww to that one.

Polymorphism is your friend here. You want each individual card to either inherit from a common base, or implement a common interface.

1 Like

I don’t think that’d what I’m after. It’s a better way but for now I’d like a way to get a reference to the script on the card object. As you said they all have different names such as twodiamonds and threediamonds. They only have one script per card object. Is there a way.

Yeah definately. Version 2 will have more polymorphism.

Polymorphism is your friend here. You want each individual card to either inherit from a common base, or implement a common interface.

If you don’t want to do that, you are looking at a long hard slog involving reflection and type checking and all sorts of crazy nonsense. You really don’t want to go down that path.

Stop. Refactor your code to provide a single interface or base class. Then continue.

Okay, it will be better in the long run. Thanks for your help.

It will also be better in the short run. Trust me. Its faster to do it this way then any alternative you can devise.

You would need to call something like:

cardScript = GameObject.FindObjectOfType();

So, if the script on one card was called SuperCoolCard, even if it inherits from a MonoBehaviour, like SuperCoolCard : MonoBehaviour, you would call:

cardScript = GameObject.FindObjectOfType(SuperCoolCard);

But then you wouldn’t be able to use the same call for each card. This is why people keep saying that you need to use polymorphism.