
It looks like you're new here. If you want to get involved, click one of these buttons!
Hi,
I need help for creating an in game button (not in a UI) but as a object. For EX- a button to open a gate but for mobile platform.
will anyone pls help me with that. I wold be really thankful.
π
I think you cam just make a UI button and set the canvas to world space. Then the UI is not on your screen but in the world. Another way to do it, is to make a raycast from where you clicked, and check if it hits an object in your scene. If it hits the button, then do what the button is supposed to do
Make a script called "WorldButton", and write this in it. Then attach the script to your button object. With this script, you can't click the button when it is behind another object, or if it is behind UI. If you want it to be able to work behind UI, remove "using UnityEngine.EventSystems;" and " && !EventSystem.current.IsPointerOverGameObject()"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class WorldButton : MonoBehaviour
{
Camera mainCamera;
void Start()
{
mainCamera = Camera.main;
}
void Update()
{
if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
{
RaycastHit hit;
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.gameObject == gameObject)
{
PressButton();
}
}
}
}
void PressButton()
{
//WRITE WHAT THE BUTTON NEEDS TO DO HERE
}
}
Answers
Thanks Zicrus,
But since I am a new to coding. I dont know how to use raycasting so will you please give me an example of it. Please I will appreciate it. Please
Well I need it for a mobile platform so sorry but that can help me in future.
I really appreciate it.βΊπ
I think it also works for mobile. Maybe with a few changes. Just replace mouse position with touch position
I am pretty sure that it will also require to change the mouse button down to touch something something.
Why making a mobile game in unity is complex. For computer there a function on clicking the object but on mobile you check the position of it then things and things.πππ
Mouse click also works on mobile. At least it does for me
Wait then i can add the event called OnMouseDown function guess.
Well I never thought that mouse click works for touch too. Lets hope is also works for OnMouseDown function too
Thanks for you help Zicrus. I think its time for some experiments