- Home /
Unity 4.6 - Access Button By Script
I have a button on my stage ( Camera - > Canvas -> JumpButton).
I have prefab that is instantiated at runtime. That prefab has a VehicleController script (C#) that contains a Jump() function.
All I want to do is simply add listener (in my VehicleController script) to that button so that it fires the Jump() function.
I've seen this post: http://answers.unity3d.com/questions/779226/unity-46-getcomponentonclick-how-do-you-add-an-eve.html?sort=oldest but I cannot get it to work with my setup. I'm having trouble targeting or access by name the JumpButton that is already in the scene.
In my VehicleController script:
Button JumpButton = null; // assign in the editor?
void Start() {
//JumpButton = //How do I find the desired button in the scene?
JumpButton.onClick.AddListener(() => {MyJumpFunction(); });
}
Any help would be greatly appreciated.
Answer by Baste · Sep 11, 2014 at 08:09 AM
The JumpButton variable should be assigned by the thing that instantiates the Vehicle. So if you have a vehicleSpawner, you do something like this:
public Button JumpButton; //Assign in editor
void SpawnVehicle() {
GameObject vehicle = Instantiate(vehiclePrefab) as GameObject;
VehicleController controller = vehicle.GetComponent<VehicleController>();
controller.JumpButton = JumpButton;
}
If you do this, the VehicleController's Start will be run when the JumpButton assigned, and you can use it as you're doing it in the script. Hope that helps!
Great! Works - thank you! Tried to upvote but do not have enough reps...
Your answer
Follow this Question
Related Questions
endless 2D background in Javascript 0 Answers
How to get stereo webcam as Object texture? 0 Answers
How can I make an image maintain it's aspect ratio in Unity UI? 2 Answers
OnMouseUp open an external file 0 Answers
bug or a feature ?? 0 Answers