- Home /
How do I use a function in a class more than once?
I am writing a script that will allow users to implement a GUI of the player statistics. One of the features is collision based showing and hiding. The following code throws Error CS0111: Type 'PlayerStatisticsGUI' already defines a member called 'OnTriggerEnter' with the same parameter types (CS0111)
Here is the code:
//Show player stats when trigger is collided with
private void OnTriggerEnter(Collider ShowTrigger) {
Show = true;
}
//Hide player stats when trigger is collided with
private void OnTriggerEnter(Collider HideTrigger) {
Show = false;
}
What is the solution to this? Is there a workaround?
Answer by christoph_r · May 27, 2014 at 10:29 PM
I don't think your code is doing what you think it does. By naming it ShowTrigger and HideTrigger you just assigned by which name you are going to call the collider that collided with your trigger. You need to tell your script what to do once a collider enters a trigger depending on certain conditions if you want different outcomes. In your case, you could simply write:
private void OnTriggerEnter(Collider col)
{
if(Show=true)
{ Show = false;}
else
{ Show = true;}
}
Or more elegantly:
private void OnTriggerEnter(Collider col)
{
Show = !Show;
}
This toggles the variable show whenever something enters the collider. By the way, variables usually begin with lower case characters so they're not confused with methods, for example.
Answer by seandanger · May 27, 2014 at 10:21 PM
You can't have 2 separate functions named the same in the same class, otherwise the compiler won't know which one is which.
The simplest thing you may need is to create 2 separate scripts, one for your HideTrigger, and one for your ShowTrigger. Otherwise, you could use some conditional code in your OnTriggerEnter function, like so:
public class TriggerExample : MonoBehaviour
{
public bool showOnTriggerEnter = false; // change this via the inspector as necessary
private void OnTriggerEnter(Collider trigger)
{
Show = showOnTriggerEnter;
}
}
Then you'd attach that component to each trigger, and set the showOnTriggerEnter variable to true for the one, and false for the other.
What do you mean create 2 different scripts? How would I make that work?
Answer by meat5000 · May 27, 2014 at 10:21 PM
Don't repeat the function.
Use (Collider trigger) and probe trigger to find the info you need. The name of the Collider inside those Argument brackets will have no bearing or connection to any actual world objects. It's just a receiver for information.
Answer by Kiwasi · May 27, 2014 at 10:32 PM
Here is the solution
private void OnTriggerEnter(Collider other){
if (other.name = "ShowTrigger"){
Show = true;
} else if (other.name = "HideTrigger"){
Show = false;
}
}
The why is slightly more complicated. Not sure how well I can explain it. You might want to refer to some c# tutorials