How to remotely (with a different C# script or js) activate function from the main C# script?
I've been searching and really havent found a solution that I could understand.
I want it as simple as possible, this is what I have:
C# function from my main script file called "mainScript.cs":
public void OpenBuyMenu ()
{
BuyMenu.enabled =! BuyMenu.enabled;
GameObject.Find("FPSController").GetComponent<FirstPersonController>().enabled =! GameObject.Find("FPSController").GetComponent<FirstPersonController>().enabled;
}
I want this function to execute when the player is within a trigger area of a certain object and the key M is pressed. Now I'm very new to C#, but in js I can build the script all the way up to activating the function above. This is the js file that could do all that:
private var enter : boolean; //this is enabled when the player is ontriggerentenr from the door
var ShowGUILabel : boolean = true; //Put it on if you want to read "press f to open the door" when you are near the door
function Update (){
if (Input.GetKeyDown(KeyCode.M) && enter == true)
{
//what goes here?
}
}
function OnGUI () {
if(ShowGUILabel == true && enter == true)
{GUI.Label(Rect(Screen.width / 2 - 100, Screen.height -100, 250, 100), "Press [M] to open Menu. ");}}
//Activate the Main function when player is near the door
function OnTriggerEnter (other : Collider){
if (other.gameObject.tag == "Player") {
enter = true;
}
}
//Deactivate the Main function when player is go away from door
function OnTriggerExit (other : Collider){
if (other.gameObject.tag == "Player") {
enter = false;
}
}
Now what I would like to know is, can I do this the easy way by adding some js coding on the spot where it says '//what goes here?" or maybe even better, how can I activate the function when the player is in the trigger area AND de M key is pressed by just using C#?
Thanks for the help!
Answer by Mich_9 · Nov 30, 2015 at 02:13 PM
You have to reference the mainScript.cs class in your other script, this is the code translate to C# of the Trigger Objetc.
using UnityEngine;
public class Trigger: MonoBehaviour
{
private bool enter; //this is enabled when the player is ontriggerentenr from the door
private bool ShowGUILabel = true; //Put it on if you want to read "press f to open the door" when you are near the door
public mainScriptClassName BuyMenu;//The reference of your mainScript.cs class
void Update()
{
if (Input.GetKeyDown(KeyCode.M) && enter == true)
{
BuyMenu.OpenBuyMenu();//Call the function OpenBuyMenu in mainScript.cs
}
}
void OnGUI()
{
if (ShowGUILabel == true && enter == true)
{
GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height - 100, 250, 100), "Press [M] to open Menu. ");
}
}
//Activate the Main function when player is near the door
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
enter = true;
}
}
//Deactivate the Main function when player is go away from door
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
enter = false;
}
}
}