- Home /
How to get variables from other Scripts on trigger enter?
Hello,
in my project, I have a DialogManager. This Manager can handle a Dialog parsed by a XML-Reader. This works fine. But now, I have more than one dialog. My idea (or my question): Get the name, or id of this NPC, if the player collides with them.
Process: Player collides with NPC A - press 'E' and a dialog (specified to NPC A) appears. The Player moves forward and collides with NPC B - press 'E' and a other(!) dialog appears.
Am I correct in this way?
Structure:
Player has a script 'DialogManger.cs' NPCs have a script 'ShowName.cs' - there is a variable 'NPCName' - this variable should be used for open different dialogs.
Thanks for reading.
Greetings,
V4mpy
Answer by mattssonon · Oct 16, 2013 at 11:12 AM
You could get a hold of the name like this:
void OnTriggerEnter(Collider other) {
string name = other.gameObject.GetComponent<ShowName>().NPCName;
}
If you make name global, e.g. declare it outside of the function, you could check which name is currently set when the 'E' key is pressed to show the proper dialogue.
Thanks for your reply. This solution sounds right and easy. But seems not to work or i am doing it wrong.
ShowName npc = other.gameObject.GetComponent<ShowName>();
if(!npc)
Debug.Log("you are wrong here...");
if(npc)
Debug.Log(npc.NPCName);
I tried this.
ShowName is on my NPCs and my Player. Is that necessary?
Btw: Same Exception.
You tried it, but what happens? And no, ShowName does not have to be on Player.
Sorry, this "Btw: Same Exception" respective to my problem. In this code above, unity display all the time "you are wrong here...".
For my understanding:
A gameobject (other) collides (in 'OnTriggerEnter') with the player. Than, my code should get the component ShowName(Script). Is that correct?
void OnTriggerEnter(Collider other) {
string name = other.gameObject.GetComponent<ShowName>().NPCName;
}
This should be in a script on Player. The ShowName script should be on the NPC the Player collides with. And yes, when the NPC collides with Player, OnTriggerEnter is called in the script on the Player and other.gameObject is the NPC object.
Hm...you are right. THIS works fine. Also in my case. $$anonymous$$y problem was: I had a Cube (my NPC) and a DialogTrigger (empty gameobject), this trigger was subordinate of the NPC. So my NPC had 2 collider...it work's now. Big thanks for your reply, you opened my eyes.
Your answer
Follow this Question
Related Questions
[C#] How to destroy a wall next to my trigger? 2 Answers
OnTriggerEnter() not called 1 Answer
Problems when i have multiple enemies on the same scene C# 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer