- Home /
How to call a function from another script in C# from array?
Here's the syntax error I get:
Assets/ScriptsNEW/PlayerController.cs(41,42): error CS1061: Type
UnityEngine.MonoBehaviour' does not > contain a definition for
deActivate' and no extension methoddeActivate' > of type
UnityEngine.MonoBehaviour' could be found (are you missing a using directive or an assembly reference?)
Here's some of the code:
private MonoBehaviour[] modes = new MonoBehaviour[3];
void Start()
{
modes[0] = (ModeA)this.GetComponent("ModeA");
modes[1] = (ModeB)this.GetComponent("ModeB");
modes[1].enabled = false;
modes[2] = (ModeC)this.GetComponent("ModeC");
modes[2].enabled = false;
}
void setMode(int s)
{
if(currMode==s){return;}
for(int i=0; i<modes.Length; i++)
{
if(modes[i].enabled == true)
{
modes[i].deActivate();
modes[i].enabled = false;
}
}
modes[s].enabled = true;
currMode = s;
}
Basically, what I want this to do is when it calls setMode, it deActivates all the other scripts. Because each script is a class all its own, I have to store them in an array of MonoBehaviour. Each script has the deActivate function but it won't work because its not default to MonoBehaviour. Do I have to make a new class of scripts called like, "Mode", or something and give them this deActivate function and then inherit from that for all these mode scripts. Is there a better way I'm missing?
But are you trying to deactivate the game object it is attached to?
Answer by pazzesco · Mar 17, 2013 at 05:10 PM
Probably the most sound way would indeed be to make a super class of "Mode", with an empty deActivate function that you can override and craft to your will. If you want to call the function on every MonoBehaviour residing on a GameObject, you could use SendMessage. In this case, you could make a parameter for deActivate on each of your "Mode" components that uniquely identifies that component. Something like this could work:
void setMode(int s)
{
if(currMode==s){return;}
this.SendMessage("deActivate", modes[s].GetType().Name, SendMessageOptions.DontRequireReceiver);
}
//...
//the deActivate function on each of your "Mode" MonoBehaviours
//...
void deActivate(string stayActiveTypeName) {
if (stayActiveTypeName != this.GetType().Name) {
//do deactivating stuff here
}
}
The problem with doing it the way I've shown is that you're going to have to repeat code for each Mode MonoBehaviour. You want to avoid that. But, unless you really hate inheritance, I'd suggest sticking with your original idea.
P.S. There is possibly a more sound method to using SendMessage in this manner. Personally, I liked your solution that inherits a base "Mode" type. It'd be very clean.
Also note that Send$$anonymous$$essage will try to call the deActivate method on ALL of your $$anonymous$$onoBehaviours on a particular GameObject. Things could get messy if you end up using the name "deActivate" on other components. You could elaborate the function names, such as "deActivate$$anonymous$$ode."