- Home /
Unity2D button as child of camera not clickable
I have this character that jumps on left click:
public class Punch : MonoBehaviour
{
public Rigidbody2D rb;
public bool clicked;
public Vector2 direction;
public static Punch instance;
// Start is called before the first frame update
void Start()
{
instance = this;
rb = GetComponent<Rigidbody2D>();
clicked = false;
direction = new Vector2(500f, 250f);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && (clicked == false))
{
rb.AddForce(direction);
print("left click");
clicked = true;
}
}
In order for the camera to follow this character, I made the camera a child of the character. This works fine. Now I added an object "Button" in the top left corner of the camera and made it a child of the camera to follow the camera exactly (and stay in the top right).
When I use this script on my button:
private void OnMouseDown()
{
Punch.instance.clicked = false;
print("TEST");
}
it does not print "Test" or reset the "clicked" variable to false. If the button is not a child of a camera, but on the same hierarchy as the character, the button works but obviously won't follow the camera / character.
What am I doing wrong and how can I fix this?
Answer by Cloky · May 18, 2020 at 12:34 PM
To anyone wondering: I found a solution (or more of a workaround) for this problem myself.
Instead of having a button as a object in the game itself, just create a UI and add the button there. This makes the management way easier and you don't have to tell the button to follow anything manually.
For the UI Button I am now using this script:
public class Reset_Button : MonoBehaviour
{
public void ResetButton()
{
Punch.instance.clicked = false;
}
}
This isn't really a workaround, as buttons are always considered to be UI and, therefore, should always be part of the canvas. If you want it to work well with any camera size, make sure to set the canvas Render $$anonymous$$ode to Screen Space - Camera and set the Render Camera to the main camera in your scene. Then, change the UI Scale $$anonymous$$ode in the Canvas Scaler component to Scale with Screen Size.
Thanks for adding this knowledge! I indeed set the main_camera to the canvas' camera for it to work properly.
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Child affecting parent rigidbody? 1 Answer
How do I have a Child tell a Parent to move without the Child itself moving 0 Answers
parent object rotate with child camera 1 Answer
Line up camera views 0 Answers