- Home /
How to make a button in FPS
Hi, I have a very simple question. I want a light to turn on, when player object is close to a light switch, and the player presses "E". Can you give an example of a script to do that?
Answer by Anton S. · Nov 26, 2010 at 06:25 PM
You could attach a collider set as trigger to the light switch and add this code to a script at the light switch:
function OnTriggerStay (other : Collider) {
if(other.parent.tag == "player" && Input.GetButtonDown("switch")){
SwitchLightOn();
}
}
It should call the function SwitchLightOn when the player comes into the trigger. You also have to set the tag of the player to player and define the button "switch" in the Input settings. I'm not sure if it'll work, i haven't tested it.
Hm Havent tried it yet, but I guess the player have to collide with the button, so I guess its not okay to just stand close to it?
All you would have to do is make the trigger collider a little bigger. Also to create a trigger for your light switch, create a cube/sphere , resize it until you have it the right size, then remove the mesh render and check 'Is Trigger' in collider settings
Okay. It seems to work, but If I have two objects : Switch and the Lamp, how do I turn the spotlight from the lamp on from a script attached to the switch?
You could add a public variable of the type GameObject to the switch and assign the Lamp to that Variable (In the Unity Editor). In your script you can run GetComponent(Lamp) on the variable and change its intensity value.
Your answer
Follow this Question
Related Questions
Click Once to play an entire animation 2 Answers
[Android] Why does my enemy die no matter where I am in the 3D environment? 1 Answer
Animate object on mouse button press 1 Answer
When my button is pressed the action reapeats 1 Answer
iOS Polygon button not working with yield WaitForSeconds 0 Answers