Component as parameter
Hi, im not sure if it does exist, but i dont know how to do somthing like that:
public void myFunction(Component **script**)
{
gameObject.GetComponent<**script**>().function;
}
If anybody know how to do, pls help me if u can. Thanks
The "Component" you have in the parameter references an instance of an object of class type "Component", but the parameter in your GetComponent call, takes a CLASS as a parameter, like say.. "< Text$$anonymous$$esh >" or "".
So, It's not quite clear what goal you are trying to achieve here. It looks like what you want, is to be able to select one, of many possible components belonging to a game object. Which component you select, depends on the parameter you are passing. Then call a specific function, that is a member of that component. If so, a question: How do you know that whatever component you select, will actually have a function called "function"?
Have you taken a look at "Scriptable Objects" yet, http://docs.unity3d.com/ScriptReference/ScriptableObject.html? You $$anonymous$$AY want to use this class, rather than component.
Answer by RudyTheDev · Sep 19, 2015 at 02:39 PM
If I understand the intention correctly, which is to call the function on the given type of script, then there are a few ways to do this. Not sure if this is suitable for your exact problem, but an OOP organized way with generics would be something like this:
using UnityEngine;
public class TestClass : MonoBehaviour
{
private void Start()
{
gameObject.AddComponent<ExampleFunctionClass1>();
gameObject.AddComponent<ExampleFunctionClass2>();
DoFunction<ExampleFunctionClass1>();
DoFunction<ExampleFunctionClass2>();
}
private void DoFunction<T>() where T : MonoBehaviourWithFunction
{
gameObject.GetComponent<T>().Function();
}
}
public abstract class MonoBehaviourWithFunction : MonoBehaviour
{
public abstract void Function();
}
public class ExampleFunctionClass1 : MonoBehaviourWithFunction
{
public override void Function()
{
Debug.Log("Function from 1!");
}
}
public class ExampleFunctionClass2 : MonoBehaviourWithFunction
{
public override void Function()
{
Debug.Log("Function from 2!");
}
}
This works because C# knows any type derived from MonoBehaviourWithFunction
will have the Function()
and the DoFunction<T>()
knows that you will tell it which type to use.
This answers both the OP question, AND the question I asked the OP in my comment. +1
Your answer
Follow this Question
Related Questions
Is this bug known? function parameter s and if statements c# 1 Answer
How to set a bool from a script equal to another bool from another script? 1 Answer
Activating Scripts in another Script? 2 Answers
Network.Instantiate passing parametrs to instantiated object, unassigned reference exception 0 Answers
Instantiate after loading scene 0 Answers