Is it possible for the same method have different return types based on what is passed in, so that for example GetScripts(new Camera()) returns a Camera and GetScripts(new Cube()) returns a Cube?
I have three classes:
public class Script
{
}
public class Camera : Script
{
}
public class Cube : Script
{
}
I’ve also got a GameObject class which contains a list of Scripts and these methods:
public void RemoveAllSqripts()
{
Scripts.Clear();
}
public void AddScript(Script script)
{
Scripts.Add(script);
}
public Script GetScript(Type type)
{
for(int i = 0; i < Scripts.Count; i++)
{
if (Scripts[i].GetType() == type)
{
return Scripts[i];
}
}
return null;
}
I have code in the main program that looks like this:
GameObject go = new GameObject();
go.AddScript(new Camera());
go.AddScript(new Cube());
Camera camera = go.GetScript(typeof(Camera));
The code line: Camera camera = go.GetScript(typeof(Camera));
doesn’t work since GetScript returns a Script, not a Camera.
Is it possible to change the return type depending on what type you pass in as parameter, so that go.GetScript(typeof(Camera))
returns a Camera and go.GetScript(typeof(Cube))
returns a Cube?
I tried using generics for the first time (I don’t quite understand them yet) and I figured out that if I rewrote the GetScript() method to something like this:
public T GetScript<T>()
{
for (int i = 0; i < Scripts.Count; i++)
{
if (Scripts[i].GetType() == typeof(T))
{
return Scripts[i];
}
}
return default(T);
}
it would return the type if it exists in the list. The problem now is that return Scripts[i];
doesn’t work, and I don’t know why. Guess I need a lesson of how generics work.
I’ve tried looking at the microsoft documentation, but it didn’t help ’cause I only understood half of what was written.
I’m grateful for any help.
Waarnov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
9
This worked:
public T GetScript<T>() where T : Script
Thanks @shingo.
Link to solution
Waarnov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0