Hey guys, Im still pretty new to coding, and Im having some trouble with a coding concept, hopefully you guys can help. Is it possible to pass types through a method?
public class CoolClass {}
void GameObject CoolMethod(Type coolType)
{
GameObject coolObject = FindObjectOfType(coolType) as GameObject;
return coolObject;
}
someGameObject = CoolMethod(CoolClass);
The error I get is “CoolClass is a type, which is not valid given the context”, which is confusing to me 
You can’t cast a class as a gameobject. If CoolClass were a monobehaviour class you could use something like (GameObject)FindObjectByName(whatever).GetComponent() because it would find the object, return it and allow you to operate on that reference to dig further.
Also since it’s a basic class and not a monobehaviour it would never exist in the scene anyway, so Find would never find anything our help you get a reference to that class directly without a monobehaviour class containing a reference to that basic class.
If you give a little more practical example it would be a bit easier to give some more specific feedback. You’re basically looking for information on Casting, Types, maybe generics.
1 Like
Agreed — as you said you’re still new to coding, I’m pretty sure what you’re trying to do, even if it were possible, would be the wrong way to solve whatever problem you actually need to solve.
So, please back up and describe what task you’re trying to accomplish, and we’ll be able to suggest the normal way of going about it.
Interesting! My bad for the sloppy code, it would indeed be a MonoBehaviour in a script attached to an object in the game.
Effectively I was looking for a way to find gameobjects with multiple scripts attached to them (like if I wanted to find an object that had both a “BadGuy” and a “Soldier” component), and have been using things along the lines of :
GameObject = coolThing;
GameObject[] coolArray = GameObject.FindObjectsOfType<CoolClassName>();
for (int i = 0; i < coolArray.Length; i++)
{
if (coolArray[i].GetComponent<SecondCoolClassName>() != null)
{
coolThing = coolArray[i];
}
}
I went to make a quick extension with a few overloads to make my code a little cleaner, and ran into my problem.
Pass the types as generic arguments
V SomeMethod<T, V>() where T : Component, where V : Component
{
T[] ts = FindObjectsOfType<T>();
if (ts != null)
{
foreach (var t in ts)
{
var v = t.gameObject.GetComponent<V>();
if (v != null) return v;
}
}
return null;
}
// find the first SomeScript that is attached to a GameObject that also has AnotherScript attached
SomeScript ss = SomeMethod<AnotherScript, SomeScript>();
1 Like
Thats perfect, learned something new. Now Im off to study up on generics! Appreciate the help guys!
1 Like